Repository navigation
fix(relay): stop advertising an agent session for a pane whose tab is gone (#12447) #17012
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
nwparker
merged 1 commit into
main
from
nwparker/relay-retire-closed-pane-agent-session
Aug 28, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| import type { AgentHookEventPayload } from '../shared/agent-hook-listener/listener-event' | ||
| import type { AgentHookSource } from '../shared/agent-hook-relay' | ||
|
|
||
| export type CachedPaneEnvelopeMeta = { source: AgentHookSource; env?: string; version?: string } | ||
|
|
||
| export type CachedPaneReplaySelection = { | ||
| event: AgentHookEventPayload | ||
| meta: CachedPaneEnvelopeMeta | ||
| } | ||
|
|
||
| /** | ||
| * Chooses which cached pane statuses a reconnecting client may be re-told about, and drops the rest. | ||
| * | ||
| * Two panes are refused, for opposite reasons: | ||
| * - a pane whose surface has been retired — the tab is gone, so replaying its status would hand the | ||
| * client a live agent pane nobody owns, which is what drives an auto-resume onto a transcript an | ||
| * orphaned agent is still writing; | ||
| * - a pane whose envelope metadata is missing — the status cache and the metadata map are populated | ||
| * and cleared in lockstep, so a key present in one and not the other is drift. Skip rather than | ||
| * guess a source that mis-tags the replay downstream. | ||
| */ | ||
| export function selectReplayableCachedPanes(input: { | ||
| cachedByPaneKey: ReadonlyMap<string, AgentHookEventPayload> | ||
| metaByPaneKey: ReadonlyMap<string, CachedPaneEnvelopeMeta> | ||
| isPaneSurfaceRetired: (paneKey: string) => boolean | ||
| dropPane: (paneKey: string) => void | ||
| }): CachedPaneReplaySelection[] { | ||
| const selected: CachedPaneReplaySelection[] = [] | ||
| // Snapshot: dropping a retired pane mutates the map being read. | ||
| for (const [paneKey, event] of Array.from(input.cachedByPaneKey.entries())) { | ||
| if (input.isPaneSurfaceRetired(paneKey)) { | ||
| input.dropPane(paneKey) | ||
| continue | ||
| } | ||
| const meta = input.metaByPaneKey.get(paneKey) | ||
| if (meta) { | ||
| selected.push({ event, meta }) | ||
| } | ||
| } | ||
| return selected | ||
| } | ||
|
|
||
| /** How many panes keep a cached status. Bounds a long-lived relay's per-pane state. */ | ||
| export const MAX_CACHED_PANES = 256 | ||
|
|
||
| /** Drop the longest-idle panes until the cache is back under its cap. Map insertion order is | ||
| * recency (writers delete-then-set), so the first key is always the oldest. */ | ||
| export function evictCachedPanesOverCap( | ||
| cachedByPaneKey: ReadonlyMap<string, unknown>, | ||
| dropPane: (paneKey: string) => void, | ||
| maxPanes: number = MAX_CACHED_PANES | ||
| ): void { | ||
| while (cachedByPaneKey.size > maxPanes) { | ||
| const oldest = cachedByPaneKey.keys().next().value | ||
| if (oldest === undefined) { | ||
| return | ||
| } | ||
| dropPane(oldest) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,206 @@ | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' | ||
| import { mkdtempSync, rmSync } from 'node:fs' | ||
| import { tmpdir } from 'node:os' | ||
| import { join } from 'node:path' | ||
| import { RelayAgentHookServer } from './agent-hook-server' | ||
| import { RelayAgentHookRuntime } from './relay-agent-hook-runtime' | ||
| import { RetiredPaneSurfaceRegistry } from './retired-pane-surfaces' | ||
| import type { AgentHookRelayEnvelope } from '../shared/agent-hook-relay' | ||
| import { makePaneKey } from '../shared/stable-pane-id' | ||
| import type { PtyHandler, PtySurfaceRetiredListener } from './pty-handler' | ||
| import type { RelayDispatcher } from './dispatcher' | ||
|
|
||
| const LEAF_ID = '11111111-1111-4111-8111-111111111111' | ||
| const PANE_KEY = makePaneKey('tab-1', LEAF_ID) | ||
|
|
||
| function hookMeta(paneKey: string): string { | ||
| return Buffer.from([paneKey, 'tab-1', '', 'wt-1', 'remote', '1'].join('\x1f')).toString('base64') | ||
| } | ||
|
|
||
| async function postHook( | ||
| server: RelayAgentHookServer, | ||
| paneKey: string, | ||
| prompt = 'hi' | ||
| ): Promise<number> { | ||
| const { port, token } = server.getCoordinates() | ||
| const res = await fetch(`http://127.0.0.1:${port}/hook/claude`, { | ||
| method: 'POST', | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| 'X-Orca-Agent-Hook-Token': token, | ||
| 'X-Orca-Agent-Hook-Meta-Encoding': 'base64', | ||
| 'X-Orca-Agent-Hook-Meta': hookMeta(paneKey) | ||
| }, | ||
| body: JSON.stringify({ hook_event_name: 'UserPromptSubmit', prompt }) | ||
| }) | ||
| return res.status | ||
| } | ||
|
|
||
| type CachedPanes = { state: { lastStatusByPaneKey: Map<string, unknown> } } | ||
|
|
||
| function cachedPaneKeys(server: RelayAgentHookServer): string[] { | ||
| return [...(server as unknown as CachedPanes).state.lastStatusByPaneKey.keys()] | ||
| } | ||
|
|
||
| describe('relay hook forwarding for a retired pane surface', () => { | ||
| let dir: string | ||
| let servers: RelayAgentHookServer[] | ||
|
|
||
| beforeEach(() => { | ||
| dir = mkdtempSync(join(tmpdir(), 'relay-retired-pane-')) | ||
| servers = [] | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| for (const server of servers) { | ||
| server.stop() | ||
| } | ||
| rmSync(dir, { recursive: true, force: true }) | ||
| }) | ||
|
|
||
| async function startServer(options: { | ||
| forward: (envelope: AgentHookRelayEnvelope) => void | ||
| isPaneSurfaceRetired?: (paneKey: string) => boolean | ||
| }): Promise<RelayAgentHookServer> { | ||
| const server = new RelayAgentHookServer({ endpointDir: dir, ...options }) | ||
| servers.push(server) | ||
| await server.start({ publishEndpoint: false }) | ||
| return server | ||
| } | ||
|
|
||
| it('forwards and caches a post from a pane that still has a tab', async () => { | ||
| const retired = new RetiredPaneSurfaceRegistry() | ||
| const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() | ||
| const server = await startServer({ | ||
| forward, | ||
| isPaneSurfaceRetired: (paneKey) => retired.isRetired(paneKey) | ||
| }) | ||
|
|
||
| expect(await postHook(server, PANE_KEY)).toBe(204) | ||
|
|
||
| expect(forward).toHaveBeenCalledTimes(1) | ||
| expect(cachedPaneKeys(server)).toEqual([PANE_KEY]) | ||
| }) | ||
|
|
||
| it('does not advertise an orphan agent whose tab was closed', async () => { | ||
| const retired = new RetiredPaneSurfaceRegistry() | ||
| const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() | ||
| const server = await startServer({ | ||
| forward, | ||
| isPaneSurfaceRetired: (paneKey) => retired.isRetired(paneKey) | ||
| }) | ||
|
|
||
| expect(await postHook(server, PANE_KEY, 'first')).toBe(204) | ||
| forward.mockClear() | ||
|
|
||
| // The user closes the tab; the agent inside the pane shell survives and keeps posting. | ||
| retired.retire(PANE_KEY) | ||
| expect(await postHook(server, PANE_KEY, 'orphan')).toBe(204) | ||
|
|
||
| expect(forward).not.toHaveBeenCalled() | ||
| // The pre-close status must go too, or a reconnect replays it as a live agent pane. | ||
| expect(cachedPaneKeys(server)).toEqual([]) | ||
| }) | ||
|
|
||
| it('does not replay a cached status for a pane retired after it was cached', async () => { | ||
| const retired = new RetiredPaneSurfaceRegistry() | ||
| const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() | ||
| const server = await startServer({ | ||
| forward, | ||
| isPaneSurfaceRetired: (paneKey) => retired.isRetired(paneKey) | ||
| }) | ||
|
|
||
| expect(await postHook(server, PANE_KEY)).toBe(204) | ||
| forward.mockClear() | ||
| retired.retire(PANE_KEY) | ||
|
|
||
| expect(server.replayCachedPayloadsForPanes()).toBe(0) | ||
| expect(forward).not.toHaveBeenCalled() | ||
| expect(cachedPaneKeys(server)).toEqual([]) | ||
| }) | ||
|
|
||
| it('forwards again once the pane key is bound by a new PTY', async () => { | ||
| const retired = new RetiredPaneSurfaceRegistry() | ||
| const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() | ||
| const server = await startServer({ | ||
| forward, | ||
| isPaneSurfaceRetired: (paneKey) => retired.isRetired(paneKey) | ||
| }) | ||
|
|
||
| retired.retire(PANE_KEY) | ||
| expect(await postHook(server, PANE_KEY, 'orphan')).toBe(204) | ||
| expect(forward).not.toHaveBeenCalled() | ||
|
|
||
| retired.restore(PANE_KEY) | ||
| expect(await postHook(server, PANE_KEY, 'reopened')).toBe(204) | ||
|
|
||
| expect(forward).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| it('an embedder that supplies no retirement source keeps forwarding everything', async () => { | ||
| const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() | ||
| const server = await startServer({ forward }) | ||
|
|
||
| expect(await postHook(server, PANE_KEY)).toBe(204) | ||
|
|
||
| expect(forward).toHaveBeenCalledTimes(1) | ||
| expect(cachedPaneKeys(server)).toEqual([PANE_KEY]) | ||
| }) | ||
| }) | ||
|
|
||
| describe('RelayAgentHookRuntime wiring', () => { | ||
| let dir: string | ||
|
|
||
| beforeEach(() => { | ||
| dir = mkdtempSync(join(tmpdir(), 'relay-retired-pane-runtime-')) | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| rmSync(dir, { recursive: true, force: true }) | ||
| }) | ||
|
|
||
| it('routes hook admission through the PTY handler and drops the cache on retirement', async () => { | ||
| const retired = new RetiredPaneSurfaceRegistry() | ||
| const surfaceRetiredListeners: PtySurfaceRetiredListener[] = [] | ||
| const ptyHandler = { | ||
| addEnvAugmenter: vi.fn(), | ||
| setExitListener: vi.fn(), | ||
| setSurfaceRetiredListener: vi.fn((listener: PtySurfaceRetiredListener | null) => { | ||
| if (listener) { | ||
| surfaceRetiredListeners.push(listener) | ||
| } | ||
| }), | ||
| isPaneSurfaceRetired: (paneKey: string) => retired.isRetired(paneKey) | ||
| } as unknown as PtyHandler | ||
| // Zero attached clients: publishAgentHookEnvelope returns before touching any sink. | ||
| const dispatcher = { | ||
| onRequest: vi.fn(), | ||
| activeClientIds: () => [] as number[] | ||
| } as unknown as RelayDispatcher | ||
|
|
||
| const runtime = new RelayAgentHookRuntime( | ||
| dispatcher, | ||
| ptyHandler, | ||
| join(dir, 'relay.sock'), | ||
| join(dir, 'hooks') | ||
| ) | ||
| await runtime.start() | ||
| try { | ||
| const server = (runtime as unknown as { hookServer: RelayAgentHookServer }).hookServer | ||
| expect(await postHook(server, PANE_KEY)).toBe(204) | ||
| expect(cachedPaneKeys(server)).toEqual([PANE_KEY]) | ||
|
|
||
| // The PTY handler retires the surface: the runtime must drop the cached status immediately, | ||
| // rather than waiting for a process exit a surviving shell never produces. | ||
| retired.retire(PANE_KEY) | ||
| expect(surfaceRetiredListeners).toHaveLength(1) | ||
| surfaceRetiredListeners[0]({ id: 'pty-1', paneKey: PANE_KEY }) | ||
| expect(cachedPaneKeys(server)).toEqual([]) | ||
|
|
||
| expect(await postHook(server, PANE_KEY, 'orphan')).toBe(204) | ||
| expect(cachedPaneKeys(server)).toEqual([]) | ||
| } finally { | ||
| runtime.stop() | ||
| } | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: stablyai/orca
Length of output: 12088
🏁 Script executed:
Repository: stablyai/orca
Length of output: 50370
🏁 Script executed:
Repository: stablyai/orca
Length of output: 35310
🏁 Script executed:
Repository: stablyai/orca
Length of output: 40887
Stop assistant retry scheduling for retired panes.
applyEvent()clears the pane state and returns, buthandleRequest()still callsscheduleAssistantMessageRetry(). That method can arm a timer from the request body. If the pane key is restored before the callback, the callback can apply the orphan event. Skip this scheduler call when the pane is retired.