Skip to content

feat(agents): pi session resume support - #8876

Merged
AmethystLiang merged 9 commits into
stablyai:mainfrom
eisen0419:feat/pi-session-resume
Jul 18, 2026
Merged

AmethystLiang merged 9 commits into
stablyai:mainfrom
eisen0419:feat/pi-session-resume

Conversation

@eisen0419

Copy link
Copy Markdown
Contributor

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:

  • The generated pi status extension captures the current session via ctx.sessionManager.getSessionId() / getSessionFile() on session_start and carries session_id + session_file on subsequent hook posts.
  • The pi hook path ingests them into AgentStatusEntry.providerSession, gated on a persisted session file — ephemeral --no-session runs are deliberately not resumable.
  • RESUMABLE_TUI_AGENTS gains '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_file is threaded as transcriptPath, mirroring the Claude/Codex transcript_path convention.

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 0
  • pnpm 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 base ef87461bf (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.ts used agent: '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)
  • Added/updated tests: extension session-metadata transport, provider-session extraction edges (ephemeral / missing file / empty id), path-form resume argv, listener session_start handling, 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_file matching the on-disk session header; --no-session runs omit session_file; and pi --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):

  • Adversarial review of the initial commit: 0 P1, 2 P2, 4 P3. The P2s (ephemeral sessions falsely marked resumable; bare-id resume argv reaching pi's interactive cross-cwd fork prompt) are fixed in the follow-up commit by gating on and resuming via the persisted session file.
  • Cross-platform pass (macOS / Linux / Windows / WSL): the change adds no new platform-specific code. New payload fields ride the existing endpoint-file parser (POSIX endpoint.env and Windows endpoint.cmd variants) and the existing WSL curl.exe fallback verbatim. Resume argv quoting goes through the shared quoteStartupArg (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.
  • Noted inherited assumption (pre-existing, not introduced here): SSH connectionId implies a posix shell. Native-Windows pi under the cmd shell is an unexercised combination (likely unreachable if pi is WSL-only on Windows).

Security Audit

session_id / session_file arrive over the existing token-authenticated loopback hook channel from the managed pi process (semi-trusted source). session_id passes normalizeSessionId (length cap, leading-dash rejection, control-char rejection); session_file is 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_file is 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.
  • Re-hydration from persisted state re-validates the session id but does not re-run the control-char check on the stored transcript path (the capture path does); backstopped by spawn-time quoting.

Notes

  • Scope honesty: verified via unit/integration tests, typecheck, full build, and a real-pi-binary hook harness including cross-cwd resume. A full in-app hibernate→revive e2e was not run here (no dev-build environment on this machine); the wiring follows the existing nine-agent precedents exactly, and we're glad to run any additional verification maintainers want.
  • pi restores provider/model/thinking from its session file on resume, so the resume argv intentionally passes no model flags.

@eisen0419
eisen0419 marked this pull request as ready for review July 15, 2026 17:20
@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Pi hook generation now captures session_id and session_file for Pi events while keeping OMP payloads unchanged. Pi session-start handling clears cached turn state. Shared session utilities recognize Pi as resumable, extract transcript paths from session_file, and construct Pi resume arguments when metadata is complete. Metadata-only session updates now flow through server, relay, IPC, persistence, and renderer ownership handling. Tests cover hook context forwarding, payload metadata, event normalization, session extraction, incomplete sessions, hibernation planning, and malformed sleeping-agent records.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: pi session resume support.
Description check ✅ Passed The description follows the required template and includes summary, screenshots, testing, AI review, security audit, and notes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/main/pi/agent-status-extension-source.test.ts (1)

184-187: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove duplicate test case.

The sessionManager loop array contains a duplicated test case (getSessionId: () => ''). Consider replacing the duplicate with a case that returns undefined for getSessionId to 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.ts
  • src/main/pi/agent-status-extension-source.ts
  • src/main/pi/agent-status-handler-source.ts
  • src/renderer/src/lib/agent-hibernation-planner.test.ts
  • src/shared/agent-hook-listener.test.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/agent-session-resume.test.ts
  • src/shared/agent-session-resume.ts
  • src/shared/workspace-session-schema.sleeping-agent.test.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/shared/agent-hook-listener.ts (1)

3886-3891: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Avoid 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 win

Duplicate Pi resume-validity gate across hydrate and relay-ingest paths.

The !providerSession || agentType !== 'pi' || !getAgentResumeArgv('pi', providerSession) check is duplicated verbatim in sanitizeHydratedEntry and ingestRemote. Since this is the sole gate deciding whether a providerSessionOnly row 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.ts
  • src/main/agent-hooks/server.ts
  • src/main/index.ts
  • src/main/pi/agent-status-extension-source.test.ts
  • src/main/pi/agent-status-handler-source.ts
  • src/relay/agent-hook-server.test.ts
  • src/relay/agent-hook-server.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/lib/resume-sleeping-agent-session.ts
  • src/renderer/src/lib/sleeping-agent-pane-ownership.ts
  • src/renderer/src/store/slices/agent-status-provider-session.test.ts
  • src/renderer/src/store/slices/agent-status.ts
  • src/shared/agent-hook-listener.test.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/agent-hook-relay.ts
  • src/shared/agent-session-resume.test.ts
  • src/shared/agent-session-resume.ts
  • src/shared/agent-status-types.ts
  • src/shared/workspace-session-schema.sleeping-agent.test.ts
  • src/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

Comment thread src/renderer/src/hooks/useIpcEvents.ts Resolved
eisen0419 and others added 5 commits July 15, 2026 17:46
…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
@AmethystLiang
AmethystLiang force-pushed the feat/pi-session-resume branch from e939e97 to cd438fc Compare July 16, 2026 01:51
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.
@AmethystLiang
AmethystLiang merged commit 3f335ef into stablyai:main Jul 18, 2026
2 of 3 checks passed
xianjianlf2 added a commit to xianjianlf2/orca that referenced this pull request Jul 18, 2026
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
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants