Repository navigation
feat(agents): pi session resume support - #8876
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughPi hook generation now captures 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/pi/agent-status-extension-source.test.ts (1)
184-187: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove duplicate test case.
The
sessionManagerloop array contains a duplicated test case (getSessionId: () => ''). Consider replacing the duplicate with a case that returnsundefinedforgetSessionIdto broaden the coverage, or simply remove it.♻️ Proposed refactor
for (const sessionManager of [ - { getSessionId: () => '', getSessionFile: () => undefined }, { getSessionId: () => '', getSessionFile: () => undefined }, + { getSessionId: () => undefined, getSessionFile: () => undefined }, { getSessionFile: () => '/tmp/pi-session.jsonl' } ]) {
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 8a05ad96-91aa-4bdf-97ff-b40387921512
📥 Commits
Reviewing files that changed from the base of the PR and between 190ed7d and f8a0e04ffaaa4c1aee16b5ee79ab345046bc538c.
📒 Files selected for processing (9)
src/main/pi/agent-status-extension-source.test.tssrc/main/pi/agent-status-extension-source.tssrc/main/pi/agent-status-handler-source.tssrc/renderer/src/lib/agent-hibernation-planner.test.tssrc/shared/agent-hook-listener.test.tssrc/shared/agent-hook-listener.tssrc/shared/agent-session-resume.test.tssrc/shared/agent-session-resume.tssrc/shared/workspace-session-schema.sleeping-agent.test.ts
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
src/shared/agent-hook-listener.ts (1)
3886-3891: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueAvoid unnecessary serialization for static objects.
Calling
parseAgentStatusPayload(JSON.stringify(...))serializes and immediately deserializes the static object. If a cast is safe here or if the underlying normalizer function is exported, consider skipping the stringification to avoid the minor runtime overhead.♻️ Proposed refactor
- const transportPayload = - payload ?? - (providerSessionOnly - ? parseAgentStatusPayload(JSON.stringify({ state: 'done', prompt: '', agentType: 'pi' })) - : null) + const transportPayload = + payload ?? + (providerSessionOnly + ? ({ state: 'done', prompt: '', agentType: 'pi' } as ParsedAgentStatusPayload) + : null)src/main/agent-hooks/server.ts (1)
236-243: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate Pi resume-validity gate across hydrate and relay-ingest paths.
The
!providerSession || agentType !== 'pi' || !getAgentResumeArgv('pi', providerSession)check is duplicated verbatim insanitizeHydratedEntryandingestRemote. Since this is the sole gate deciding whether aproviderSessionOnlyrow is trustworthy enough to keep, extracting it into one shared helper avoids the two copies drifting if the Pi resume rule changes later.♻️ Proposed refactor
+function isValidPiProviderSessionOnly( + providerSession: AgentProviderSessionMetadata | undefined, + agentType: AgentType | undefined +): boolean { + return Boolean( + providerSession && agentType === 'pi' && getAgentResumeArgv('pi', providerSession) + ) +} + // sanitizeHydratedEntry: - if ( - providerSessionOnly && - (!providerSession || payload.agentType !== 'pi' || !getAgentResumeArgv('pi', providerSession)) - ) { + if (providerSessionOnly && !isValidPiProviderSessionOnly(providerSession, payload.agentType)) { return null } // ingestRemote: - if ( - envelope.providerSessionOnly === true && - (!providerSession || - normalizedPayload.agentType !== 'pi' || - !getAgentResumeArgv('pi', providerSession)) - ) { + if ( + envelope.providerSessionOnly === true && + !isValidPiProviderSessionOnly(providerSession, normalizedPayload.agentType) + ) { return }Also applies to: 1413-1420
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 3136da28-055b-4652-a20f-93612e4600ae
📥 Commits
Reviewing files that changed from the base of the PR and between f8a0e04ffaaa4c1aee16b5ee79ab345046bc538c and e939e97a3e66b8602e54d5c53c52d1e7a9e52ca7.
📒 Files selected for processing (21)
src/main/agent-hooks/server.test.tssrc/main/agent-hooks/server.tssrc/main/index.tssrc/main/pi/agent-status-extension-source.test.tssrc/main/pi/agent-status-handler-source.tssrc/relay/agent-hook-server.test.tssrc/relay/agent-hook-server.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/hooks/useIpcEvents.tssrc/renderer/src/lib/resume-sleeping-agent-session.tssrc/renderer/src/lib/sleeping-agent-pane-ownership.tssrc/renderer/src/store/slices/agent-status-provider-session.test.tssrc/renderer/src/store/slices/agent-status.tssrc/shared/agent-hook-listener.test.tssrc/shared/agent-hook-listener.tssrc/shared/agent-hook-relay.tssrc/shared/agent-session-resume.test.tssrc/shared/agent-session-resume.tssrc/shared/agent-status-types.tssrc/shared/workspace-session-schema.sleeping-agent.test.tssrc/shared/workspace-session-sleeping-agents.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- src/main/pi/agent-status-handler-source.ts
- src/shared/agent-session-resume.test.ts
- src/main/pi/agent-status-extension-source.test.ts
- src/shared/agent-session-resume.ts
…fixture
The 'drops malformed sleeping agent resume records' test used agent:'pi' as
its example of an unknown/non-resumable agent, expecting the record to be
dropped. This PR added 'pi' to RESUMABLE_TUI_AGENTS, making that fixture
valid and retained, so the toBeUndefined assertion broke. Switch the
malformed-case fixture to a genuinely non-resumable sentinel
('definitely-not-an-agent') so the drop-malformed path is still exercised;
no other assertions changed.
Pi's `session_start` hook now carries the session file needed to resume a sleeping pane, but until now Orca either discarded it or treated it as a fake status transition. Thread a `providerSessionOnly` envelope through the hook listener, relay, main-process server, and renderer store so resume identity (and its session-file-scoped equality/claim key) can be persisted and replayed without emitting prompt telemetry or a visible working/done row.
Pi's agent_end hook marks a turn done, but the underlying TUI session stays alive and resumable. Previously a `done` status wiped sleeping records and launch config as if the session ended, so hibernation, manual worktree sleep, and quit-capture all lost Pi's resume identity. - Track a "live recovery" record for done-but-still-resumable Pi sessions, exempting it from the usual done-state cleanup paths in agent-status.ts and agent-hibernation-planner.ts - Gate providerSessionOnly rows and sleeping-agent schema records on actual resumability (getAgentResumeArgv) instead of trusting the presence of a provider session - Wait for Pi to persist its session file before advertising resume metadata, and treat `/reload` as a non-terminal event so it doesn't clobber visible status - Extend SSH relay envelopes to carry providerSessionOnly so remote hosts get the same behavior
e939e97 to
cd438fc
Compare
Split captureAllSleepingAgentSessions into 'periodic' and 'quit' modes so a background checkpoint can no longer downgrade a confirmed-quit record or promote a completed Pi session without an authoritative transcript path. Updates all call sites and tests accordingly.
Remove unnecessary JSON.stringify wrapper and call the appropriate normalization function directly.
OMP terminals report status through the managed Pi-compatible extension, but Orca never recorded OMP's provider session id, so a cold terminal restore (when the prior PTY cannot be reattached) could not build an `omp --resume <id>` startup command and fell back to an unresumed terminal — unlike Claude/Codex/Pi. Feed the existing sleeping-session/cold-restore pipeline the missing source fact instead of adding an OMP-specific path, reusing the session metadata transport that stablyai#8876 introduced for Pi resume: - For kind 'omp', refresh the shared `sessionMetadata` from the handler ctx (`ctx.sessionManager.getSessionId()`) on every event, and spread it into every posted payload. Unlike Pi (which resumes by transcript file and gates its metadata on that file existing), OMP resumes by id alone, so the latest handler-captured id rides every post as-is. Refreshing on every event matters because the transport keeps only the latest pending post and a session can switch within a process. Pi's generated source is byte-for-byte unchanged. - Add `omp` to `RESUMABLE_TUI_AGENTS`, parse its `session_id` in `extractAgentProviderSession`, and return `['omp', '--resume', <id>]` from `getAgentResumeArgv`. Warm daemon reattachment is unaffected: cold-restore consumption of the sleeping record is unchanged, so it still cannot launch a duplicate agent (stablyai#5232/stablyai#5240 invariant). Closes stablyai#8962
* feat(agents): pi session resume support
* fix(pi): require persisted session files for resume
* test(sleeping-agent): use non-resumable sentinel in malformed-record fixture
The 'drops malformed sleeping agent resume records' test used agent:'pi' as
its example of an unknown/non-resumable agent, expecting the record to be
dropped. This PR added 'pi' to RESUMABLE_TUI_AGENTS, making that fixture
valid and retained, so the toBeUndefined assertion broke. Switch the
malformed-case fixture to a genuinely non-resumable sentinel
('definitely-not-an-agent') so the drop-malformed path is still exercised;
no other assertions changed.
* Add durable resume identity for Pi sessions without fabricating turn sta
Pi's `session_start` hook now carries the session file needed to resume
a sleeping pane, but until now Orca either discarded it or treated it
as a fake status transition. Thread a `providerSessionOnly` envelope
through the hook listener, relay, main-process server, and renderer
store so resume identity (and its session-file-scoped equality/claim
key) can be persisted and replayed without emitting prompt telemetry
or a visible working/done row.
* Add durable resume identity for completed Pi sessions
Pi's agent_end hook marks a turn done, but the underlying TUI session
stays alive and resumable. Previously a `done` status wiped sleeping
records and launch config as if the session ended, so hibernation,
manual worktree sleep, and quit-capture all lost Pi's resume identity.
- Track a "live recovery" record for done-but-still-resumable Pi
sessions, exempting it from the usual done-state cleanup paths in
agent-status.ts and agent-hibernation-planner.ts
- Gate providerSessionOnly rows and sleeping-agent schema records on
actual resumability (getAgentResumeArgv) instead of trusting the
presence of a provider session
- Wait for Pi to persist its session file before advertising resume
metadata, and treat `/reload` as a non-terminal event so it doesn't
clobber visible status
- Extend SSH relay envelopes to carry providerSessionOnly so remote
hosts get the same behavior
* Add explicit periodic/quit mode to sleeping-agent session capture
Split captureAllSleepingAgentSessions into 'periodic' and 'quit' modes
so a background checkpoint can no longer downgrade a confirmed-quit
record or promote a completed Pi session without an authoritative
transcript path. Updates all call sites and tests accordingly.
* Use normalizeAgentStatusPayload for default pi status
Remove unnecessary JSON.stringify wrapper and call the appropriate normalization function directly.
---------
Co-authored-by: Jinjing <[email protected]>
Summary
pi is a recognized TuiAgent with first-class status-extension wiring (main + SSH relay), but it was missing from
RESUMABLE_TUI_AGENTS— so pi panes could not survive worktree sleep, app quit-restore, or agent hibernation: the pane came back dead and the conversation was lost.This PR adds pi to the resumable set, following the nine existing agent precedents:
ctx.sessionManager.getSessionId()/getSessionFile()onsession_startand carriessession_id+session_fileon subsequent hook posts.AgentStatusEntry.providerSession, gated on a persisted session file — ephemeral--no-sessionruns are deliberately not resumable.RESUMABLE_TUI_AGENTSgains'pi'; resume argv is['pi', '--session', <session-file path>]. The path form is cwd-independent and always non-interactive (a bare id can hit pi's interactive cross-project fork prompt).session_fileis threaded astranscriptPath, mirroring the Claude/Codextranscript_pathconvention.User-visible: pi workers now hibernate and revive with conversation context intact.
Screenshots
No visual change.
Testing
pnpm lint— passed (41 reliability gates, localization parity checks)pnpm typecheck— all three tsconfigs, exit 0pnpm test— honest accounting: on our macOS test box the full suite shows load-induced flaky failures in unrelated renderer suites both on this branch and on clean baseef87461bf(different failure sets per run, 15–20s timeouts under load). The one deterministic failure actually caused by this PR —workspace-session-schema.sleeping-agent.test.tsusedagent: 'pi'as its malformed-record sentinel, which this PR made valid — is fixed here by switching the fixture to a genuinely non-resumable sentinel. All PR-touched suites plus that schema suite pass deterministically: 170/170.pnpm build— full build passed (renderer, native, macOS computer-use targets)session_starthandling, omp payload identity, hibernation-planner gating.Additionally verified against the real pi binary (0.80.6) with a mock hook server: real runs emit
session_id+session_filematching the on-disk session header;--no-sessionruns omitsession_file; andpi --session <absolute session file>resumes with context intact from a different cwd, non-interactively.AI Review Report
Multi-agent review pipeline (implementer, independent adversarial reviewer, separate cross-platform/security auditor — different models):
endpoint.envand Windowsendpoint.cmdvariants) and the existing WSLcurl.exefallback verbatim. Resume argv quoting goes through the sharedquoteStartupArg(posix single-quote escaping, PowerShell quote doubling, cmd caret-escaping); a leading-dash or metacharacter-bearing path cannot escape quoting on posix/powershell. SSH remotes resume on the capture host, so no cross-host path translation occurs.connectionIdimplies a posix shell. Native-Windows pi under thecmdshell is an unexercised combination (likely unreachable if pi is WSL-only on Windows).Security Audit
session_id/session_filearrive over the existing token-authenticated loopback hook channel from the managed pi process (semi-trusted source).session_idpassesnormalizeSessionId(length cap, leading-dash rejection, control-char rejection);session_fileis control-char-checked and is only ever emitted as the quoted value of--session— no shell-injection vector through the changed paths. No new secrets, no new IPC channels; omp (which shares the extension source generator) is scoped out with a payload-identity test.Two low-severity hardening notes from our audit, disclosed deliberately rather than patched — happy to add either if you prefer:
session_fileis not additionally checked to be absolute, existing, or confined to pi's session root before use as resume argv; bounded by pi's own session-load behavior and the loopback token gate.Notes