Repository navigation
feat(computer): prewarm Pi on Room presence with dynamic MCP sync - #661
Conversation
There was a problem hiding this comment.
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)
mountManagedMcptreats every"warning"or"error"notification raised duringmcp_servers_changeas a sync failure. Pi's MCP extension reports a server that fails to connect withreportProblems→ctx.ui.notify("MCP servers need attention: …", "warning")(Pidist/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,
attachwaits for the connection to fail (up topiAttachBudget= 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 loaderrors), 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,
canSyncMCPis true.wiredis then always true for both the prestart and the Run (pi_runtime.go:619,pi_prestart.go:213,launchProcess'spiPrepareEmptyMCP), so--extensionis added either way. With the extension missing, a reviewed Run already fails inpiCheckExtension. With residents disabled, prestart is not eligible, and forrun.start,authorization.ReviewsPermissions()equalsPermissionReviewer != nil. Nothing changes behavior through this field. Drop the field and its three|| spec.ReviewPermissionschecks.
Verified as fine
- The RPC ordering in
syncMCPholds: Pi awaits the extension command handler, including itsctx.ui.inputdialog, before it emits thepromptresponse{disposition:"handled"}(Picore/agent-session.js:1611-1615,modes/rpc/rpc-mode.js:307-309). The verdict is therefore delivered bydeliverMCPSyncbefore the reply, and theselect … defaultinpi_prestart.go:372-383does not race. - The
pendingChangesnon-empty check is sound:McpServerRegistry.register/unregistercalls the change listener synchronously, andExtensionRunner.emitinvokes the first handler before any await (Picore/mcp-servers.js:209-219,core/extensions/runner.js:813-820). Servers registered during extension load are read onsession_start(runner.js:242-243), so cold spawns with servers keep their MCP tools. - Same-shape reuse stays in memory:
residentMCPShapeblanks URLs before computing the shape (mcp_front.go:41-51), so per-Run port changes take thefront.Bindbranch, notattach. This backs the PR's critical-path claim. - Prestart session matching:
resolver.go:286-289setsCreateProviderSessionIDfor 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).prestartCreatedis 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-emptysessionId. - 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).mainrequires 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 noci:lane inscripts/check-plan.mjs), the@linger/computerTS tests, or-race. I ran these locally:vitest run tests/agent/runner-gateway/remote-codex-provider-prepare.test.ts: 17/17 passed.apps/computervitest 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 Pirun 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-racein 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.
37a87e1 to
eeee81b
Compare
|
Addressed both review findings, tightened the tests, and rebased onto latest
|
There was a problem hiding this comment.
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. Thenotifywrapper now records onlytype === "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:265proves that a warning still gives{ ok: true }and that anerrorgives{ ok: false }. - P3 —
ReviewPermissionsfield has no effect (runtime.go): Resolved.RunSpec.ReviewPermissionsand its uses inexecutor.goandpi_runtime.go(launchProcess,args) are deleted. The remainingReviewPermissionsidentifiers 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.
registerMcpServerandunregisterMcpServercallapplyRuntimeChange, which emitsmcp_servers_changethroughvoid this.emit(...)(core/extensions/runner.js:244).emitcalls the first handler synchronously before its firstawait(runner.js:813-819). So the wrapped handler has already pushed its promise intopendingChangesby the timeregisterMcpServerreturns, which is the assumption behindawaitChanges' "handler did not run" check (pi-mcp.mjs:212-218). A thrown handler is caught byemit, but the wrapper's rejected promise still failsPromise.all, sosync()reports{ ok: false }. - What the sync verdict waits for. Pi's
mcp_servers_changehandler awaitsstartConnectionfor 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
loadConfignow returns no servers, and the managed servers are registered during extension load (pi-mcp.mjs:207-209). Pi reads registrations made beforesession_startwhen the session starts (runner.js:242-243,index.js:971+), and the servers keepexposure: "direct"(pi-mcp.mjs:60). So a cold-spawn first prompt still waits for them as before. - Verdict ordering in the Daemon.
answerDialoghands thelinger.mcp_syncplaceholder tosyncChsynchronously 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 thepromptreply arrives after the verdict. The non-blockingselectinsyncMCP(pi_prestart.go) is therefore safe. An unsupported extension is caught byhasCommand, so/linger-sync-mcpis never sent to the model as a user prompt. - Attach failure path. Any
attacherror closes the new front (deferred), recordsattach_failed, retires the process and returnsstale=truefor a cold spawn (pi_runtime.go:148-168).mcpFront.Closeis nil-safe (mcp_front.go:177-180), so swapping to or from an empty MCP set is safe. - Reuse rules.
piMismatchkeeps a prestart bound to its own session and to the same create or resume mode (pi_resident.go). MCP differences are ignored only whencanSyncMCPis set (ManagedMCPExtension != "" && residents enabled,pi_runtime.go:350). Transcript validation is skipped only for an adoptedprestartCreatedprocess. - Prestart resources.
prestartreleases the session lock when validation fails. If initialization fails or the process cannot be parked, it retires the process. A repeated prepare returnsParked=false(already ready). The covering test is inpi_prestart_test.go. - Agent Service.
piis allowed only for presence prepare (accepted_inputstaysruntime_unsupportedfor non-Codex runtimes) and requires a non-emptysessionId(remote-codex-provider.ts:869-920).envelope.schema.jsonalready allowspi, 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.mddocuments the new prestart and attach flow.
Process notes
- The branch is 6 commits behind
main, andmainrequires 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 passedvitest 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.
Summary
Entering a Room previously skipped
provider.preparefor Pi (runtime_unsupportedin Agent Service andnot_eligiblein 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
Agent Service (
apps/node-services)piin Room-presenceprovider.prepareinRemoteRuntimeProvider.#sendProviderPrepare(kept disabled foraccepted_input, matching Claude) and require a non-empty retainedsessionId.remote-codex-provider-prepare.test.tscovering Pi presence prepare,accepted_inputskip, missingsessionIdskip, andantigravityskip.Local Computer Daemon (
apps/computer/local-daemon)piinexecuteProviderPrepareandExecutor.PrepareProvider, with a 40s prepare timeout for Pi (piProviderPrepareTimeout) to cover Pi's 30s RPC startup budget plus Context View and thinking-level setup.piRuntime.prestart(pi_prestart.go): launches Pi with the managed extension (pi-mcp.mjs), empty privatelinger-mcp.json, andmcp__*in--tools; verifiesget_stateand applies clamped thinking levels (applyThinkingLevel); parks the process without sending a prompt.piMismatchandprobeIdleWithTranscriptto match Claude's prestart semantics (AssignSessionIDvsResumeID) and skip.jsonlexistence validation when adopting a newly created, unmaterialized prestart session.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 freshmcpFront, writes the rewrittenlinger-mcp.json, verifiesget_commandsexposeslinger-sync-mcp, runs/linger-sync-mcp, and reads the structured verdict from thelinger.mcp_syncRPC dialog before submitting the Run prompt. Any attachment failure recycles the process (attach_failed) and falls back to a cold spawn.apps/computer/local-daemon/README.mdto document Pi prestart and dynamic MCP attachment.Managed Pi Extension (
apps/computer/tools/pi-mcp.mjs)createMcpExtensionwith an empty staticloadConfigand register managed servers through Pi's extension API (pi.registerMcpServer/pi.unregisterMcpServer) so/linger-sync-mcpcan add, replace, or remove MCP servers in place.mcp_servers_changeusing property descriptors (handling Pi's getter-onlyExtensionContext.ui), await connection/disconnection completion, record structured"warning"/"error"notifications, and report{ ok, error? }vialinger.mcp_sync.Compatibility & Rollout
contracts/runner-gateway/envelope.schema.jsonalready allows"pi"inProviderPrepare.runtime_type, so no contract change is required.provider.prepareforpiand repliesnot_eligiblewithout error.hasCommandchecksget_commandsbefore 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_readyCritical PathmcpFrontin memory).attachrewrites the privatelinger-mcp.jsonand runs local RPCget_commands+/linger-sync-mcpto 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
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 passedpnpm --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/providerandgo test -count=1 ./internal/provider/native— all passedcd apps/computer/local-daemon && GOOS=windows GOARCH=amd64 go build ./...— passedLINGER_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 + realpi-mcp.mjs+ real QuickJS + mock OpenAI & Streamable HTTP MCP servers; verified single Pi process spawned across presence prepare, Run 1mcp__echo__ping+mcp__computer__ui_exec, and Run 2 live MCP swap tomcp__second__greetwith zero recycles)make check-computer-release— passedmake -C apps/teamhub lint-go-daemon && make check-computer-go— passedmake 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 ingo-local-daemon-process.test.tsall passed (the unrelated Codex fake tests ingo-local-daemon-process.test.tscurrently fail onmaindue tocodex-cli 0.100.0 < 0.166.0, tracked by test(teamhub): give the process fixture's Codex a version the Daemon accepts #646)