Skip to content

fix(pi): finish the dialog-wait signal on every surface - #19533

Merged
nwparker merged 10 commits into
mainfrom
gatsby74/pi-ui-prompt-followups
Sep 8, 2026
Merged

nwparker merged 10 commits into
mainfrom
gatsby74/pi-ui-prompt-followups

Conversation

@nwparker

@nwparker nwparker commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​487 $\color{#cf222e}{\Huge{\mathbf{−}}}$​15 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​472
Prod 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​232 $\color{#cf222e}{\Huge{\mathbf{−}}}$​35 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​197

Follow-ups to #18836. That PR made a Pi extension dialog report waiting instead of working; the readiness review found four P2 gaps it left behind. This closes those, plus everything a source-level review turned up.

Reviewed against the real Pi 0.85.1 TypeScript source (pi-mono at tag v0.85.1), not against inference or the docs. That changed several conclusions — three of the defects below were invisible without reading Pi's own implementation.

What was still wrong

  1. Mobile and the CLI never saw the wait. The status hook reported waiting, but the titlebar spinner repainted a working frame every 80ms, so every surface whose only evidence is the OSC title still read the pane as busy mid-turn.
  2. ctx.ui is a throwing getter, and the guard was on the wrong side of the try. createContext() defines get ui() { runner.assertActive(); … } (runner.ts:726-729), which throws once a session-replacing dialog invalidates the runner. Optional chaining short-circuits on null/undefined, not on a getter that throws — so ctx?.ui?.setTitle threw after the depth decrement but before markerPainted cleared, stranding the pane on π ! … until the next turn. Reproduced through Pi's own loader (jiti) with a throwing getter.
  3. Pi is a second, unsynchronized writer of the same title. updateTerminalTitle() writes a byte-identical π - <session> - <cwd> from four call sites, two of which can fire while a dialog is open (session_info_changed, the win32 update-check restore). None is forwarded to extensions, so not-overwriting the marker was never enough — it has to be re-asserted.
  4. ui_prompt_end is not guaranteed. resetExtensionUI() hides an open dialog by disposing the component and never resolves its promise, so withUIPrompt's finally(finish) never runs and Pi emits no close at all for a dialog killed by /new, /resume, /fork or /reload. The wait stuck until the next agent_start.
  5. A title builder could kill the pi process. pi.getSessionName() asserts runner liveness the same way ctx.ui does, and process.cwd() throws ENOENT once a worktree is unlinked under a live pane. Both were evaluated as arguments, outside the paint guard — and four of the six call sites are timer callbacks, where an escape is an uncaught exception that Pi turns into exit(1). The cwd route was reachable today.
  6. The completion bell could ring for a dialog, not a turn, and a modal swallowed the assistant's last reply.

What changed

  • The titlebar extension paints the π ! needs-input marker for the dialog's duration and re-asserts it — every 80ms while a turn's spinner runs, and on a separate 1s timer otherwise, so it survives agent_settled, stopAnimation, and the idle-maintenance cap.
  • All ctx.ui access goes through resolvePainter/paintTitle, both try-wrapped; state is mutated only after a paint has actually succeeded. paintTitle takes a builder so the title is constructed inside the same guard.
  • Both extensions release the wait on session_start and session_shutdown — the only sound recovery, since no close is coming. agent_start remains the third boundary.
  • Idleness at close comes from local turn state (piTurnInFlight), with ctx.isIdle() consulted only while a turn is in flight.
  • Only the pane-owning process may assert the marker (ORCA_PI_TITLE_MARKER_OWNED, mirroring ORCA_PI_STATUS_OWNED). The spinner stays per-process.
  • The modal guard preserves an assistant message_end instead of clearing it with the stale tool/question fields.
  • getPiOmpRuntimeDetectionSourceLines is factored out so both extensions share one OMP check.

esbuild is declared as a devDependency: tests/tools/pi-ui-prompt-runtime-smoke.mjs (landed in #18836) imports it without a declaration.

Compatibility

No wire change — waiting/done are the existing vocabulary and the ! marker predates this branch on the OMP side. Generated omp and prime-agent sources were regenerated and diffed: byte-identical to main apart from dead declarations. All five generated variants parse under esbuild and load through jiti with every handler fired. Registering ui_prompt_* on Pi < 0.84.4 is safe — pi.on() never validates event names, in any version.

Known limitations (verified, not fixed)

  • A Pi title write is observed before it is corrected — up to 1s on an idle pane, 80ms mid-turn. It fires no callbacks: permission → idle fails every gate in createAgentStatusTracker.
  • A mid-turn dialog now produces an agent-idle title fact (working → permission satisfies the first gate). It does not notify: both dispatch points suppress it while a fresh non-done hook row exists, and the hook channel says waiting. This is established Orca behaviour — a Gemini permission prompt does the same today, and is less gated because Gemini has no hook channel. The suppression depends on the status extension's row existing, so a pane where it was skipped (skipped-user-owned) would ping like Gemini does.
  • The win32 npm update-check can clobber the title, and a title Orca classifies as null following a non-working status fires onAgentExited. The hazard class is pre-existing, but this branch makes one new state reachable: pre-branch a mid-turn clobber was shielded because lastStatus === 'working' fails that gate, and a mid-turn dialog now moves the pane to permission. Contained — startup one-shot, recovery bounded to one 80ms spinner frame by the re-assert, and restorableExitStatus is set.
  • /llama download progress runs through ctx.ui.custom, so a long download reads as waiting-for-input. The event carries no field distinguishing it from a real dialog.
  • ORCA_PI_TITLE_MARKER_OWNED is never released, matching ORCA_PI_STATUS_OWNED's existing behaviour.

Testing

  • pnpm test src/main/pi — 145 passed
  • pnpm test src/shared/agent-hook-listener — 198 passed
  • pnpm tc — clean; pnpm run check:code-quality:changed — 0 findings

New coverage includes a ctx whose ui is a throwing getter, a process.cwd() that throws ENOENT, a getSessionName() that throws on a stale runtime (both driven through timer paths), Pi overwriting the title mid-dialog, a session replacement that drops the dialog with no close, and a non-owning process declining the marker. Each new test was confirmed to fail against the pre-fix source.

Follow-ups to #18836, from its readiness review.

- Paint pi's `!` needs-input state marker while a dialog is open, so the
  80ms spinner frame stops repainting a working title over a mid-turn
  wait. Mobile and the CLI read the title, so they saw `working` where
  the desktop already showed `waiting`.
- Keep the assistant reply that lands while a dialog is open. The modal
  guard cleared tool fields and the `message_end` capture with them, so
  a turn ending under a dialog left the preview on the previous message.
- Report `ui_prompt_end` even when `ctx.isIdle()` throws on a runner the
  modal itself invalidated; the lost post stranded the pane on `waiting`.
- Declare the `esbuild` the runtime smoke tool imports.
From review of the previous commit.

- Settling under an open dialog no longer retires the marker. stopAnimation
  painted the plain title unconditionally, so agent_settled, a resolved
  agent_end, or an idle auto_compaction_end erased it mid-dialog — and
  because that also cleared the timer, the close then painted the plain
  title again and the wait was lost for good.
- Track the dialog as a boolean, not a depth counter. Pi does its own
  nesting accounting and emits one pair per stack, which is what the status
  extension already assumes; two files disagreeing on that would have let an
  inner close release the outer wait.
- Reset the flag on agent_start in both extensions. A turn cannot begin under
  a dialog holding input focus, so it is the one boundary that can recover a
  close that never arrived instead of pinning the pane forever.
- Leave OMP to its approval events: it reports waits through those already,
  and painting the marker there too would put title and hook in disagreement.
…lose

From review of the previous commit.

- Report working, not done, when ui_prompt_end's isIdle() throws. done is
  not cosmetic: it reaches dispatchCompletion and fires the pane's finished
  notification, so a turn that is still running would announce itself. The
  real done still arrives from agent_end/agent_settled.
- Keep the idle-maintenance frame cap accruing while a dialog holds the
  title, so a dialog left open cannot suspend the guard that stops a
  compaction spinner whose end event never came.
- Guard the dialog handlers against a ctx without ui. The source is
  generated and untypechecked, and pi does not document the ctx it passes
  these two events; a TypeError there would surface on every dialog.
From review of the previous commit.

- Re-arm the completion report when ui_prompt_end's isIdle() throws. The
  fallback posts working, but the finished turn had already reported its
  end, so nothing further would ever fire and an idle pane sat spinning.
- Count dialog depth in both extensions instead of trusting pi to emit one
  pair per stack. The guarantee is undocumented, and if it ever does emit a
  pair per dialog, an inner close would release the wait the outer dialog
  still holds. A counter costs nothing and drops the dependency.
From review of the previous commit.

- Fall back to agentEndReported when ctx.isIdle is unavailable or throws.
  The previous guess of working stranded the common case — a dialog opened
  at idle — because no later event was coming to correct it, and the
  agentEndReported re-arm it relied on could not fire either. A turn that
  already reported its end is not still running, and that is knowledge this
  process holds without needing ctx at all.
- Only suppress spinner frames once the marker is actually painted. Pi may
  pass a ctx with no ui, and freezing the title on its last working frame
  is the opposite of what the marker is for.
- Gate the titlebar dialog handlers on the OMP runtime too, not just the
  installed kind: a bare-shell OMP launch runs inside a pi-kind pane, and
  the status extension already defers there. Extracted that check so both
  extensions share it rather than carrying two copies.
From review of the previous commit.

- Track turn-in-flight separately from agentEndReported. That flag also
  dedupes the completion post, so it starts false on a pane that has not
  run a turn — which read as still-running and left a dialog opened before
  the first prompt spinning forever.
- Retry the marker paint on each dialog open instead of only the outermost,
  so an outer ctx without ui cannot decide the whole nested stack goes
  unmarked.
- Fall back to the opening ctx when the close carries no ui. Nothing else
  clears the needs-input marker, so the pane would have kept asking for
  attention until the next turn.
The close path paints through the ctx captured at open time, which is the
one a session-switching modal is most likely to have invalidated. Guard
both paint sites so a throw cannot reject the handler and leave the title
on the needs-input marker, and make local turn state the floor for the
status extension's idleness verdict instead of a fallback.
@coderabbitai

coderabbitai Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: df5f3826-c560-4b09-a70d-4fab845b7635

📥 Commits

Reviewing files that changed from the base of the PR and between be27eb2 and f04ce0a.

📒 Files selected for processing (6)
  • src/main/pi/agent-status-extension-source.test.ts
  • src/main/pi/agent-status-handler-source.ts
  • src/main/pi/agent-status-ui-prompt-source.ts
  • src/main/pi/agent-status-ui-prompt.test.ts
  • src/main/pi/titlebar-extension-source.test.ts
  • src/main/pi/titlebar-extension-source.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.


📝 Walkthrough

Walkthrough

The Pi status extensions now track nested prompt depth and turn state across session and agent events. Prompt closure uses local turn state when idleness is unavailable. The titlebar extension accepts the agent kind, detects runtime conditions, and preserves a needs-input marker during prompts. Modal assistant messages remain available after prompt closure. Tests cover nested prompts, stale state, recovery, runtime behavior, and titlebar errors. The development dependencies add esbuild version ^0.25.12.

Merge Risk: ⚪ Minimal · up to f04ce

The change improves Pi dialog markers and status recovery across lifecycle and failure cases. No actionable merge-blocking risk remains, and the covered behavior is ready to merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 10 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description gives detailed context, changes, rationale, compatibility notes, limitations, and testing results. However, it omits the required Visual Proof section and does not provide the required… Add the required Fixes #<issue> entry, attach before-and-after visual proof or write N/A with a reason, and complete or explicitly mark the remaining template sections and checklist items.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely describes the main change: completing Pi dialog-wait signaling across all surfaces.
Full details: Description check

Explanation

The description gives detailed context, changes, rationale, compatibility notes, limitations, and testing results. However, it omits the required Visual Proof section and does not provide the required Fixes # linked-issue entry. It also omits the repository checklist and several template sections.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Titlebar π ! needs-input marker — the titlebar extension now paints the ! marker for the duration of a Pi dialog and suppresses spinner frames while it is up, so mobile and the CLI (whose only evidence is the OSC title) classify the pane as permission mid-turn. Frames still accrue so the idle-maintenance cap cannot be suspended by a stuck dialog.
  • Dialog depth instead of a boolean — both extensions count promptDepth/piUiPromptDepth, so an inner close cannot release the wait the outer dialog still holds, and agent_start resets it as the recovery boundary for a lost close.
  • Idleness decided from local turn state — ui_prompt_end uses !piTurnInFlight as the floor and consults ctx.isIdle() only while a turn is in flight, wrapped in try/catch, so a session-switching modal that invalidates its runner strands neither a waiting pane nor rings the completion bell early.
  • Assistant reply preserved under a modal — extractPiToolFields keeps lastAssistantMessage on a message_end that lands while a dialog is open, while still clearing stale tool/question fields.
  • OMP runtime detection shared — getPiOmpRuntimeDetectionSourceLines is factored out so a bare-shell OMP launch inside a pi-kind pane defers to OMP's approval events on both the titlebar and status surfaces.
  • esbuild devDependency — declared for the already-landed tests/tools/pi-ui-prompt-runtime-smoke.mjs.

The dialog-state machine is consistent across both generated extensions, every paint site on the dialog path is guarded against a missing or invalidated ctx, and the new tests pin exact state transitions (including the cap-ordering and stopAnimation-under-dialog behavior) rather than loose truthiness checks.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

…closes

Reviewed against real Pi 0.85.1 source rather than inference:

- ctx.ui is a getter that calls assertActive() and throws once a session-
  replacing dialog invalidates the runner, so optional chaining never
  screened it out and the probe sat outside the try. A throw landed after
  the depth decrement but before markerPainted cleared, stranding the
  needs-input marker until the next turn.
- Pi writes the same terminal title from its own writers with no event we
  observe, so the marker is now re-asserted rather than merely not
  overwritten, on a slow timer that outlives the spinner and its cap.
- resetExtensionUI drops an open dialog without resolving its promise, so
  a replaced or reloaded session never emits the matching ui_prompt_end.
  Both extensions now release the wait on session_start and shutdown.
paintTitle caught the setTitle throw but not the two calls one argument to
its left: pi.getSessionName() asserts runner liveness the same way ctx.ui
does, and process.cwd() throws ENOENT once the worktree is unlinked under a
live pane. Four of the six call sites are timer callbacks, where an escape
is an uncaught exception and pi exits(1) through its own handler — so the
cwd route was reachable today. paintTitle now takes a builder and runs it
inside the existing try.
The spinner is harmlessly per-process, but the marker is status the pane
reports, and child agents inherit ORCA_PANE_KEY. Gate the two dialog
handlers on a PID claim, mirroring ORCA_PI_STATUS_OWNED in the status hook.
@nwparker
nwparker merged commit bba68b1 into main Sep 8, 2026
20 of 21 checks passed
@nwparker
nwparker deleted the gatsby74/pi-ui-prompt-followups branch September 8, 2026 10:07

@pullfrog pullfrog 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.

ℹ️ No critical issues — one minor residual gap noted inline. The three new commits are a solid tightening of the dialog-wait handling.

Reviewed changes

  • Marker re-assert timer — the titlebar extension re-asserts the π ! marker on a 1s interval (and every 80ms frame mid-turn), so Pi's own title writes (session_info_changed, the win32 update-check restore) can't silently retire an open dialog.
  • Paint behind a guard — resolvePainter/paintTitle accept a title builder evaluated inside the try/catch, so getSessionName()/process.cwd() throwing from a timer callback can no longer exit(1) the Pi process.
  • Session-boundary release — both extensions reset dialog state on session_start/session_shutdown; the titlebar also repaints the base title on shutdown.
  • Pane-ownership guard — ORCA_PI_TITLE_MARKER_OWNED limits the marker to the pane-owning process (mirroring ORCA_PI_STATUS_OWNED); the spinner stays per-process.
  • Shared OMP runtime detection — getPiOmpRuntimeDetectionSourceLines is factored out and reused by the titlebar extension.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

' // Why: pi tears an open dialog down through resetExtensionUI without resolving its',
' // promise, so a replaced session never emits the matching ui_prompt_end and the wait',
' // would stick forever. Reset without posting: shutdown is not a turn boundary, and',
' // the session_start that follows republishes the corrected state.',

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.

This release is passive: session_shutdown posts nothing, and session_start only republishes a done when the resumed session's session_file already exists on disk (the listener's providerSessionOnly fallback in agent-hook-listener.ts:114, which for Pi requires a non-null extractAgentProviderSession → a present session_file). For /new (fresh session, transcript not yet created) and /reload (the reason === 'reload' early-return posts nothing), a dialog Pi tears down without a close leaves the pane on waiting (Pi - action required) until the next turn event. The release tests all include a follow-up tool_execution_end, which masks the idle case.

Technical details
# Session-boundary release is passive for /new and /reload

## Affected sites
- src/main/pi/agent-status-ui-prompt-source.ts:34 — `session_shutdown` resets `piUiPromptDepth` without posting.
- src/main/pi/agent-status-handler-source.ts:12 — `session_start` resets depth then returns early for `reason === 'reload'`.
- src/shared/agent-hook-listener/providers/pi-family-events.ts:19 — `session_start` returns null (no status) when `ui_prompt_active` is absent.
- src/shared/agent-hook-listener.ts:114 — the `providerSessionOnly` → `done` fallback fires only when `extractAgentProviderSession` is non-null, which for Pi needs `session_file` in the payload (agent-session-resume.ts:214).

## Required outcome
- A `/new` or `/reload` that kills an open dialog must eventually clear the `waiting` status with no follow-up turn event, or the residual gap should be documented as a known limitation.

## Suggested approach
- Post a terminal status from `session_shutdown` (e.g. `ui_prompt_end` with `is_idle: true`, or a `done`), or clear `lastStatusByPaneKey` on the listener side for a Pi `session_start`/`session_shutdown` carrying no `ui_prompt_active`.

## Open questions for the human
- Is `/new` guaranteed to emit a later `session_start` with a created `session_file` that could produce `done`? `getPersistedSessionMetadata` says Pi publishes the path *before* creating the transcript, so likely not.

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.

1 participant