Skip to content

feat(computer): prewarm Pi on Room presence with dynamic MCP sync - #661

Merged
NightRain233 merged 1 commit into
mainfrom
feat/pi-provider-prepare
Nov 25, 2026
Merged

NightRain233 merged 1 commit into
mainfrom
feat/pi-provider-prepare

Conversation

@NightRain233

Copy link
Copy Markdown
Contributor

Summary

Entering a Room previously skipped provider.prepare for Pi (runtime_unsupported in Agent Service and not_eligible in the Local Computer Daemon), leaving the first message in a Room to pay full cold Pi process startup (~19s). This PR adds Room-presence prewarming for Pi together with in-place dynamic MCP attachment so prestarted Pi processes are actually adopted by the first Run (and resident Pi processes can also swap MCP servers between turns without restarting).

Changes

  1. Agent Service (apps/node-services)

    • Allow pi in Room-presence provider.prepare in RemoteRuntimeProvider.#sendProviderPrepare (kept disabled for accepted_input, matching Claude) and require a non-empty retained sessionId.
    • Add unit tests in remote-codex-provider-prepare.test.ts covering Pi presence prepare, accepted_input skip, missing sessionId skip, and antigravity skip.
  2. Local Computer Daemon (apps/computer/local-daemon)

    • Enable pi in executeProviderPrepare and Executor.PrepareProvider, with a 40s prepare timeout for Pi (piProviderPrepareTimeout) to cover Pi's 30s RPC startup budget plus Context View and thinking-level setup.
    • Implement piRuntime.prestart (pi_prestart.go): launches Pi with the managed extension (pi-mcp.mjs), empty private linger-mcp.json, and mcp__* in --tools; verifies get_state and applies clamped thinking levels (applyThinkingLevel); parks the process without sending a prompt.
    • Update piMismatch and probeIdleWithTranscript to match Claude's prestart semantics (AssignSessionID vs ResumeID) and skip .jsonl existence validation when adopting a newly created, unmaterialized prestart session.
    • Implement piRuntime.attach + piProcess.syncMCP: when adopting a resident Pi process whose MCP shape differs (e.g., empty prestart -> Run MCP servers, or MCP servers changed between turns), opens a fresh mcpFront, writes the rewritten linger-mcp.json, verifies get_commands exposes linger-sync-mcp, runs /linger-sync-mcp, and reads the structured verdict from the linger.mcp_sync RPC dialog before submitting the Run prompt. Any attachment failure recycles the process (attach_failed) and falls back to a cold spawn.
    • Update apps/computer/local-daemon/README.md to document Pi prestart and dynamic MCP attachment.
  3. Managed Pi Extension (apps/computer/tools/pi-mcp.mjs)

    • Mount Pi's createMcpExtension with an empty static loadConfig and register managed servers through Pi's extension API (pi.registerMcpServer / pi.unregisterMcpServer) so /linger-sync-mcp can add, replace, or remove MCP servers in place.
    • Wrap mcp_servers_change using property descriptors (handling Pi's getter-only ExtensionContext.ui), await connection/disconnection completion, record structured "warning" / "error" notifications, and report { ok, error? } via linger.mcp_sync.

Compatibility & Rollout

  • Wire contract: contracts/runner-gateway/envelope.schema.json already allows "pi" in ProviderPrepare.runtime_type, so no contract change is required.
  • Mixed versions:
    • Newer Agent Service + older Daemon: the Daemon decodes provider.prepare for pi and replies not_eligible without error.
    • Newer Daemon + older/unsupported Pi extension: hasCommand checks get_commands before sending /linger-sync-mcp, so an unsupported command is never sent as a user prompt; adoption recycles (attach_failed) and falls back to cold spawn.

User Message → provider_ready Critical Path

  • No network round trip or file walk is added to cold spawns or warm-same-MCP reuses (same-shape MCP reuses continue to rebind mcpFront in memory).
  • On adoption of a prestarted process (or a resident process whose MCP server set changed), attach rewrites the private linger-mcp.json and runs local RPC get_commands + /linger-sync-mcp to connect the Run's local MCP proxy endpoints; this avoids a full ~19s Pi cold process launch and falls back to cold spawn on error.

Scope Notes

  • Out of scope (potential follow-up): pre-warming local model readiness (ensureLocalModel) or KV prompt prefill during Room presence.

Verification

  • pnpm --filter @linger/node-services exec vitest run tests/agent/runner-gateway/remote-codex-provider-prepare.test.ts — 17/17 passed
  • pnpm --filter @linger/computer typecheck && pnpm --filter @linger/computer lint && pnpm --filter @linger/computer test — 7/7 passed (1 skipped)
  • cd apps/computer/local-daemon && go test -count=1 ./internal/daemon ./internal/provider and go test -count=1 ./internal/provider/native — all passed
  • cd apps/computer/local-daemon && GOOS=windows GOARCH=amd64 go build ./... — passed
  • LINGER_GO_LOCAL_DAEMON_TEST=1 pnpm --filter @linger/node-services exec vitest run tests/agent/runner-gateway/go-local-daemon-process.test.ts -t "prestarts Pi on presence" — passed (real Go Daemon + real Pi 1.2.0 + real pi-mcp.mjs + real QuickJS + mock OpenAI & Streamable HTTP MCP servers; verified single Pi process spawned across presence prepare, Run 1 mcp__echo__ping + mcp__computer__ui_exec, and Run 2 live MCP swap to mcp__second__greet with zero recycles)
  • make check-computer-release — passed
  • make -C apps/teamhub lint-go-daemon && make check-computer-go — passed
  • make check-repository-gate BASE=origin/main — passed (commitlint, env inventory, Prettier, doc links)
  • make check BASE=origin/main — check-repository, check-docs, check-desktop, check-node-services, and the Pi/Claude tests in go-local-daemon-process.test.ts all passed (the unrelated Codex fake tests in go-local-daemon-process.test.ts currently fail on main due to codex-cli 0.100.0 < 0.166.0, tracked by test(teamhub): give the process fixture's Codex a version the Daemon accepts #646)

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Approve with nits (1 P2, 1 P3)

Scope: base main, merge base 94ada676, 1 commit, 20 files reviewed at 37a87e1. Loaded coderbook, ponytail-review, karpathy-guidelines. Ran in a separate session. Pi 1.2.0 sources (@earendil-works/pi-coding-agent, the version pinned in apps/computer/package.json) were read to verify the RPC and extension assumptions.

Findings

P2

1. An MCP connection warning fails the warm attach, so a Run that has one unreachable MCP server ends up slower than a cold spawn (apps/computer/tools/pi-mcp.mjs:858-870, :943; apps/computer/local-daemon/internal/provider/native/pi_runtime.go:156-176)

  • mountManagedMcp treats every "warning" or "error" notification raised during mcp_servers_change as a sync failure. Pi's MCP extension reports a server that fails to connect with reportProblems → ctx.ui.notify("MCP servers need attention: …", "warning") (Pi dist/extensions/mcp/index.js:1112, :540). On a cold spawn, that same failure is only a notification and the Run continues.
  • Scenario: a Run's MCP set includes a server whose daemon-side target refuses connections. When the Run adopts the prestart, or a resident whose MCP set changed, attach waits for the connection to fail (up to piAttachBudget = 15s), gets {ok:false}, retires the process (attach_failed), and then pays the full cold spawn anyway. The same thing happens on every later adoption for that Context, and each time a resident process that could have served the Run is killed. The prewarm becomes a net latency loss.
  • Fix: make the warm path as strict as the cold path. Fail the verdict only on exceptions thrown by the sync itself (missing handler, registration error, MCP failed to load errors), and let per-server connection warnings pass, as they do on a cold start. Alternatively, collect only "error".

P3

2. RunSpec.ReviewPermissions has no observable effect (apps/computer/local-daemon/internal/provider/native/runtime.go:791-794, pi_runtime.go:251,264,339, executor.go:569)

  • With residents enabled and the extension installed, canSyncMCP is true. wired is then always true for both the prestart and the Run (pi_runtime.go:619, pi_prestart.go:213, launchProcess's piPrepareEmptyMCP), so --extension is added either way. With the extension missing, a reviewed Run already fails in piCheckExtension. With residents disabled, prestart is not eligible, and for run.start, authorization.ReviewsPermissions() equals PermissionReviewer != nil. Nothing changes behavior through this field. Drop the field and its three || spec.ReviewPermissions checks.

Verified as fine

  • The RPC ordering in syncMCP holds: Pi awaits the extension command handler, including its ctx.ui.input dialog, before it emits the prompt response {disposition:"handled"} (Pi core/agent-session.js:1611-1615, modes/rpc/rpc-mode.js:307-309). The verdict is therefore delivered by deliverMCPSync before the reply, and the select … default in pi_prestart.go:372-383 does not race.
  • The pendingChanges non-empty check is sound: McpServerRegistry.register/unregister calls the change listener synchronously, and ExtensionRunner.emit invokes the first handler before any await (Pi core/mcp-servers.js:209-219, core/extensions/runner.js:813-820). Servers registered during extension load are read on session_start (runner.js:242-243), so cold spawns with servers keep their MCP tools.
  • Same-shape reuse stays in memory: residentMCPShape blanks URLs before computing the shape (mcp_front.go:41-51), so per-Run port changes take the front.Bind branch, not attach. This backs the PR's critical-path claim.
  • Prestart session matching: resolver.go:286-289 sets CreateProviderSessionID for Pi while the session is unmaterialized. piMismatch (pi_resident.go:496-503) requires the same id in the same create or resume mode, and the transcript check is skipped only for an adopted, created prestart (pi_runtime.go:643-645). prestartCreated is cleared after adoption.
  • An empty MCP prepare is eligible: mcpNamespace(nil) returns {"mcpServers":{}} (child_env.go:112-116).
  • Attach failure releases resources: the new front is closed on error (pi_prestart.go:289-293), the process is retired, and the previous front is closed only after a successful sync.
  • Agent Service gating: Pi stays excluded for accepted_input (remote-codex-provider.ts:995) and requires a non-empty sessionId.
  • No CJK in added lines or in the commit message. The commit author is linked (NightRain233).

Unverified: the real-process test go-local-daemon-process.test.ts ("prestarts Pi on presence") needs LINGER_GO_LOCAL_DAEMON_TEST=1 and real Pi. CI does not run it, and I did not run it.

Process notes

  • The branch is 1 commit behind main (d60d1043). main requires up-to-date branches, so rebase before merging.

CI

  • All CI checks that ran passed: computer-go, computer-go-windows, desktop, web, repository-gate, CodeQL.
  • CI does not run check-node-services (it has no ci: lane in scripts/check-plan.mjs), the @linger/computer TS tests, or -race. I ran these locally:
    • vitest run tests/agent/runner-gateway/remote-codex-provider-prepare.test.ts: 17/17 passed.
    • apps/computer vitest run tests/computer-tools.test.ts: 4/4 passed.
    • go test -race -count=1 ./internal/provider/native -run 'TestPiPrestart|TestPiResidentAttaches|TestPiUnusedPrestart': passed.
  • A broader -race -run Pi run of the whole package (218s on a loaded host) reported FAIL. Its output was not captured, so I can't name the failing test. The PR's new tests pass under -race in isolation. Rerunning the broad set was beyond the test budget, so this is not attributed to the PR.

Automated review by Claude Code


Automated review of 37a87e1 by Claude Code.

Allow Room-presence provider.prepare to prestart Pi ahead of the first Run and dynamically attach or swap managed MCP servers when a Run adopts a resident Pi process:

- Agent Service (remote-codex-provider.ts): allow pi in presence provider.prepare (kept disabled for accepted_input) and require a non-empty retained sessionId.
- Local Computer Daemon: allow pi in provider.prepare with a 40s prepare timeout covering Pi's 30s RPC startup budget, implement Pi prestart (get_state + thinking clamp + park without prompt), allow adopting an unmaterialized prestarted session before its JSONL transcript exists, and dynamically attach changed MCP sets via /linger-sync-mcp with cold-spawn fallback on failure.
- Managed Pi extension (pi-mcp.mjs): register managed MCP servers through Pi's extension API so /linger-sync-mcp can add, replace, or remove servers in place and report structured verdicts via linger.mcp_sync.
- Tests & Docs: add unit tests across node-services, computer-tools, and Go daemon packages, add a real-process integration test covering real Go Daemon + real Pi + real pi-mcp.mjs across prestart and two Runs with MCP replacement, and update apps/computer/local-daemon/README.md.
@NightRain233
NightRain233 force-pushed the feat/pi-provider-prepare branch from 37a87e1 to eeee81b Compare November 24, 2026 15:38
@NightRain233

Copy link
Copy Markdown
Contributor Author

Addressed both review findings, tightened the tests, and rebased onto latest main:

  • P2 (per-server MCP connection warnings): updated mountManagedMcp in apps/computer/tools/pi-mcp.mjs to fail the sync verdict only on "error" notifications (e.g., MCP failed to load) or thrown exceptions, letting per-server "warning" notifications pass through as on cold start. Updated apps/computer/tests/computer-tools.test.ts to cover both warning pass-through and hard-error failure.
  • P3 (RunSpec.ReviewPermissions): dropped the redundant field from RunSpec, executor.go, and pi_runtime.go.
  • Trimmed diff: deduplicated the Claude/Pi presence-prepare harness in go-local-daemon-process.test.ts and tightened boilerplate across computer-tools.test.ts, pi_prestart_test.go, provider_prepare_join_unix_test.go, and remote-codex-provider-prepare.test.ts (~365 fewer net lines while keeping all unit and real-process coverage intact).
  • Rebased onto origin/main and re-ran check-repository-gate, lint-go-daemon, Go -race and uncached package tests, Windows cross-build, @linger/node-services check, @linger/computer checks, check-computer-release, and both real-process Claude & Pi presence tests.

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Approve (0 P0, 0 P1, 0 P2, 0 P3)

Scope: follow-up review of eeee81b against base main. The previous review was on 37a87e1. The branch was rebased since then (old merge base 94ada676, new merge base f60d6091), so I compared the PR commit across the rebase with git range-diff, and checked the whole merge-base diff again for P0/P1 problems. 1 commit, 19 files. Helper skills loaded: coderbook. ponytail-review and karpathy-guidelines were not loaded; I applied their checklists from the review instructions. The review ran in a separate session.

Previous findings

  • P2 — MCP connection warnings treated as sync failure (apps/computer/tools/pi-mcp.mjs): Resolved. The notify wrapper now records only type === "error" (apps/computer/tools/pi-mcp.mjs:186). Per-server "warning" notices pass through as they do on a cold start. apps/computer/tests/computer-tools.test.ts:265 proves that a warning still gives { ok: true } and that an error gives { ok: false }.
  • P3 — ReviewPermissions field has no effect (runtime.go): Resolved. RunSpec.ReviewPermissions and its uses in executor.go and pi_runtime.go (launchProcess, args) are deleted. The remaining ReviewPermissions identifiers are the existing Claude and Codex policy fields.

Findings

None.

Verified as fine

  • Pi extension-event semantics. I read the Pi 1.2.0 sources the extension pins. registerMcpServer and unregisterMcpServer call applyRuntimeChange, which emits mcp_servers_change through void this.emit(...) (core/extensions/runner.js:244). emit calls the first handler synchronously before its first await (runner.js:813-819). So the wrapped handler has already pushed its promise into pendingChanges by the time registerMcpServer returns, which is the assumption behind awaitChanges' "handler did not run" check (pi-mcp.mjs:212-218). A thrown handler is caught by emit, but the wrapper's rejected promise still fails Promise.all, so sync() reports { ok: false }.
  • What the sync verdict waits for. Pi's mcp_servers_change handler awaits startConnection for each added server and reports load failures as an "error" notify (extensions/mcp/index.js:1078-1110). That is exactly what the wrapper now treats as failure.
  • Cold start with no prestart. Static loadConfig now returns no servers, and the managed servers are registered during extension load (pi-mcp.mjs:207-209). Pi reads registrations made before session_start when the session starts (runner.js:242-243, index.js:971+), and the servers keep exposure: "direct" (pi-mcp.mjs:60). So a cold-spawn first prompt still waits for them as before.
  • Verdict ordering in the Daemon. answerDialog hands the linger.mcp_sync placeholder to syncCh synchronously on the stdout reader (pi_review.go:53-56, deliverMCPSync) before it writes the "ok" response. The command handler awaits that response before it returns, so the prompt reply arrives after the verdict. The non-blocking select in syncMCP (pi_prestart.go) is therefore safe. An unsupported extension is caught by hasCommand, so /linger-sync-mcp is never sent to the model as a user prompt.
  • Attach failure path. Any attach error closes the new front (deferred), records attach_failed, retires the process and returns stale=true for a cold spawn (pi_runtime.go:148-168). mcpFront.Close is nil-safe (mcp_front.go:177-180), so swapping to or from an empty MCP set is safe.
  • Reuse rules. piMismatch keeps a prestart bound to its own session and to the same create or resume mode (pi_resident.go). MCP differences are ignored only when canSyncMCP is set (ManagedMCPExtension != "" && residents enabled, pi_runtime.go:350). Transcript validation is skipped only for an adopted prestartCreated process.
  • Prestart resources. prestart releases the session lock when validation fails. If initialization fails or the process cannot be parked, it retires the process. A repeated prepare returns Parked=false (already ready). The covering test is in pi_prestart_test.go.
  • Agent Service. pi is allowed only for presence prepare (accepted_input stays runtime_unsupported for non-Codex runtimes) and requires a non-empty sessionId (remote-codex-provider.ts:869-920). envelope.schema.json already allows pi, so the contract does not change.
  • Repository rules. No CJK in added lines or in the commit message. No new env vars, no contract or generated changes, and no cross-app imports. apps/computer/local-daemon/README.md documents the new prestart and attach flow.

Process notes

  • The branch is 6 commits behind main, and main requires branches to be up to date, so it needs a rebase before merging.
  • A single commit, with no merge or fixup commits. The commit author is linked to NightRain233.

CI

All reported checks pass: computer-go, computer-go-windows, desktop, web, repository-gate, CodeQL. The other checks were skipped by path filtering. CI does not run @linger/computer TS tests, node-services tests, or the Daemon's Go tests with -race, so I ran these locally:

  • go test -race -count=1 -p 4 -run 'TestPiPrestart|TestPiUnusedPrestart|TestPiResidentAttaches|TestPiResident' ./internal/provider/native/ — ok (62.6s)
  • vitest run tests/computer-tools.test.ts (@linger/computer) — 4/4 passed
  • vitest run tests/agent/runner-gateway/remote-codex-provider-prepare.test.ts (@linger/node-services) — 17/17 passed

I did not run the real-Pi process test (go-local-daemon-process.test.ts, "prestarts Pi on presence"). The PR description says it passed.

Automated review by Claude Code


Automated review of eeee81b by Claude Code.

@NightRain233
NightRain233 added this pull request to the merge queue Nov 25, 2026
Merged via the queue into main with commit 9818be2 Nov 25, 2026
15 checks passed
@NightRain233
NightRain233 deleted the feat/pi-provider-prepare branch November 25, 2026 02:13
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