Repository navigation
chore: sync upstream (agegr/pi-web @ 5d4c0b5) - #20
Merged
Merged
Conversation
Fork refused any running session, but that limit was pi-web's own: pi's AgentSessionRuntime.fork() aborts the run and swaps sessions because the TUI holds one session per process. pi-web's fork never goes through it - it opens a separate SessionManager on the source file and copies the path with createBranchedSession(), so the running AgentSession is untouched. The only reason fork refused a running source was the shutdown that follows it, a leftover from when fork mutated the wrapper in place. fork and fork_branch now refuse only a running `!` shell command. The copy needs finished entries alone, which pi appends synchronously in this process, so the file already holds them. An idle source is still shut down after a fork; a running one keeps its run and stays marked as running in the sidebar. A source whose first assistant message has not landed has no file yet and gets pi's "has not been saved yet" wording instead of an opaque "Entry not found". The fork button and the quoted "ask in new chat" action now stay available during a run, and a failed fork shows a notice instead of only logging. In-session branching stays blocked mid-run, as pi requires: one file has one leaf, and the running agent appends under it. BranchNavigator, however, still switched while running - it loaded the other branch into the view while navigate_tree failed silently on the server, so the live run rendered under the wrong branch. It now renders read-only with a note while the session runs or compacts, and handleLeafChange refuses too. Co-authored-by: Claude Opus 5.5 <[email protected]>
pi 0.99 ships codemode, tool_search and MCP as built-in extensions of the CLI; pi-web loads none of them. ADR 0006 records how pi-web will: load the three factories as builtin entries so -builtin:<name> and replacement work as in the CLI, let a per-wrapper host register MCP servers lazily before each prompt so changes apply on the next message without a reload, manage servers from a Settings section that works without a session, and keep the safety work (environment scrubbing, per-entry approval of project mcp.json, Read-only policy, narrower file references) invisible to users. It also lays out the phased rollout this series starts with P0. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Agent, get_subagent_result and steer_subagent are now registered with exposure "model-only". pi declares and activates them like direct tools, but never lets another tool reach them through ctx.executeTool(), so a codemode script cannot start, collect or steer a subagent. A run started from a script would record the nested call id as its parentToolCallId, which no transcript entry carries, and the chat would lose its link to the child session. An integration test drives a real AgentSession to show the model can still call them while ctx.executeTool() cannot. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…g tool results /api/files?sessionId= reads a file outside the allowed roots when its path appears in the session. Transcript system messages carry every tool schema, and MCP, codemode and third-party extension results relay text a remote party controls, so any path in them became readable. Only pi's coding tools and the subagent tools now authorize paths from their result text. Other results still authorize their details.fullOutputPath and the arguments of the coding-tool calls they made through ctx.executeTool(); context_edit replacements and the codemode store never count. User and assistant messages and the model's own tool call arguments count as before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ronments MCP support needs SDK modules the package does not export: the connection class, the stdio transport, the mcp.json editor and OAuth sign-in. lib/pi-sdk-internals.ts loads them by file URL from the SDK copy pi-web runs, refuses a second copy (PI_PACKAGE_DIR, a realpath mismatch, a different pi-mcp instance), and caches one load per process on globalThis. Contract tests fail on an SDK upgrade that moves them. lib/mcp-transport.ts builds the transport factory: stdio servers start with inheritEnv: false and the environment project bash commands get, so PI_WEB_PASSWORD, PORT, NODE_ENV and NEXT_* never reach them, and an entry that references PI_WEB_PASSWORD is refused. A fixture MCP server checks both end to end. Nothing imports either module yet. Loading them was checked under Turbopack dev and a webpack production build. Co-Authored-By: Claude Opus 5.5 <[email protected]>
withExtensionTools() re-activated every direct or model-only extension tool whenever a preset was applied, ignoring defaultActive: false, so loading codemode and tool_search would have switched both on in every session, and a preset change dropped what an extension or tool_search had activated. resolveActiveToolNames() replaces it: a preset replaces only the coding tools and every other tool that is active, registered and not hidden is carried. Startup carries the SDK's initial loadout (so +codemode from defaultTools survives), set_tools the current set, reload the set pi rebuilt. After navigate_tree, which restores the branch's loadout from its transcript, a normal session applies its pinned selection again, so a Read-only pin no longer brings write and edit back. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… session_shutdown Closing an MCP connection has no upper bound, so a wrapper could sit in session_shutdown indefinitely while still registered and alive. isAlive() now turns false as soon as shutdown() starts, so routes stop sending work to a wrapper about to be disposed. Extensions get PI_WEB_SHUTDOWN_DEADLINE_MS (5 s by default) to handle session_shutdown, after which the wrapper logs once and disposes anyway; the timer is unref'd. A wrapper removes its registry entry only while the entry still points at it, so a late cleanup cannot unregister its replacement. The new variable is documented in the README and pi-web --help. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A codemode script's tool calls emit tool_execution_* events with parentToolCallId, and codemode republishes every call made so far on each start and end. The SSE projection now sends nested starts and ends slim and drops nested updates (testing for nesting before the update rebuild, which lost parentToolCallId), removes result from every tool_execution_end (the browser reads only its ids; bash could carry 1 MiB), omits entry_appended, and keeps the newest 200 codemode calls. The stream coalesces tool_execution_update per toolCallId (latest wins within 150 ms) and discards a pending update before forwarding that call's end. The wrapper no longer replays nested ids on reconnect, and the client keeps nested events out of its running-tools phase. Co-Authored-By: Claude Opus 5.5 <[email protected]>
useAgentSession held one extension dialog and one custom panel. Two concurrent requests (tools running in parallel, each gated by a permission extension) overwrote each other, and the hidden one never got an answer, hanging the run until Stop. Both are now FIFO queues keyed by request id: the head is shown with a "+N more" label, an answer, cancel or extension_ui_closed removes exactly its id, a reconnect replay does not duplicate an entry, and a custom panel's re-render updates its entry in place. A tool change that rebuilds the wrapper clears both queues, since the old wrapper's close events never arrive. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…and Skills The Plugins and Skills panels now build on shared blocks in components/SettingsUi.tsx (scope tag and switch, add-source panel, detail grid, footer status, trust notice), itemsToSwitch() and lib/display-path.ts, which the MCP section will reuse. OAuthPastePanel is extracted from ModelsConfig. Plugins' hard-coded English moves to i18n (en, zh-CN, zh-TW), and reasons that lived only in a title tooltip, which a touch screen cannot show, are visible text: why the project scope is unavailable, why Reload session needs an open session, and the footer diagnostics. Subagent profile paths in a sibling folder that shares the cwd prefix are no longer shown as ./-other/... Co-Authored-By: Claude Opus 5.5 <[email protected]>
…igation resolveActiveToolNames() still added every extension tool pi activates on registration on each apply, so a direct tool an extension had switched off came back after reload, and navigation overrode a branch's recorded loadout. pi already activates those tools itself, all of them when it builds or reloads a session and each newly registered one later, so the carried set holds them: nothing else is added now. Navigation carries the session's own tools over from the branch it left: codemode, tool_search and pi-web's subagent tools, which the built-in subagent setting turns on for the whole session. Other extension tools follow the target branch's loadout, as in the pi CLI. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Once a closing wrapper reported itself dead, the next request started a replacement on the same session file while the old one was still in session_shutdown. An extension appending there would branch the file away from the replacement, and dispose() releases provider resources such as a Codex websocket by session id, which the replacement shares. startRpcSession() now waits for the closing wrapper to dispose, at most the shutdown deadline plus a second, sharing the wait through the start lock. setRpcSessionTools() waits for that or for a start already under way, then applies the selection to the wrapper it left, instead of writing through a second SessionManager and reporting success for a start that came up without it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eam was down A close event sent while a tab's SSE was down never arrives, so the queued request stayed at the head and hid every later one; a stale custom panel could not be dismissed at all. The connected event now lists the extension UI request ids the session still holds, which it replays right after, and the client keeps only those in both queues, preserving the surviving entries so typed input survives a reconnect. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… sessions The pi CLI prepends these from a module the SDK does not export, so Pi Web sessions loaded none of them and "defaultTools": ["+codemode"] did nothing. Normal sessions now add the SDK's exported factories under the CLI's names as replaceable built-ins, so -builtin:<name>, project overrides and replacement by a third-party extension behave as in the CLI. Chat-only and subagent sessions still load none of them. The MCP extension gets a loadConfig that returns no servers, keeping only the file's autoEnableCodemode: it connects nothing from mcp.json on session_start, so its startup wait, which ignores Stop, never arms. Pi Web will register the servers a session connects itself (ADR 0006). Servers it is given connect through the environment-scrubbing transport, and /mcp login opens no browser on the server host. MCP stays off when PI_WEB_DISABLE_MCP is set or the SDK internals adapter cannot load. Code mode is offered only after a once-per-process self-test has run a script through the SDK's own sandbox, whose QuickJS worker and wasm are resolved from the SDK's files at run time; a tool that fails every call is worse than none. A built-in that cannot run keeps its builtin:<name> entry with an empty factory. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…made A codemode card showed its input as JSON, with the script escaped into one string, and its result began with the "Script completed / Wall time / Output:" header. While a script ran, the card stayed empty and the status line said only "Running codemode", because its progress snapshots carry calls but no text. The card now shows the script highlighted as JavaScript, the calls it made as rows inside the card (status, arguments, duration, error, model cost and total), and the output without the header. Collapsed, it shows the script's first meaningful line and the call count. The newest 20 calls are listed and earlier ones fold behind a button; a progress snapshot's omitted calls are counted. Running snapshots go to activeToolResults like shell output, so calls appear as they run, and the status line names the newest running call. Streamed input and a third-party "codemode" tool without a code argument keep the generic view. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Code mode offers Automatic or Always on (ADR 0006). Automatic writes
nothing: codemode registers inactive and the MCP extension activates it
when a codemode-exposure server connects. Always on adds +codemode to the
global defaultTools, so new sessions start with it active.
/api/tools/settings stays the only writer of that key. GET reports the
choice on every platform, and PUT takes either { enabled } for the
PowerShell switch, still Windows-only, or { codemode }. The edit drops only
the entries naming codemode and appends +codemode, which works on plain
and modifier-only lists alike; a modifier-only list left empty is removed,
since defaultTools: [] means no tools rather than pi's defaults.
Both switches now share lib/global-settings-file.ts, a locked
read-modify-write that takes the lock pi's SettingsManager takes on the
same file. The route reads the two values one after the other: run
together, the second reader found the lock held and backed off for a
second.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A Read-only session pins coding tools that cannot change anything, but MCP tools stay callable beside them, directly or from a codemode script. A tool_call policy now blocks every MCP tool whose server does not mark it readOnlyHint: true while the session's pinned selection is read-only: it names tools and none of bash, powershell, edit or write. No pin follows pi's configured tools and is not read-only. MCP tools are those the MCP extension registers, and any tool named mcp__ by another MCP extension. A codemode script's calls pass through tool_call too, so they are blocked the same way. The pin is read from the session entries, which set_tools writes before applying it and cannot change mid-run. The hint is the server's own, so the policy guards against model mistakes, not against a malicious server (ADR 0006). The MCP test fixture gains a record tool without annotations, so the blocked path can be tested without starting processes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The MCP extension connects nothing from mcp.json on its own. A host beside it now reads the global and project mcp.json and hands the servers a session should connect to the extension with pi.registerMcpServer() (ADR 0006): - Nothing connects until a prompt starts a run. Before it, the wrapper asks the host to sync: entries whose canonical JSON changed are unregistered and registered again, so an edit made anywhere reaches every open session on its next message. The prompt then waits up to 10 s for servers still connecting; one that outlasts a full wait is not waited for again. - The wait runs in the wrapper before AgentSession.prompt(), because before_agent_start runs before a run has an abort signal. Stop ends it and rejects the message unsent, which returns it to the composer. - The extension reports no connection state, so the host watches the transports it opens through pi-web's factory, without wrapping them: ready once every tool and resource list is answered, failed when the transport closes first or cannot be built. - A server is unregistered only once its transport exists. The extension assigns the connection it closes only after loading the MCP runtime, so unregistering earlier left it nothing to close while it connected the server anyway. - A host idle for PI_WEB_MCP_IDLE_MS (10 minutes) after its last run unregisters its servers; the next prompt registers them again. - The host stays inactive unless /mcp belongs to builtin:mcp, so a replacement MCP extension never receives servers to connect through its own transport. Project entries wait for approval, which nothing grants until the Settings panel lands, and servers with codemode exposure are registered as deferred when the codemode sandbox cannot run. Co-Authored-By: Claude Opus 5.5 <[email protected]>
MCP tools are registered as mcp__<server>__<tool>, sanitized and shortened with a hash past 64 characters, and their cards showed that name. A card now reads server/tool, as pi's TUI labels them, taking the real names from the result's details when it has arrived and parsing the registered name until then; the registered name stays in the tooltip. The calls a codemode script makes and the running-tool status line use the same label. MCP servers often answer with one compacted JSON document as text; such a result is shown indented. Anything else, including JSON surrounded by other text, is shown as sent. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The MCP host stopped its idle timer when a prompt began preparing and started it again only at agent_end. A prompt that registers servers and then starts no run never reaches agent_end: Stop during the wait, a slash command such as /mcp, a preflight that rejects the message. Its servers stayed connected for as long as the session was open, whatever PI_WEB_MCP_IDLE_MS said. The timer now also starts when prepareForPrompt() returns and whenever a sync finishes, so a sync that Stop gave up on and that completes later in the queue still counts. It stays stopped from agent_start to agent_end and while a prompt waits for its servers, so neither a run nor that wait is cut short. Co-Authored-By: Claude Opus 5.5 <[email protected]>
pi registers MCP tools as mcp__<server>__<tool>, sanitized to [A-Za-z0-9_-] and hashed past 64 characters, so the name cannot be split back: docs.v2/search.pages and docs_v2/search_pages register alike, and either part may contain "__". Parsing it showed docs_v2/search_pages for docs.v2's search.pages, split names with "__" in the wrong place, and garbled hashed ones, on running cards, in the status line and in a codemode script's calls, which carry only that name. A card now reads server/tool only from its result's details, where the MCP extension records the real names. Everywhere else the call keeps its registered name, which is also the name a codemode script calls it by. Co-Authored-By: Claude Opus 5.5 <[email protected]>
removeWorktree() matched the caller's path against `git worktree list`, which reports real paths, without resolving links first. A path that runs through a link was refused as "Not a worktree of this repository": on macOS that is any path under os.tmpdir(), since /var is a link to /private/var, so the forced-removal test added in agegr#1007 always failed there. Pi Web's own callers pass paths Git reported and were not affected; findCurrentWorktreePath() already resolved its path this way. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Project .pi/mcp.json entries now follow the project's trust instead of waiting for a per-entry approval that nothing could grant yet. The host already passes ctx.isProjectTrusted() to the SDK's loadMcpConfig, which reads the project file only for a trusted project, so the approval check and the waiting-approval state are removed. Per-entry approval is dropped from ADR 0006 rather than deferred to P2: a trusted project's .pi/extensions run inside the same boundary, earlier and without approval, so gating only MCP entries stopped neither a malicious repository nor inherited trust, and made Pi Web and the CLI disagree about which servers run. P2 keeps the visibility part: the panel and the trust dialog list project servers with the command each would run. A contract test pins the SDK behavior the host now relies on: a project's mcp.json is read only when trusted and replaces global entries by name. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The MCP host decided whether to read a project's .pi/mcp.json from ctx.isProjectTrusted(), the wrapper's SettingsManager flag. That flag is fixed when the wrapper is built and refreshed only on reload, and it is true for a folder that needed no trust at that moment. A .pi/mcp.json that appeared afterwards (git pull, `pi mcp add -l`, the model's write tool) therefore connected on the session's next prompt, stdio command included, without anyone trusting the project. A decision revoked in the CLI did not reach an open session either. The host now asks its mayReadProjectConfig(cwd) option on every sync. The default, mayReadProjectConfigNow() in lib/project-trust.ts, reads the folder's resources and trust.json each time. It is true only while a decision, exact or inherited, trusts a folder that requires trust. It is not getProjectTrustStatus().trusted, which is true for a folder with no trust-requiring resources: loadMcpConfig looks at the folder again when it opens the file, so a file landing between the two looks would be read with no decision. Answering false there loses nothing, because .pi/mcp.json alone makes a folder require trust. createMcpExtensionConfigLoader uses the same read for autoEnableCodemode. The SDK calls loadConfig only on session_start, so that one flag still follows a trust change only at the next reload. The read fails closed. If trust.json cannot be parsed, or is still locked after the store's ~200 ms synchronous wait, the project counts as untrusted and its connected servers are unregistered until a read succeeds. Each distinct error is logged once, with the trust.json path, because the lock error does not name the file. While the project file may not be read, the host records each name it declares with the new not-trusted state, for Settings to show later. Problems are keyed by scope and name, because a project entry may share its name with a connected global one. The names are read after loadMcpConfig, so a file that just landed is reported at once. The file is repository-controlled and nobody has trusted it, so only its mcpServers keys are read: nothing is validated, resolved or run. The path must resolve to a regular file of at most 1 MiB inside the project. It is opened once with O_NOFOLLOW | O_NONBLOCK and checked through fstat, so a link elsewhere, a FIFO or a device is never read. loadMcpConfig's errors[] are now logged once per process each instead of dropped. Tests run on real trust.json and mcp.json files: - A file written after the session started is not read until the project is trusted, even when ctx says trusted, which the unit fixture makes throw. An exact false removes the server, inherited trust connects it, and an exact false beneath a trusted parent does not. - Global servers, including one sharing a name with an untrusted project entry, stay connected throughout. - A file landing between the trust read and the SDK's read is not read. - An unparsable or a locked trust.json fails closed with one warning. - Config errors are logged once. - Names are read only from a regular file inside the project: not through a link elsewhere, a FIFO or an oversized file. - autoEnableCodemode follows the fresh read. - An integration test drives a real AgentSessionWrapper whose SettingsManager reports trusted. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Settings › MCP and the trust dialog need to show what each mcp.json
declares, and for a project that nobody has trusted yet that is exactly
the point: the command an entry would run has to be checkable before
anyone trusts the folder. GET /api/mcp (optional ?cwd=) therefore reads
the files and nothing else. It never builds a transport, resolves a
${VAR}, runs a !command, calls oauthSettings(), or touches
McpOAuthCredentialStore, which creates mcp-auth.json and a lock just to
read it. The signed-in hint is a raw parse of mcp-auth.json, keyed as the
SDK keys it (String(new URL(url))).
lib/mcp-config-read.ts reads the global <agentDir>/mcp.json and the
project <cwd>/.pi/mcp.json separately. loadMcpConfig() cannot serve: it
skips an untrusted project's file and merges by name, hiding the global
entry a project entry replaces. Each file is parsed as the SDK parses it
(no BOM stripped, the same shape check, autoEnableCodemode a boolean), and
each entry checked with the SDK's validateMcpServerConfig(); an invalid
entry is still listed with the SDK's reason. Without the internals,
entries are listed unvalidated and a leading ! still marks a command. A
global entry is shadowedByProject only when the project's entry would
load. The project file is repository-controlled, so its real path (a link
in the file or in .pi/) must stay inside the allowed roots, a dangling
link is refused rather than read as no file, and the resolved path is
opened once with O_NOFOLLOW | O_NONBLOCK and checked through fstat, so a
FIFO is never read and nothing past 1 MiB is parsed. The global file is
the user's: a link is followed wherever it leads.
Nothing literal reaches the browser. Env and header values are sent as
names only; command, args and url go through lib/mcp-secrets.ts, a pure
module the importer will share. Traps found in review:
- Checking only whitespace-free values left a spaced token whole: a full
command line in `command`, `--auth-header "Bearer ghp_…"`, a bare key in
the query string. A value of several words is now masked word by word,
whitespace kept, and Bearer / Basic / Token or a credential `Name:`
makes the next word a secret. Connection strings (`Password=…;`) and
`--auth user:pass` are masked too.
- command, args and url are used as written; the SDK expands nothing
there. Only placeholder-shaped values count as references in them:
${NAME}, or $NAME in environment-variable capitals, which wrappers such
as mcp-remote or sh -c expand. `$Passw0rd` is masked. The fields the SDK
resolves keep its own syntax ($name of any case, $$ and $! escapes).
- V8 quotes up to ten characters on either side of an unexpected token
instead of giving a position, and the old filter missed the form with a
leading ellipsis, so a single-quoted password reached the panel whole.
The message now keeps the token only when it is punctuation and gives
the position that context stood for, in V8's own wording.
configKey, which later statuses compare against, is an HMAC of the
entry's canonical JSON under a random per-process key, never the JSON
itself (every literal value) nor a plain hash (a weak password in an
otherwise visible entry would not survive it).
transport and usesOAuth follow the SDK's transport, which picks HTTP
whenever the key `url` is present. The validator passes
{ type: "stdio", command, url } as stdio, but it connects over HTTP and
runs its header !commands, so it is reported as HTTP. Only an entry the
validator refuses, which never connects, gets the validator's reading.
The response also says whether MCP can run, as a typed reason:
operator-disabled (PI_WEB_DISABLE_MCP), internals-unavailable,
builtin-disabled (with the settings path). readBuiltinExtensionSwitches()
asks the SDK's DefaultPackageManager with only the two `extensions` lists,
so -builtin:mcp and `!builtin:*` patterns resolve as the loader resolves
them and no package is installed or looked up. Code mode reports the
global preference, -builtin:codemode, and peekCodemodeSandbox(): the
settled self-test result, or not-checked, never starting the self-test.
Route refusals are a typed McpRefusalReason (cwd-invalid, cwd-denied,
cwd-not-directory, internal) for the panel to translate.
ProjectTrustStatus gains decision, decisionPath and inherited from
ProjectTrustStore.getEntry(), so exact trust, trust through a parent, an
explicit false and no decision can be told apart, also for a fresh
folder. A folder that requires no trust never failed on a broken
trust.json before, so that failure goes to decisionError instead of
throwing. mayReadProjectConfigNow() and projectTrustReloadOptions() check
for trust-requiring resources first, so neither locks trust.json for a
fresh folder on every prompt. trustProject() builds the status it returns
from what it wrote: reading trust.json back could fail on the lock, and
POST /api/project-trust would then report a saved decision as a 500 and
skip rebuilding the cwd's wrappers.
findWebPasswordReference() is split into findWebPasswordField() and the
exported resolvedConfigValues() walk, which now skips non-string values so
it is safe on unvalidated entries; its messages are unchanged.
canonicalJson() is exported from mcp-host.
Tests pin:
- Both files described with exact shapes and no literal secret in the
output; an untrusted project listed with its command; !command fields
labelled and never run (a touch marker stays absent); PI_WEB_PASSWORD
flagged, an escaped $$ not; no mcp-auth.json or lock created.
- Unparsable, wrong-shape and bad autoEnableCodemode files, BOM included,
each with a message that quotes nothing from the file: long and short
files, single-quoted secrets mid-file and on later lines, exact
positions.
- Shadowing only by a loadable project entry; invalid entries with the
SDK's reason; a url beside type stdio reported as HTTP.
- Project link policy (dangling, outside, allowed sibling root, linked
.pi folder, directory, too large, FIFO); global link followed.
- Masking of URLs (userinfo, named and bare query parts, path tokens),
args, spaced values and whole command lines, connection strings,
placeholders versus $Passw0rd, and literalSecretFields on the same.
- On a trusted merge the per-file reader agrees with loadMcpConfig().
- Trust status exact / inherited / false / none, through a link, and an
unreadable store for a fresh folder; trustProject() succeeds when every
read after the write fails.
- peekCodemodeSandbox() never starts the self-test; the builtin switches
resolve -builtin:mcp, project overrides and patterns from files.
- The route: no cwd, cwd refusals, MCP off with servers still listed,
builtin-disabled, Code mode preference and an unreadable settings file.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ADR 0006 gave up per-entry approval of a project's .pi/mcp.json in
exchange for visibility: trusting the folder connects every entry, in Pi
Web and in the pi CLI, so the trust dialog has to show what that means
before anyone clicks. GET /api/project-trust now returns the trust
status plus mcpFile and mcpServers, read by readProjectMcpServers() the
same file-only way GET /api/mcp reads them: no transport is built, no
${VAR} expanded, no !command run, the OAuth store never opened, and env
and header values reach the browser as names only. replacesGlobal marks
a project entry that replaces the user's global server of its name once
trusted, the counterpart of shadowedByProject.
The dialog fetches that listing each time it opens (no-store, 10 s
timeout, late answers dropped), because the file can change after the
page loaded. Trust stays disabled until it answers, so the list cannot
appear under a click already on its way; a failed or timed-out listing
stops holding it back. Each server shows its transport, its command line
or URL, the working directory, refused entries with the SDK's reason,
entries turned off in the file, the fields holding a !command, and the
host variables it reads. File problems are translated per reason; for
link-outside and too-large the dialog says the servers are not listed
but Pi still loads them once trusted, since the SDK follows links and
has no size cap.
Traps found in review:
- A header such as `Authorization: Bearer ${GITHUB_TOKEN}` or an
oauth.clientSecret of `${AWS_SECRET_ACCESS_KEY}` sends a host variable
to the repository's URL on every connection, and the dialog showed
only the URL. McpServerInfo gains variableReferences: the variables
each resolved field reads, named through the SDK's
getConfigValueEnvVarNames() (or templateVariableNames(), a local port
pinned against it, without internals), never expanded. They resolve
from Pi Web's whole process.env, not the sanitized environment a stdio
server starts from. HTTP entries say "sends ... to this server", stdio
entries "passes ... to the command". A refused entry shows neither
these nor its !command fields, since it never connects.
- Repository text was shown raw with white-space: pre-wrap, so a run of
newlines pushed `curl … | sh` out of view and a U+202E override made
`sj.revres` read as `server.js`. revealHiddenCharacters() turns
controls, format characters (bidi, zero-width, tags), separators,
variation selectors, blank fillers and every space but U+0020 into
\u{XXXX} escapes. It never uses \n, which a Windows path like C:\new
would collide with. An argument holding one is quoted, the entry gets a
warning line, and the CSS collapses white space again.
- The command was shown unquoted on the belief that the SDK hands it to a
shell. It spawns it with cross-spawn and no shell, so
`./tools/lint --check` is one file name. The command is now quoted by
the same rule as the arguments.
- An unreadable trust.json answered 500 before the listing ran. The pi
CLI holds its lock while writing and the store gives up after about
200 ms, so the dialog enabled Trust with nothing listed, and a click
once the lock was gone trusted the folder unseen. The listing no longer
depends on the store: GET answers 500 trust-unreadable with the listing
beside it, and the dialog shows both.
- The PI_WEB_PASSWORD line read as a reassurance ("Pi Web will not
connect it"). The pi CLI shares the decision and does not refuse the
variable, so the line is now a warning that the CLI would send it.
- POST refusals were English sentences the dialog showed in every
locale. Every refusal now carries a reason: request-denied (403) and
content-type (415), checked as the plugins route checks them,
cwd-invalid / cwd-not-directory / cwd-denied, trust-not-required and
session-busy (409), internal (500). AppShell keeps { error, reason }
and the dialog renders mcp.reason.<code>, showing the raw error only
as the diagnostic of an internal or network failure. The fresh status
goes back to AppShell through onStatus, so a folder trusted elsewhere,
or no longer needing trust, says so, offers Close instead of Trust,
and loses its stale restricted-mode banner.
All layout moved from inline styles to .project-trust-* classes in
app/settings.css: only the body scrolls, the trust error and buttons sit
outside it, and the backdrop pads with the safe area, with the iOS
standalone fallback Settings uses. All strings are in en, zh-CN and
zh-TW. The dialog uses trust.mcp.* keys, and the shared mcp.transport.*,
mcp.field.*, mcp.server.*, mcp.fileProblem.* and mcp.reason.* keys are
ready for Settings › MCP to reuse.
Tests pin:
- the route lists an untrusted folder's entries from the file, with
masked args and URL, names only, commandFields, variableReferences and
replacesGlobal. The `!touch` marker never runs, neither a literal nor a
referenced host value reaches the body, and the agent dir gains no
mcp-auth.json or trust write.
- the listing survives an unparsable and a locked trust.json, and every
GET and POST refusal carries its reason code.
- POST checks origin and content type, refuses a folder with nothing to
trust, and trusts the folder on success.
- the reader names variables but runs nothing, and the local parser
agrees with the SDK's on escapes and malformed references.
- the display helpers quote the command, escape newline padding and
U+202E, and leave Windows backslashes alone.
- the dialog renders each server's text, the hidden-character warning,
the PI_WEB_PASSWORD warning, translated POST failures, the
already-trusted / no-longer-required notices without a Trust button,
and the trust-store failure beside the list. Every key it uses exists,
no inline style is left, the CSS collapses white space, and AppShell
keeps the reason and follows onStatus.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Settings › MCP will add a server from whatever the user copied: an
endpoint URL, an install link, a command line, a `pi | claude | codex |
gemini mcp add` line, or another client's JSON. lib/mcp-import.ts turns
that text into pi mcp.json entries, `{ ok: true, servers, notes }` or
`{ ok: false, notes }`, each server `{ name, config, fields, notes,
source, rawPi }` plus originalName and scopeHint. It is pure, so the
browser preview and the server's re-parse of the same text agree; the
server still validates the filled-in entry with the SDK before writing
(S12). Notes are `{ code, params }` from MCP_IMPORT_NOTE_CODES (84 codes,
each with a severity in MCP_IMPORT_NOTE_SEVERITY), never sentences. The
formats live in mcp-import-core/json/cli/links.ts; lib/shell-words.ts
splits a command line without a shell, and lib/jsonc.ts is the
JSON-with-comments reader models-config-store already had, now also
dropping block comments (byte-identical to the SDK's stripJsonComments on
everything pi accepts).
Other clients store literals, but pi resolves `${NAME}`, `$NAME` and a
leading `!command` in env values, header values and oauth.clientSecret.
Literals there are escaped (`$` to `$$`, a leading `!` to `$!`):
unescaped, a pasted `"!curl … | sh"` header would run on the Pi Web host
at every connection. command, args, url and cwd are used raw by the SDK
and are never escaped. `pi mcp add` and the rawPi toggle keep values as
written, and a `!command` is then noted. References (`${env:X}`,
`{env:X}`, `%X%`, Gemini's `$X`) become `${X}` only in those three fields;
pi substitutes nothing elsewhere, so a reference in command, args or url
becomes a field to fill in, except a leading `$HOME`/`${userHome}` (`~`)
and `${workspaceFolder}` (`.`). Every config is built fresh from known
keys and every dropped key is noted: validateMcpServerConfig returns the
object it was given and would accept milliseconds as seconds. Timeouts are
read in the unit of the client that wrote them (Gemini milliseconds, Cline
seconds), and a guessed unit is a warning. URL userinfo moves into a Basic
Authorization header, because pi's fetch refuses a URL with credentials.
`pi mcp add` is a port of the module-private SDK cli.js grammar
(maxPositionals 2, `-l`, an option on the wrong transport refused,
splitting at the first `=`, `--help` anywhere, an empty name refused). The
integration test runs the real runMcpCommand into a temp dir for 34 argv
cases and 5 mixed-quoting command lines and compares the written entry
byte for byte. One leniency: an invalid name is sanitized with a note
instead of refused, since the panel lets the user edit it.
Traps found in review:
- parseMcpImport and fillMcpImportFields never throw, because the server
route re-parses the request body and a throw is a 500. A malformed
percent-escape in URL userinfo (`https://%zz@…`) threw URIError from an
unguarded decodeURIComponent, and `$'\U110000'` threw RangeError from
String.fromCodePoint; bash prints such an escape as text, and so does
shell-words now. An unbounded `…_here` placeholder pattern took
quadratic time on a long `a-a-a-…` paste; its run is bounded.
- Secret classification is lib/mcp-secrets.ts, not a second classifier.
The importer's own one missed `--header "Authorization: Bearer sk-…"`
arguments, userinfo in an argument (`postgresql://admin:pw@db/prod`),
run-together names (PGPASSWORD, NGROK_AUTHTOKEN) and a token in a URL
path, so a project-scope refusal built on it could be bypassed.
findLiteralSecretPaths is literalSecretFields with per-argument paths,
and password fields use the same rules.
- A name pi accepts is kept as written (`_x`, `my--server`, 60
characters): sanitizing valid names broke `pi mcp add` parity. A name
the source chose that mcp.json already holds is kept and noted
(`name-taken` with a suggestedName), so S12 can answer its typed 409
instead of silently adding `name-2`; only derived names avoid
takenNames.
- Quoted and unquoted text is joined before a CLI's grammar reads it:
`'A=$'B` is the one argument `A=$B`, and reading the parts separately
turned that pi reference into a literal.
- Management commands (`pi mcp remove x`, `claude mcp login x`, `pi install
npm:…`) are refused (`cli-not-a-server`): imported as a stdio server,
the Test after Add would run them on the host. `claude mcp serve` and
`codex mcp-server` still import.
- A legacy `/sse` address is refused also when a CLI's transport is
guessed from the URL (claude or gemini without `-t`, codex `--url`); an
explicit http transport and `pi mcp add` keep it.
- github.com serves no MCP endpoint: the registry index and account pages
are explained (`github-page`) like repository pages.
- An example path keeps its `--flag=` or `NAME=` prefix; only the path is
asked for.
- `${userHome}` in a resolved field becomes `${HOME}` with a warning
(`home-variable-translated`): Windows does not set HOME.
- fillMcpImportFields takes `{ reference: "NAME" }` to store `${NAME}`
instead of a literal secret (ADR decision 8), only for fields whose
values pi resolves; a reference is not a secretPath.
lib/mcp-secrets.ts is S2's helper, byte-identical to the file in
26e409e (sha256 4f1b1a95…bb70), so this slice builds and tests on its
own; on feat/mcp-settings-p2 it is the same file.
Tests: jsonc (comments, SDK byte parity), shell-words (quoting, `$'…'`
incl. code points past U+10FFFF, continuations, refusals, Windows paths),
mcp-import (table tests per format with real payloads; SSE and WebSocket
refusals; explained links; base64; escaping and the pi toggle;
references; placeholders and prefixed example paths; names kept, taken
and deduplicated; timeout units; fills with values and references;
literal secrets agreeing with literalSecretFields; management commands;
every prefix of every sample, malformed escapes included, parses and
fills without throwing; a 200 000-character paste in linear time; every
note code written and given a severity), and mcp-import.integration
against the real SDK (`pi mcp add` parity, escape round-trips through
resolveConfigValueOrThrow, configValueEnvVarNames vs
getConfigValueEnvVarNames, the validator port on 38 cases, filled configs
accepted, a foreign `!touch marker` never run, a reference resolved from
the environment).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ransports
Two lifecycle gaps in the MCP host, found in review.
An extension command waited for MCP. The wrapper prepared MCP before
every prompt sent while no run was going: it registered the session's
servers and waited up to 10 s for the ones still connecting. pi runs an
extension command at the very start of prompt() and starts no run for
it, so /ping from another extension, or /mcp reconnect, started servers
and waited for them for nothing, and Stop meanwhile withdrew the
command. mcpPromptPreparation() in lib/mcp-command.ts now reads the
message against the session's extension commands by invocation name,
as pi does (a leading /, the name up to the first space):
- another extension's command skips MCP altogether;
- the built-in /mcp registers the servers without waiting
(prepareForPrompt(signal, { wait: false })). It cannot skip: it looks
its servers up among the registered ones, and the host registers them
only before prompts, so /mcp login docs as a session's first message
would answer "No MCP server named";
- anything else (text, a prompt template, /skill:name) waits as before.
A late connection could start out of reach. unregister() waited at most
5 s for the extension to open the connection it closes. A plain
mcp_servers_change does not move the extension's generation, so a
connection it assigned after that unregister was never closed. In Pi
Web the gap is a few microtasks, since runtime.js, the module the
extension loads before assigning, is imported before any host exists,
but the cap alone guaranteed nothing. The host now counts each
registration it unregistered without a transport (by name and
configKey), and its factory refuses the next transport asked for one
while no live registration claims it: the connection fails and nothing
starts. The wait is the replaceWaitMs option, so a test can run the
timeout path.
Tests: the classification (lib/mcp-command.test.mjs); the refused late
transport, a re-registration of the same content still followed, and
/mcp registering without waiting (lib/mcp-host.test.mjs); and through a
real session, another extension's command returning at once with no
server registered while /mcp registers a server that never answers
without waiting for it (lib/mcp-host.integration.test.mjs). AGENTS.md
and ADR 0006 describe both.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A placeholder inside a longer value read as three lines of reasons, and
"Authorization" did not say whether to type the token or "Bearer" and the
token. The box now shows the paste's placeholder, one line says what is
stored around the value (`Bearer ‹your value›`, or `Bearer ${GH_TOKEN}` once
read from a variable), and an optional field names the header it leaves out.
A plain placeholder needs no reason and no "In the paste" line, and that a
typed secret keeps the server global is said once, under the scope switch.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…xample
The empty paste box offered four examples, one of them Claude's, while the
importer reads nineteen formats: pi, Claude, Codex and Gemini command lines,
`code --add-mcp`, five clients' JSON configs, a registry server.json and four
install links. Each now has an example beside its format's name (the
preview's "Read as" words), under "Supported formats".
`ConfigAddSourcePanel` takes `{ label, value }` examples beside plain ones;
a click puts only the value in the box, and the label stacks above it on a
phone. A test fails when a format has no example, or its example is not read
as that format with nothing to fill in.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Skills, Sub-agents, Plugins and MCP each chose a scope somewhere else, at
another size: under the search box, beside the submit button, or in a
hand-made "Save to" field. Every add pane now puts a ConfigSaveTarget (the
switch and the path that choice writes to) first under its title, where a
detail pane shows its scope tag and path. Skills, Plugins and MCP build
their heading from ConfigAddSourceHeading, so the skills.sh link sits at
the right of the title like pi.dev/packages and github.com/mcp; a new
sub-agent's header shows the switch in place of the tag.
- The path is shown whole and wraps between folders on a phone.
- MCP keeps why Add waits beside Add; Trust and the fresh-folder note
move up with the switch.
- Project plugins install to <project>/.pi/{npm,git}, not .pi/agent/.
- Drop the sentences under the skills search and the MCP paste box.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The name box sat at the very end of the add pane, below the preview and every value to fill in, while the note saying where the name came from sat up with the preview's notes. The name is the server's key in mcp.json and its row in the list, so it now comes right after the paste (and the server picker), with the importer's notes about it (derived, sanitized, deduplicated, taken) under its box. Those notes go once the name is edited, since they would describe a name no longer there. Co-Authored-By: Claude Opus 5.5 <[email protected]>
AGENTS.md had grown to 177 KB, and pi and Claude Code load all of it into every session whatever the task touches. The design notes now live in docs/agents/, one file per area, and AGENTS.md keeps what applies to any change (quick start, architecture, file map, old Safari, session file format) plus an index saying which note to read before changing which files. The move is verbatim: subsection headings go up one level, and the five "see **X**" references that now cross files name the file they point at. AGENTS.md drops to 27 KB. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Prism's `vs` theme puts a 1px #ddd border on <pre>, which `customStyle` never overrode: in light mode every code block drew a second line inside its wrapper's border. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The expanded card showed the script as a highlighted javascript code block, with its own header, copy button and frame inside the card. It now sits in the plain input box other tools use, as text in place of the input JSON; the calls it made are still listed below it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… MCP Re-mirrors the files the upstream sync changed whose demo copies were still byte-identical to the fork's merge base (AgentsConfig, BranchNavigator, useKeyboardShortcuts, agent-event-wire, settings-navigation, i18n), plus the two client-safe modules AgentsConfig now imports (display-path, settings-ui-helpers). Adds the MCP overview to the demo's in-browser mock so a copied Settings › MCP panel finds a route rather than a 404; Test and sign-in are refused with the demo notice, as installs are. The remaining pre-adapted mirrors are deferred to a follow-up PR.
Settings shows why a control is unavailable as visible text, never only a title tooltip, which a touch screen cannot show. The Models panel predated that rule: a models.json provider's switch put its reason (the last enabled models, a project scope, a provider missing from the runtime) into its label and tooltip, and a built-in provider's last-model reason lived only in the Disable all tooltip and the row switch's label. The provider switch now keeps its name and points at a note under the detail header (EnabledModelsProviderSwitchNote) with aria-describedby. A built-in provider's rows and Disable all point at the section's scope and last-model notes the same way. ADR 0004 records the reversal. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every claim in AGENTS.md and docs/agents/*.md was checked against the current code. About forty no longer held and are corrected, among them: how a refreshed page rejoins a running session's events, the compaction Stop button, what a missing tool-selection entry means, the order in which a closing session releases MCP, provider auth going through ModelRuntime, the architecture's createAgentSessionFromServices(), and several File Map routes. ADR 0002 gets a dated update for the tool-selection and exact-prompt changes; ADR 0006 uses the action's current label. The notes are then trimmed to what an editor needs: history, issue labels and test inventories go, rationale the code already comments is dropped, trade-offs an ADR records become a pointer, and the File Map is one line per file. Rationale with no comment yet moves into the code as comments (mcp-host, rpc-manager, worktree, mcp-config-file, AppShell), and three comments that repeated outdated claims are corrected. Notes total 130 KB, down from 185 KB; AGENTS.md, loaded into every session, is 21 KB. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Code mode pane gets a second row for the global codemode.inlineBudget, the estimated tokens the codemode tool's description spends declaring MCP tools (pi's default 3000). One server with many tools fills that budget, so it decides what an MCP server costs on every request. PUT /api/tools/settings takes codemodeInlineBudget (a whole number up to 1 000 000, or null for pi's default) under the settings lock, keeps codemode.mode, and refuses a codemode that is not an object. GET /api/mcp reports the value as sessions read it, a value pi ignores, and a trusted project whose own settings decide it. ADR 0006 is corrected in place: the budget is no longer file-only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
get_tools reported each tool's definition description, but pi's prepareLoadout hooks rewrite the declared ones: codemode's definition holds only its intro, while the model gets the tools scripts can call, their MCP namespaces and types. Report active tools' descriptions from agent.state.tools instead. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A validated server's Tools row is now a dropdown of the five exposures,
from Code mode (the default) to hidden, with one line saying what the
choice costs. It decides how much of a server reaches the model on every
request, from nothing through a name and a count to every tool's schema.
POST /api/mcp takes set-exposure { scope, name, exposure } behind the
switch's guards. setMcpServerExposure() writes the SDK editor's bytes:
codemode removes the key and toolExposure is kept, which GET counts and
the row names. Open sessions apply it at their next message, when the
host registers the changed entry again and the SDK reconnects the
server. GET reports -builtin:tool-search, which leaves deferred tools to
Code mode scripts alone, and the row warns about it.
The server pane's explanatory text is trimmed to one line per row: the
"on" state, the values-hidden note, the Authorization sign-in line and a
closed connection's summary say less.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Settings › MCP's add pane linked github.com/mcp, whose Install buttons cannot be pasted. It now links glama.ai, smithery.ai, mcp.so and the official registry at registry.modelcontextprotocol.io. ConfigAddSourceHeading and ConfigAddSourcePanel take a catalogs list in place of one catalogHref/catalogLabel/catalogIcon; Plugins and Skills pass one entry each. The links wrap together, right-aligned, when the title row is narrow. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…in tools
The Code mode pane gets a Built-in tools row for the global codemode.mode:
Direct ("on", pi's default) keeps read, bash, edit, write and the session's
other active tools declared while Code mode is on; In scripts ("only") leaves
their declarations out of requests and lists them in the codemode
description, within the tool list budget, so the model calls them from
scripts. A preset still bounds them: a direct tool is callable only while
active.
PUT /api/tools/settings takes codemodeMode under the settings lock: "only"
is written as itself, "on" removes the key (and a codemode object it leaves
empty), and a codemode that is not an object is refused. GET /api/mcp
reports the mode as sessions read it, a value that is neither mode, and a
trusted project whose own settings decide it; the row also says that under
Automatic, "only" waits for an MCP server to turn Code mode on. The mode and
the budget share their writer, the project merge check and one read. ADR
0006 is corrected in place: codemode.mode is no longer file-only.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
registry.modelcontextprotocol.io was the longest label by far and wrapped the catalog links on narrower panes. The registry's own name is shorter and, unlike a made-up short host, is not mistaken for an address. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each row of the Code mode pane said "Applies only to sessions started afterwards"; the intro now says it once. The descriptions of Always on, the Built-in tools options, the Automatic note and the tool list budget are cut to one short sentence each; the setting names and fine print stay in ADR 0006 and docs/agents. The pressed option of a scope switch was told apart only by its background; it is now bold too, as the small switch's already was. Every label in the three locales still fits the fixed-width button. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…de's In scripts Under codemode.mode "only", the active direct tools stay active and callable from scripts, but requests leave their declarations out, so the model sees codemode alone. The toolbar's Tools panel listed every active tool and so still showed read, bash, edit and write. get_tools now reports declarationHidden for each tool, from the AgentSession's private _hiddenDeclarations (pi 0.99; nothing hidden when it cannot be read), and the panel lists only active tools whose declarations requests carry. Presets still read active. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Settings › MCP's add pane links github.com/mcp after the MCP Registry, alongside glama.ai, smithery.ai and mcp.so. Its Install buttons still cannot be pasted, but its list is worth browsing. The five links fit on the title row. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Bump @earendil-works/pi-agent-core, pi-ai, pi-coding-agent and pi-tui
from 0.99.1 to 1.0.0 (releases v0.99.2, v1.0.0) and adapt to the
changes that reach pi-web:
- MCP OAuth credentials are keyed by server name and URL
(`mcp__<name>|<url>`), with the old URL-only record taken over by the
first server that reads it. Sign-in flows, sign-out counts and guards,
`signOutMcpServer()` and the Settings signed-in hint follow the new key,
so servers sharing a URL keep separate accounts.
- `codemode-deferred` is now an alias of `codemode`, whose tools are no
longer listed in the codemode description (scripts find them with
searchTools()). Settings drops the option and its strings, reads an
entry holding the alias as `codemode`, and keys statuses by the
validator's copy (`mcpEntryConfigKey()`), as the host keys
`loadMcpConfig()`'s entries.
- The first prompt waits only for servers with `direct` tools; codemode
scripts and tool_search wait for the others. The host's own, abortable
wait follows suit, and the extension gets `startupWaitMs: 0`, since its
wait ignores Stop and now covers servers the host registers.
- `auth: { provider }` sends a pi provider's token instead of OAuth: it
turns OAuth sign-in off, Test passes the provider token, and Settings
shows the provider. Settings and the Test/sign-in routes refuse what
`loadMcpConfig()` now skips: `auth` in a project file, and names that
differ only in `-` and `_`.
- The paste importer ports the validator's new rules, reads
`description` (pi syntax only), `oauth.clientName` and
`oauth.authServerMetadataUrl`, and `pi mcp add --description` /
`--oauth-client-name`; it never imports `auth`.
- Settings › MCP shows a server's `description`.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI on main has failed since e17d2cc in four files that pass locally: - Tests that build a 5,000-level structure called JSON.stringify on it, which recurses once per level and overflows the smaller stack of the Linux runners. The JSON text is now built with String.repeat. - The MCP host's waits and the codemode self-test's limit use unref'd timers, so they never keep a server process alive. Node 22's test runner cancels a test whose only pending work is such a timer ("Promise resolution is still pending but the event loop has already resolved"), and with it every later test of the file. Those files now hold a ref'd interval for their lifetime. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Regular merge of upstream
agegr/pi-webintomain: 73 commits over2bb48f5..6fcd7d4(52 in the first merge @5d4c0b5, 21 in the second @6fcd7d4). Ancestry preserved so the fork's behind-counter resets to 0; no rebase, no squash.Nothing was merged. This PR is for review only; the owner decides.
Highlights
MCP server management in Settings (the bulk of the sync, ADR 0006)
Settings › MCP: lists bothmcp.jsonfiles read-only from the files (no server started, no value resolved), switches/removes servers with a 60 s Undo, and tests one server's connection (POST /api/mcp/test)./api/mcp/sign-in, polled; a pasted redirect address, the loopback callback, refresh-only endings, and a sign-out that bars an in-flight token write).claude/codex/geminiJSON, VS Code, Zed, opencode, registry JSON,pi mcp addCLI); secret refs, host-variable confirmation, and trusting a fresh folder in the same step./api/tools/settings), the read-only policy that blocks MCP tools withoutreadOnlyHint, and a per-session MCP host that connectsmcp.jsonservers before a prompt..pi/mcp.jsonservers before anyone trusts the folder.Other features
server/toolfrom their result's details, with indented JSON results.SettingsUi), localizing Skills and Plugins.lib/mcp-import*.ts,lib/shell-words.ts,lib/jsonc.ts,lib/stacked-dialog.ts,lib/regular-file.ts,lib/key-serializer.ts,lib/display-path.ts,lib/mcp-secrets.ts,lib/pi-sdk-internals.ts.Notable fixes
session_shutdownwithPI_WEB_SHUTDOWN_DEADLINE_MS; wait for a closing wrapper before reopening its session; idle out servers registered for a prompt that starts no run.withExtensionToolsfrom forcing inactive tools on; queue extension dialogs and custom panels by request id; drop extension UI requests the server closed; preserve drafts when selecting history edits; slim nested SSE tool events and coalesce updates.Conflict resolution
12 files conflicted. Upstream authored
components/,lib/,app/,e2e/anddocs/, so those took the upstream side; the conflicts below were re-applied around fork-only work.AGENTS.md### Subagentssection (pi-subagents owns delegation), the fork'ssubagents/*route list, and theBEGIN:nextjs-agent-rulesnote. Bothdocs/adr/0006-*files exist (different subjects).lib/rpc-manager.tsresolveActiveToolNames()(carry-based) and dropped the fork'sACTIVE_ON_REGISTRATION_EXPOSURES/withExtensionToolscopy. Kept the fork's built-in-engine removal: nocreateSubagentController/createSubagentExtension/SUBAGENT_CONTROLLERis reintroduced;readSubagentSessionResources()+SUBAGENT_CONTROL_TOOL_NAMESstay.lib/rpc-manager.test.mjslib/api-types.tsAgentCatalogAgent,SubagentRunInfo) plus upstream'sMcpExposure/McpImportNote.components/MessageView.tsxSubagentToolDetailsfrom@/lib/api-types(the engine that defined it is gone) plus upstream's codemode/MCP display imports.components/AgentsConfig.tsxactiveprop (useAgentsRefresh) and the fork's profile editor; added upstream'strustprop anddisplayPathWithin/shortenPath. Its one conflict-resolution whitespace jam is split in7b965bd.components/AppShell.tsxMcpErrorResponse.components/ChatWindow.tsxonSubagentRunsChange+setExtensionWidgets; took upstream'sonOpenSettingsand the waiting-dialog counters.components/SettingsPanel.tsx/.test.mjsactive={section === "agents"}; took upstream'strust/McpConfig/projectTrustwiring and the trust-reload tests.lib/subagent-extension.ts,.test.mjs,.integration.test.mjsFork-specific files protected
package.json—name@dreadster3/pi-web, version0.0.4, forkhomepage/repository/bugs,publishConfig,bin(upstream would have set@agegr/pi-web). Verified after the merge.package.nix,flake.nix,flake.lock— fork branding and the packaged build, untouched.README*.md,LICENSE— fork URLs/npm scope and the extra copyright line..gitignore— the fork's.playwright-mcp/and.pi/entries..github/workflows/*— unchanged by upstream; left as they are.bin/pi-web.js— the fork's--versionsupport (upstream does not have it);bin/pi-web-options.jsmerged both sides' help text.lib/subagents.ts,lib/subagent-overrides.ts,lib/pi-subagents-catalog.ts,lib/pi-subagents-*.ts,app/api/subagents/{catalog,tools,overrides,eject},components/AgentSessionPanel.tsx,hooks/useAgentsRefresh.ts.Demo parity (first sync; partial, the rest deferred)
The static demo in
demo/mirrors the app's client code. This PR carries the mirrors that were still byte-identical to the fork's merge base and are import-closed within the demo, plus the mock route a copied Settings › MCP panel will need:components/{AgentsConfig,BranchNavigator}.tsx,hooks/useKeyboardShortcuts.ts,lib/{agent-event-wire,settings-navigation}.ts,lib/i18n/messages/{en,zh-CN,zh-TW}.ts.AgentsConfignow imports them:lib/display-path.ts,components/settings-ui-helpers.ts.lib/api-types.tsgained the MCP/trust types the copied panels read;ProjectTrustStatusgaineddecision/decisionPath/inherited.mock/data/mcp.ts+settings-routes.tsanswerGET /api/mcp(overview),enable/disable,set-enabledandremovefrom in-memory state; Test and sign-in are refused with the demo notice, as installs are. No test run starts a real server.Demo parity deferred
The demo's own
SettingsPanel.tsxhas no Settings › MCP section yet, so nothing in the demo currently calls/api/mcp; the mock is there for when that port lands. The pre-adapted mirrors below each need a hand port (perdemo/README.md: copy the file, re-apply the demo edits, search fordemo/@/mock). They are not in this PR:components/SettingsPanel.tsxmcpsection +projectTrustwiring; demo copy is still the fork basecomponents/AppShell.tsxProjectTrustFailure, branch-lock state,openSettingsSection(base-path-saferouter.replacemust survive)components/ChatWindow.tsxonOpenSettings,waitingExtensionDialog*, base-path asset prefixescomponents/ModelsConfig.tsxcomponents/EnabledModelsSection.tsxConfigSwitch'sdescribedByprop andproviderSwitchBlockKeyinenabled-models-helpers.ts, neither in the demo (second sync)components/AgentsConfig.tsx3eb8a9d). Blocked, not just unported: the demo's ownSettingsUi.tsxhas neitherConfigSaveTargetnorConfigAddSourceHeading, so a copy of the fork's file is not import-closed in the democomponents/{PluginsConfig,SkillsConfig,SettingsUi}.tsxconfig-scope-*,config-add-source-*,config-detail-grid,config-footer-status-details,config-noticeCSScomponents/{ProjectTrustDialog,ChatInput,MessageView}.tsxlib/stacked-dialog.ts,lib/mcp-server-display.ts,lib/codemode-view.ts,lib/mcp-tool-display.ts,components/CodemodeToolView.tsxmirrored firsthooks/useAgentSession.tslib/codemode-view.ts,lib/extension-ui-queue.ts,lib/mcp-command.tsapp/{globals,settings}.cssREADME.mdFollow-up plan (separate PR): mirror the shared lib/component dependencies listed above, then port
SettingsPanel+AppShell, then the CSS, then re-run the demo's ownlint/typecheck/build. The siblingfeat/settings-context-tabPR will update the demo mirror files it touches (SettingsPanelmirror,settings.css, i18n) for the new Context tab, so the ports should land after it to avoid double work.Validation
First sync, in this worktree (
node v24.20.0,npm 11.19.0, pi 0.99.1). Superseded by Second-sync validation below.npx tsc --noEmitnpm run lintESLint: No issues found)npm testenv -i); 6 failures in the normal shell — identical to pristineupstream/main, see belowtscover the mirrored files + the mock (explicitpaths/typeRoots)The failing tests reproduce identically on pristine
upstream/main— not merge breakageUpstream's own CI on
mainis red right now (CI run @ 5d4c0b5's parent, and the one before it), so a red test job on this PR is expected and does not indicate a bad merge.Verified side by side on this host (
node v24.20.0, same environment):npm testfails 6 tests on pristineupstream/main(2237/2243) and the identical set on this branch (2328/2334 — the branch adds the fork's tests). The failures fall into two groups:Stack-depth (pass with
--stack-size=8000; the only failures underenv -i), all in upstream-authored files that are byte-identical to upstream:lib/mcp-config-read.test.mjs— "an entry nested deeper than the stack allows is listed with the rest of its file"lib/mcp-config-key.test.mjs— "an entry nested far deeper than the stack allows still gets a key"lib/mcp-host.test.mjs— "an untrusted project's entry nested thousands of levels deep stops neither the global servers nor the other reports"All three use
JSON.stringifyon a 5,000-level nested array, which overflows V8 at the default stack.Environment-sensitive (disappear under
env -i; caused by this shell's inheritedHOME/XDG and pi-agent env such asPI_WEB_IDLE_TIMEOUT_MS=0, not by the merge):lib/skill-lock.test.mjs— "uses the CLI global lock location" (expects~/.agents; this host'sXDG_STATE_HOMEredirects it)lib/rpc-manager-idle-timeout.test.mjs— "defaults to the 10-minute idle timeout when the env var is unset or blank"lib/rpc-manager-shutdown.test.mjs— "idle timer preserves extension-owned session work until it becomes inactive"An earlier revision of this section wrongly attributed only the first group to the host and claimed upstream CI was green — corrected after re-verification against pristine
upstream/mainand upstream's CI logs. Left as they are — not fixed or skipped, so upstream remains byte-identical.Also note: this shell inherits a pi-agent environment (
PI_PACKAGE_DIR,PI_WEB_IDLE_TIMEOUT_MS=0,PI_SUBAGENTS_*), which makes SDK-internals and idle-timeout tests fail for reasons unrelated to the merge. Tests were run with a clean environment (env -i), giving the 2328/2331 above.Second sync (agegr/pi-web @
6fcd7d4)Merge commit
281ce88(parents71f340f+6fcd7d4). The 21 commits the freeze note listed as "next sync", merged in full — the branch now contains all ofupstream/main(rev-list --count HEAD..upstream/main= 0).9f8447adocs(agents): move topic notes out ofAGENTS.mdintodocs/agents/279e228docs(agents): correct outdated notes and trim them to their rulesde91212,c8fc3c0,b183176,3eb8a9d,dba11f4,0b2d4fa,d702bc6,6c599e9,9d5b077,4e1edd8,e851b03mcp/settings add-pane, exposure and Code mode work82e5539,cfcf2a1chat: codemode script box, light-theme code block border8800b5amodels: say why a model switch cannot move in visible text834b6b8,7b3df71tools: show the declarations the model is sente77a4e5chore(deps): upgrade pi to 1.0.0dda61b2test: pass on Node 22 CI runners6fcd7d4Release v0.10.0Conflict resolution (4 files)
AGENTS.md,components/AgentsConfig.tsx,package.json,package-lock.json.AGENTS.md— followed upstream's restructure: upstream's## Topic Notesindex and the newdocs/agents/*.mdfiles land verbatim. Fork-owned content re-rooted into the new structure: the fork'ssubagents/*route list replaces upstream's singlesubagents/settings/route.tsline,lib/subagents.ts/lib/subagent-overrides.ts(+subagent-profile-precedence.ts,pi-subagents-*.ts) replacesubagent-settings.ts,AgentsConfig.tsxkeeps the fork description, and theBEGIN:nextjs-agent-rulesnote stays. The fork's### Subagentssection moved intodocs/agents/subagents.md— upstream's ownsubagent*.ts/app/api/subagents/**home in the new layout — replacing upstream's text there, which documents the built-in engine this fork removed.docs/adr/0003-*and0005-*(the removed engine's ADRs) stay as history.components/AgentsConfig.tsx— upstream moved the new-profile scope picker intoConfigSaveTargetin the detail header. Took that, kept the fork's rewritten profile editor (rawtools/excludeTools/extensionshandling, catalog rows, disable provenance), and dropped the fork's now-duplicate scope toggle in the Basics section.package.json— upstream's dependency set (pi 1.0.0) plus the fork'sname/version/homepage/repository/bugs/publishConfig/bin.package-lock.json— upstream's lockfile this time, since the pi 1.0.0 upgrade changed the dependency tree (the first sync kept the fork's, which had two extraintegrityhashes, but that tree is gone now). Fork identity re-applied on top.Second-sync validation
npx tsc --noEmit(pi 1.0.0 installed)npm run lintnpm test(clean env)tsc --noEmitThe three
JSON.stringify-overflow tests the first sync reported as host-specific failures now pass — upstream fixed them indda61b2, which this sync brings. Failure-count delta vs before: 3 → 0.The pi 1.0.0 upgrade is what the first sync's
tschit: the worktree's install dir is a symlink to the main checkout, which still has pi 0.99.1, so gates were run against an isolated install of this lockfile in/tmp(nothing in the main worktree touched).Round-2 polish
Two follow-up commits on this branch, re-validated on a fresh
npm ciof this branch's lockfile (pi 1.0.0,node v24.20.0,env -i):7b965bdfix(agents): split a jammed line after conflict mergecomponents/AgentsConfig.tsx(MINOR-A1; cosmetic, 2+/1−)e0e1db7chore(demo): re-mirror the i18n messages after the second syncdemo/lib/i18n/messages/{en,zh-CN,zh-TW}.tsonto the committedlib/sources (MINOR-A2; data-only, byte-identical after)npx tsc --noEmitnpx tsc --noEmitnpm test(env -i)npx eslint components/AgentsConfig.tsxDemo parity (this pass)
Re-mirrored (were still byte-identical to the fork's merge base, import-closed):
components/{MermaidBlock,ToolDefinitionsPanel}.tsx,lib/{pi-types,tool-presets}.ts.Newly deferred:
components/EnabledModelsSection.tsx(added to the deferred table above) — upstream's version needsConfigSwitch'sdescribedByprop andproviderSwitchBlockKeyinenabled-models-helpers.ts, both new in this range and neither in the demo. Nothing that was already deferred got ported this pass. Also re-mirrored in the round-2 polish commite0e1db7:lib/i18n/messages/{en,zh-CN,zh-TW}.ts(data-only, byte-identical copies).OBS-A3 (accepted): the four mirrors above ride inside merge commit
281ce88instead of a separate demo commit as the first sync did (71f340f). Deviation noted, not corrected — the content is verified byte-identical.Notes for review
package-lock.jsononly changed its rebranding lines (name/version); upstream's dependency set was unchanged in this window.docs/adr/0006-mcp-and-code-mode.md(upstream) anddocs/adr/0006-delegate-subagents-to-pi-subagents.md(fork) both exist and cover different subjects — the number collision is expected.