Unify tab agent identity with the agent-status pipeline (#7059)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -107,7 +107,8 @@ function makeWorktreeInfo(
|
||||
}
|
||||
|
||||
const HOST_SESSION_FILE = '/Users/ada/.claude/projects/-repo-orca/session-1.jsonl'
|
||||
const WSL_SESSION_FILE = '\\\\wsl$\\Ubuntu\\home\\ada\\.claude\\projects\\-repo-orca\\session-1.jsonl'
|
||||
const WSL_SESSION_FILE =
|
||||
'\\\\wsl$\\Ubuntu\\home\\ada\\.claude\\projects\\-repo-orca\\session-1.jsonl'
|
||||
|
||||
describe('resolveAiVaultSessionResumeState', () => {
|
||||
it('prefers the session worktree over the active workspace', () => {
|
||||
|
||||
@@ -95,7 +95,7 @@ export default function SortableTab({
|
||||
// Older persisted tabs without this field fall back to the generic icon.
|
||||
const shellForIcon = tab.shellOverride
|
||||
|
||||
// Why: foreground process and hook status make the tab icon reflect the
|
||||
// Why: hook status and title evidence make the tab icon reflect the
|
||||
// coding harness currently running in the pane, not just the launch command.
|
||||
const tabAgent = useTabAgent(tab)
|
||||
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPaneForegroundAgentTracker } from './pane-foreground-agent-tracker'
|
||||
import type { PaneForegroundAgentEntry } from '@/store/slices/pane-foreground-agent'
|
||||
|
||||
const COMMAND_SETTLE_MS = 350
|
||||
const WRAPPER_RESOLVE_RETRY_MS = 1200
|
||||
const SECOND_WRAPPER_RETRY_MS = 3500
|
||||
|
||||
describe('createPaneForegroundAgentTracker', () => {
|
||||
const readForegroundProcess = vi.fn<(ptyId: string) => Promise<string | null>>()
|
||||
const publish = vi.fn<(entry: PaneForegroundAgentEntry) => void>()
|
||||
let ptyId: string | null = 'pty-1'
|
||||
|
||||
function makeTracker(): ReturnType<typeof createPaneForegroundAgentTracker> {
|
||||
return createPaneForegroundAgentTracker({
|
||||
getPtyId: () => ptyId,
|
||||
isTrackablePtyId: (id) => !id.startsWith('remote:') && !id.startsWith('ssh:'),
|
||||
readForegroundProcess,
|
||||
publish
|
||||
})
|
||||
}
|
||||
|
||||
async function flushSettleRead(ms: number): Promise<void> {
|
||||
await vi.advanceTimersByTimeAsync(ms)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
readForegroundProcess.mockReset()
|
||||
publish.mockReset()
|
||||
ptyId = 'pty-1'
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllTimers()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('reads the foreground once after a command starts and publishes the recognized agent', async () => {
|
||||
readForegroundProcess.mockResolvedValue('claude')
|
||||
const tracker = makeTracker()
|
||||
|
||||
tracker.onCommandStarted()
|
||||
expect(publish).toHaveBeenCalledExactlyOnceWith({ agent: null, shellForeground: false })
|
||||
expect(readForegroundProcess).not.toHaveBeenCalled()
|
||||
|
||||
await flushSettleRead(COMMAND_SETTLE_MS)
|
||||
|
||||
expect(readForegroundProcess).toHaveBeenCalledExactlyOnceWith('pty-1')
|
||||
expect(publish).toHaveBeenLastCalledWith({ agent: 'claude', shellForeground: false })
|
||||
})
|
||||
|
||||
it('re-reads on a bounded ladder while the read still sees an interpreter wrapper', async () => {
|
||||
// Why: daemon shell/helper→agent ancestry resolution has been observed to
|
||||
// take >1.5s for real node-wrapped CLIs, so the ladder gets two re-reads.
|
||||
readForegroundProcess
|
||||
.mockResolvedValueOnce('node')
|
||||
.mockResolvedValueOnce('node')
|
||||
.mockResolvedValueOnce('claude')
|
||||
const tracker = makeTracker()
|
||||
|
||||
tracker.onCommandStarted()
|
||||
await flushSettleRead(COMMAND_SETTLE_MS)
|
||||
expect(readForegroundProcess).toHaveBeenCalledTimes(1)
|
||||
expect(publish).toHaveBeenLastCalledWith({ agent: null, shellForeground: false })
|
||||
|
||||
await flushSettleRead(WRAPPER_RESOLVE_RETRY_MS)
|
||||
expect(readForegroundProcess).toHaveBeenCalledTimes(2)
|
||||
|
||||
await flushSettleRead(SECOND_WRAPPER_RETRY_MS)
|
||||
expect(readForegroundProcess).toHaveBeenCalledTimes(3)
|
||||
expect(publish).toHaveBeenLastCalledWith({ agent: 'claude', shellForeground: false })
|
||||
})
|
||||
|
||||
it('stops after the ladder and publishes no identity for a persistent unknown process', async () => {
|
||||
readForegroundProcess.mockResolvedValue('some-unknown-tool')
|
||||
const tracker = makeTracker()
|
||||
|
||||
tracker.onCommandStarted()
|
||||
await flushSettleRead(
|
||||
COMMAND_SETTLE_MS + WRAPPER_RESOLVE_RETRY_MS + SECOND_WRAPPER_RETRY_MS + 10_000
|
||||
)
|
||||
|
||||
expect(readForegroundProcess).toHaveBeenCalledTimes(3)
|
||||
expect(publish).toHaveBeenLastCalledWith({ agent: null, shellForeground: false })
|
||||
})
|
||||
|
||||
it('does not treat a nested shell seen mid-command as prompt proof', async () => {
|
||||
// Why: 133;D cancels pending reads, so a read that still runs means the
|
||||
// command is live — a shell foreground here is a nested sh/bash, and a
|
||||
// shell-foreground mark would suppress live title identity in the pane.
|
||||
readForegroundProcess.mockResolvedValue('sh')
|
||||
const tracker = makeTracker()
|
||||
|
||||
tracker.onCommandStarted()
|
||||
await flushSettleRead(
|
||||
COMMAND_SETTLE_MS + WRAPPER_RESOLVE_RETRY_MS + SECOND_WRAPPER_RETRY_MS + 10_000
|
||||
)
|
||||
|
||||
expect(readForegroundProcess).toHaveBeenCalledTimes(3)
|
||||
expect(publish).not.toHaveBeenCalledWith({ agent: null, shellForeground: true })
|
||||
expect(publish).toHaveBeenLastCalledWith({ agent: null, shellForeground: false })
|
||||
})
|
||||
|
||||
it('recognizes an agent started from a nested shell on a ladder re-read', async () => {
|
||||
readForegroundProcess.mockResolvedValueOnce('bash').mockResolvedValueOnce('gemini')
|
||||
const tracker = makeTracker()
|
||||
|
||||
tracker.onCommandStarted()
|
||||
await flushSettleRead(COMMAND_SETTLE_MS)
|
||||
await flushSettleRead(WRAPPER_RESOLVE_RETRY_MS)
|
||||
|
||||
expect(publish).toHaveBeenLastCalledWith({ agent: 'gemini', shellForeground: false })
|
||||
})
|
||||
|
||||
it('marks shell foreground on command finished without any foreground read', () => {
|
||||
const tracker = makeTracker()
|
||||
|
||||
tracker.onCommandFinished()
|
||||
|
||||
expect(publish).toHaveBeenCalledExactlyOnceWith({ agent: null, shellForeground: true })
|
||||
expect(readForegroundProcess).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('cancels a pending read when the command finishes first', async () => {
|
||||
readForegroundProcess.mockResolvedValue('claude')
|
||||
const tracker = makeTracker()
|
||||
|
||||
tracker.onCommandStarted()
|
||||
tracker.onCommandFinished()
|
||||
await flushSettleRead(COMMAND_SETTLE_MS + WRAPPER_RESOLVE_RETRY_MS)
|
||||
|
||||
expect(readForegroundProcess).not.toHaveBeenCalled()
|
||||
expect(publish).toHaveBeenLastCalledWith({ agent: null, shellForeground: true })
|
||||
})
|
||||
|
||||
it('never reads or publishes for remote or ssh panes', async () => {
|
||||
ptyId = 'remote:web-env-1@@terminal-1'
|
||||
const tracker = makeTracker()
|
||||
|
||||
tracker.onCommandStarted()
|
||||
tracker.onCommandFinished()
|
||||
await flushSettleRead(COMMAND_SETTLE_MS + WRAPPER_RESOLVE_RETRY_MS)
|
||||
|
||||
ptyId = 'ssh:conn@@pty-9'
|
||||
tracker.onCommandStarted()
|
||||
tracker.onCommandFinished()
|
||||
await flushSettleRead(COMMAND_SETTLE_MS + WRAPPER_RESOLVE_RETRY_MS)
|
||||
|
||||
expect(readForegroundProcess).not.toHaveBeenCalled()
|
||||
expect(publish).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('drops a stale read result when a newer command superseded it', async () => {
|
||||
let resolveFirstRead: (value: string | null) => void = () => {}
|
||||
readForegroundProcess
|
||||
.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise<string | null>((resolve) => {
|
||||
resolveFirstRead = resolve
|
||||
})
|
||||
)
|
||||
.mockResolvedValueOnce('codex')
|
||||
const tracker = makeTracker()
|
||||
|
||||
tracker.onCommandStarted()
|
||||
await flushSettleRead(COMMAND_SETTLE_MS)
|
||||
tracker.onCommandStarted()
|
||||
resolveFirstRead('claude')
|
||||
await flushSettleRead(COMMAND_SETTLE_MS)
|
||||
|
||||
expect(publish).toHaveBeenLastCalledWith({ agent: 'codex', shellForeground: false })
|
||||
expect(publish).not.toHaveBeenCalledWith({ agent: 'claude', shellForeground: false })
|
||||
})
|
||||
|
||||
it('stops publishing after dispose', async () => {
|
||||
readForegroundProcess.mockResolvedValue('claude')
|
||||
const tracker = makeTracker()
|
||||
|
||||
tracker.onCommandStarted()
|
||||
publish.mockReset()
|
||||
tracker.dispose()
|
||||
await flushSettleRead(COMMAND_SETTLE_MS + WRAPPER_RESOLVE_RETRY_MS)
|
||||
|
||||
expect(readForegroundProcess).not.toHaveBeenCalled()
|
||||
expect(publish).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,105 @@
|
||||
import { recognizeAgentProcess } from '../../../../shared/agent-process-recognition'
|
||||
import type { PaneForegroundAgentEntry } from '@/store/slices/pane-foreground-agent'
|
||||
|
||||
// Why: the read must land after the shell has exec'd the command; and when it
|
||||
// still sees a node/python wrapper, the daemon resolves that ancestry
|
||||
// asynchronously — observed to take >1.5s for real node-wrapped CLIs — so
|
||||
// give its cache two bounded re-reads, not an open-ended retry loop.
|
||||
const COMMAND_SETTLE_MS = 350
|
||||
const WRAPPER_RESOLVE_RETRY_DELAYS_MS = [1200, 3500] as const
|
||||
|
||||
type PaneForegroundAgentTrackerDeps = {
|
||||
getPtyId: () => string | null
|
||||
/** Local panes only — remote/SSH foreground reads are expensive RPCs and
|
||||
* their replayed OSC streams must not produce process evidence. */
|
||||
isTrackablePtyId: (ptyId: string) => boolean
|
||||
readForegroundProcess: (ptyId: string) => Promise<string | null>
|
||||
publish: (entry: PaneForegroundAgentEntry) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes process-table identity for a pane at OSC 133 command boundaries:
|
||||
* one foreground read when a command starts (that is when the foreground
|
||||
* changes), and a no-RPC shell-foreground mark when it finishes — 133;D is
|
||||
* the ONLY source of shell-foreground proof; reads never produce it.
|
||||
*/
|
||||
export function createPaneForegroundAgentTracker(deps: PaneForegroundAgentTrackerDeps): {
|
||||
onCommandStarted: () => void
|
||||
onCommandFinished: () => void
|
||||
dispose: () => void
|
||||
} {
|
||||
let disposed = false
|
||||
let readTimer: number | null = null
|
||||
let readGeneration = 0
|
||||
|
||||
const trackablePtyId = (): string | null => {
|
||||
const ptyId = deps.getPtyId()
|
||||
return ptyId && deps.isTrackablePtyId(ptyId) ? ptyId : null
|
||||
}
|
||||
|
||||
const cancelPendingRead = (): void => {
|
||||
readGeneration += 1
|
||||
if (readTimer !== null) {
|
||||
window.clearTimeout(readTimer)
|
||||
readTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
const scheduleRead = (delayMs: number, retryIndex: number): void => {
|
||||
const generation = readGeneration
|
||||
readTimer = window.setTimeout(() => {
|
||||
readTimer = null
|
||||
void readForeground(generation, retryIndex)
|
||||
}, delayMs)
|
||||
}
|
||||
|
||||
async function readForeground(generation: number, retryIndex: number): Promise<void> {
|
||||
const ptyId = trackablePtyId()
|
||||
if (disposed || generation !== readGeneration || !ptyId) {
|
||||
return
|
||||
}
|
||||
const processName = await deps.readForegroundProcess(ptyId).catch(() => null)
|
||||
if (disposed || generation !== readGeneration) {
|
||||
return
|
||||
}
|
||||
const recognized = recognizeAgentProcess(processName)
|
||||
if (recognized) {
|
||||
deps.publish({ agent: recognized.agent, shellForeground: false })
|
||||
return
|
||||
}
|
||||
// Why: a shell seen here is NOT prompt proof — 133;D cancels pending reads,
|
||||
// so a still-live generation means the command is running and the shell is
|
||||
// a nested one (sh/bash without integration); marking shell-foreground
|
||||
// would suppress live title identity. Only 133;D proves the prompt.
|
||||
const retryDelay = WRAPPER_RESOLVE_RETRY_DELAYS_MS[retryIndex]
|
||||
if (retryDelay !== undefined && processName) {
|
||||
scheduleRead(retryDelay, retryIndex + 1)
|
||||
return
|
||||
}
|
||||
deps.publish({ agent: null, shellForeground: false })
|
||||
}
|
||||
|
||||
return {
|
||||
onCommandStarted() {
|
||||
cancelPendingRead()
|
||||
if (!trackablePtyId()) {
|
||||
return
|
||||
}
|
||||
// Why: the foreground left the prompt the moment C fired — stale
|
||||
// shell-foreground evidence must not clear the command that just started.
|
||||
deps.publish({ agent: null, shellForeground: false })
|
||||
scheduleRead(COMMAND_SETTLE_MS, 0)
|
||||
},
|
||||
onCommandFinished() {
|
||||
cancelPendingRead()
|
||||
if (!trackablePtyId()) {
|
||||
return
|
||||
}
|
||||
deps.publish({ agent: null, shellForeground: true })
|
||||
},
|
||||
dispose() {
|
||||
disposed = true
|
||||
cancelPendingRead()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,6 +156,8 @@ type StoreState = {
|
||||
setAgentStatus: ReturnType<typeof vi.fn>
|
||||
removeAgentStatus: ReturnType<typeof vi.fn>
|
||||
dropAgentStatus: ReturnType<typeof vi.fn>
|
||||
setPaneForegroundAgent: ReturnType<typeof vi.fn>
|
||||
clearPaneForegroundAgent: ReturnType<typeof vi.fn>
|
||||
markTerminalTabUnread: ReturnType<typeof vi.fn>
|
||||
markTerminalPaneUnread: ReturnType<typeof vi.fn>
|
||||
markAgentCompletionPaneUnread: ReturnType<typeof vi.fn>
|
||||
@@ -743,6 +745,8 @@ describe('connectPanePty', () => {
|
||||
),
|
||||
removeAgentStatus: vi.fn(),
|
||||
dropAgentStatus: vi.fn(),
|
||||
setPaneForegroundAgent: vi.fn(),
|
||||
clearPaneForegroundAgent: vi.fn(),
|
||||
markTerminalTabUnread: vi.fn(),
|
||||
markTerminalPaneUnread: vi.fn(),
|
||||
markAgentCompletionPaneUnread: vi.fn()
|
||||
|
||||
@@ -87,6 +87,8 @@ import {
|
||||
import { createBrowserUuid } from '@/lib/browser-uuid'
|
||||
import { makePaneKey, parseLegacyNumericPaneKey } from '../../../../shared/stable-pane-id'
|
||||
import { createTerminalCommandLifecycle } from './terminal-command-lifecycle'
|
||||
import { createPaneForegroundAgentTracker } from './pane-foreground-agent-tracker'
|
||||
import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id'
|
||||
import { dispatchTerminalCommandFinishedEvent } from '@/hooks/terminal-command-finished-event'
|
||||
import { e2eConfig } from '@/lib/e2e-config'
|
||||
import {
|
||||
@@ -1736,9 +1738,17 @@ export function connectPanePty(
|
||||
}
|
||||
return pendingWrite.then(() => interruptInference.flushPending())
|
||||
}
|
||||
const paneForegroundAgentTracker = createPaneForegroundAgentTracker({
|
||||
getPtyId: () => transport.getPtyId(),
|
||||
isTrackablePtyId: (id) => !isRemoteRuntimePtyId(id) && parseAppSshPtyId(id) === null,
|
||||
readForegroundProcess: (id) => window.api.pty.getForegroundProcess(id),
|
||||
publish: (entry) => useAppStore.getState().setPaneForegroundAgent(cacheKey, entry)
|
||||
})
|
||||
const commandLifecycle = createTerminalCommandLifecycle({
|
||||
onCommandStarted: () => paneForegroundAgentTracker.onCommandStarted(),
|
||||
onCommandFinished: () => {
|
||||
clearCommandInferredPaneAgentAfterPtySideEffects()
|
||||
paneForegroundAgentTracker.onCommandFinished()
|
||||
// Why: the finished command may have moved HEAD or the index (e.g.
|
||||
// `git checkout`); nudge git UI now instead of waiting for a poll.
|
||||
dispatchTerminalCommandFinishedEvent(deps.worktreeId)
|
||||
@@ -1977,6 +1987,7 @@ export function connectPanePty(
|
||||
// Why: a dead terminal has no running agent — remove its explicit status
|
||||
// entry so the hover UI only shows what is running *now*.
|
||||
useAppStore.getState().removeAgentStatus(cacheKey)
|
||||
useAppStore.getState().clearPaneForegroundAgent(cacheKey)
|
||||
// The runtime graph is the CLI's source for live terminal bindings, so
|
||||
// we must republish when a pane loses its PTY instead of waiting for a
|
||||
// broader layout change that may never happen.
|
||||
@@ -5956,6 +5967,7 @@ export function connectPanePty(
|
||||
pendingGeometryReportRaf = null
|
||||
}
|
||||
commandLifecycle.dispose()
|
||||
paneForegroundAgentTracker.dispose()
|
||||
agentCompletionCoordinator.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ import type { Terminal, IDisposable } from '@xterm/xterm'
|
||||
|
||||
type TerminalCommandLifecycleOptions = {
|
||||
onCommandFinished: (bestEffortExitCode: number | null) => void
|
||||
/** OSC 133;C — the shell exec'd a command; the pane's foreground changed. */
|
||||
onCommandStarted?: () => void
|
||||
}
|
||||
|
||||
type OscTerminator = {
|
||||
@@ -54,6 +56,10 @@ export function createTerminalCommandLifecycle(options: TerminalCommandLifecycle
|
||||
|
||||
const handleOsc133 = (payload: string): void => {
|
||||
const [sequence, exitCode] = payload.split(';')
|
||||
if (sequence === 'C') {
|
||||
options.onCommandStarted?.()
|
||||
return
|
||||
}
|
||||
if (sequence === 'D') {
|
||||
options.onCommandFinished(parseBestEffortExitCode(exitCode))
|
||||
}
|
||||
|
||||
@@ -1189,6 +1189,7 @@ export function useTerminalPaneLifecycle({
|
||||
useAppStore.getState().setCacheTimerStartedAt(paneKey, null)
|
||||
clearTerminalPaneUnread(paneKey)
|
||||
useAppStore.getState().dropAgentStatus(paneKey)
|
||||
useAppStore.getState().clearPaneForegroundAgent(paneKey)
|
||||
}
|
||||
if (transport) {
|
||||
if (isDetachedToTab) {
|
||||
|
||||
@@ -37,9 +37,7 @@ export function isSupportedAiVaultResumeTargetStatus(status: AiVaultResumeTarget
|
||||
return status === 'local' || status === 'ssh'
|
||||
}
|
||||
|
||||
export function isWslStoredAiVaultSessionFile(
|
||||
sessionFilePath: string | null | undefined
|
||||
): boolean {
|
||||
export function isWslStoredAiVaultSessionFile(sessionFilePath: string | null | undefined): boolean {
|
||||
return Boolean(sessionFilePath && isWslUncPath(sessionFilePath))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
hasCompletedTabAgent,
|
||||
resolveCompletedTabAgent,
|
||||
resolveFocusedCompletedTabAgent,
|
||||
resolveFocusedTabAgent,
|
||||
resolveSiblingCompletedTabAgent,
|
||||
resolveSiblingTabAgent,
|
||||
resolveTabAgent
|
||||
resolveSiblingTabAgent
|
||||
} from './tab-agent'
|
||||
import type { AgentStatusEntry, AgentType } from '../../../shared/agent-status-types'
|
||||
import type { TerminalLayoutSnapshot } from '../../../shared/types'
|
||||
import type { TerminalLayoutSnapshot, TuiAgent } from '../../../shared/types'
|
||||
|
||||
// Composed exactly the way useTabAgent layers the resolvers: focused pane
|
||||
// first, then any sibling agent pane in the tab.
|
||||
function resolveTabAgent(
|
||||
map: Record<string, AgentStatusEntry>,
|
||||
layout: TerminalLayoutSnapshot | undefined,
|
||||
tabId: string
|
||||
): TuiAgent | null {
|
||||
return resolveFocusedTabAgent(map, layout, tabId) ?? resolveSiblingTabAgent(map, layout, tabId)
|
||||
}
|
||||
|
||||
const LEAF_A = '11111111-1111-4111-8111-111111111111'
|
||||
const LEAF_B = '22222222-2222-4222-8222-222222222222'
|
||||
@@ -97,8 +104,8 @@ describe('resolveTabAgent', () => {
|
||||
state: 'done' as const
|
||||
}
|
||||
}
|
||||
expect(hasCompletedTabAgent(map, 'tab-1')).toBe(true)
|
||||
expect(resolveCompletedTabAgent(map, 'tab-1')).toBe('openclaude')
|
||||
expect(resolveFocusedCompletedTabAgent(map, undefined, 'tab-1')).toBe('openclaude')
|
||||
expect(resolveSiblingCompletedTabAgent(map, undefined, 'tab-1')).toBeNull()
|
||||
})
|
||||
|
||||
it('exposes focused and sibling completed hook identity separately', () => {
|
||||
|
||||
@@ -4,27 +4,13 @@ import { isTerminalLeafId, makePaneKey, parsePaneKey } from '../../../shared/sta
|
||||
import { agentTypeToIconAgent } from './agent-status'
|
||||
|
||||
/**
|
||||
* Resolve a terminal tab's agent from hook-reported status. This is the
|
||||
* FALLBACK signal for the tab-bar icon — the live foreground process
|
||||
* (see useTabAgent) is the primary, dev-friendly source. Hook status is what
|
||||
* drives the icon for SSH/remote panes (where foreground polling is too
|
||||
* costly) and during the brief window before the first foreground poll lands.
|
||||
*
|
||||
* Prefers the focused pane's agent so a split tab's icon tracks the pane in
|
||||
* view; falls back to any agent pane in the tab. Returns null when no pane
|
||||
* reports an iconable agent.
|
||||
* Resolve a terminal tab's agent from hook-reported status — the PRIMARY
|
||||
* identity signal for the tab-bar icon (composed by useTabAgent): the same
|
||||
* already-computed state that drives the sidebar agent rows, kept live by the
|
||||
* OSC 133 command-finished machinery that drops entries when a process exits.
|
||||
* Focused-pane resolvers track the pane in view; sibling resolvers cover the
|
||||
* rest of a split tab.
|
||||
*/
|
||||
export function resolveTabAgent(
|
||||
agentStatusByPaneKey: Record<string, AgentStatusEntry>,
|
||||
layout: TerminalLayoutSnapshot | undefined,
|
||||
tabId: string
|
||||
): TuiAgent | null {
|
||||
return (
|
||||
resolveFocusedTabAgent(agentStatusByPaneKey, layout, tabId) ??
|
||||
resolveSiblingTabAgent(agentStatusByPaneKey, layout, tabId)
|
||||
)
|
||||
}
|
||||
|
||||
export function resolveFocusedTabAgent(
|
||||
agentStatusByPaneKey: Record<string, AgentStatusEntry>,
|
||||
layout: TerminalLayoutSnapshot | undefined,
|
||||
@@ -76,24 +62,6 @@ function agentFromStatusEntry(entry: AgentStatusEntry | undefined): TuiAgent | n
|
||||
return agentTypeToIconAgent(entry.agentType)
|
||||
}
|
||||
|
||||
export function hasCompletedTabAgent(
|
||||
agentStatusByPaneKey: Record<string, AgentStatusEntry>,
|
||||
tabId: string
|
||||
): boolean {
|
||||
return resolveCompletedTabAgent(agentStatusByPaneKey, tabId) !== null
|
||||
}
|
||||
|
||||
export function resolveCompletedTabAgent(
|
||||
agentStatusByPaneKey: Record<string, AgentStatusEntry>,
|
||||
tabId: string,
|
||||
layout?: TerminalLayoutSnapshot
|
||||
): TuiAgent | null {
|
||||
return (
|
||||
resolveFocusedCompletedTabAgent(agentStatusByPaneKey, layout, tabId) ??
|
||||
resolveSiblingCompletedTabAgent(agentStatusByPaneKey, layout, tabId)
|
||||
)
|
||||
}
|
||||
|
||||
export function resolveFocusedCompletedTabAgent(
|
||||
agentStatusByPaneKey: Record<string, AgentStatusEntry>,
|
||||
layout: TerminalLayoutSnapshot | undefined,
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
// @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 { useAppStore } from '@/store'
|
||||
import { makePaneKey } from '../../../shared/stable-pane-id'
|
||||
import type { PaneForegroundAgentEntry } from '@/store/slices/pane-foreground-agent'
|
||||
import type { TerminalTab, TuiAgent } from '../../../shared/types'
|
||||
import {
|
||||
resolveLaunchedAgentExitEvidence,
|
||||
resolveTabAgentFromSignals,
|
||||
useTabAgent
|
||||
} from './use-tab-agent'
|
||||
|
||||
const initialAppState = useAppStore.getInitialState()
|
||||
const LEAF_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const PANE_KEY = makePaneKey('tab-1', LEAF_ID)
|
||||
let latestHookAgent: TuiAgent | null | undefined
|
||||
const hookRoots: Root[] = []
|
||||
|
||||
function HookProbe({ tab }: { tab: TerminalTab }): null {
|
||||
latestHookAgent = useTabAgent(tab)
|
||||
return null
|
||||
}
|
||||
|
||||
async function renderHookProbe(tab: TerminalTab): Promise<Root> {
|
||||
const container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
const root = createRoot(container)
|
||||
hookRoots.push(root)
|
||||
await act(async () => {
|
||||
root.render(createElement(HookProbe, { tab }))
|
||||
})
|
||||
return root
|
||||
}
|
||||
|
||||
async function setPaneForeground(entry: PaneForegroundAgentEntry): Promise<void> {
|
||||
await act(async () => {
|
||||
useAppStore.getState().setPaneForegroundAgent(PANE_KEY, entry)
|
||||
})
|
||||
}
|
||||
|
||||
describe('resolveTabAgentFromSignals process identity', () => {
|
||||
it('ranks the recognized foreground process above title and launch bootstrap', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
hasObservedAgentSignal: true,
|
||||
isRemote: false,
|
||||
title: '✦ Gemini CLI',
|
||||
hookAgent: null,
|
||||
processAgent: 'aider',
|
||||
launchAgent: 'codex'
|
||||
})
|
||||
).toBe('aider')
|
||||
})
|
||||
|
||||
it('keeps live hook identity above process identity', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
hasObservedAgentSignal: true,
|
||||
isRemote: false,
|
||||
title: 'Terminal 1',
|
||||
hookAgent: 'claude',
|
||||
processAgent: 'aider',
|
||||
launchAgent: undefined
|
||||
})
|
||||
).toBe('claude')
|
||||
})
|
||||
|
||||
it('suppresses launch identity on shell-foreground evidence despite a stale agent title', () => {
|
||||
// Why: OSC 133;D is process-grade exit proof — a TUI that died without
|
||||
// restoring its title must not keep painting the tab.
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
hasObservedAgentSignal: true,
|
||||
isRemote: false,
|
||||
title: '✳ Claude Code',
|
||||
hookAgent: null,
|
||||
processAgent: null,
|
||||
processShellForeground: true,
|
||||
launchAgent: 'claude'
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('suppresses stuck-title identity once shell foreground is proven on a manual pane', () => {
|
||||
// Why: pre-probe-removal, the foreground read cleared icons for TUIs that
|
||||
// died with a stuck title; shell-foreground evidence restores that.
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
hasObservedAgentSignal: true,
|
||||
isRemote: false,
|
||||
title: '✳ Claude Code',
|
||||
hookAgent: null,
|
||||
processAgent: null,
|
||||
processShellForeground: true,
|
||||
launchAgent: undefined
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps remote title identity even when a shell-foreground flag is passed', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
hasObservedAgentSignal: true,
|
||||
isRemote: true,
|
||||
title: '✳ Claude Code',
|
||||
hookAgent: null,
|
||||
processAgent: null,
|
||||
processShellForeground: true,
|
||||
launchAgent: undefined
|
||||
})
|
||||
).toBe('claude')
|
||||
})
|
||||
|
||||
it('keeps launch identity while the recognized process is still in the foreground', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
hasObservedAgentSignal: true,
|
||||
isRemote: false,
|
||||
title: 'zsh',
|
||||
hookAgent: null,
|
||||
processAgent: 'codex',
|
||||
launchAgent: 'codex'
|
||||
})
|
||||
).toBe('codex')
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveLaunchedAgentExitEvidence shell-foreground gate', () => {
|
||||
const baseArgs = {
|
||||
title: '✳ Claude Code',
|
||||
hasObservedAgentSignal: true,
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
processShellForeground: true
|
||||
}
|
||||
|
||||
it('counts shell-foreground proof as local launched-agent exit evidence', () => {
|
||||
expect(resolveLaunchedAgentExitEvidence({ ...baseArgs, isRemote: false })).toBe(true)
|
||||
})
|
||||
|
||||
it('never counts a shell-foreground flag as remote launched-agent exit evidence', () => {
|
||||
expect(resolveLaunchedAgentExitEvidence({ ...baseArgs, isRemote: true })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useTabAgent process signals', () => {
|
||||
const clearTabLaunchAgent = vi.fn()
|
||||
const baseTab: TerminalTab = {
|
||||
id: 'tab-1',
|
||||
ptyId: 'pty-1',
|
||||
worktreeId: 'wt-1',
|
||||
title: 'Terminal 1',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
latestHookAgent = undefined
|
||||
clearTabLaunchAgent.mockReset()
|
||||
useAppStore.setState(initialAppState, true)
|
||||
useAppStore.setState({
|
||||
ptyIdsByTabId: { 'tab-1': ['pty-1'] },
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-1': {
|
||||
root: { type: 'leaf', leafId: LEAF_ID },
|
||||
activeLeafId: LEAF_ID,
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { [LEAF_ID]: 'pty-1' }
|
||||
}
|
||||
},
|
||||
agentStatusByPaneKey: {},
|
||||
clearTabLaunchAgent
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
hookRoots.splice(0).forEach((root) => {
|
||||
act(() => root.unmount())
|
||||
})
|
||||
document.body.replaceChildren()
|
||||
useAppStore.setState(initialAppState, true)
|
||||
})
|
||||
|
||||
it('shows the recognized foreground agent for a manual launch with no hooks or titles', async () => {
|
||||
await renderHookProbe(baseTab)
|
||||
expect(latestHookAgent).toBeNull()
|
||||
|
||||
await setPaneForeground({ agent: 'aider', shellForeground: false })
|
||||
|
||||
expect(latestHookAgent).toBe('aider')
|
||||
expect(clearTabLaunchAgent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('clears hookless launch identity on shell-foreground evidence despite a stale title', async () => {
|
||||
const launchedTab = { ...baseTab, launchAgent: 'aider' as const, title: '⠸ aider working' }
|
||||
const root = await renderHookProbe(launchedTab)
|
||||
|
||||
await setPaneForeground({ agent: 'aider', shellForeground: false })
|
||||
expect(latestHookAgent).toBe('aider')
|
||||
expect(clearTabLaunchAgent).not.toHaveBeenCalled()
|
||||
|
||||
// Why: OSC 133;D marks the launched command exiting; the stale spinner
|
||||
// title must not keep the launch identity alive.
|
||||
await setPaneForeground({ agent: null, shellForeground: true })
|
||||
await act(async () => {
|
||||
root.render(createElement(HookProbe, { tab: launchedTab }))
|
||||
})
|
||||
|
||||
expect(clearTabLaunchAgent).toHaveBeenCalledWith('tab-1')
|
||||
})
|
||||
|
||||
it('does not clear launch identity from shell foreground before any agent activity', async () => {
|
||||
const launchedTab = { ...baseTab, launchAgent: 'aider' as const }
|
||||
await renderHookProbe(launchedTab)
|
||||
|
||||
// Pre-start window: the shell prompt (or a quick setup command) finishing
|
||||
// is not evidence the launched agent ever ran.
|
||||
await setPaneForeground({ agent: null, shellForeground: true })
|
||||
|
||||
expect(latestHookAgent).toBe('aider')
|
||||
expect(clearTabLaunchAgent).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -79,61 +79,37 @@ function twoPaneLayout(): TerminalLayoutSnapshot {
|
||||
}
|
||||
|
||||
describe('resolveTabAgentFromSignals', () => {
|
||||
it('uses a recognized foreground agent as the live local source of truth', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: 'codex',
|
||||
hasObservedAgentSignal: true,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: 'Terminal 1',
|
||||
hookAgent: 'claude',
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'claude'
|
||||
})
|
||||
).toBe('codex')
|
||||
})
|
||||
|
||||
it('keeps launch intent during the pre-start shell window', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: null,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: 'Terminal 1',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'claude'
|
||||
})
|
||||
).toBe('claude')
|
||||
})
|
||||
|
||||
it('lets shell foreground clear stale identity even when the title still names an agent', () => {
|
||||
it('trusts live hook identity at a shell title until the hook row is dropped', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: null,
|
||||
hasObservedAgentSignal: true,
|
||||
shellForegroundAfterAgentSignal: true,
|
||||
isRemote: false,
|
||||
title: '✳ Claude Code',
|
||||
title: 'zsh',
|
||||
hookAgent: 'claude',
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'claude'
|
||||
})
|
||||
).toBeNull()
|
||||
).toBe('claude')
|
||||
})
|
||||
|
||||
it('maps OpenClaude titles to the distinct OpenClaude tab icon', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '⠋ OpenClaude',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: undefined
|
||||
})
|
||||
).toBe('openclaude')
|
||||
@@ -142,39 +118,30 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it('keeps title fallback for real Gemini, MiMo, and Pi titles', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '✦ Gemini CLI',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: undefined
|
||||
})
|
||||
).toBe('gemini')
|
||||
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: 'MiMo Code',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: undefined
|
||||
})
|
||||
).toBe('mimo-code')
|
||||
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: 'π - my-project',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: undefined
|
||||
})
|
||||
).toBe('pi')
|
||||
@@ -183,14 +150,11 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it("uses completed OpenClaude hook identity over Claude's generic task-title heuristic", () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: true,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '✳ Say hi',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: true,
|
||||
completedHookAgent: 'openclaude',
|
||||
focusedCompletedHookAgent: 'openclaude',
|
||||
launchAgent: 'openclaude'
|
||||
})
|
||||
).toBe('openclaude')
|
||||
@@ -199,13 +163,10 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it('keeps launch identity over title identity while hooks have not arrived', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '✳ Say hi',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'openclaude'
|
||||
})
|
||||
).toBe('openclaude')
|
||||
@@ -214,13 +175,10 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it("keeps Codex launch intent over Claude's generic spinner title fallback", () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '⠸ codex-quarter-flash-202606191419',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'codex'
|
||||
})
|
||||
).toBe('codex')
|
||||
@@ -229,13 +187,10 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it('does not infer Claude identity from a generic spinner title without context', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '⠸ investigating startup',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: undefined
|
||||
})
|
||||
).toBeNull()
|
||||
@@ -245,13 +200,10 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
for (const title of ['. investigating startup', '* investigating startup', '✳ investigating']) {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title,
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: undefined
|
||||
})
|
||||
).toBeNull()
|
||||
@@ -261,13 +213,10 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it('keeps launch identity over explicit title identity until stronger signals arrive', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '⠸ Claude Code',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'codex'
|
||||
})
|
||||
).toBe('codex')
|
||||
@@ -276,28 +225,22 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it("uses Codex hook identity over Claude's generic task-title heuristic", () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: true,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '✳ improve-pr-actions-customization',
|
||||
hookAgent: 'codex',
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'codex'
|
||||
})
|
||||
).toBe('codex')
|
||||
})
|
||||
|
||||
it('keeps launch identity over explicit Claude Code titles without hook or foreground evidence', () => {
|
||||
it('keeps launch identity over explicit Claude Code titles without hook evidence', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '✳ Claude Code',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'openclaude'
|
||||
})
|
||||
).toBe('openclaude')
|
||||
@@ -306,13 +249,10 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it('lets an explicit title override stale launch identity after the pane shows newer activity', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: true,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '✳ Claude Code',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'codex'
|
||||
})
|
||||
).toBe('claude')
|
||||
@@ -321,43 +261,10 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it('does not let an explicit title override launch identity before any activity is observed', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '✳ Claude Code',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'codex'
|
||||
})
|
||||
).toBe('codex')
|
||||
})
|
||||
|
||||
it('lets shell foreground clear the icon after an agent was observed running', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: null,
|
||||
hasObservedAgentSignal: true,
|
||||
shellForegroundAfterAgentSignal: true,
|
||||
isRemote: false,
|
||||
title: 'zsh',
|
||||
hookAgent: 'claude',
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'claude'
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('does not let a pre-start shell sample suppress a later hook signal', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: null,
|
||||
hasObservedAgentSignal: true,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: 'Terminal 1',
|
||||
hookAgent: 'codex',
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'codex'
|
||||
})
|
||||
).toBe('codex')
|
||||
@@ -366,13 +273,10 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it('prefers explicit hook identity over a conflicting title mention', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: true,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '✳ Gemini CLI',
|
||||
hookAgent: 'claude',
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'claude'
|
||||
})
|
||||
).toBe('claude')
|
||||
@@ -381,13 +285,10 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it('prefers explicit hook identity over ordinary non-Claude title identity', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: true,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '✦ Gemini CLI',
|
||||
hookAgent: 'claude',
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'gemini'
|
||||
})
|
||||
).toBe('claude')
|
||||
@@ -396,14 +297,11 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it('lets focused-pane hook identity override launch metadata in split tabs', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: true,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: 'Terminal 1',
|
||||
hookAgent: 'claude',
|
||||
siblingHookAgent: 'gemini',
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'codex'
|
||||
})
|
||||
).toBe('claude')
|
||||
@@ -412,14 +310,11 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it('keeps unresolved launch metadata ahead of sibling-pane hook fallback', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: 'Terminal 1',
|
||||
hookAgent: null,
|
||||
siblingHookAgent: 'claude',
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'codex'
|
||||
})
|
||||
).toBe('codex')
|
||||
@@ -428,29 +323,23 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it('uses sibling-pane hook fallback when no launch metadata exists', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: 'Terminal 1',
|
||||
hookAgent: null,
|
||||
siblingHookAgent: 'claude',
|
||||
hasCompletedHook: false,
|
||||
launchAgent: undefined
|
||||
})
|
||||
).toBe('claude')
|
||||
})
|
||||
|
||||
it('keeps launch identity over Claude-owned task text without hook or foreground evidence', () => {
|
||||
it('keeps launch identity over Claude-owned task text without hook evidence', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '✳ Gemini CLI',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'gemini'
|
||||
})
|
||||
).toBe('gemini')
|
||||
@@ -459,26 +348,20 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it('keeps launch identity over Claude-owned punctuation-prefixed task text', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '. Compare Opencode Vs Orca',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'opencode'
|
||||
})
|
||||
).toBe('opencode')
|
||||
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '* Review Codex behavior',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'codex'
|
||||
})
|
||||
).toBe('codex')
|
||||
@@ -487,56 +370,87 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it('treats Claude-prefixed title text as Claude only when it names Claude', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '✳ Claude Code',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: undefined
|
||||
})
|
||||
).toBe('claude')
|
||||
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: false,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: '. Claude Code compare Opencode',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: undefined
|
||||
})
|
||||
).toBe('claude')
|
||||
})
|
||||
|
||||
it('keeps local launch identity when only a shell title suggests exit', () => {
|
||||
it('clears local launch identity once observed activity vanishes at a shell title', () => {
|
||||
// Why: matches the clear effect — the dropped hook row plus a shell title
|
||||
// is the crash/kill exit evidence, so the resolver must not lag it.
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: true,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: 'zsh',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'codex'
|
||||
})
|
||||
).toBe('codex')
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('skips local foreground authority for remote worktrees', () => {
|
||||
it('keeps launch identity at a shell title while a sibling hook row is live', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
hasObservedAgentSignal: true,
|
||||
isRemote: false,
|
||||
title: 'zsh',
|
||||
hookAgent: null,
|
||||
siblingHookAgent: 'gemini',
|
||||
launchAgent: 'claude'
|
||||
})
|
||||
).toBe('claude')
|
||||
})
|
||||
|
||||
it('keeps remote launch identity at a shell title without completed-hook evidence', () => {
|
||||
// Why: remote hook rows also drop on transport blips, so vanished activity
|
||||
// alone must not count as exit evidence for remote panes.
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
hasObservedAgentSignal: true,
|
||||
isRemote: true,
|
||||
title: 'zsh',
|
||||
hookAgent: null,
|
||||
launchAgent: 'claude'
|
||||
})
|
||||
).toBe('claude')
|
||||
})
|
||||
|
||||
it('treats the neutral default title as exit evidence alongside shell titles', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
hasObservedAgentSignal: true,
|
||||
isRemote: false,
|
||||
title: 'Terminal 2',
|
||||
defaultTitle: 'Terminal 2',
|
||||
hookAgent: null,
|
||||
focusedCompletedHookAgent: 'claude',
|
||||
launchAgent: 'claude'
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps hook identity for remote panes', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: null,
|
||||
hasObservedAgentSignal: true,
|
||||
shellForegroundAfterAgentSignal: true,
|
||||
isRemote: true,
|
||||
title: 'Terminal 1',
|
||||
hookAgent: 'codex',
|
||||
hasCompletedHook: false,
|
||||
launchAgent: 'claude'
|
||||
})
|
||||
).toBe('codex')
|
||||
@@ -545,32 +459,30 @@ describe('resolveTabAgentFromSignals', () => {
|
||||
it('keeps completed remote hook identity after the terminal title returns to a shell', () => {
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: true,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: true,
|
||||
title: 'zsh',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: true,
|
||||
completedHookAgent: 'codex',
|
||||
focusedCompletedHookAgent: 'codex',
|
||||
launchAgent: 'codex'
|
||||
})
|
||||
).toBe('codex')
|
||||
})
|
||||
|
||||
it('keeps local launch identity after a completed hook until foreground proves shell exit', () => {
|
||||
it('clears local launch identity once a completed hook and shell title prove exit', () => {
|
||||
// Why: without foreground probing, a completed hook plus the title back at
|
||||
// a shell is the process-gone evidence — the same signals that clear the
|
||||
// sidebar row — so stale launch identity must not keep painting the tab.
|
||||
expect(
|
||||
resolveTabAgentFromSignals({
|
||||
foreground: undefined,
|
||||
hasObservedAgentSignal: true,
|
||||
shellForegroundAfterAgentSignal: false,
|
||||
isRemote: false,
|
||||
title: 'zsh',
|
||||
hookAgent: null,
|
||||
hasCompletedHook: true,
|
||||
focusedCompletedHookAgent: 'claude',
|
||||
launchAgent: 'claude'
|
||||
})
|
||||
).toBe('claude')
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -619,103 +531,84 @@ describe('useTabAgent', () => {
|
||||
window.api = originalApi
|
||||
})
|
||||
|
||||
it('uses unrecognized non-shell foreground as launch lifecycle evidence', async () => {
|
||||
getForegroundProcess.mockResolvedValueOnce('node').mockResolvedValueOnce('zsh')
|
||||
it('never probes the foreground process', async () => {
|
||||
const paneKey = makePaneKey('tab-1', LEAF_ID)
|
||||
useAppStore.setState({
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-1': {
|
||||
root: { type: 'leaf', leafId: LEAF_ID },
|
||||
activeLeafId: LEAF_ID,
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { [LEAF_ID]: 'pty-1' }
|
||||
}
|
||||
},
|
||||
agentStatusByPaneKey: {
|
||||
[paneKey]: workingAgentStatus(paneKey)
|
||||
}
|
||||
})
|
||||
|
||||
const root = await renderHookProbe(baseTab)
|
||||
await rerenderHookProbe(root, { ...baseTab, title: '✳ Codex' })
|
||||
await rerenderHookProbe(root, { ...baseTab, title: 'zsh' })
|
||||
|
||||
expect(latestHookAgent).toBe('codex')
|
||||
expect(getForegroundProcess).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not clear launch identity while the live hook row persists at a shell title', async () => {
|
||||
const paneKey = makePaneKey('tab-1', LEAF_ID)
|
||||
useAppStore.setState({
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-1': {
|
||||
root: { type: 'leaf', leafId: LEAF_ID },
|
||||
activeLeafId: LEAF_ID,
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { [LEAF_ID]: 'pty-1' }
|
||||
}
|
||||
},
|
||||
agentStatusByPaneKey: {
|
||||
[paneKey]: workingAgentStatus(paneKey)
|
||||
}
|
||||
})
|
||||
|
||||
await renderHookProbe({ ...baseTab, title: 'zsh' })
|
||||
|
||||
expect(latestHookAgent).toBe('codex')
|
||||
expect(clearTabLaunchAgent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('clears launch identity when a previously observed hook row drops at a shell title', async () => {
|
||||
const paneKey = makePaneKey('tab-1', LEAF_ID)
|
||||
useAppStore.setState({
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-1': {
|
||||
root: { type: 'leaf', leafId: LEAF_ID },
|
||||
activeLeafId: LEAF_ID,
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { [LEAF_ID]: 'pty-1' }
|
||||
}
|
||||
},
|
||||
agentStatusByPaneKey: {
|
||||
[paneKey]: workingAgentStatus(paneKey)
|
||||
}
|
||||
})
|
||||
|
||||
const root = await renderHookProbe(baseTab)
|
||||
|
||||
expect(latestHookAgent).toBe('codex')
|
||||
expect(clearTabLaunchAgent).not.toHaveBeenCalled()
|
||||
|
||||
// Why: crash/kill exits drop the live row without a completed hook.
|
||||
await act(async () => {
|
||||
useAppStore.setState({ agentStatusByPaneKey: {} })
|
||||
})
|
||||
await rerenderHookProbe(root, { ...baseTab, title: 'zsh' })
|
||||
|
||||
expect(clearTabLaunchAgent).toHaveBeenCalledExactlyOnceWith('tab-1')
|
||||
expect(latestHookAgent).toBeNull()
|
||||
expect(getForegroundProcess).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('retries helper foreground so daemon-derived agent beats stale launch identity', async () => {
|
||||
vi.useFakeTimers()
|
||||
getForegroundProcess.mockResolvedValueOnce('uv').mockResolvedValueOnce('claude')
|
||||
|
||||
try {
|
||||
await renderHookProbe({ ...baseTab, launchAgent: 'opencode' })
|
||||
|
||||
expect(latestHookAgent).toBe('opencode')
|
||||
expect(getForegroundProcess).toHaveBeenCalledExactlyOnceWith('pty-1')
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(250)
|
||||
})
|
||||
await flushHookEffects()
|
||||
|
||||
expect(getForegroundProcess).toHaveBeenCalledTimes(2)
|
||||
expect(latestHookAgent).toBe('claude')
|
||||
} finally {
|
||||
vi.clearAllTimers()
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not retry unknown helper foreground without launch intent', async () => {
|
||||
vi.useFakeTimers()
|
||||
getForegroundProcess.mockResolvedValue('uv')
|
||||
|
||||
try {
|
||||
await renderHookProbe({ ...baseTab, launchAgent: undefined })
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(10_000)
|
||||
})
|
||||
await flushHookEffects()
|
||||
|
||||
expect(getForegroundProcess).toHaveBeenCalledExactlyOnceWith('pty-1')
|
||||
expect(latestHookAgent).toBeNull()
|
||||
} finally {
|
||||
vi.clearAllTimers()
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps one post-throttle shell retry to observe daemon-derived launch identity', async () => {
|
||||
vi.useFakeTimers()
|
||||
getForegroundProcess
|
||||
.mockResolvedValueOnce('zsh')
|
||||
.mockResolvedValueOnce('zsh')
|
||||
.mockResolvedValueOnce('zsh')
|
||||
.mockResolvedValueOnce('zsh')
|
||||
.mockResolvedValueOnce('claude')
|
||||
|
||||
try {
|
||||
await renderHookProbe({ ...baseTab, launchAgent: 'opencode' })
|
||||
|
||||
expect(latestHookAgent).toBe('opencode')
|
||||
expect(getForegroundProcess).toHaveBeenCalledExactlyOnceWith('pty-1')
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(250 + 1250 + 3500)
|
||||
})
|
||||
await flushHookEffects()
|
||||
|
||||
expect(getForegroundProcess).toHaveBeenCalledTimes(4)
|
||||
expect(latestHookAgent).toBe('opencode')
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(750)
|
||||
})
|
||||
await flushHookEffects()
|
||||
|
||||
expect(getForegroundProcess).toHaveBeenCalledTimes(5)
|
||||
expect(latestHookAgent).toBe('claude')
|
||||
} finally {
|
||||
vi.clearAllTimers()
|
||||
vi.useRealTimers()
|
||||
}
|
||||
expect(clearTabLaunchAgent).toHaveBeenCalledWith('tab-1')
|
||||
})
|
||||
|
||||
it('uses completed local hook status as launch lifecycle evidence after remount', async () => {
|
||||
const paneKey = makePaneKey('tab-1', LEAF_ID)
|
||||
getForegroundProcess.mockResolvedValueOnce('zsh')
|
||||
useAppStore.setState({
|
||||
agentStatusByPaneKey: {
|
||||
[paneKey]: completedAgentStatus(paneKey)
|
||||
@@ -724,9 +617,9 @@ describe('useTabAgent', () => {
|
||||
|
||||
await renderHookProbe({ ...baseTab, title: 'zsh' })
|
||||
|
||||
expect(clearTabLaunchAgent).toHaveBeenCalledExactlyOnceWith('tab-1')
|
||||
expect(clearTabLaunchAgent).toHaveBeenCalledWith('tab-1')
|
||||
expect(latestHookAgent).toBeNull()
|
||||
expect(getForegroundProcess).toHaveBeenCalledExactlyOnceWith('pty-1')
|
||||
expect(getForegroundProcess).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('treats paired runtime PTYs as remote-like for completed hook fallback', async () => {
|
||||
@@ -771,7 +664,6 @@ describe('useTabAgent', () => {
|
||||
|
||||
it('does not use completed sibling hook status as focused launch lifecycle evidence', async () => {
|
||||
const siblingPaneKey = makePaneKey('tab-1', SECOND_LEAF_ID)
|
||||
getForegroundProcess.mockResolvedValueOnce('zsh')
|
||||
useAppStore.setState({
|
||||
ptyIdsByTabId: { 'tab-1': ['pty-focus', 'pty-sibling'] },
|
||||
terminalLayoutsByTabId: { 'tab-1': twoPaneLayout() },
|
||||
@@ -789,6 +681,144 @@ describe('useTabAgent', () => {
|
||||
|
||||
expect(latestHookAgent).toBe('claude')
|
||||
expect(clearTabLaunchAgent).not.toHaveBeenCalled()
|
||||
expect(getForegroundProcess).toHaveBeenCalledExactlyOnceWith('pty-focus')
|
||||
expect(getForegroundProcess).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not clear remote launch identity when the hook row drops at a shell title', async () => {
|
||||
const remotePtyId = 'remote:web-env-1@@terminal-1'
|
||||
const paneKey = makePaneKey('tab-1', LEAF_ID)
|
||||
useAppStore.setState({
|
||||
ptyIdsByTabId: { 'tab-1': [remotePtyId] },
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-1': {
|
||||
root: { type: 'leaf', leafId: LEAF_ID },
|
||||
activeLeafId: LEAF_ID,
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { [LEAF_ID]: remotePtyId }
|
||||
}
|
||||
},
|
||||
agentStatusByPaneKey: {
|
||||
[paneKey]: workingAgentStatus(paneKey)
|
||||
}
|
||||
})
|
||||
const remoteTab = { ...baseTab, ptyId: remotePtyId, launchAgent: 'claude' as const }
|
||||
|
||||
const root = await renderHookProbe(remoteTab)
|
||||
|
||||
// Why: remote rows also drop on transport blips (reconnect, snapshot gaps)
|
||||
// that say nothing about the process — only a completed hook may clear.
|
||||
await act(async () => {
|
||||
useAppStore.setState({ agentStatusByPaneKey: {} })
|
||||
})
|
||||
await rerenderHookProbe(root, { ...remoteTab, title: 'zsh' })
|
||||
|
||||
expect(clearTabLaunchAgent).not.toHaveBeenCalled()
|
||||
expect(latestHookAgent).toBe('claude')
|
||||
})
|
||||
|
||||
it('does not clear launch identity while a sibling hook row is still live', async () => {
|
||||
const focusedPaneKey = makePaneKey('tab-1', LEAF_ID)
|
||||
const siblingPaneKey = makePaneKey('tab-1', SECOND_LEAF_ID)
|
||||
useAppStore.setState({
|
||||
ptyIdsByTabId: { 'tab-1': ['pty-focus', 'pty-sibling'] },
|
||||
terminalLayoutsByTabId: { 'tab-1': twoPaneLayout() },
|
||||
agentStatusByPaneKey: {
|
||||
[focusedPaneKey]: workingAgentStatus(focusedPaneKey),
|
||||
[siblingPaneKey]: workingAgentStatus(siblingPaneKey)
|
||||
}
|
||||
})
|
||||
const splitTab = { ...baseTab, ptyId: 'pty-focus', launchAgent: 'claude' as const }
|
||||
|
||||
const root = await renderHookProbe(splitTab)
|
||||
|
||||
// Focused row drops but the sibling agent still runs: no exit evidence yet.
|
||||
await act(async () => {
|
||||
useAppStore.setState({
|
||||
agentStatusByPaneKey: { [siblingPaneKey]: workingAgentStatus(siblingPaneKey) }
|
||||
})
|
||||
})
|
||||
await rerenderHookProbe(root, { ...splitTab, title: 'zsh' })
|
||||
expect(clearTabLaunchAgent).not.toHaveBeenCalled()
|
||||
|
||||
await act(async () => {
|
||||
useAppStore.setState({ agentStatusByPaneKey: {} })
|
||||
})
|
||||
await rerenderHookProbe(root, { ...splitTab, title: 'zsh' })
|
||||
expect(clearTabLaunchAgent).toHaveBeenCalledWith('tab-1')
|
||||
})
|
||||
|
||||
it('clears launch identity at the neutral default title after a completed hook', async () => {
|
||||
const paneKey = makePaneKey('tab-1', LEAF_ID)
|
||||
useAppStore.setState({
|
||||
agentStatusByPaneKey: {
|
||||
[paneKey]: completedAgentStatus(paneKey)
|
||||
}
|
||||
})
|
||||
|
||||
// Why: the inferred-interrupt flow resets titles to the tab's default
|
||||
// ("Terminal N"), not a shell name — that must still count as exit.
|
||||
await renderHookProbe({ ...baseTab, title: 'Terminal 3', defaultTitle: 'Terminal 3' })
|
||||
|
||||
expect(clearTabLaunchAgent).toHaveBeenCalledWith('tab-1')
|
||||
})
|
||||
|
||||
it('clears hookless launch identity once its own title evidence ends at a shell', async () => {
|
||||
const geminiTab = { ...baseTab, launchAgent: 'gemini' as const, title: '✦ Gemini CLI' }
|
||||
|
||||
// Why: agents without hook integration prove activity via a title naming
|
||||
// the launched agent; the later shell title is then exit evidence.
|
||||
const root = await renderHookProbe(geminiTab)
|
||||
expect(clearTabLaunchAgent).not.toHaveBeenCalled()
|
||||
|
||||
await rerenderHookProbe(root, { ...geminiTab, title: 'zsh' })
|
||||
|
||||
expect(clearTabLaunchAgent).toHaveBeenCalledWith('tab-1')
|
||||
})
|
||||
|
||||
it('does not treat a layout-less multi-pane completed row as focused exit evidence', async () => {
|
||||
const siblingPaneKey = makePaneKey('tab-1', SECOND_LEAF_ID)
|
||||
useAppStore.setState({
|
||||
ptyIdsByTabId: { 'tab-1': ['pty-focus', 'pty-sibling'] },
|
||||
terminalLayoutsByTabId: {},
|
||||
agentStatusByPaneKey: {
|
||||
[siblingPaneKey]: completedAgentStatus(siblingPaneKey)
|
||||
}
|
||||
})
|
||||
|
||||
await renderHookProbe({ ...baseTab, ptyId: 'pty-focus', title: 'zsh', launchAgent: 'claude' })
|
||||
|
||||
expect(clearTabLaunchAgent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not clear launch identity on the commit that switches pane generations', async () => {
|
||||
const paneKey = makePaneKey('tab-1', LEAF_ID)
|
||||
const boundLayout = {
|
||||
root: { type: 'leaf', leafId: LEAF_ID } as const,
|
||||
activeLeafId: LEAF_ID,
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { [LEAF_ID]: 'pty-1' }
|
||||
}
|
||||
useAppStore.setState({
|
||||
terminalLayoutsByTabId: { 'tab-1': boundLayout },
|
||||
agentStatusByPaneKey: { [paneKey]: workingAgentStatus(paneKey) }
|
||||
})
|
||||
|
||||
const root = await renderHookProbe(baseTab)
|
||||
expect(latestHookAgent).toBe('codex')
|
||||
|
||||
// Why: a respawn/focus switch can land the new ptyId, the dropped row, and
|
||||
// a shell title in one commit — the previous generation's observed signal
|
||||
// must not clear the new generation's launch identity.
|
||||
await act(async () => {
|
||||
useAppStore.setState({
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-1': { ...boundLayout, ptyIdsByLeafId: { [LEAF_ID]: 'pty-2' } }
|
||||
},
|
||||
agentStatusByPaneKey: {}
|
||||
})
|
||||
})
|
||||
await rerenderHookProbe(root, { ...baseTab, title: 'zsh' })
|
||||
|
||||
expect(clearTabLaunchAgent).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
/* oxlint-disable react-doctor/no-adjust-state-on-prop-change -- Why: tab agent foreground state is synchronized from PTY/remote agent signals and shell foreground events. */
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useAppStore } from '@/store'
|
||||
import { recognizeAgentProcess } from '../../../shared/agent-process-recognition'
|
||||
import { isShellProcess } from '../../../shared/agent-detection'
|
||||
import { worktreeUsesRemoteConnection } from '@/store/slices/terminals'
|
||||
import { parseRemoteRuntimePtyId } from '@/runtime/runtime-terminal-stream'
|
||||
import { isTerminalLeafId, makePaneKey } from '../../../shared/stable-pane-id'
|
||||
import {
|
||||
resolveFocusedCompletedTabAgent,
|
||||
resolveFocusedTabAgent,
|
||||
@@ -16,37 +15,58 @@ import type { TerminalTab, TuiAgent } from '../../../shared/types'
|
||||
|
||||
export { resolveExplicitTerminalTitleAgentType as resolveTabAgentFromTitle } from '../../../shared/terminal-title-agent-type'
|
||||
|
||||
const HELPER_FOREGROUND_RETRY_DELAYS_MS = [250, 1250, 3500, 750] as const
|
||||
|
||||
function getTitleForegroundKey(title: string, launchAgent?: TuiAgent): string {
|
||||
const titleAgent = launchAgent ? null : resolveExplicitTerminalTitleAgentType(title)
|
||||
if (titleAgent) {
|
||||
return `agent:${titleAgent}`
|
||||
}
|
||||
if (isShellProcess(title)) {
|
||||
return 'shell'
|
||||
}
|
||||
const stableTitle = title
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
// Why: unknown agents may still animate leading status glyphs. Include the
|
||||
// stable title body so first launch from "Terminal 1" triggers one poll,
|
||||
// without polling on every spinner frame.
|
||||
.replace(/^(?:[✳✦⏲◇✋⠀-⣿]+|[.*]\s)\s*/, '')
|
||||
.slice(0, 48)
|
||||
return `unknown:${stableTitle}`
|
||||
// A shell name, or the tab's neutral default title — where Orca's
|
||||
// inferred-interrupt reset parks it. Blank titles are no evidence either way.
|
||||
function titleShowsNoAgent(title: string, defaultTitle?: string): boolean {
|
||||
const trimmed = title.trim()
|
||||
return trimmed.length > 0 && (isShellProcess(trimmed) || trimmed === defaultTitle?.trim())
|
||||
}
|
||||
|
||||
export function resolveTabAgentFromSignals(args: {
|
||||
foreground: TuiAgent | null | undefined
|
||||
hasObservedAgentSignal: boolean
|
||||
shellForegroundAfterAgentSignal: boolean
|
||||
isRemote: boolean
|
||||
/**
|
||||
* Probe-free evidence that a launched agent exited: the title shows no agent,
|
||||
* no live hook row remains in the tab, and either the hook completed or
|
||||
* previously observed activity vanished. The vanished-activity disjunct is
|
||||
* local-only: remote rows also drop on transport blips that say nothing about
|
||||
* the process.
|
||||
*/
|
||||
export function resolveLaunchedAgentExitEvidence(args: {
|
||||
title: string
|
||||
defaultTitle?: string
|
||||
isRemote: boolean
|
||||
hasObservedAgentSignal: boolean
|
||||
hookAgent: TuiAgent | null
|
||||
siblingHookAgent?: TuiAgent | null
|
||||
hasCompletedHook: boolean
|
||||
completedHookAgent?: TuiAgent | null
|
||||
processAgent?: TuiAgent | null
|
||||
processShellForeground?: boolean
|
||||
}): boolean {
|
||||
if (args.hookAgent || args.siblingHookAgent || args.processAgent) {
|
||||
return false
|
||||
}
|
||||
// Why: OSC 133;D proved the foreground returned to the shell — process-grade
|
||||
// exit evidence that doesn't depend on the agent leaving a clean title.
|
||||
// Local-only by construction (remote panes have no shell-foreground producer);
|
||||
// the gate keeps the invariant even for out-of-pipeline callers.
|
||||
if (!args.isRemote && args.processShellForeground && args.hasObservedAgentSignal) {
|
||||
return true
|
||||
}
|
||||
if (!titleShowsNoAgent(args.title, args.defaultTitle)) {
|
||||
return false
|
||||
}
|
||||
return args.hasCompletedHook || (!args.isRemote && args.hasObservedAgentSignal)
|
||||
}
|
||||
|
||||
export function resolveTabAgentFromSignals(args: {
|
||||
hasObservedAgentSignal: boolean
|
||||
isRemote: boolean
|
||||
title: string
|
||||
defaultTitle?: string
|
||||
hookAgent: TuiAgent | null
|
||||
siblingHookAgent?: TuiAgent | null
|
||||
focusedCompletedHookAgent?: TuiAgent | null
|
||||
siblingCompletedHookAgent?: TuiAgent | null
|
||||
processAgent?: TuiAgent | null
|
||||
processShellForeground?: boolean
|
||||
launchAgent?: TuiAgent
|
||||
}): TuiAgent | null {
|
||||
const launchAgent = args.launchAgent ?? null
|
||||
@@ -55,62 +75,71 @@ export function resolveTabAgentFromSignals(args: {
|
||||
// A live title that explicitly names a *different* agent, once the pane has
|
||||
// shown any activity, overrides that stale launch identity so the tab icon
|
||||
// tracks what is actually running (codex launch reused for claude, etc.).
|
||||
// Why: OSC 133;D proved this local pane's foreground is back at the shell,
|
||||
// so any title-derived identity is stale by definition — a TUI that died
|
||||
// with a stuck title must not keep painting the tab through the title layer.
|
||||
const processProvesShell = !args.isRemote && args.processShellForeground === true
|
||||
const titleOverridesLaunch =
|
||||
launchAgent !== null &&
|
||||
explicitTitleAgent !== null &&
|
||||
explicitTitleAgent !== launchAgent &&
|
||||
args.hasObservedAgentSignal
|
||||
const titleAgent = titleOverridesLaunch
|
||||
? explicitTitleAgent
|
||||
: launchAgent
|
||||
? null
|
||||
: explicitTitleAgent
|
||||
const titleLooksShell = isShellProcess(args.title)
|
||||
// Why: remote panes cannot cheaply prove shell foreground after hook exit,
|
||||
// so keep the last completed hook identity instead of flashing unknown.
|
||||
const titleAgent = processProvesShell
|
||||
? null
|
||||
: titleOverridesLaunch
|
||||
? explicitTitleAgent
|
||||
: launchAgent
|
||||
? null
|
||||
: explicitTitleAgent
|
||||
const hasCompletedHook = (args.focusedCompletedHookAgent ?? null) !== null
|
||||
const noAgentTitle = titleShowsNoAgent(args.title, args.defaultTitle)
|
||||
// Why: remote pane titles can lag their runtime, so keep the last completed
|
||||
// hook identity instead of flashing unknown when the title reads as a shell.
|
||||
const completedHookAgent =
|
||||
!args.isRemote && titleLooksShell && args.hasCompletedHook ? null : args.completedHookAgent
|
||||
!args.isRemote && (noAgentTitle || processProvesShell) && hasCompletedHook
|
||||
? null
|
||||
: (args.focusedCompletedHookAgent ?? args.siblingCompletedHookAgent ?? null)
|
||||
const focusedHookAgent = args.hookAgent ?? null
|
||||
const fallbackHookAgent = args.siblingHookAgent ?? completedHookAgent ?? null
|
||||
const localShellForegroundClearedLaunch =
|
||||
!args.isRemote && args.foreground === null && args.shellForegroundAfterAgentSignal
|
||||
const remoteCompletedHookAtShellTitle = args.isRemote && titleLooksShell && args.hasCompletedHook
|
||||
const activeLaunchAgent =
|
||||
localShellForegroundClearedLaunch || remoteCompletedHookAtShellTitle ? null : launchAgent
|
||||
// Why: titleAgent now ranks ahead of launch/fallback hooks because, once the
|
||||
const launchedAgentExited = resolveLaunchedAgentExitEvidence({
|
||||
title: args.title,
|
||||
defaultTitle: args.defaultTitle,
|
||||
isRemote: args.isRemote,
|
||||
hasObservedAgentSignal: args.hasObservedAgentSignal,
|
||||
hookAgent: focusedHookAgent,
|
||||
siblingHookAgent: args.siblingHookAgent,
|
||||
hasCompletedHook,
|
||||
processAgent: args.processAgent,
|
||||
processShellForeground: args.processShellForeground
|
||||
})
|
||||
const activeLaunchAgent = launchedAgentExited ? null : launchAgent
|
||||
const processAgent = args.processAgent ?? null
|
||||
// Why: titleAgent ranks ahead of launch/fallback hooks because, once the
|
||||
// pane has shown activity, a live explicit title is the freshest identity
|
||||
// signal — it beats a launchAgent gone stale through pane reuse. Before any
|
||||
// activity, titleAgent is null while launchAgent exists, so launch bootstrap
|
||||
// still wins the startup window.
|
||||
if (args.isRemote || args.foreground === undefined) {
|
||||
return focusedHookAgent ?? titleAgent ?? activeLaunchAgent ?? fallbackHookAgent
|
||||
}
|
||||
if (args.foreground) {
|
||||
return args.foreground
|
||||
}
|
||||
// Why: once a local pane has returned to a shell, a stale hook should not keep
|
||||
// painting it as an agent tab.
|
||||
if (args.shellForegroundAfterAgentSignal) {
|
||||
return null
|
||||
}
|
||||
return focusedHookAgent ?? titleAgent ?? activeLaunchAgent ?? fallbackHookAgent
|
||||
// still wins the startup window. Process identity (the recognized foreground
|
||||
// process) is ground truth below hooks — it covers agents that emit neither
|
||||
// hooks nor titles.
|
||||
return focusedHookAgent ?? processAgent ?? titleAgent ?? activeLaunchAgent ?? fallbackHookAgent
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve which coding-harness agent a terminal tab is running, for its tab-bar
|
||||
* icon. Layered signals, most-authoritative first:
|
||||
* icon. Identity flows through the same already-computed state as the sidebar
|
||||
* agent rows — no foreground probing. Layered signals, most-authoritative
|
||||
* first:
|
||||
*
|
||||
* 1. Live foreground process — the ground truth for what's running *now*: the
|
||||
* only signal that reverts to the terminal glyph when the agent exits to a
|
||||
* shell, or flips when a different agent starts in the same pane. Checked
|
||||
* event-driven (only when the tab's title changes — exactly when an agent
|
||||
* starts/exits/takes a turn), never on an interval, and only for local panes
|
||||
* (SSH foreground inspection is a 15s-timeout RPC). A recognized agent wins;
|
||||
* a recognized shell authoritatively means "no agent".
|
||||
* 2. Hook status — accurate provider identity from native integrations, and
|
||||
* available for SSH/remote panes where foreground polling is too costly.
|
||||
* 3. launchAgent — what Orca launched here; instant bootstrap before hooks or
|
||||
* foreground polling arrive, and the owned identity for startup windows.
|
||||
* 1. Hook status — provider identity from native integrations; the live entry
|
||||
* for the pane, dropped by the same OSC 133 command-finished machinery that
|
||||
* clears the sidebar row when the process exits.
|
||||
* 2. Process identity — the recognized foreground process, read at OSC 133
|
||||
* command boundaries (local panes only); covers agents that emit neither
|
||||
* hooks nor titles, and its shell-foreground mark is title-independent
|
||||
* exit evidence.
|
||||
* 3. launchAgent — what Orca launched here; instant bootstrap before hooks
|
||||
* arrive, cleared once hook/process/title evidence shows the launched
|
||||
* agent exited.
|
||||
* 4. Title — legacy/unknown-session fallback, and the live override when a pane
|
||||
* is reused: once the pane has shown activity, a title that explicitly names
|
||||
* a different agent than launchAgent wins over that stale launch identity.
|
||||
@@ -138,11 +167,23 @@ export function useTabAgent(tab: TerminalTab): TuiAgent | null {
|
||||
tab.id
|
||||
)
|
||||
)
|
||||
const completedHookAgent = focusedCompletedHookAgent ?? siblingCompletedHookAgent
|
||||
const hasCompletedHook = focusedCompletedHookAgent !== null
|
||||
const clearTabLaunchAgent = useAppStore((s) => s.clearTabLaunchAgent)
|
||||
const focusedPaneKey = useAppStore((s) => {
|
||||
const activeLeafId = s.terminalLayoutsByTabId[tab.id]?.activeLeafId
|
||||
return activeLeafId && isTerminalLeafId(activeLeafId) ? makePaneKey(tab.id, activeLeafId) : null
|
||||
})
|
||||
const processAgent = useAppStore((s) =>
|
||||
focusedPaneKey ? (s.paneForegroundAgentByPaneKey[focusedPaneKey]?.agent ?? null) : null
|
||||
)
|
||||
const processShellForeground = useAppStore((s) =>
|
||||
focusedPaneKey
|
||||
? Boolean(s.paneForegroundAgentByPaneKey[focusedPaneKey]?.shellForeground)
|
||||
: false
|
||||
)
|
||||
|
||||
// The focused pane's PTY (single-pane tabs have exactly one leaf).
|
||||
// The focused pane's PTY (single-pane tabs have exactly one leaf). Only used
|
||||
// to reset per-process-generation signals when the pane is respawned.
|
||||
const ptyId = useAppStore((s) => {
|
||||
const layout = s.terminalLayoutsByTabId[tab.id]
|
||||
const activeLeafId = layout?.activeLeafId
|
||||
@@ -151,10 +192,18 @@ export function useTabAgent(tab: TerminalTab): TuiAgent | null {
|
||||
return leafPty
|
||||
}
|
||||
const ptyIds = s.ptyIdsByTabId[tab.id] ?? []
|
||||
// Why: without a focused leaf, a split tab's first PTY can be a sibling
|
||||
// shell. Only single-PTY fallback foreground is authoritative.
|
||||
return ptyIds.length === 1 ? ptyIds[0]! : null
|
||||
})
|
||||
// Why: with no layout to prove which pane a completed row belongs to, only a
|
||||
// single-pane tab may treat it as focused-pane exit evidence — a sibling's
|
||||
// done row must not clear another pane's launch identity.
|
||||
const completedHookScopeKnown = useAppStore((s) => {
|
||||
const layout = s.terminalLayoutsByTabId[tab.id]
|
||||
if (layout?.activeLeafId && isTerminalLeafId(layout.activeLeafId)) {
|
||||
return true
|
||||
}
|
||||
return (s.ptyIdsByTabId[tab.id] ?? []).length <= 1
|
||||
})
|
||||
const hasRemoteRuntimePty = useAppStore((s) => {
|
||||
const layout = s.terminalLayoutsByTabId[tab.id]
|
||||
const ptyIds = new Set(s.ptyIdsByTabId[tab.id] ?? [])
|
||||
@@ -166,134 +215,92 @@ export function useTabAgent(tab: TerminalTab): TuiAgent | null {
|
||||
const isRemoteWorktree = useAppStore((s) => worktreeUsesRemoteConnection(s, tab.worktreeId))
|
||||
const isRemoteLike = isRemoteWorktree || hasRemoteRuntimePty
|
||||
|
||||
// undefined = no conclusive local reading (defer to title/hook/launchAgent);
|
||||
// null = foreground is a shell; TuiAgent = recognized agent process.
|
||||
const [foreground, setForeground] = useState<TuiAgent | null | undefined>(undefined)
|
||||
const [hasObservedAgentSignal, setHasObservedAgentSignal] = useState(false)
|
||||
const [shellForegroundAfterAgentSignal, setShellForegroundAfterAgentSignal] = useState(false)
|
||||
const hasObservedAgentSignalRef = useRef(false)
|
||||
const titleForegroundKey = getTitleForegroundKey(tab.title, tab.launchAgent)
|
||||
const signalGenerationRef = useRef<string | null>(null)
|
||||
const completedHookEvidence = hasCompletedHook && completedHookScopeKnown
|
||||
|
||||
useEffect(() => {
|
||||
setForeground(undefined)
|
||||
setHasObservedAgentSignal(false)
|
||||
hasObservedAgentSignalRef.current = false
|
||||
setShellForegroundAfterAgentSignal(false)
|
||||
}, [ptyId, isRemoteLike])
|
||||
|
||||
useEffect(() => {
|
||||
const fallbackAgentSignal =
|
||||
!tab.launchAgent && (resolveExplicitTerminalTitleAgentType(tab.title) || siblingHookAgent)
|
||||
// Why: a completed structured hook proves a launched agent existed, but
|
||||
// local launch cleanup still waits for current foreground-shell evidence.
|
||||
if (focusedHookAgent || hasCompletedHook || fallbackAgentSignal) {
|
||||
// Why: reset and re-seed in one effect so a pane respawn both invalidates
|
||||
// the previous generation's signal and immediately re-observes a still-live
|
||||
// hook row instead of leaving the signal stuck false.
|
||||
const generation = `${ptyId ?? ''}|${String(isRemoteLike)}`
|
||||
if (signalGenerationRef.current !== generation) {
|
||||
signalGenerationRef.current = generation
|
||||
hasObservedAgentSignalRef.current = false
|
||||
setHasObservedAgentSignal(false)
|
||||
}
|
||||
const explicitTitleAgent = resolveExplicitTerminalTitleAgentType(tab.title)
|
||||
// Why: for launched panes, only a title naming the launched agent counts as
|
||||
// its activity — other-agent or sibling evidence must not arm exit clearing
|
||||
// for an agent that never produced evidence of its own.
|
||||
const fallbackAgentSignal = tab.launchAgent
|
||||
? explicitTitleAgent === tab.launchAgent
|
||||
: Boolean(explicitTitleAgent || siblingHookAgent)
|
||||
// Why: a recognized foreground process is focused-pane ground truth, so it
|
||||
// arms exit clearing even for agents with no hook or title integration.
|
||||
if (focusedHookAgent || completedHookEvidence || processAgent || fallbackAgentSignal) {
|
||||
hasObservedAgentSignalRef.current = true
|
||||
setHasObservedAgentSignal(true)
|
||||
}
|
||||
}, [focusedHookAgent, hasCompletedHook, siblingHookAgent, tab.launchAgent, tab.title])
|
||||
|
||||
useEffect(() => {
|
||||
if (!ptyId || isRemoteLike) {
|
||||
return
|
||||
}
|
||||
const localPtyId = ptyId
|
||||
let cancelled = false
|
||||
const helperForegroundRetryTimers: number[] = []
|
||||
// Why: re-runs when ptyId or tab.title changes — a title change is the event
|
||||
// signalling a possible foreground transition (agent start, exit, or turn).
|
||||
// One RPC per transition, not a timer; cancellation coalesces rapid churn.
|
||||
function readForeground(retryIndex = 0): void {
|
||||
window.api.pty
|
||||
.getForegroundProcess(localPtyId)
|
||||
.then((process) => {
|
||||
applyForegroundProcess(process, retryIndex)
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) {
|
||||
setForeground(undefined)
|
||||
}
|
||||
})
|
||||
}
|
||||
function scheduleHelperForegroundRetry(retryIndex: number): void {
|
||||
const delay = HELPER_FOREGROUND_RETRY_DELAYS_MS[retryIndex]
|
||||
if (delay === undefined) {
|
||||
return
|
||||
}
|
||||
// Why: the daemon resolves shell/helper -> agent ancestry asynchronously
|
||||
// after the first foreground read, so give its short cache a bounded re-read.
|
||||
const timer = window.setTimeout(() => {
|
||||
readForeground(retryIndex + 1)
|
||||
}, delay)
|
||||
helperForegroundRetryTimers.push(timer)
|
||||
}
|
||||
function applyForegroundProcess(process: string | null, retryIndex: number): void {
|
||||
if (cancelled) {
|
||||
return
|
||||
}
|
||||
const recognized = recognizeAgentProcess(process)
|
||||
if (recognized) {
|
||||
hasObservedAgentSignalRef.current = true
|
||||
setHasObservedAgentSignal(true)
|
||||
setForeground(recognized.agent)
|
||||
} else if (process && isShellProcess(process)) {
|
||||
setShellForegroundAfterAgentSignal(hasObservedAgentSignalRef.current)
|
||||
setForeground(null)
|
||||
if (tab.launchAgent && !hasObservedAgentSignalRef.current) {
|
||||
scheduleHelperForegroundRetry(retryIndex)
|
||||
}
|
||||
} else {
|
||||
if (process && tab.launchAgent) {
|
||||
// Why: for Orca-owned launches, an unrecognized non-shell process
|
||||
// is enough lifecycle evidence to clear launch intent when the pane
|
||||
// later returns to a shell, without using title text as identity.
|
||||
hasObservedAgentSignalRef.current = true
|
||||
setHasObservedAgentSignal(true)
|
||||
}
|
||||
setForeground(undefined)
|
||||
if (process && tab.launchAgent) {
|
||||
scheduleHelperForegroundRetry(retryIndex)
|
||||
}
|
||||
}
|
||||
}
|
||||
readForeground()
|
||||
return () => {
|
||||
cancelled = true
|
||||
helperForegroundRetryTimers.forEach((timer) => window.clearTimeout(timer))
|
||||
}
|
||||
}, [ptyId, isRemoteLike, tab.launchAgent, titleForegroundKey])
|
||||
}, [
|
||||
ptyId,
|
||||
isRemoteLike,
|
||||
focusedHookAgent,
|
||||
completedHookEvidence,
|
||||
processAgent,
|
||||
siblingHookAgent,
|
||||
tab.launchAgent,
|
||||
tab.title
|
||||
])
|
||||
|
||||
useEffect(() => {
|
||||
if (!tab.launchAgent) {
|
||||
return
|
||||
}
|
||||
const titleLooksShell = isShellProcess(tab.title)
|
||||
const foregroundSawExitedAgent =
|
||||
!isRemoteLike && foreground === null && shellForegroundAfterAgentSignal
|
||||
const remoteHookCompletedAtShellTitle = isRemoteLike && hasCompletedHook && titleLooksShell
|
||||
if (foregroundSawExitedAgent || remoteHookCompletedAtShellTitle) {
|
||||
// Why: AND the state with the ref — the ref is generation-safe within this
|
||||
// commit (the observe effect above already reset it), while the state can
|
||||
// lag one render behind a pane focus/respawn switch.
|
||||
const launchedAgentExited = resolveLaunchedAgentExitEvidence({
|
||||
title: tab.title,
|
||||
defaultTitle: tab.defaultTitle,
|
||||
isRemote: isRemoteLike,
|
||||
hasObservedAgentSignal: hasObservedAgentSignal && hasObservedAgentSignalRef.current,
|
||||
hookAgent: focusedHookAgent,
|
||||
siblingHookAgent,
|
||||
hasCompletedHook: completedHookEvidence,
|
||||
processAgent,
|
||||
processShellForeground
|
||||
})
|
||||
if (launchedAgentExited) {
|
||||
clearTabLaunchAgent(tab.id)
|
||||
}
|
||||
}, [
|
||||
clearTabLaunchAgent,
|
||||
foreground,
|
||||
hasCompletedHook,
|
||||
completedHookEvidence,
|
||||
focusedHookAgent,
|
||||
siblingHookAgent,
|
||||
hasObservedAgentSignal,
|
||||
isRemoteLike,
|
||||
shellForegroundAfterAgentSignal,
|
||||
processAgent,
|
||||
processShellForeground,
|
||||
tab.defaultTitle,
|
||||
tab.id,
|
||||
tab.launchAgent,
|
||||
tab.title
|
||||
])
|
||||
|
||||
return resolveTabAgentFromSignals({
|
||||
foreground,
|
||||
hasObservedAgentSignal,
|
||||
shellForegroundAfterAgentSignal,
|
||||
isRemote: isRemoteLike,
|
||||
title: tab.title,
|
||||
defaultTitle: tab.defaultTitle,
|
||||
hookAgent: focusedHookAgent,
|
||||
siblingHookAgent,
|
||||
hasCompletedHook,
|
||||
completedHookAgent,
|
||||
focusedCompletedHookAgent,
|
||||
siblingCompletedHookAgent,
|
||||
processAgent,
|
||||
processShellForeground,
|
||||
launchAgent: tab.launchAgent
|
||||
})
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import { createBrowserSlice } from './slices/browser'
|
||||
import { createRateLimitSlice } from './slices/rate-limits'
|
||||
import { createSshSlice } from './slices/ssh'
|
||||
import { createAgentStatusSlice } from './slices/agent-status'
|
||||
import { createPaneForegroundAgentSlice } from './slices/pane-foreground-agent'
|
||||
import { createDiffCommentsSlice } from './slices/diffComments'
|
||||
import { createDetectedAgentsSlice } from './slices/detected-agents'
|
||||
import { createWorktreeNavHistorySlice } from './slices/worktree-nav-history'
|
||||
@@ -61,6 +62,7 @@ export const useAppStore = create<AppState>()((...a) => ({
|
||||
...createRateLimitSlice(...a),
|
||||
...createSshSlice(...a),
|
||||
...createAgentStatusSlice(...a),
|
||||
...createPaneForegroundAgentSlice(...a),
|
||||
...createDiffCommentsSlice(...a),
|
||||
...createDetectedAgentsSlice(...a),
|
||||
...createWorktreeNavHistorySlice(...a),
|
||||
|
||||
@@ -131,6 +131,7 @@ import { createBrowserSlice } from './browser'
|
||||
import { createRateLimitSlice } from './rate-limits'
|
||||
import { createSshSlice } from './ssh'
|
||||
import { createAgentStatusSlice } from './agent-status'
|
||||
import { createPaneForegroundAgentSlice } from './pane-foreground-agent'
|
||||
import { createDiffCommentsSlice } from './diffComments'
|
||||
import { createDetectedAgentsSlice } from './detected-agents'
|
||||
import { createWorktreeNavHistorySlice } from './worktree-nav-history'
|
||||
@@ -167,6 +168,7 @@ function createTestStore() {
|
||||
...createRateLimitSlice(...a),
|
||||
...createSshSlice(...a),
|
||||
...createAgentStatusSlice(...a),
|
||||
...createPaneForegroundAgentSlice(...a),
|
||||
...createDiffCommentsSlice(...a),
|
||||
...createDetectedAgentsSlice(...a),
|
||||
...createWorktreeNavHistorySlice(...a),
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createTestStore } from './store-test-helpers'
|
||||
import type { TerminalTab } from '../../../../shared/types'
|
||||
|
||||
function terminalTab(id: string, worktreeId: string): TerminalTab {
|
||||
return {
|
||||
id,
|
||||
ptyId: null,
|
||||
worktreeId,
|
||||
title: 'Terminal 1',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
}
|
||||
|
||||
describe('pane foreground agent slice', () => {
|
||||
it('sets, value-bails, and clears entries per pane key', () => {
|
||||
const store = createTestStore()
|
||||
store
|
||||
.getState()
|
||||
.setPaneForegroundAgent('tab-1:leaf-1', { agent: 'aider', shellForeground: false })
|
||||
const first = store.getState().paneForegroundAgentByPaneKey
|
||||
|
||||
store
|
||||
.getState()
|
||||
.setPaneForegroundAgent('tab-1:leaf-1', { agent: 'aider', shellForeground: false })
|
||||
expect(store.getState().paneForegroundAgentByPaneKey).toBe(first)
|
||||
|
||||
store.getState().clearPaneForegroundAgent('tab-1:leaf-1')
|
||||
expect(store.getState().paneForegroundAgentByPaneKey).toEqual({})
|
||||
})
|
||||
|
||||
it('sweeps only the closed tab prefix, not sibling tabs or prefix-share ids', () => {
|
||||
const store = createTestStore()
|
||||
store
|
||||
.getState()
|
||||
.setPaneForegroundAgent('tab-1:leaf-1', { agent: 'aider', shellForeground: false })
|
||||
store
|
||||
.getState()
|
||||
.setPaneForegroundAgent('tab-10:leaf-1', { agent: 'codex', shellForeground: false })
|
||||
|
||||
store.getState().clearPaneForegroundAgentByTabPrefix('tab-1')
|
||||
|
||||
expect(Object.keys(store.getState().paneForegroundAgentByPaneKey)).toEqual(['tab-10:leaf-1'])
|
||||
})
|
||||
|
||||
it('sweeps every tab of a worktree on wholesale teardown', () => {
|
||||
const store = createTestStore()
|
||||
store.setState({
|
||||
tabsByWorktree: {
|
||||
'wt-1': [terminalTab('tab-1', 'wt-1'), terminalTab('tab-2', 'wt-1')],
|
||||
'wt-2': [terminalTab('tab-3', 'wt-2')]
|
||||
}
|
||||
})
|
||||
store
|
||||
.getState()
|
||||
.setPaneForegroundAgent('tab-1:leaf-1', { agent: 'aider', shellForeground: false })
|
||||
store.getState().setPaneForegroundAgent('tab-2:leaf-1', { agent: null, shellForeground: true })
|
||||
store
|
||||
.getState()
|
||||
.setPaneForegroundAgent('tab-3:leaf-1', { agent: 'codex', shellForeground: false })
|
||||
|
||||
const before = store.getState().paneForegroundAgentByPaneKey
|
||||
store.getState().clearPaneForegroundAgentByWorktree('wt-missing')
|
||||
expect(store.getState().paneForegroundAgentByPaneKey).toBe(before)
|
||||
|
||||
store.getState().clearPaneForegroundAgentByWorktree('wt-1')
|
||||
|
||||
expect(Object.keys(store.getState().paneForegroundAgentByPaneKey)).toEqual(['tab-3:leaf-1'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { StateCreator } from 'zustand'
|
||||
import type { AppState } from '../types'
|
||||
import type { TuiAgent } from '../../../../shared/types'
|
||||
|
||||
export type PaneForegroundAgentEntry = {
|
||||
/** Recognized agent process in the pane's foreground; null when unknown. */
|
||||
agent: TuiAgent | null
|
||||
/** True once the foreground is proven back at the shell (OSC 133;D) —
|
||||
* process-grade launched-agent exit evidence, independent of titles. */
|
||||
shellForeground: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Process-table identity for local panes, read at OSC 133 command boundaries
|
||||
* (see pane-foreground-agent-tracker). Sits below hook rows in the tab-icon
|
||||
* resolution; covers agents that emit neither hooks nor titles.
|
||||
*/
|
||||
export type PaneForegroundAgentSlice = {
|
||||
paneForegroundAgentByPaneKey: Record<string, PaneForegroundAgentEntry>
|
||||
setPaneForegroundAgent: (paneKey: string, entry: PaneForegroundAgentEntry) => void
|
||||
clearPaneForegroundAgent: (paneKey: string) => void
|
||||
/** Wholesale teardown sweeps (tab close, worktree sleep/remove) retire pane
|
||||
* keys without per-pane close events — clear their entries too. */
|
||||
clearPaneForegroundAgentByTabPrefix: (tabIdPrefix: string) => void
|
||||
clearPaneForegroundAgentByWorktree: (worktreeId: string) => void
|
||||
}
|
||||
|
||||
export const createPaneForegroundAgentSlice: StateCreator<
|
||||
AppState,
|
||||
[],
|
||||
[],
|
||||
PaneForegroundAgentSlice
|
||||
> = (set) => ({
|
||||
paneForegroundAgentByPaneKey: {},
|
||||
setPaneForegroundAgent: (paneKey, entry) => {
|
||||
set((s) => {
|
||||
const current = s.paneForegroundAgentByPaneKey[paneKey]
|
||||
if (
|
||||
current &&
|
||||
current.agent === entry.agent &&
|
||||
current.shellForeground === entry.shellForeground
|
||||
) {
|
||||
return s
|
||||
}
|
||||
return {
|
||||
paneForegroundAgentByPaneKey: { ...s.paneForegroundAgentByPaneKey, [paneKey]: entry }
|
||||
}
|
||||
})
|
||||
},
|
||||
clearPaneForegroundAgent: (paneKey) => {
|
||||
set((s) => {
|
||||
if (!(paneKey in s.paneForegroundAgentByPaneKey)) {
|
||||
return s
|
||||
}
|
||||
const next = { ...s.paneForegroundAgentByPaneKey }
|
||||
delete next[paneKey]
|
||||
return { paneForegroundAgentByPaneKey: next }
|
||||
})
|
||||
},
|
||||
clearPaneForegroundAgentByTabPrefix: (tabIdPrefix) => {
|
||||
set((s) => clearEntriesByTabPrefixes(s.paneForegroundAgentByPaneKey, [`${tabIdPrefix}:`]) ?? s)
|
||||
},
|
||||
clearPaneForegroundAgentByWorktree: (worktreeId) => {
|
||||
// Why: entries carry no worktreeId, so this must run while the worktree's
|
||||
// tabs are still in tabsByWorktree (removeWorktree prunes them only after
|
||||
// awaiting terminal teardown).
|
||||
set((s) => {
|
||||
const prefixes = (s.tabsByWorktree[worktreeId] ?? []).map((tab) => `${tab.id}:`)
|
||||
return clearEntriesByTabPrefixes(s.paneForegroundAgentByPaneKey, prefixes) ?? s
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
function clearEntriesByTabPrefixes(
|
||||
entries: Record<string, PaneForegroundAgentEntry>,
|
||||
tabPrefixes: string[]
|
||||
): Pick<PaneForegroundAgentSlice, 'paneForegroundAgentByPaneKey'> | null {
|
||||
if (tabPrefixes.length === 0) {
|
||||
return null
|
||||
}
|
||||
const staleKeys = Object.keys(entries).filter((paneKey) =>
|
||||
tabPrefixes.some((prefix) => paneKey.startsWith(prefix))
|
||||
)
|
||||
if (staleKeys.length === 0) {
|
||||
return null
|
||||
}
|
||||
const next = { ...entries }
|
||||
for (const paneKey of staleKeys) {
|
||||
delete next[paneKey]
|
||||
}
|
||||
return { paneForegroundAgentByPaneKey: next }
|
||||
}
|
||||
@@ -32,6 +32,7 @@ import { createBrowserSlice } from './browser'
|
||||
import { createRateLimitSlice } from './rate-limits'
|
||||
import { createSshSlice } from './ssh'
|
||||
import { createAgentStatusSlice } from './agent-status'
|
||||
import { createPaneForegroundAgentSlice } from './pane-foreground-agent'
|
||||
import { createDiffCommentsSlice } from './diffComments'
|
||||
import { createDetectedAgentsSlice } from './detected-agents'
|
||||
import { createWorktreeNavHistorySlice } from './worktree-nav-history'
|
||||
@@ -77,6 +78,7 @@ export function createTestStore() {
|
||||
...createRateLimitSlice(...a),
|
||||
...createSshSlice(...a),
|
||||
...createAgentStatusSlice(...a),
|
||||
...createPaneForegroundAgentSlice(...a),
|
||||
...createDiffCommentsSlice(...a),
|
||||
...createDetectedAgentsSlice(...a),
|
||||
...createWorktreeNavHistorySlice(...a),
|
||||
|
||||
@@ -1184,6 +1184,9 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
// so retention suppressors are planted: a live→gone transition inside the
|
||||
// same frame as the tab close cannot re-snapshot a row we just dropped.
|
||||
get().dropAgentStatusByTabPrefix(tabId)
|
||||
// Why: retired pane keys never recur, so stranded foreground entries would
|
||||
// accumulate for the renderer's whole lifetime.
|
||||
get().clearPaneForegroundAgentByTabPrefix(tabId)
|
||||
// Why: closing a tab permanently retires every pane under it (a reopen mints
|
||||
// a fresh leafId at epoch 0), so drop the panes' hibernation output epochs to
|
||||
// keep that module-level map from growing for the renderer's whole lifetime.
|
||||
@@ -2374,6 +2377,7 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
sleepingPaneKeys: opts?.sleepingPaneKeys,
|
||||
retainedCompletionEvidence
|
||||
})
|
||||
get().clearPaneForegroundAgentByWorktree(worktreeId)
|
||||
|
||||
if (ptyIds.length === 0 && expectedRuntimePtyIds.length === 0) {
|
||||
return
|
||||
|
||||
@@ -22,6 +22,7 @@ import type { BrowserSlice } from './slices/browser'
|
||||
import type { RateLimitSlice } from './slices/rate-limits'
|
||||
import type { SshSlice } from './slices/ssh'
|
||||
import type { AgentStatusSlice } from './slices/agent-status'
|
||||
import type { PaneForegroundAgentSlice } from './slices/pane-foreground-agent'
|
||||
import type { DiffCommentsSlice } from './slices/diffComments'
|
||||
import type { DetectedAgentsSlice } from './slices/detected-agents'
|
||||
import type { WorktreeNavHistorySlice } from './slices/worktree-nav-history'
|
||||
@@ -56,6 +57,7 @@ export type AppState = RepoSlice &
|
||||
RateLimitSlice &
|
||||
SshSlice &
|
||||
AgentStatusSlice &
|
||||
PaneForegroundAgentSlice &
|
||||
DiffCommentsSlice &
|
||||
DetectedAgentsSlice &
|
||||
WorktreeNavHistorySlice &
|
||||
|
||||
Reference in New Issue
Block a user