fix: gracefully handle stale ctx after session replacement#2
Open
RobGilto wants to merge 1 commit into
Open
Conversation
When pi replaces a session mid-handler (e.g. Could you clarify what you'd like? For example: - **"Show me the pi system prompt"** — I can display my current instructions - **"Help me write a prompt"** — I can help craft a prompt for a specific task - **"Explain pi prompt templates"** — I can read the relevant docs - **Something else entirely?** What are you looking for?), the extension's captured ctx becomes stale and throws. This wraps all pi.on() handlers with a safeHandler that catches stale-context errors silently — the old session no longer exists, so there is nothing useful to do. The error was: Extension error: This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload().
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Problem
When running
pi -p "prompt", the extension throws an error after the response is delivered:The
-pflag causes pi to create a session, run the prompt, then replace/reload the session. The extension's event handlers still hold a reference to the oldctxand try to use it after replacement.Fix
Add a
safeHandlerwrapper inhook-context.tsthat catches stale-context errors and returns silently. When a session is replaced mid-handler, the old session no longer exists — there is nothing useful the handler can do, so silently returning is the correct behavior.All 9
pi.on()registrations across 5 hook modules are wrapped:session-hooks.ts—session_start,session_shutdownprompt-hooks.ts—input,before_agent_startcompact-hooks.ts—session_before_compact,session_compactstop-hooks.ts—agent_endtool-hooks.ts—tool_call,tool_resultTesting