Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
docs(adr): rewrite the decision records by hand
vastsad5736010d977
diff --git a/docs/adr/0001-use-electron.md b/docs/adr/0001-use-electron.mdindex dd32fb278..9ce1cf9a2 100644--- a/docs/adr/0001-use-electron.md+++ b/docs/adr/0001-use-electron.md@@ -6,33 +6,19 @@## ContextPI-Desktop needs desktop distribution, local permission control, session UI, and-system integration capabilities. The main candidate options are Electron and-Tauri.+system integration. The candidates were Electron and Tauri.## Decision-Adopt **Electron** as the desktop shell.--## Rationale--1. Close to the technical path of the already-researched ChatGPT Desktop /- WorkBuddy, making it easier to draw on their engineering experience-2. Smoother fit between the Node ecosystem and pi's TypeScript runtime-3. More mature native modules, debugging toolchain, and packaging resources-4. The team's current roadmap clearly prefers Electron+Adopt **Electron**: it continues the researched ChatGPT Desktop / WorkBuddy path,+fits pi's TypeScript runtime in the Node ecosystem, has maturer native modules and+packaging tooling, and matches the roadmap.## Consequences-### Positive-- Fast development speed-- The agent runtime can be placed directly on the main/node side-- Later integration of pty, sqlite, and auto-update is more conventional--### Negative-- Heavier bundle size and memory footprint relative to Tauri-- Requires strict enforcement of the Electron security baseline+Fast development and conventional pty, sqlite, and auto-update integration, at the+cost of a heavier bundle and a strictly enforced security baseline.## Alternatives-- Tauri 2: lighter, but inconsistent with the current roadmap; dropped as the- MVP baseline+- Tauri 2: lighter, but off the current roadmap; dropped as the MVP baseline.diff --git a/docs/adr/0002-use-pi-agent-harness.md b/docs/adr/0002-use-pi-agent-harness.mdindex ddcad0579..240ca66d4 100644--- a/docs/adr/0002-use-pi-agent-harness.md+++ b/docs/adr/0002-use-pi-agent-harness.md@@ -5,42 +5,21 @@## Context-We need an extensible multi-model agent loop, rather than implementing tool-calling, streaming events, and provider adapters from scratch.+The product needs an extensible multi-model agent loop, not an in-house+implementation of tool calling, streaming events, and provider adapters.## Decision-Use the following packages as the kernel:--- `@earendil-works/pi-ai`-- `@earendil-works/pi-agent-core`--Optionally adopt later:--- `@earendil-works/pi-coding-agent`-- `@earendil-works/pi-storage-sqlite-node`--## Rationale--1. Unified LLM provider interface-2. Clear agent event model, well suited to a desktop UI-3. Provides extensibility across the tool calling / session / skills ecosystem-4. Projects such as LiveAgent have already validated it as a viable kernel for- desktop products+Use `@earendil-works/pi-ai` and `@earendil-works/pi-agent-core` as the kernel,+with `@earendil-works/pi-coding-agent` and+`@earendil-works/pi-storage-sqlite-node` optional later.## Consequences-### Positive-- Avoids building an in-house agent framework-- Can keep pace with upstream capability evolution--### Negative-- Requires adapting to pi's events and version constraints (Node >= 22.19)-- Some desktop product requirements must be filled in at the upper layer- ourselves (permission UX, session product model)+- Capability gains arrive with pi, and the desktop layer adapts to its event+ model and Node version floor.## Alternatives-- Build our own agent loop: high cost, no-- Use another coding agent directly as the kernel: inconsistent with the "based- on pi" goal+- Own agent loop or another coding agent as kernel: rejected; both contradict+ building on pi.diff --git a/docs/adr/0003-agent-in-main-process.md b/docs/adr/0003-agent-in-main-process.mdindex a2110f3f4..22272f9f6 100644--- a/docs/adr/0003-agent-in-main-process.md+++ b/docs/adr/0003-agent-in-main-process.md@@ -2,39 +2,19 @@- Status: Superseded in part by ADR 0010 / ADR 0011- Date: 2026-07-25-- Updated: 2026-07-25## Context-The original MVP placed the full agent loop in Electron main process for-simplicity.+An all-in-main agent loop gave no strong systems backend, no isolated native+capability, and no privilege boundary around host work.-1. Prefer a stronger systems backend-2. Keep pi Agent Harness as the model/agent engine-3. Improve long-term isolation and native capability quality+## Decision-## Original Decision--MVP agent loop in Electron main process.--## Revised Direction--Adopt a hybrid model:--- **Rust backend host core** owns desktop host services, tools sandbox, plugin- host boundary, persistence adapters, and privileged operations-- **Node/TypeScript pi runtime** remains the agent loop engine (`pi-ai` +- `pi-agent-core`) and runs as a controlled sidecar/utility process-- **Electron main** becomes a thin orchestrator between renderer IPC and- Rust/Node services+A Rust host core owns host services, the tool sandbox, persistence adapters, and+privileged operations; a Node `pi-ai` + `pi-agent-core` sidecar stays the agent+loop; Electron main is a thin orchestrator between renderer IPC and both.## Consequences-### Positive-- Better native/host capability foundation-- Clearer privilege boundary-- Keeps pi ecosystem leverage--### Negative-- Higher integration complexity than pure Node main-- Requires stable local RPC between Electron/Rust/Node+- Stronger native foundation and privilege boundary; the pi ecosystem stays.+- More integration complexity and a stable local RPC across three processes.diff --git a/docs/adr/0004-no-gateway-in-mvp.md b/docs/adr/0004-no-gateway-in-mvp.mdindex cd561ece1..dfc601750 100644--- a/docs/adr/0004-no-gateway-in-mvp.md+++ b/docs/adr/0004-no-gateway-in-mvp.md@@ -5,31 +5,17 @@## Context-Products such as LiveAgent provide a remote WebUI/Gateway. Whether PI-Desktop-should add remote control capability in the first phase is a trade-off that-needs to be made.+Products such as LiveAgent ship a remote WebUI/Gateway, so the first release had+to decide whether remote control of the local agent belongs in scope.## Decision-The MVP will **not** build a remote Gateway / browser-based remote control.--## Rationale--1. It conflicts in priority with the local-first desktop closed-loop goal-2. A remote link would significantly increase authentication, synchronization,- and security complexity-3. We should first prove that the local agent UX and permission model hold up+The MVP builds no remote Gateway and no browser-based remote control. The+local-first desktop loop and its permission model are proven first; a remote link+would add authentication, synchronization, and security work ahead of that.## Consequences-### Positive-- Scope convergence-- Simpler security model--### Negative-- No browser-based remote control of the local agent in the short term--## Follow-up--If remote capability is to be built, a separate ADR must be added, with its own-dedicated milestone.+- Scope converges and the security model stays simple.+- No browser-based remote control of the local agent in the short term.+- Remote capability needs its own ADR and milestone.diff --git a/docs/adr/0005-user-installable-plugin-system.md b/docs/adr/0005-user-installable-plugin-system.mdindex 899b99d0d..6296f9d19 100644--- a/docs/adr/0005-user-installable-plugin-system.md+++ b/docs/adr/0005-user-installable-plugin-system.md@@ -6,45 +6,18 @@## Context-Built-in features alone are not enough. Users need to install and develop-plugins that extend:--- commands-- panels-- agent tools-- skills+Built-in features are not enough: users must install plugins that extend+commands, panels, agent tools, and skills without the app loading arbitrary+Electron main scripts.## Decision-Adopt a first-party **plugin system**:--- directory-based plugin packages-- `manifest.json` contribution + permission declarations-- command palette integration-- agent tool registration support-- local install / enable / disable / uninstall-- default-deny permissions with explicit grants--## Rationale--1. Enables user customization without forking the app-2. Safer than arbitrary Electron main-script loading-3. Serves both UI extension and agent extension-4. Leaves room for a later marketplace protocol+Adopt a first-party plugin system of directory packages whose `manifest.json`+declares contributions and permissions, with local install, enable, disable,+and uninstall and default-deny permissions with explicit grants.## Consequences-### Positive-- Extensible product surface-- Clear contribution model-- Aligns with skills/tools ecosystems--### Negative-- Extra architecture and security complexity-- Needs management UI, validation, and auditing--## Scope control--- MVP prioritizes local plugin loading, not marketplace-- First contributions: commands / panel / agentTools / skills-- Plugins are isolated and permissioned by default+- Users extend the product without forking it, across UI and agent surfaces.+- The host owns validation, auditing, and a management UI.+- The marketplace stays out of scope for now.diff --git a/docs/adr/0006-plugin-marketplace-postponed.md b/docs/adr/0006-plugin-marketplace-postponed.mdindex 210de291e..57a8258c5 100644--- a/docs/adr/0006-plugin-marketplace-postponed.md+++ b/docs/adr/0006-plugin-marketplace-postponed.md@@ -5,36 +5,20 @@## Context-We need plugin extensibility, and there is a choice between building the-marketplace first or building the local plugin runtime first.+Plugin extensibility is required, but a marketplace without a stable runtime+would only distribute packages that cannot run safely, and local plugins+already satisfy the core customization demand.## Decision-1. First complete the **local plugin system** (loading, permissions, commands,- tools, lifecycle)-2. Treat the **plugin marketplace** as a deferred capability; freeze the- protocol and data model first-3. The first version of the marketplace only does browse / download /- verification / manual update, with no transactions or social features--## Rationale--1. Without a stable runtime, the marketplace would only distribute packages that- cannot run safely-2. Local plugins already satisfy the core "user customization" demand-3. The marketplace involves trust, signing, and a remote supply chain, which are- significantly more complex+Complete the local plugin system first: loading, permissions, commands, tools,+and lifecycle. Keep the marketplace deferred with its protocol and data model+frozen, and let its first version only browse, download, verify, and manually+update packages, since trust, signing, and the remote supply chain are harder+than local execution.## Consequences-### Positive-- The core path is more stable-- Can be validated first with sample plugins and internal distribution--### Negative-- No one-click store experience in the short term--## Follow-up trigger conditions--Once R1/R2 are complete and the plugin API is basically stable, start R4-Marketplace.+- Users get a stable core path instead of a store experience in the short term.+- The plugin contract stays free to change while the marketplace contract is+ frozen text only.diff --git a/docs/adr/0007-plugin-package-format.md b/docs/adr/0007-plugin-package-format.mdindex 09b488920..ffd329f75 100644--- a/docs/adr/0007-plugin-package-format.md+++ b/docs/adr/0007-plugin-package-format.md@@ -5,30 +5,22 @@## Context-We need a plugin package format that is convenient for local sharing and-marketplace download.+Plugins need one distributable package format that is easy to share locally,+download from a marketplace, and verify before installation.## Decision-Adopt `.piplug` as the product-level distribution extension. Its contents are a-zip archive, with a `manifest.json` at the root.--## Rationale--1. Simple to implement, cross-platform-2. Easy to do checksum / signing-3. Developer-friendly (can be unzipped and inspected locally)+`.piplug` is the product-level distribution extension; the payload is a zip+archive with `manifest.json` at the root. The same verification logic covers+packages and loose local directories. Path-safety checks run before installation,+and marketplace packages carry at least a sha256 checksum.## Consequences-### Positive-- Lightweight toolchain-- Can share unified verification logic with local directory packages--### Negative-- Must guard against zip slip and oversized-package attacks+- A lightweight toolchain that developers can unzip and inspect.+- Installation must reject zip-slip paths and oversized archives.-## Constraints+## Alternatives-- Path safety checks must be performed before installation-- Marketplace packages must provide at least sha256+- An opaque single-file bundle: rejected because it is harder to inspect and+ verify before install.diff --git a/docs/adr/0008-plugin-runtime-isolation-target.md b/docs/adr/0008-plugin-runtime-isolation-target.mdindex ee7f7248c..396006a80 100644--- a/docs/adr/0008-plugin-runtime-isolation-target.md+++ b/docs/adr/0008-plugin-runtime-isolation-target.md@@ -5,32 +5,33 @@## Context-Plugin code is untrusted; we must prevent it from dragging down or intruding-into the host.+Plugin code is untrusted. Running it inside the host process would let a plugin+crash or intrude on the host and hand it direct access to host objects and+environment.## Decision-Target architecture: the plugin main runs in a **separate process**-(UtilityProcess/Child Process) and accesses the Host API via RPC.+Each plugin main runs in a separate process (UtilityProcess / child process) and+reaches the Host API only over RPC: every `pi.*` call passes the host API+allowlist and the permission gateway before it reaches a host service. Plugins+receive a minimal environment, contribution points register by descriptor with+the callable half staying in the plugin process, and a dying plugin is+contained — pending calls reject with `PLUGIN_CRASHED`, contributions are+deregistered, and the renderer learns about it through `pluginChanged`.-If MVP progress is constrained, a lighter isolation may be adopted temporarily,-but it must not break:--- The permission gateway-- The API allowlist-- Unified registration of contribution points-- Crash non-fatality--## Rationale--1. Crash isolation-2. Clearer permission proxying-3. Resource limits can be added later+Capability sandboxing (D009), resource limits, and load-time review of declared+manifest permissions remain future work.## Consequences-### Positive-- Better security and stability+- Plugins gain crash isolation and a narrower reachable surface, at higher+ implementation and debugging cost.+- A plugin must go through the RPC API; it holds no host object and no host+ process environment.+- Raw Node access inside the plugin process stays outside permission gating+ until D009 lands.++## Alternatives-### Negative-- Higher implementation and debugging cost+- Run plugin code in the host process: rejected because one plugin failure+ would take the host down with it.diff --git a/docs/adr/0009-english-first-globalization.md b/docs/adr/0009-english-first-globalization.mdindex b237effce..372cc5d5c 100644--- a/docs/adr/0009-english-first-globalization.md+++ b/docs/adr/0009-english-first-globalization.md@@ -5,32 +5,18 @@## Context-PI-Desktop targets global users and open contribution. Chinese-only product-surfaces would block international adoption and plugin ecosystem growth.+PI-Desktop targets global users and open contribution; Chinese-only product+surfaces would block international adoption and plugin growth.## Decision-PI-Desktop is **English-first**:--1. Product UI default language: **English**-2. Specs, ADRs, code comments, commits, issues, plugin docs: **English primary**-3. i18n framework is required from early UI work-4. Additional locales (including Chinese) are optional packs, not the source of- truth--## Localization Rules--- Source strings live in English-- No hard-coded non-English UI copy in core code-- Locale packs use stable message IDs-- Plugin manifests/docs recommended in English; localized fields optional later+The project is English-first. UI source strings, specs, ADRs, comments,+commits, issues, and plugin docs are authored in English, and core code carries+no hard-coded non-English copy. The i18n framework is required from early UI+work; other locales, Chinese included, ship as optional locale packs keyed by+stable message IDs and are never the source of truth.## Consequences-### Positive-- Global-ready baseline-- Easier external contribution-- Cleaner plugin ecosystem language default--### Negative-- Chinese copy becomes a translation layer, not primary authoring format+- External contribution and the plugin ecosystem share one language default.+- Chinese copy becomes a translation layer, not the authoring format.diff --git a/docs/adr/0010-rust-backend-host-core.md b/docs/adr/0010-rust-backend-host-core.mdindex 6ce367cd3..89a2210ea 100644--- a/docs/adr/0010-rust-backend-host-core.md+++ b/docs/adr/0010-rust-backend-host-core.md@@ -5,55 +5,20 @@## Context-PI-Desktop needs a robust local backend for:--- filesystem tools-- process/command execution-- plugin isolation boundary-- secure storage adapters+PI-Desktop needs a local backend for filesystem tools, command execution, plugin+isolation, secure storage, and long-running host services. A TypeScript backend+inside Electron main is workable but weak for systems work and isolation.## Decision-Use **Rust as the backend host core**.--### Responsibility split--| Layer | Tech | Owns |-|---|---|---|-| UI | React + TypeScript | rendering, UX state |-| Electron shell | TypeScript | windows, preload bridge, app lifecycle |-| Host core | **Rust** | tools, permissions gateway, plugin host services, persistence adapters, privileged ops |-| Agent engine | Node/TypeScript (pi) | model providers, agent loop, tool-calling orchestration |--### Communication--```text-Renderer- → Electron preload/main IPC- → Rust host core (local RPC / FFI / sidecar protocol)- ↔ Node pi agent runtime (sidecar)-```--Implementation choice for Electron↔Rust transport may be:--1. Rust sidecar process over stdio/JSON-RPC or protobuf, or-2. native Node/Electron addon bindings--MVP target: **Rust sidecar + local RPC** for clearer isolation.--## Non-goals--- Rewrite pi itself in Rust-- Replace pi agent loop in MVP-- Move UI into Rust+Use **Rust as the backend host core**. Rendering stays in React, windows and+lifecycle stay in Electron main, providers and the agent loop stay with pi in Node,+and Rust owns tools, the permission gateway, plugin host services, persistence+adapters, and privileged operations. The renderer reaches Rust through IPC plus a+local RPC or FFI; the MVP uses a Rust sidecar over local RPC for the clearest+isolation. Rewriting pi or the UI in Rust is out of scope.## Consequences-### Positive-- Strong systems backend-- Better isolation and performance headroom-- Cleaner security boundary for tools/plugins--### Negative-- More moving parts than pure TS main-- Requires packaging Rust binary with Electron app+- Tools and plugins get a real security boundary instead of Electron main.+- A second binary must be built and shipped.diff --git a/docs/adr/0011-host-rpc-and-storage-defaults.md b/docs/adr/0011-host-rpc-and-storage-defaults.mdindex 23ddc44cb..1070bba30 100644--- a/docs/adr/0011-host-rpc-and-storage-defaults.md+++ b/docs/adr/0011-host-rpc-and-storage-defaults.md@@ -3,48 +3,24 @@- Status: Accepted; mode-profile clause superseded in part by ADR 0053;permission-timeout clause amended by ADR 0310- Date: 2026-07-25+- Related: `docs/spec/03-runtime/06-host-rpc-protocol.md`## Context-After baseline 0.3.0, implementation still depended on several high-impact-defaults:--- Electron ↔ Rust transport-- SQLite ownership-- default interaction mode-- former restricted-profile tool split (superseded by ADR 0053)+Several high-impact defaults — the Electron↔Rust transport, SQLite ownership, the+default interaction mode, and how permission approvals end — were still open after+baseline 0.3.0, and each one fixes process and data ownership.## Decision-Freeze the following defaults for implementation:--1. Transport = **Rust sidecar + stdio JSON-RPC (NDJSON)**-2. SQLite ownership = **Rust host-core only**-3. Default mode = **Agent**-4. The former restricted profile was read-only; this mode-profile clause is- superseded by ADR 0053, which supersedes the historical operating-state- decision in ADR 0052 and replaces it with the current Plan workflow-5. Local permission approvals have **no automatic deadline**; they remain- pending until an explicit decision, cancellation, or host/process shutdown-6. Session grants = **by toolName**-7. First release platform = **macOS arm64 only**-8. TS schema = **typebox**-9. i18n = **i18next**+Freeze: Rust sidecar over stdio JSON-RPC (NDJSON); SQLite owned by host-core alone;+Agent as the default mode; permission approvals without an automatic deadline;+session grants keyed by toolName; macOS arm64 first; typebox schemas; i18next. The+former restricted (read-only) profile clause is superseded by ADR 0053, which replaces+the operating-state decision of ADR 0052 with the current Plan workflow.## Consequences-### Positive-- M1/M2 can proceed without re-litigating core choices-- Clear process and data ownership-- Explicit host-owned operating-state and permission policy--### Negative-- JSON-RPC text protocol may later need binary upgrade-- Exclusive Rust DB ownership requires mature host RPC coverage early--## Related docs--- `docs/spec/08-meta/decisions-log.md`-- `docs/spec/03-runtime/06-host-rpc-protocol.md`-- `docs/spec/03-runtime/07-process-model.md`-- `docs/spec/04-ux/03-permission-ux.md`+- Process and data ownership stays unambiguous.+- Exclusive Rust database ownership requires host RPC coverage early.+- The text JSON-RPC protocol may later need a binary upgrade.diff --git a/docs/adr/0012-universal-provider-model-coverage.md b/docs/adr/0012-universal-provider-model-coverage.mdindex 9283075eb..e724680fe 100644--- a/docs/adr/0012-universal-provider-model-coverage.md+++ b/docs/adr/0012-universal-provider-model-coverage.md@@ -2,51 +2,32 @@- Status: Accepted- Date: 2026-07-25+- Related: `docs/spec/03-runtime/11-provider-model-system.md`## Context-Product requirement:--> Provider support must cover market vendors/models broadly, not a small fixed set.+Providers must cover market vendors and models broadly rather than a small fixed+set, but maintaining every vendor SDK in-house is unrealistic. pi-ai already+abstracts many providers, and most long-tail vendors expose OpenAI-compatible+APIs.## Decision-1. Use **pi-ai** as the native multi-provider engine-2. Treat **OpenAI-compatible providers** as first-class-3. Ship a **refreshable model catalog** + **user-defined model IDs**-4. Do **not** enforce a closed product allowlist that blocks unknown models-5. Expose major vendors in UI presets, while allowing arbitrary custom endpoints+Use pi-ai as the native multi-provider engine and treat OpenAI-compatible+endpoints as first-class. Ship a refreshable model catalog plus user-defined model+ids, do not enforce a closed allowlist, and show major vendors as UI presets while+allowing arbitrary custom endpoints.## Consequences-### Positive-- Broad market coverage with manageable engineering scope-- Practical path to "support market vendors/models"-- Native quality where pi-ai has integrations-- Easy support for gateways and local model servers-- Universal escape hatch for everything else--### Negative / tradeoffs-- Capability quality differs by vendor-- Catalog/capability metadata may be incomplete (especially for obscure models)- and needs refresh/manual overrides-- OpenAI-compatible quirks still need compatibility flags-- Catalog freshness depends on refresh/bundled snapshots--## Alternatives considered--1. **Tiny fixed vendor list only** (e.g., only 3-4 top vendors)- - Rejected: fails globalization and user expectation-2. **Build and maintain all vendor SDKs ourselves** (e.g., reimplement every- vendor SDK in Rust)- - Rejected: duplicates pi-ai, slows delivery, high maintenance-3. **Only OpenAI-compatible, no native providers**- - Rejected: worse UX/quality for major vendors with native quirks-4. **Hardcoded closed/fixed model allowlist**- - Rejected: models churn weekly; blocks power users--## Follow-up specs--- `docs/spec/03-runtime/11-provider-model-system.md`-- `docs/spec/03-runtime/12-provider-config-schema.md`-- `docs/spec/03-runtime/13-model-catalog-and-selection.md`+- Broad coverage with manageable scope; gateways and local model servers use the+ same path.+- Capability quality varies by vendor, and metadata for obscure models may be+ incomplete or stale.+- Adding a vendor usually needs provider metadata only, not an app change.++## Alternatives++- Fixed list of a few top vendors — rejected: fails the coverage requirement.+- Reimplement every vendor SDK in-house — rejected: duplicates pi-ai and is+ expensive to maintain.diff --git a/docs/adr/0013-compact-settings-directory.md b/docs/adr/0013-compact-settings-directory.mdindex 99855ed68..e51a3988b 100644--- a/docs/adr/0013-compact-settings-directory.md+++ b/docs/adr/0013-compact-settings-directory.md@@ -5,50 +5,32 @@## Context-Baseline 0.4.0 froze the broad Codex-aligned settings rail in D062–D065. That-directory exposed Personal, Integrations, and Coding groups containing-standalone Appearance and Providers destinations plus numerous placeholder rows.+Baseline 0.4.0 froze a broad Codex-aligned settings rail in D062–D065, with+grouped destinations and many placeholder rows. The shipped local-first+workflows need fewer top-level choices, and changing frozen visual-parity+decisions requires an explicit baseline decision rather than a silent rewrite.## DecisionKeep the full-page settings shell, Back to app action, search control, rail-metrics, content cards, and theme behavior from D063/D070.--Replace the broad grouped directory with exactly four destinations in this-order:--1. General-2. Configuration-3. Import sessions-4. About+metrics, content cards, and theme behavior from D063/D070, and replace the+grouped directory with exactly four destinations in this order: General,+Configuration, Import sessions, About. Appearance becomes a card inside General+and Providers a card inside Configuration, neither as a standalone destination,+and no placeholder destinations render. Provider deep links target the+Providers card; plugin management stays on the app shell's Plugins destination.## Consequences-- The settings rail is shorter and contains only implemented, useful- destinations.-- Theme controls remain discoverable under General.-- Provider management remains reachable from model setup flows without consuming- another rail row.-- Plugin management remains reachable from the app shell without duplicating it- in Settings.-- The full-page shell and established light/dark visual metrics do not change.+- The rail only holds implemented destinations, with theme and provider+ management still reachable as cards.+- The shell and its visual metrics are unchanged.+- Specs and E2E assert the four-item order; D090 supersedes the navigation+ portions of D062–D065 and the Account-specific metric in D070.## Alternatives-### Keep the broad Codex directory--Rejected because empty and low-value destinations obscure the implemented local-workflows.--### Remove Appearance or Providers entirely--Rejected because theme selection and provider configuration are required product-capabilities; consolidation preserves them without separate destinations.--## References--- `docs/spec/00-baseline.md`-- `docs/spec/04-ux/01-ui-ia.md`-- `docs/spec/04-ux/06-settings-ia.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `docs/spec/08-meta/decisions-log.md` (D090)+- Keep the broad Codex directory: rejected, empty destinations obscure the+ implemented workflows.+- Drop Appearance or Providers entirely: rejected, both are required product+ capabilities.diff --git a/docs/adr/0014-host-owned-storage-schema-v2.md b/docs/adr/0014-host-owned-storage-schema-v2.mdindex 9f1516581..4d64635d6 100644--- a/docs/adr/0014-host-owned-storage-schema-v2.md+++ b/docs/adr/0014-host-owned-storage-schema-v2.md@@ -2,62 +2,40 @@- Status: Accepted- Date: 2026-07-26+- Related: ADR 0011, D086## Context-The original desktop persistence model split durable state across a limited-SQLite schema and Electron-owned JSON files. Session messages stored a lossy-text projection, project identity was represented as a singleton workspace,-scheduled tasks bypassed the Rust host, and several product surfaces had no-durable model for turns, artifacts, task runs, model metadata, or indexed-search.+Durable state was split between a limited SQLite schema and Electron-owned JSON+files: session messages kept a lossy text projection, project identity was a+singleton workspace, scheduled tasks bypassed the Rust host, and turns,+artifacts, task runs, model metadata, and indexed search had no durable model.+Those boundaries conflict with the host-ownership rule in ADR 0011 and make+protocol behavior depend on which process wrote last.## Decision-Adopt schema v2 in the single host-owned `pi.sqlite` database.--The Rust host is the exclusive writer for:--- namespaced key/value configuration;-- projects and project-scoped sessions;-- canonical transcript blocks and turn lifecycle data;-- model catalog metadata;-- artifacts;-- scheduled tasks and task-run history;-- indexed, prunable audit events.+Adopt schema v2 in the single host-owned `pi.sqlite` database. The Rust host is+the exclusive writer for namespaced configuration, projects and project-scoped+sessions, canonical transcript blocks and turn lifecycle, model catalog metadata,+artifacts, scheduled tasks with run history, and indexed prunable audit events.+Electron reaches that state only through host RPC, and imported scheduled-task+JSON stops being authoritative. Migrations are ordered Rust functions keyed by+`PRAGMA user_version`; the v1-to-v2 step takes a one-shot backup, preserves+recoverable data, and completes transactionally, with idempotent session, project,+and legacy task imports.## Consequences- Durable state has one ownership boundary and one migration mechanism.-- Transcript blocks, turns, usage, artifacts, project grouping, task history,- and search can evolve without renderer-owned persistence.-- A migration failure is surfaced instead of silently opening a partially- upgraded database.-- The backup consumes additional disk space until the user removes it.-- Protocol, storage, migration, and E2E specifications must move together with- future structural changes.+- Transcripts, turns, usage, artifacts, grouping, task history, and search can+ evolve without renderer-owned persistence.+- A migration failure is surfaced instead of opening a partially upgraded+ database, at the cost of backup disk space until the user removes it.## Alternatives-### Extend the v1 tables without rebuilding--Rejected because the v1 message shape is lossy and the split ownership model-would remain.--### Keep scheduled tasks in Electron JSON--Rejected because it violates the host-owned persistence boundary and prevents-atomic task/run lifecycle updates.--### Let the renderer write SQLite directly--Rejected because concurrent writers would couple UI lifecycle to data integrity-and bypass host RPC validation.--## References--- `docs/adr/0011-host-rpc-and-storage-defaults.md`-- `docs/spec/03-runtime/04-data-storage.md`-- `docs/spec/03-runtime/06-host-rpc-protocol.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `docs/spec/08-meta/decisions-log.md` (D086)+- Extend the v1 tables in place: rejected because the v1 message shape stays lossy+ and the split ownership remains.+- Let the renderer write SQLite: rejected because concurrent writers couple UI+ lifecycle to data integrity and bypass host RPC validation.diff --git a/docs/adr/0015-responsive-settings-content.md b/docs/adr/0015-responsive-settings-content.mdindex 02067f333..2f16a3f25 100644--- a/docs/adr/0015-responsive-settings-content.md+++ b/docs/adr/0015-responsive-settings-content.md@@ -5,55 +5,31 @@## Context-D070 established a 720px settings content band from a 1200px-wide Codex gold-capture, and D090 retained those visual metrics while simplifying the settings-directory. That fixed cap leaves increasingly large unused space on wider-windows even though the full-page settings shell and right pane already resize-with the native window.+D070 fixed the settings content band at 720px from a Codex capture and D090 kept+that metric while simplifying the directory. The fixed cap wastes space on wider+windows, although the settings shell and right pane already resize natively.## Decision-The settings content inner container fills 100% of the width available in the-right pane after the 275px rail and pane gutters. CSS flex layout owns resizing;-the renderer does not add window listeners, viewport calculations, or JavaScript-layout state.+The settings content inner container fills 100% of the width left in the right pane+after the fixed navigation rail and pane gutters. CSS flex layout owns the resizing;+the renderer adds no window listeners, viewport math, or JavaScript layout state.-This supersedes only D070's 720px content-band cap and the portion of D090 that-retained that cap. All other D070 and D090 navigation, chrome, spacing, card,-theme, and interaction decisions remain unchanged.+This supersedes only D070's 720px cap and the part of D090 that retained it (D092);+every other D070 and D090 navigation, chrome, spacing, card, theme, and interaction+decision stands.## Consequences-- Settings cards expand and contract immediately as the native window resizes.-- Wide windows no longer reserve an arbitrary empty area to the right of the- content.-- The minimum supported window width continues to preserve the fixed rail and- existing pane gutters without horizontal page scrolling.-- Settings specs and E2E coverage must verify narrow, default, and wide window- sizes.+- Cards follow the native window immediately, so wide windows reserve no empty area+ beside the content.+- The minimum supported window width still fits the rail and gutters without+ horizontal scrolling.## Alternatives-### Keep the 720px maximum--Rejected because it ignores the available native window width and wastes space-on larger displays.--### Calculate width in React--Rejected because the existing flex layout already exposes the correct available-pane width, while JavaScript window listeners add unnecessary state and-synchronization work.--### Use a viewport-width formula--Rejected because manually subtracting the rail and gutters duplicates CSS layout-knowledge and can drift into overflow.--## References--- `docs/spec/00-baseline.md`-- `docs/spec/04-ux/06-settings-ia.md`-- `docs/spec/04-ux/07-ui-design-system.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `docs/spec/08-meta/decisions-log.md` (D092)+- Keep the 720px maximum: it ignores the available width.+- Measure in React: flex layout already exposes the pane width while listeners add+ state to synchronize.+- Use a viewport-width formula: it duplicates CSS layout knowledge and drifts into+ overflow.diff --git a/docs/adr/0016-sidebar-organization-and-multi-project-tabs.md b/docs/adr/0016-sidebar-organization-and-multi-project-tabs.mdindex b8f3f7cff..fb8ad3199 100644--- a/docs/adr/0016-sidebar-organization-and-multi-project-tabs.md+++ b/docs/adr/0016-sidebar-organization-and-multi-project-tabs.md@@ -6,81 +6,57 @@## ContextD088 replaced the mixed Recents list with one current-project group plus-path-less Temporary sessions. That made the workspace boundary visible, but it-also forced every project switch to replace the only project group and removed-basic organization controls.+path-less Temporary sessions, which made the workspace boundary visible but+forced every project switch to replace the only group and removed basic+organization controls. Users working across repositories need several projects+retained at once, collapsible inactive groups, and pin/archive on project and+conversation rows without deleting durable data. The host still exposes exactly+one selected workspace, and enlarging that to a multi-workspace registry would+make background tool execution depend on whichever tab was selected last.## Decision### Retained project tabs-- The renderer retains an ordered set of normalized project paths.-- Opening a project adds its path without closing other tabs.-- Closing a tab removes only its retained sidebar entry.+The renderer keeps an ordered set of normalized project paths, each rendered as+an independently collapsible sidebar group alongside a separate path-less+Temporary group. Opening a project adds a tab without closing others and+activating one calls the existing `project.set`; closing a tab drops only the+sidebar entry and never archives projects or sessions.### Renderer-owned organization metadata-- Project metadata is keyed by normalized full path and contains `pinned`,- `archived`, `collapsed`, and optional manual `order`.-- Conversation metadata is keyed by durable session id and contains `pinned`,- `archived`, and optional manual `order`.-- User-facing sidebar ordering supports `recent`, `created`, `oldest`, and- `name`.-- Archive is non-destructive.-- The presentation record is best-effort renderer local storage.+Project metadata is keyed by normalized full path (`pinned`, `archived`,+`collapsed`, optional manual `order`) and conversation metadata by durable+session id (`pinned`, `archived`, optional `order`), stored as best-effort+renderer local storage with no privileged data. Sort supports `recent`,+`created`, `oldest`, and `name`, with pinned rows first and archive+non-destructive and recoverable through the archived view.### Session workspace isolation-- The project associated with a session is the authority for that session's tool- root.-- Selecting another project or conversation never aborts a running turn.-- Temporary sessions have no project root.+The project persisted on the session is the authority for that session's tool+root: `tools.execute` resolves the workspace from `session.projectPath` /+`project_id`, not from the mutable active tab, so switching projects or+conversations never aborts a running turn and Temporary sessions inherit no+project access.This supersedes D088's one-current-project and no-multi-project-tree-limitations, and restores scoped project/conversation row actions superseded-with D068. D088's exact-path grouping, scoped draft reuse, and Temporary session-boundary remain in force.+limitations and restores the scoped project/conversation row actions superseded+with D068; D088's exact-path grouping, scoped draft reuse, and Temporary session+boundary remain in force. No new renderer IPC channel is required.## Consequences-- The sidebar can show several project groups in one independently scrollable- region while the main pane still shows one destination/transcript.-- Project/session pin, archive, collapse, sort, and open paths survive app- restart when renderer preferences are available.-- Activating a missing or inaccessible retained path reports the existing- workspace error without silently deleting the tab or its sessions.-- Host tool execution must load the session before resolving its workspace.-- The Projects index remains the durable project directory and the recovery path- for closed or archived sidebar tabs.+- Inactive projects, pin, archive, collapse, and sort survive app restart when+ renderer preferences are available; clearing them resets presentation only.+- Tool execution must load the session before resolving its workspace.+- Host-owned projects and sessions stay authoritative, with the Projects index+ still the recovery path for closed or archived tabs.## Alternatives-### Keep exactly one project group--Rejected because it discards the working set on every project switch and makes-parallel session work cumbersome.--### Store archive and pin flags in the host schema--Rejected for this iteration because the flags affect only local presentation.--### Add one host workspace per open tab--Rejected because only tool execution needs a workspace root, and the durable-session already identifies it.--### Open each project in a separate native window--Rejected because it multiplies window/process state and does not solve-conversation organization in the primary workbench.--## References--- `docs/spec/03-runtime/03-tools-and-permissions.md`-- `docs/spec/03-runtime/04-data-storage.md`-- `docs/spec/03-runtime/06-host-rpc-protocol.md`-- `docs/spec/04-ux/01-ui-ia.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/04-ux/09-interaction-patterns.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `docs/spec/08-meta/decisions-log.md` (D093)+- Store pin and archive flags in the host schema: rejected because they affect+ only local presentation.+- Open each project in a separate native window: rejected because it multiplies+ window and process state without solving conversation organization.diff --git a/docs/adr/0017-remove-composer-workspace-context-rail.md b/docs/adr/0017-remove-composer-workspace-context-rail.mdindex 647033579..7d60e85ba 100644--- a/docs/adr/0017-remove-composer-workspace-context-rail.md+++ b/docs/adr/0017-remove-composer-workspace-context-rail.md@@ -5,54 +5,36 @@## Context-D056, D066, D067, and D087 established a composer-attached rail that displayed-the current project, a Local environment label, and best-effort Git branch-metadata. Later visual refinements also assigned dedicated height, spacing,-surface, and elevation rules to that rail.+D056, D066, D067, and D087 attached a rail to the composer showing the current+project, a Local label, and best-effort Git branch metadata. The project entry+duplicated navigation already in the home hero, sidebar, and Projects+destination, and Local and branch were passive: the renderer showed `main` when+detection returned nothing.## Decision-The home and thread-docked composer variants never render project, Local, or-branch context chrome. The composer shell reserves no height, seam, separator,-or elevation for the removed rail.+Neither composer variant renders project, Local, or branch chrome, and the+composer shell reserves no height, seam, separator, or elevation for it.-This decision changes presentation only. Project selection, active-workspace-persistence, session project binding, Git branch detection, Projects metadata,-and workspace-scoped tools remain unchanged and available through their existing-non-composer surfaces.+Presentation only: project selection, active-workspace persistence, session+project binding, Git branch detection, Projects metadata, and workspace-scoped+tools keep working through their existing non-composer surfaces.++This supersedes the workspace-chip and context-rail portions of D052, D055,+D056, D066, D067, and D087; it is D095 in baseline 0.4.4.## Consequences-- The composer is a single prompt surface in every workspace state.-- Project selection no longer has a composer-local shortcut.-- Existing project navigation continues through the home hero, sidebar, and- Projects destination.-- Branch metadata remains visible where Projects uses it, without a misleading+- The composer is one prompt surface in every workspace state and loses its+ composer-local project shortcut.+- Branch metadata stays visible where Projects uses it, without a misleadingcomposer fallback.-- Specs and visual regression scenarios assert the rail's absence.## Alternatives-### Keep the complete rail--Rejected because two of its three values were passive and the project action-duplicated existing navigation.--### Keep only the project action--Rejected because it would preserve a dedicated composer surface for an action-already available in the surrounding shell.--### Hide the rail only in one composer variant--Rejected because inconsistent home and thread layouts would retain extra chrome-and make the prompt surface shift when a transcript starts.--## References--- `docs/spec/00-baseline.md`-- `docs/spec/04-ux/01-ui-ia.md`-- `docs/spec/04-ux/07-ui-design-system.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `docs/spec/08-meta/decisions-log.md` (D095)+- Keep the complete rail: rejected, two values were passive and the project+ action duplicated navigation.+- Keep only the project action: rejected, it preserves composer chrome for an+ action the shell already offers.+- Hide the rail in one variant only: rejected, the layouts would differ and the+ prompt surface would shift when a transcript starts.diff --git a/docs/adr/0018-end-to-end-thinking-mode.md b/docs/adr/0018-end-to-end-thinking-mode.mdindex 030cdc25a..b158992af 100644--- a/docs/adr/0018-end-to-end-thinking-mode.md+++ b/docs/adr/0018-end-to-end-thinking-mode.md@@ -5,17 +5,18 @@## Context-The desktop previously exposed an effort label that lived only in renderer-state. The pi runtime was constructed with reasoning disabled, the selected-level never crossed IPC, and assistant thinking events had no durable or visible-representation.+The desktop once showed an effort label that lived only in renderer state: the pi+runtime ran with reasoning disabled, the level never crossed IPC, and thinking+events had no durable or visible form. Removing that decorative control fixed the+misleading UI but left reasoning-capable models without a selector, although Pi+already exposes reasoning metadata, supported levels, provider-specific request+serialization, and separate thinking stream blocks.## Decision-Thinking mode is a session-scoped runtime configuration with the canonical-levels `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`.--The complete path is:+Thinking mode is session-scoped runtime configuration with the canonical levels+`off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`, carried along one+path:```textmodel capability -> session.thinkingLevel -> renderer/main IPC@@ -23,55 +24,30 @@ model capability -> session.thinkingLevel -> renderer/main IPC-> UiMessage.thinking -> host canonical blocks -> transcript disclosure```-- Model capability is inferred from pi's built-in catalog when the provider has- no explicit override.-- Capability-aware UI/main/sidecar boundaries use the same nearest-supported- clamp.-- The Composer renders the selector only for a reasoning-capable selected- provider/model and persists changes through `session.configure`.-- Thinking text remains separate from answer text in streaming events,- persistence, rendering, and copy actions.-- Host schema v3 adds `sessions.thinking_level`; assistant reasoning is stored- as a canonical `thinking` content block.-- The shared/host protocol version advances to 2 because session and message- wire shapes changed.+- Model capability comes from pi's catalog unless the provider sets an explicit+ override, a provider without reasoning resolves to `off`, the renderer and Main+ apply the capability-aware nearest-supported clamp, and the host validates the+ enum without provider knowledge.+- The Composer renders the selector only for a reasoning-capable model and persists+ through `session.configure`; thinking text stays separate from answer text in+ streaming, persistence, rendering, and copy.+- Host schema v3 adds `sessions.thinking_level` and stores reasoning as a canonical+ `thinking` content block, migrating v2 sessions to `off`; the shared and host+ protocol version advances to 2.++This extends D091 and records D096: a reasoning control is visible only because it+now has an end-to-end runtime implementation.## Consequences-- Reasoning selection survives restart and applies to the next turn in that- session.-- Sparse model capability sets, including models that cannot fully disable- reasoning and boolean-like custom sets such as `["off","high"]`, resolve- consistently across Settings, Composer, main, and sidecar.-- Thinking-only stream updates can open the transcript without creating an empty- answer bubble.-- Search and answer-copy behavior exclude thinking text.-- Older databases migrate additively; older protocol peers fail the normal- version handshake rather than silently dropping the new fields.+- The selection survives restart and applies to the next turn, including sparse+ capability sets such as `["off","high"]`.+- Thinking-only updates open the transcript without an empty answer bubble, and+ search and answer copy exclude thinking text.## Alternatives-### Keep effort in renderer-local storage--Rejected because it cannot affect requests or survive as session truth.--### Put thinking text inside the assistant answer--Rejected because it corrupts answer markdown, copy semantics, search text, and-the distinction pi already provides between reasoning and final output.--### Enable one generic reasoning boolean--Rejected because pi models expose different and sometimes sparse supported-levels; collapsing them loses model capability information.--## References--- `docs/spec/03-runtime/01-ipc-protocol.md`-- `docs/spec/03-runtime/02-agent-runtime.md`-- `docs/spec/03-runtime/04-data-storage.md`-- `docs/spec/03-runtime/06-host-rpc-protocol.md`-- `docs/spec/03-runtime/11-provider-model-system.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `docs/spec/08-meta/decisions-log.md` (D096)+- Renderer-local effort: it cannot affect requests or persist.+- Thinking text inside the answer: it corrupts markdown, copy, search, and pi's+ reasoning/output split.+- One generic reasoning boolean: it discards sparse per-model levels.diff --git a/docs/adr/0019-work-panel-subsystems.md b/docs/adr/0019-work-panel-subsystems.mdindex d3a1f9cc6..5e1c6d69a 100644--- a/docs/adr/0019-work-panel-subsystems.md+++ b/docs/adr/0019-work-panel-subsystems.md@@ -2,53 +2,37 @@- Status: Superseded in part by ADR 0108 and ADR 0170- Date: 2026-07-26-- Deciders: PI-Desktop maintainers-- Related: [01-ui-ia](../spec/04-ux/01-ui-ia.md) ·- [08-component-spec §5](../spec/04-ux/08-component-spec.md) ·- [01-ipc-protocol §13a](../spec/03-runtime/01-ipc-protocol.md) ·- [ADR 0108](0108-remove-built-in-interactive-terminal.md) ·+- Related: [ADR 0108](0108-remove-built-in-interactive-terminal.md) ·[ADR 0170](0170-work-panel-browser-as-bundled-plugin.md)## Context-The work panel was introduced as a docked surface for workspace review, embedded-browser preview, file browsing, and an interactive shell. Each surface needed a-host-owned boundary because the sandboxed renderer could not safely perform-workspace or window operations itself.+The work panel docks workspace review, browser preview, file browsing, and, once,+an interactive shell beside the conversation. The sandboxed renderer cannot do+workspace or window work itself, so each surface needs a host-owned boundary.## Decision-The retained work-panel subsystems are:+1. **Browser.** Bundled plugin `pi.browser` provides Chrome and agent CDP+ (ADR 0170); Electron Main owns the guest `WebContentsView`, navigation and+ popup policy, permission denial, and bounds clamping.+2. **Review.** Review snapshots and guarded rollback open only on explicit user+ action, never from a tool result (D451).+3. **Files.** Project browsing is the bundled `pi.files` plugin over the public+ contributed-view and filesystem APIs.+4. **Transcript resources.** File and URL artifacts stay session-scoped tabs.-1. **Browser.** Chrome and agent CDP ship as bundled plugin `pi.browser` (ADR- 0170).-2. **Review.** Message-owned review snapshots and guarded rollback remain- host-integrated; Review opens only on explicit user action and never from a- tool result (D451).-3. **Files.** Project browsing is supplied by the bundled `pi.files` plugin over- the public contributed-view and filesystem APIs.-4. **Transcript resources.** File and URL artifacts remain session-scoped tabs- opened by the conversation rather than generic launchers.--The former interactive-terminal subsystem is not part of the current product.-Its removal, including the desktop IPC and packaging cleanup, is defined by ADR-0108.+The interactive terminal is gone (ADR 0108); Agent Bash is an independent+non-interactive tool.## Consequences-- The renderer remains sandboxed and native Browser/plugin surfaces continue to- use the existing measured-bounds and visibility rules.-- Review and file artifacts retain conversation ownership, while project- browsing uses the bundled Files plugin.-- Interactive shell access is provided by an external terminal rather than by a- PI-Desktop work-panel tab.+- Native surfaces keep their bounds rules and the renderer stays sandboxed.+- Review and artifacts keep conversation ownership; browsing is a plugin.## Alternatives considered-- Making every panel surface an agent tool was rejected because user-driven- browsing and review would inherit agent permissions, truncation, and audit- semantics.-- Giving bundled plugins private host capabilities was rejected because it would- bypass the public plugin boundary.-- Keeping the former interactive shell was rejected by ADR 0108 to remove its- separate native and lifecycle surface.+- Every surface as an agent tool: rejected; browsing and review would inherit+ agent permissions.+- Private host capabilities for bundled plugins: rejected; it bypasses the public+ plugin boundary.diff --git a/docs/adr/0020-configuration-provider-studio.md b/docs/adr/0020-configuration-provider-studio.mdindex 7c7246231..38408f978 100644--- a/docs/adr/0020-configuration-provider-studio.md+++ b/docs/adr/0020-configuration-provider-studio.md@@ -2,51 +2,31 @@- Status: Accepted- Date: 2026-07-26+- Related: [ADR 0013](0013-compact-settings-directory.md)## Context-The Agent/Configuration tab housed defaults and providers as stacked settings-rows and a dense always-on form. That layout made readiness hard to scan, buried-the default provider, and made multi-provider management feel like a raw CRUD-form rather than a modern desktop control surface.+Agent/Configuration showed defaults and providers as stacked rows and one dense+form, which buried the default provider and felt like a raw CRUD form. Both stay+in that section per ADR 0013, so only presentation and density change.## Decision-Settings → Agent/Configuration is presented as a **provider studio**:--1. A compact Defaults card for the default provider/model pair-2. A vendor-account section with one row per OAuth account, including edit, test- connection, and remove actions-3. A modal OpenAI-compatible add/edit provider composer-4. Card-based provider management with secret badges, thinking presets, test- connection, make default, and delete--Secrets remain write-only after save. No new settings rail destinations are-introduced.+Agent/Configuration becomes a provider studio: a compact Defaults card for the+default provider/model pair, a vendor-account section with one row per OAuth+account offering edit, test connection, and remove, a modal OpenAI-compatible+add/edit composer, and card-based provider management with secret badges,+thinking presets, test connection, make default, and delete. Secrets remain+write-only after save and no new rail destination appears.## Consequences-- Configuration is easier to scan with multiple providers and accounts-- The page keeps one visual hierarchy without a separate summary hero-- Empty and populated states both have clear next actions-- Specs, e2e, and i18n describe the studio presentation-- Future vendor presets can land as composer entry points without changing the- rail IA+- Several providers and accounts stay scannable without a summary hero.+- Empty and populated states both offer a clear next action.+- Vendor presets can later land as composer entries without touching the rail.## Alternatives-### Keep the dense stacked form-Rejected because it optimizes for first entry only and degrades once several-providers exist.--### Split Providers back into a rail destination-Rejected because the compact directory intentionally merged Providers into-Agent/Configuration; this redesign improves the existing section instead of-reopening navigation breadth.--## References--- `docs/spec/04-ux/06-settings-ia.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/08-meta/decisions-log.md` (D107)-- `docs/adr/0013-compact-settings-directory.md`+- Keep the dense stacked form: rejected; it only optimizes for first entry.+- Split Providers into its own rail destination: rejected; ADR 0013 merged it+ into Agent/Configuration on purpose.diff --git a/docs/adr/0021-platform-application-chrome.md b/docs/adr/0021-platform-application-chrome.mdindex c517afbd7..24b30a493 100644--- a/docs/adr/0021-platform-application-chrome.md+++ b/docs/adr/0021-platform-application-chrome.md@@ -2,58 +2,46 @@- Status: Superseded in part by ADR 0025- Date: 2026-07-26+- Related: D010, D118## Context-Electron's default chrome does not satisfy all three desktop conventions used by-PI-Desktop. macOS needs a conventional native application menu and inset traffic-lights. Frameless Windows and Linux windows need visible application menus plus-minimize, maximize/restore, and close controls.+Electron's default chrome fits none of the three desktop conventions PI-Desktop+needs: macOS wants a native application menu and inset traffic lights, while+frameless Windows and Linux windows want visible application menus plus window+controls. Renderer-owned commands such as New Task cannot run in Main directly,+and native editing, zoom, fullscreen, and window operations must not become an+arbitrary privileged command bridge.## Decision1. macOS keeps `hiddenInset` traffic lights and installs a native Electronapplication menu.-2. Windows and Linux use the shared frameless 46px shell with a renderer menubar- and renderer-drawn window controls.-3. Renderer-owned menu commands use the fixed `APP_MENU_COMMANDS` allowlist.-4. The preload exposes only the operating-system identifier and allowlisted IPC- channels required by the chrome.-5. Native commands wait for a renderer-ready acknowledgement before delivery.-6. Windows and Linux packaging remains shell-readiness work.+2. Windows and Linux use the shared frameless shell with a renderer menubar and+ renderer-drawn window controls.+3. Renderer-owned menu commands pass through the fixed `APP_MENU_COMMANDS`+ allowlist; native menu and window operations use separate fixed allowlists.+4. The preload exposes only the OS identifier and the allowlisted IPC channels the+ chrome needs.+5. Native commands wait for a renderer-ready acknowledgement before delivery,+ window creation is single-flight, and closing or reloading resets the+ acknowledgement.+6. Windows and Linux packaging remains shell-readiness work and does not change+ the macOS-arm64 first-release scope in D010.## Consequences-- Each platform receives familiar menus and window controls without exposing- arbitrary Main-process execution.-- A native menu command can recreate the macOS window without racing renderer- subscription setup or creating duplicate windows.-- Windows and Linux require native-runner packaging and visual qualification- before release.-- Custom chrome must preserve keyboard, focus, localization, drag-region, and- maximize-state behavior across renderer reloads.+- Each platform gets familiar menus and window controls without arbitrary+ Main-process execution.+- A native command can recreate the macOS window without racing renderer+ subscription or duplicating windows.+- Windows and Linux need native-runner packaging and visual qualification, and+ custom chrome must keep keyboard, focus, localization, drag-region, and+ maximize state across reloads.## Alternatives-### Keep Electron's default menu and frame everywhere--Rejected because the existing hidden titlebar design would remain incomplete on-Windows and Linux, while macOS would lack product-specific commands.--### Implement every menu action in the renderer--Rejected because native editing and window operations belong to Electron Main-and must remain behind an explicit capability boundary.--### Send commands after a fixed delay--Rejected because renderer subscription timing varies by machine and reload-state.--## References--- `docs/spec/03-runtime/01-ipc-protocol.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/04-ux/09-interaction-patterns.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-067)-- `docs/spec/08-meta/decisions-log.md` (D118)+- Keep Electron's default menu and frame everywhere: rejected because the hidden+ titlebar design would stay incomplete and macOS would lack product commands.+- Send commands after a fixed delay: rejected because subscription timing varies,+ while an acknowledgement is deterministic.diff --git a/docs/adr/0022-application-update-delivery.md b/docs/adr/0022-application-update-delivery.mdindex 1a5cec04a..351372d3c 100644--- a/docs/adr/0022-application-update-delivery.md+++ b/docs/adr/0022-application-update-delivery.md@@ -2,84 +2,59 @@- Status: Accepted (amended by D364 / D603 / D628 / ADR 0197, D450 / ADR 0289; issue #1098)- Date: 2026-07-26-- Deciders: PI-Desktop core-- Related: D120, D126, D364, D603, D628, D010, D450, ADR 0021, ADR 0197, ADR 0289+- Related: D010, D078, D120, D126, D164, D450, D603, D628, ADR 0021, ADR 0197, ADR 0289## Context-PI-Desktop needs a release-update path that preserves the renderer sandbox, does-not expose feed configuration to untrusted UI code, and reflects each platform's-actual installer capabilities. A single automatic-install policy is not-appropriate: unsigned macOS packages cannot provide a qualified in-app upgrade-lane, while Windows NSIS and Linux AppImage support electron-updater's-download-and-install flow.+PI-Desktop needs an update path that preserves the renderer sandbox, keeps feed+configuration out of untrusted UI code, and reflects what each platform's+installer can actually do. A single automatic-install policy cannot cover targets+whose signing and installer guarantees differ.## Decision-1. Electron Main exclusively owns `electron-updater`, the fixed GitHub Releases- feed, update polling, and install lifecycle.-2. Development builds keep updates disabled.-3. The updater always sets `allowPrerelease = false`. electron-updater would- otherwise pin prerelease installs (for example `0.2.0-rc.6`) to the same- custom channel (`rc`) and never offer a newer stable GitHub latest release.-4. Automatic checks run after startup and periodically.-5. Feed manifests and artifact hashes are generated by electron-builder.-6. D126 later lifts D010's macOS-only publication scope and publishes all- platform artifacts and update manifests produced by the release matrix.-7. Dual-locale product "what's new" text (D164) is maintained in- `packages/shared` as EN + zh-CN catalogs.+Electron Main exclusively owns `electron-updater`, the fixed GitHub Releases+feed, polling, and the install lifecycle; renderer IPC exposes only allowlisted+check, state, release-link, and install operations, and no caller can supply a+feed URL. Development builds keep updates disabled. Packaged macOS, Windows NSIS,+and Linux AppImage download and install in-app, while deb/rpm Linux and Windows+ZIP builds (`piDistribution = "zip"`) use notify-and-link so an NSIS installer+cannot replace a no-install run; legacy portable executables stay manual when+`PORTABLE_EXECUTABLE_FILE` is present. The updater always sets+`allowPrerelease = false`, because electron-updater would otherwise pin a+prerelease install to its custom channel and never offer a newer stable release.+Checks run after startup and periodically: automatic failures stay ambient, while+explicit checks surface status and errors through the menu and Settings → Info,+and a downloaded update stays actionable until install or normal shutdown.+Manifests and artifact hashes come from electron-builder, the client ships no+GitHub credential, and it fails closed when the feed or package cannot be+validated. Dual-locale "what's new" text lives in `packages/shared` as EN + zh-CN+catalogs; Main formats notes for the discovered version with the product locale+and attaches them as `UpdateState.releaseNotes`, so the renderer never supplies a+notes URL. D126 lifts D010's macOS-only publication scope, and D450 / ADR 0289+qualifies the signed macOS in-app channel on that same feed.++### Amendments++D450 / ADR 0289 makes official GitHub tag macOS artifacts Developer ID-signed,+notarized, and stapled, so packaged macOS joins the in-app lane; unsigned local+packaging without a certificate stays available (D078). D603 replaces the+Windows self-extracting portable executable with a normal ZIP stamped+`piDistribution = "zip"`. Issue #1098 lets `PI_DESKTOP_UPDATE_CACHE_DIR` relocate+electron-updater's Windows download cache: Main reads the cache subdirectory from+the packaged `app-update.yml`, adopts existing baselines and staged updates from+`%LOCALAPPDATA%`, preserves unknown or already-populated destinations, and+removes the legacy directory only when empty. D628 adds a persisted per-install+`updatePreference` (`automatic` or `manual`) in Host-owned app settings, excluded+from portable configuration sync, plus a persisted banner dismissal that cancels+the download and install-on-quit for that version. D364 keeps the ambient banner+consistent with that stored state.## Consequences-- Update state is process-owned and consistent across the application menu,- Settings, and the ambient banner.-- The sandboxed renderer cannot redirect update traffic or install arbitrary- packages.-- Windows NSIS, Linux AppImage, and packaged macOS can update in-app from- published tag feeds; Linux deb and Windows ZIP users install from the release- page after extracting the archive.-- Prerelease installs graduate to newer stable releases through the same latest- feed; a dedicated RC channel is not active.-- In-app bilingual release highlights ship with the build and follow the product- locale without a second network surface.--## Alternatives--- Renderer-owned updater: rejected because it violates the process and sandbox- boundary.-- Caller-provided feed URLs: rejected because it creates an arbitrary package- installation path.-- Force one delivery mode on every platform: rejected because installer and- signing guarantees differ by target.--## Amendment (D450 / ADR 0289)--Official GitHub tag macOS artifacts are Developer ID-signed, notarized, and-stapled. Packaged macOS therefore uses the same in-app `electron-updater` lane-as Windows NSIS and Linux AppImage.--## Amendment (D603)--The Windows no-install lane now publishes a normal ZIP archive instead of-electron-builder's self-extracting `portable` executable. The release helper-builds NSIS and ZIP separately and stamps the ZIP app metadata with-`piDistribution = "zip"`; the updater uses that marker to keep the ZIP manual-even though ordinary ZIP launches do not set `PORTABLE_EXECUTABLE_FILE`.--## Amendment (issue #1098)--For Windows NSIS installs, `PI_DESKTOP_UPDATE_CACHE_DIR` may set an absolute,-writable base for electron-updater's download cache. Main reads the cache's-subdirectory name from the packaged `app-update.yml`, adopts the installer and-block-map differential baselines plus any staged update from `%LOCALAPPDATA%` on-startup, then removes the legacy cache directory only when empty.--## Amendment (D628)--Settings → Info exposes a persisted per-install `updatePreference` with-`automatic` and `manual` values. Automatic preserves the existing in-app-installer lane.--An update-banner dismissal is also persisted for its available version. In-app-dismissal cancels an active download and disables install-on-quit for that-version.+- Update state is process-owned and identical across the menu, Settings, and the+ banner; the sandboxed renderer cannot redirect traffic or install packages.+- NSIS, AppImage, and packaged macOS update in-app from published tag feeds; deb+ and ZIP users install from the release page after extracting the archive.+- Prerelease installs graduate to stable through the latest feed; rollback,+ staged rollout, and a dedicated RC channel remain operational follow-ups.diff --git a/docs/adr/0023-independent-conversation-session-fork.md b/docs/adr/0023-independent-conversation-session-fork.mdindex ea7b701f9..46f860843 100644--- a/docs/adr/0023-independent-conversation-session-fork.md+++ b/docs/adr/0023-independent-conversation-session-fork.md@@ -6,45 +6,53 @@ Accepted.## Context-PI-Desktop already preserves linear regenerate variants within one conversation.-Users also need a Codex-style command that copies the current conversation so-later prompts and configuration changes can diverge without rewriting the-source.+PI-Desktop already keeps linear regenerate variants inside one conversation, but+users also need a Codex-style command that copies the conversation so later prompts+and configuration changes diverge without rewriting the source. Composing+`session.create` with message replacement in the renderer would expose partial+children, lose canonical transcript blocks, omit per-session execution+configuration, and cross the Rust host's persistence ownership, while protocol v4+would let an older host fail only when the new command runs.## Decision-- Protocol v5 adds required host RPC `session.fork` and renderer IPC+- Protocol v5 adds the required host RPC `session.fork` and renderer IPC`session/fork`.-- The Rust host owns one snapshot operation: by default it copies the source's- complete active canonical transcript into a new session and remaps message and- tool-call identifiers.-- The child inherits project, provider, model, mode, thinking, and permission- mode.-- Referenced existing files under the source session's `scratch/<id>/pasted/`- directory are copied into the child's own input directory.-- No parent/child lineage is stored.-- Assistant response Fork uses the bounded snapshot directly.-- Whole-session fork remains idle-only.-- A handled file or index failure removes the child transcript and copied inputs- and leaves no visible child.+- The Rust host owns one snapshot: it copies the source's complete active canonical+ transcript into a new session and remaps message and tool-call identifiers.+ Optional `throughMessageId` ends the snapshot inclusively there; an unknown+ boundary creates no child and returns `NOT_FOUND`.+- The child inherits project, provider, model, mode, thinking, and permission mode,+ but no turns, regenerate revisions, notifications, artifacts, session grants,+ scratch outputs, pin state, or live runtime state. Files under the source's+ `scratch/<id>/pasted/` directory are copied into the child's own input directory and+ the references rewritten before indexing, so pasted inputs survive source deletion+ without widening scratch access.+- No parent/child lineage is stored: this is an independent copy, not a message tree.+ Response Fork uses the bounded snapshot, and Response Edit builds the same child and+ stores original and edited tails in its linear revision store.+- Whole-session fork stays idle-only. A desktop message-scoped fork may copy a+ completed assistant prefix while a later turn runs (issue #837): under the same host+ lock as append/publication, a non-assistant, streaming/error, or live-turn anchor is+ rejected with `CONFLICT`, which Electron maps to `AGENT_BUSY`, and the renderer+ sends only the anchor id so the parent keeps running.+- A handled file or index failure removes the child and copied inputs; crashes follow+ the transcript store's orphan-file recovery.## Consequences-- Renderer and host binaries from protocol v4 are rejected during startup- instead of failing lazily when Create branch is selected.-- Source and child can evolve, reconfigure, persist, and delete independently.-- Fork storage cost is proportional to the active transcript and its referenced- pasted inputs.-- Message-scoped Fork/Edit storage cost is proportional to the canonical prefix- through the selected response plus any child-only revision payloads.-- Every child has a new session id and first creates/reseeds its own pi runtime;- edited context never reuses cache state built from the source transcript.+- Protocol v4 peers are rejected at startup instead of failing on Create branch.+- Source and child evolve, reconfigure, persist, and delete independently, and each+ child reseeds its own pi runtime instead of reusing source cache state.+- Storage cost tracks the copied transcript, its pasted inputs, and child-only+ revision payloads.+- There is no ancestry UI, merge operation, or message-level branch tree; Edit+ rollback stays a two-entry linear revision family (D109).## Alternatives-- Renderer-owned `create + replaceMessages`: rejected because it is not atomic- across the host-owned transcript and index.-- Persistent parent/child lineage: deferred because the requested workflow only- needs an independent copy and D109 keeps message revision navigation linear.-- Copy regenerate revisions: rejected because revision roots and message- identifiers would require a second branch graph and ambiguous pager history.+- Renderer-owned `create + replaceMessages`: not atomic across the host-owned+ transcript and index.+- Persistent parent/child lineage: deferred, since D109 keeps revisions linear.+- Copy regenerate revisions: it would need a second branch graph and ambiguous pager+ history.diff --git a/docs/adr/0024-composer-commands-and-file-references.md b/docs/adr/0024-composer-commands-and-file-references.mdindex 6c3766d5a..59c02217d 100644--- a/docs/adr/0024-composer-commands-and-file-references.md+++ b/docs/adr/0024-composer-commands-and-file-references.md@@ -3,57 +3,64 @@- Status: Accepted- Date: 2026-07-27- Deciders: PI-Desktop core-- Related: D123, D124, D125, D197, D209, D250, ADR 0019 (work panel subsystems), ADR 0059 (clipboard file paste), ADR 0070 (compact reference display), ADR 0106 (core five builtin commands), D114 (scratch dir), D119 (transcript file store)+- Related: D123, D124, D125, D197, D209, D250, ADR 0019, ADR 0059, ADR 0070, ADR 0106, D114, D119## Context-The composer is a plain textarea today. The command palette (Cmd/Ctrl+Shift+P)-holds app commands, but the chat input itself has no in-place command system and-no way to reference workspace files, and spec 08 §11.7 explicitly scope-cut-both.+The composer is a plain textarea: the command palette holds app commands, but the+chat input has no in-place command system and no way to reference workspace+files, and spec 08 §11.7 scope-cut both. The embedded pi runtime defines both+concepts for its CLI:-- **Prompt templates**: markdown files in `<workspace>/.pi/prompts/` and+- **Prompt templates**: markdown files in `.pi/prompts/` and`~/.pi/agent/prompts/` with `description` / `argument-hint` frontmatter.-- **`@path` references**: literal text in the prompt; the model follows up with- its Read tool.-- pi's built-in slash commands (`/new`, `/model`, …) are client-side behaviors- of its TUI, not runtime features.+ `/name args` expands client-side and is sent as an ordinary user message, so+ the model never sees the slash form.+- **`@path` references**: literal prompt text the model follows up on with its+ Read tool — no inlining, no attachment conversion.++PI-Desktop uses the low-level `Agent` class, so neither is active today, although+the installed package exports the reusable loader and expansion helpers.## Decision-1. **Slash commands come from three sources**, merged into one composer menu: pi- prompt templates (project dir overrides user-global on name conflict), the- builtin command-palette registry (slash aliases defined in- `electron/main/builtin-commands.ts`, executed by the existing renderer-side- switch), and plugin palette commands (executed via `commandPalette/execute`).-2. **Template expansion happens in the Electron main `agent/prompt` handler,- before persistence.** The persisted user message stores `content = expanded- text` plus a new optional `command` field holding the typed invocation- (`/name args`).-3. **`@path` stays a plain-text light reference** exactly like pi CLI at prompt- dispatch.-4. **Workspace file index is served by Electron main**, not agent tools — same- rationale as ADR 0019: user-initiated browsing must not spam permission- prompts or the audit trail.--## Alternatives considered--- **Expand templates in the agent sidecar**: keeps pi imports in one place, but- main persists the user message first, so the sidecar cannot influence what- reseed replays without a second write path.-- **Migrate the runtime to `AgentHarness`** for `promptFromTemplate`: replaces- the whole prompt/loop integration for one feature.-- **Inline referenced file content into the prompt** (pi CLI argument-mode- behavior): inflates context, needs truncation rules and an attachment channel- for binaries.-- **Reuse `fs/list` recursively from the renderer**: one IPC round-trip per- directory level makes fuzzy search sluggish and chatty.+1. **Slash commands come from three merged sources**: pi prompt templates+ (project directory overrides user-global on a name conflict), the builtin+ command-palette registry holding the five core commands (ADR 0106), and plugin+ palette commands executed via `commandPalette/execute`. Unknown `/foo` is sent+ as literal text, matching the pi CLI.+2. **Template expansion happens in the Electron main `agent/prompt` handler+ before persistence.** The persisted user message stores `content` (expanded)+ plus an optional `command` field with the typed invocation, so agent reseed+ replays identical model context and the transcript renders a compact chip.+3. **`@path` stays a plain-text light reference** at dispatch. Fuzzy autocomplete+ inserts `@dir/` when a directory is accepted, and completed files become+ renderer-owned compact references (ADR 0070) that serialize to+ `@relative/path ` (quoted when the path contains spaces); Plan and Agent both+ carry Read/Glob/Grep. Nothing is inlined, and clipboard files or images+ arrive as session-scratch references (ADR 0059) instead of pi-ai+ `ImageContent`.+4. **Electron main serves the workspace file index**, not agent tools, so+ user-initiated browsing raises no permission prompts or audit entries (ADR+ 0019). Read-only `pi-desktop/fs/index` returns up to 8000 workspace-rooted+ entries and `pi-desktop/composer/commands` returns the merged command list;+ both fail soft without a workspace and change no host RPC version.+ *(Amended by D669: while that index is truncated, `pi-desktop/fs/search`+ answers a typed query from the full listing.)*++## Alternatives++- Expand templates in the agent sidecar: main persists the message first, so+ reseed could not replay the expansion without a second write path. Rejected.+- Migrate the runtime to `AgentHarness`: replaces the whole prompt/loop+ integration for one feature. Rejected; the helpers give identical semantics.+- Inline referenced file content: inflates context and needs truncation rules and+ a binary attachment channel. Rejected; the Read-tool reference is pi's+ interactive semantic.## Consequences-- The composer gains a keyboard-first autocomplete surface (D125 defines the- interaction/IME contract — the first explicit IME spec in the project).-- `.pi/prompts` templates become shared assets between pi CLI and PI-Desktop.-- The transcript user-message schema gains an optional `command` field;- renderers that ignore it keep working.-- Inline binary attachments and preview tiles remain deferred.+- The composer gains a keyboard-first autocomplete surface (D125 defines the IME+ contract), and `.pi/prompts` templates become assets shared with the pi CLI.+- The transcript user message gains an optional `command` field that renderers+ may ignore; inline binary attachments stay deferred.diff --git a/docs/adr/0025-menu-free-windows-linux-chrome.md b/docs/adr/0025-menu-free-windows-linux-chrome.mdindex 9c3fb8f10..21a5f422b 100644--- a/docs/adr/0025-menu-free-windows-linux-chrome.md+++ b/docs/adr/0025-menu-free-windows-linux-chrome.md@@ -2,59 +2,37 @@- Status: Accepted- Date: 2026-07-27-- Deciders: PI-Desktop core- Related: D118, D129, ADR 0021## Context-ADR 0021 introduced a native macOS system menu and a renderer-owned-File/Edit/View/Window/Help menubar inside Windows/Linux windows. The in-window-menubar consumes the left side of the 46px titlebar and applies a macOS menu-model to frameless Windows/Linux chrome.+ADR 0021 applied a macOS menu model to frameless chrome and gave Windows/Linux+windows a renderer-owned File/Edit/View/Window/Help menubar. The menu surface now+stays specific to the macOS system menu, while Windows/Linux still need window+controls and access to common commands.## Decision-1. macOS keeps the conventional native Electron application menu and- hidden-inset traffic lights defined by ADR 0021.-2. Windows/Linux keep the frameless 46px titlebar and renderer-drawn minimize,- maximize/restore, and close controls, but render no application menubar- inside the window.-3. Windows/Linux titlebar navigation reclaims the space previously reserved for- File/Edit/View/Window/Help.-4. Common Windows/Linux application, close-window, zoom, and fullscreen- shortcuts are handled without a visible menu.-5. Existing allowlisted menu-command and native-action IPC stays in place for- the macOS system menu, renderer readiness, and shortcut dispatch.+macOS keeps the native Electron application menu and the hidden-inset traffic+lights from ADR 0021. Windows/Linux keep the frameless titlebar and+renderer-drawn minimize, maximize/restore, and close controls but render no+menubar, and titlebar navigation reclaims that space. Common application,+close-window, zoom, and fullscreen shortcuts work without a visible menu, while+standard editing shortcuts stay native web content. The allowlisted menu-command+and native-action IPC stays for the macOS menu, renderer readiness, and shortcut+dispatch, adding no privileged surface.## Consequences-- The window titlebar is quieter and gives navigation the full left edge.-- macOS retains the platform-standard system menu and all native roles.-- Windows/Linux users rely on visible in-app controls, Settings -> Info, the- command palette, and keyboard shortcuts instead of an in-window menubar.-- F10 and Shift+F10 are no longer consumed by renderer shell chrome.-- The removed renderer menubar component, styling, focus model, and localized- popover behavior no longer require maintenance or qualification.+- Titlebar space goes to navigation; F10 / Shift+F10 are no longer consumed by+ renderer shell chrome.+- Windows/Linux users reach commands through in-app controls, Settings -> Info,+ the command palette, and shortcuts.+- The removed menubar component, styling, focus model, and localized popovers+ need no maintenance.## Alternatives-### Keep the renderer menubar but hide it by default--Rejected because an Alt/F10-revealed menu still reserves a platform concept that-product direction does not want inside the window.--### Remove all menu-related IPC--Rejected for this change because the macOS system menu still dispatches-allowlisted renderer commands, and Windows/Linux shortcuts can reuse the bounded-native-action surface without broadening Main-process authority.--## References--- `docs/adr/0021-platform-application-chrome.md`-- `docs/spec/03-runtime/01-ipc-protocol.md`-- `docs/spec/04-ux/01-ui-ia.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/04-ux/09-interaction-patterns.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-067)-- `docs/spec/08-meta/decisions-log.md` (D129)+- Hide the menubar by default: an Alt/F10-revealed menu still reserves the concept+ in-window.+- Remove all menu IPC: the macOS menu still dispatches allowlisted commands.diff --git a/docs/adr/0026-project-archive-in-settings.md b/docs/adr/0026-project-archive-in-settings.mdindex 6dcbd4adc..5a686f2a9 100644--- a/docs/adr/0026-project-archive-in-settings.md+++ b/docs/adr/0026-project-archive-in-settings.md@@ -2,63 +2,41 @@- Status: Superseded in part by ADR 0036 (destination count/order)- Date: 2026-07-27-- Deciders: PI-Desktop core-- Related: D066, D090, D093, D133, ADR 0013, ADR 0016+- Related: [ADR 0013](0013-compact-settings-directory.md) ·+ [ADR 0016](0016-sidebar-organization-and-multi-project-tabs.md) (D066, D090,+ D093, D133)## Context-The home sidebar currently exposes both an independent Projects destination and-retained project groups. Active work happens through the retained groups, while-the Projects destination primarily acts as a durable directory for discovering,-archiving, restoring, reopening, and closing historical project records.+The home sidebar exposed both a Projects destination and retained project+groups, duplicating the project concept and giving archival management the same+prominence as task creation. The frozen four-destination Settings directory+from ADR 0013 had no place for that management surface.## Decision-1. Remove the standalone Projects destination from the home sidebar, app page- state, and global page-search results.-2. Add **Project archive** (`项目归档`) to Settings after Import and before Info.-3. Reuse the durable Projects index in the archive.-4. The Settings archive always includes archived project records.-5. Activating a project or project session leaves Settings and returns to chat.-6. The home sidebar keeps retained project groups and the persistent new-project- action.-7. Settings and global settings search index Project archive and its archive,- restore, project-title, and project-search terms.+Remove the standalone Projects destination from the sidebar, app page state, and+global page search, and add **Project archive** (`项目归档`) to Settings after+Import and before Info, making five destinations. The archive reuses the durable+Projects index with its search, add, activate, session expansion, pin,+archive/restore, and close actions, always includes archived rows, and does not+apply the sidebar's archived-session visibility filter to expanded details.+Activating a project or session returns to chat; archiving or closing keeps the+destination visible. The sidebar keeps retained project groups and the+persistent new-project action, and storage, renderer metadata, and the+one-visible-workspace activation model are unchanged.## Consequences-- The home sidebar has one fewer primary destination and gives more visual- priority to active project and session work.-- Historical and closed projects remain recoverable through Settings, including- imported paths that are not retained as sidebar tabs.+- The sidebar has one fewer primary destination; historical projects stay+ recoverable through Settings, including imported paths.- Settings grows from four to five destinations, superseding ADR 0013 only for- the destination count and ordering.-- No IPC, host RPC, database, security, or project-activation contract changes.-- Existing persisted project/session archive metadata remains compatible.+ destination count and ordering.+- No IPC, host RPC, database, security, or activation contract changes.## Alternatives-### Keep Projects in both the home sidebar and Settings--Rejected because duplicate navigation leaves ownership unclear and does not-reduce the home sidebar's primary menu.--### Show only archived rows--Rejected because closed but unarchived durable projects would lose their only-index-based recovery path.--### Put project management inside Basics--Rejected because a full searchable project index is a destination-scale tool,-not an application-default row or compact settings card.--## References--- `docs/spec/00-baseline.md`-- `docs/spec/03-runtime/04-data-storage.md`-- `docs/spec/04-ux/01-ui-ia.md`-- `docs/spec/04-ux/06-settings-ia.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-038)-- `docs/spec/08-meta/decisions-log.md` (D133)+- Projects in both the sidebar and Settings: rejected; duplicate navigation+ leaves ownership unclear.+- Show only archived rows: rejected; closed but unarchived projects would lose+ their only index-based recovery path.diff --git a/docs/adr/0027-pi-model-catalog-authority.md b/docs/adr/0027-pi-model-catalog-authority.mdindex dcdb30f5e..b60c59b33 100644--- a/docs/adr/0027-pi-model-catalog-authority.md+++ b/docs/adr/0027-pi-model-catalog-authority.md@@ -5,72 +5,40 @@## Context-PI-Desktop previously read reasoning hints from pi-ai but rebuilt a smaller-runtime model with desktop-owned defaults and provider-level overrides. Known-models therefore lost pi's context window, output limit, input modes, pricing,-headers, and parts of their compatibility record.+PI-Desktop read reasoning hints from pi-ai but rebuilt a smaller runtime model+with desktop defaults and provider overrides, so known models lost their context+window, output limit, input modes, pricing, headers, and parts of their+compatibility record. Two owners of model behavior also forced per-model patches+such as MiMo thinking dialects.## DecisionFor every model resolved from pi-ai's built-in catalog, pi-ai is the sole-authority for model metadata and compatibility behavior.--- Electron main resolves one complete serializable pi model snapshot: name, base- URL, reasoning flag, thinking-level map, input modes, pricing, context window,- output limit, headers, and compatibility data.-- The sidecar uses that snapshot verbatim and replaces only the runtime- connection identity: selected model id, configured provider id, selected API- adapter, and an explicitly configured endpoint URL.-- PI-Desktop does not rewrite known-model reasoning support, thinking levels,- context limits, output limits, temperature, or compatibility flags.-- Provider Settings no longer expose model-parameter overrides, and the model- menu no longer enables reasoning for an unknown model.-- A free-form model id that pi does not recognize remains allowed.-- Cached/discovered model lists remain selection and offline-discovery data;- they do not override runtime model semantics.-- Corrections to a known model belong upstream in pi-ai or in a pi-ai upgrade,- not in a PI-Desktop model-specific patch.--This supersedes D102 and the provider-override clauses of D096/D107. It does not-change the durable session thinking-level enum or transcript handling from ADR-0018.+authority for metadata and compatibility behavior. Electron main resolves one+complete serializable pi model snapshot (name, base URL, reasoning flag,+thinking-level map, input modes, pricing, context window, output limit, headers,+compatibility data) that the sidecar uses verbatim, replacing only the connection+identity: model id, provider id, API adapter, and an explicitly configured+endpoint URL. PI-Desktop rewrites no reasoning, thinking levels, limits,+temperature, or compatibility flags, and Provider Settings expose no+model-parameter overrides; corrections to a known model belong upstream in pi-ai.+A free-form model id pi does not recognize stays a generic text-only,+non-reasoning fallback with conservative limits, and cached or discovered lists+remain selection data. This supersedes D102 and the provider-override clauses of+D096/D107 (D136) without changing ADR 0018's thinking-level enum or transcript+handling.## Consequences-- Known models retain the complete metadata shipped by the pinned pi-ai version- across native and compatible endpoints.-- PI-Desktop has one less model matrix to maintain and cannot drift silently- from pi's adapters.-- Updating pi-ai may intentionally change available thinking levels or model- limits and must be covered by catalog-resolution tests.-- Unknown custom models remain usable for text, but model-specific reasoning,- vision, pricing, and large-context guarantees wait until pi recognizes them.-- Legacy provider override fields may remain readable in persisted records for- compatibility, but they no longer affect runtime resolution.+- Known models keep the metadata of the pinned pi-ai version across native and+ compatible endpoints, with one less model matrix to maintain.+- A pi-ai upgrade may intentionally change levels or limits, so catalog+ resolution needs tests.+- Legacy override fields stay readable but no longer affect resolution, and+ unknown models are text-only until pi knows them.## Alternatives-### Merge provider overrides over pi metadata--Rejected because it preserves dual ownership and can produce combinations the-selected adapter or model does not support.--### Keep only thinking compatibility from pi--Rejected because it continues discarding context, output, input, pricing, and-other model-specific fields.--### Reject unknown model ids--Rejected because it would violate the product's free-form custom-provider policy-and turn the bundled catalog into a closed allowlist.--## References--- `docs/spec/03-runtime/02-agent-runtime.md`-- `docs/spec/03-runtime/11-provider-model-system.md`-- `docs/spec/03-runtime/12-provider-config-schema.md`-- `docs/spec/03-runtime/13-model-catalog-and-selection.md`-- `docs/spec/04-ux/06-settings-ia.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `docs/spec/08-meta/decisions-log.md` (D136)+- Merge provider overrides over pi metadata: keeps dual ownership and unsupported+ combinations.+- Reject unknown model ids: turns the catalog into a closed allowlist.diff --git a/docs/adr/0028-session-scoped-work-panel-contexts.md b/docs/adr/0028-session-scoped-work-panel-contexts.mdindex 4efc8b73e..872251ee0 100644--- a/docs/adr/0028-session-scoped-work-panel-contexts.md+++ b/docs/adr/0028-session-scoped-work-panel-contexts.md@@ -6,63 +6,43 @@## Context-The renderer previously owned one global work-panel tab set. Selecting another-conversation or workspace closed the panel and destroyed every tab, as required-by D128.+The renderer owned one global work-panel tab set, and D128 required that selecting+another conversation or workspace close the panel and destroy every tab, which+discarded useful tools on return. It also raced with permission-gated tools: an+artifact finishing during a switch either flashed the panel open and closed or was+dropped by the background-session guard, and BrowserPreview could resolve a+relative path against the visible workspace instead of its own.## Decision-Each conversation owns a renderer-memory work-panel context containing its open-state, ordered tabs, active tab, file request, and Browser resource.+Each conversation owns a renderer-memory work-panel context: open state, ordered+tabs, active tab, file request, and Browser resource.-- Selecting a conversation saves the current projection and atomically restores- the destination context.-- New and forked conversations begin with an empty context.+- Switching conversations saves the current projection and atomically restores+ the destination one; switching away never deletes either, and deleting a+ conversation drops its context. Contexts stay transient, so only panel width+ survives relaunch.- Review and BrowserPreview artifacts are recorded against their originating- `sessionId`, including while that conversation is in the background.-- Background artifacts update retained state only.-- BrowserPreview events carry `sessionId`.-- Selecting a workspace without an active conversation hides the current panel- projection while retaining the prior conversation's state.-- Work-panel contexts remain transient.+ `sessionId`, including in the background, and background artifacts update+ retained state only — never opening, activating, navigating, resizing, or+ focusing the visible panel.+- BrowserPreview events carry `sessionId`; Electron Main resolves local preview+ paths from that durable session's `projectPath` and navigates only when the+ originating conversation's Browser tab is visible.-This adopts D142 and supersedes only D128's requirement to close and clear tabs-on visible session/workspace changes. D128's artifact triggers, deduplication,-and close/collapse rules remain unchanged; its no-launcher rule is amended by-ADR 0068.+This adopts D142 and supersedes only D128's requirement to close and clear tabs on+visible session or workspace changes; D128's artifact triggers, deduplication, and+close rules remain, with its no-launcher rule amended by ADR 0068.## Consequences-- Returning to a conversation restores its tools without reinterpreting paths- against another workspace.-- Permission completion and asynchronous navigation no longer produce a- transient panel open/close cycle or lose the resulting artifact.-- The renderer retains bounded per-session UI state until deletion or relaunch;- it does not add durable storage or schema migration.-- The embedded browser remains one hardened Main-process WebContentsView.-- The former interactive terminal process/cache is no longer part of the- work-panel runtime; Browser remains the Main-owned native resource.+- Returning to a conversation restores its tools without reinterpreting paths.+- Permission completion no longer flashes the panel or loses the artifact.+- Bounded per-session UI state is retained without new storage or migration.## Alternatives-### Keep clearing tabs on every context change--Rejected because it loses task continuity and cannot avoid both permission-completion flashes and dropped background artifacts.--### Persist panel contexts in host storage--Rejected because tabs and Browser resources are transient presentation state.--### Key every backend panel subsystem by conversation--Rejected for this change.--## References--- `docs/spec/04-ux/01-ui-ia.md`-- `docs/spec/04-ux/03-permission-ux.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/04-ux/09-interaction-patterns.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `docs/spec/08-meta/decisions-log.md` (D142)+- Keep clearing tabs on every context change — rejected: loses continuity and+ cannot avoid both failure modes.+- Persist contexts in host storage — rejected: transient presentation state would+ need schema plus stale-resource cleanup for no workflow gain.diff --git a/docs/adr/0029-separate-window-and-panel-resize-ownership.md b/docs/adr/0029-separate-window-and-panel-resize-ownership.mdindex 6390316d1..e2696db82 100644--- a/docs/adr/0029-separate-window-and-panel-resize-ownership.md+++ b/docs/adr/0029-separate-window-and-panel-resize-ownership.md@@ -1,73 +1,48 @@# ADR 0029: Separate native-window and work-panel resize ownership-- Status: Superseded in part by ADR 0032+- Status: Superseded in part by ADR 0032 (the clamp of the panel inside the+ existing client area and the ban on panel-driven native geometry)- Date: 2026-07-28-- Related: [01-ui-ia](../spec/04-ux/01-ui-ia.md) ·- [08-component-spec §5](../spec/04-ux/08-component-spec.md) ·- [09-interaction-patterns §8](../spec/04-ux/09-interaction-patterns.md) ·- [01-ipc-protocol](../spec/03-runtime/01-ipc-protocol.md) · decision D156--> ADR 0032 supersedes the clauses that responsively clamp the panel inside the-> existing client area and prohibit all panel-driven native geometry changes.-> Main ownership of BrowserWindow geometry, renderer ownership of committed-> panel width, and the divider gesture/commit rules remain in force.+- Related: D156## Context-Work-panel visibility and divider commits previously called `window/resizeBy` so-Electron could grow or shrink the native window. Renderer `window.resize` events-then inferred whether the user moved the native right edge and wrote part of-that delta back into the panel width.+Panel visibility and divider commits called `window/resizeBy` so Electron could+resize the native window, while renderer `window.resize` events inferred a+right-edge gesture and wrote part of that delta back into the panel width. The+panel changed the native window and the native window changed the panel,+producing a second layout jump after divider release, stale growth on rapid+open/close, and preferences mutated during an unrelated resize.## Decision-Native window geometry and renderer column geometry have independent owners:-1. Electron Main exclusively owns `BrowserWindow` bounds and persists the actualnormal bounds.-2. The renderer owns one preferred work-panel width in localStorage.-3. Native window-edge gestures resize the shell only.-4. The work-panel divider resizes internal columns only.+2. The renderer owns one preferred panel width in localStorage, clamped against+ the current viewport, visible sidebar, and MainChat reserve into the effective+ width.+3. Native edge gestures resize the shell only: they may temporarily clamp the+ effective panel width but never overwrite its preference.+4. The divider resizes internal columns only; pointer math is anchored to the+ gesture start, release commits once, and Escape, pointer cancellation, or lost+ capture roll back.5. Opening, collapsing, session-switching, and closing the panel never changenative bounds on any platform.-6. The renderer-to-Main `window/resizeBy` IPC method, programmatic resize- attribution tickets, panel growth tracking, and persisted-width offset are- removed.+6. The `window/resizeBy` method, resize attribution tickets, panel growth+ tracking, and persisted-width offset are removed.## Consequences-- Divider feedback remains continuous through release instead of triggering a- second native resize.-- Native edge behavior is symmetric and matches platform window conventions.-- Windows, macOS, and Linux share one panel interaction model.-- A temporarily constrained panel returns to its preferred width when space- becomes available.-- The preload surface is smaller, and Electron window-state persistence no- longer needs a panel-specific offset.+- Divider feedback stays continuous through release, and a temporarily+ constrained panel returns to its preferred width when space appears.+- Native edge behavior is symmetric, so Windows, macOS, and Linux share one panel+ interaction model.+- The preload surface shrinks; window state is flushed synchronously on close so a+ pending debounce cannot lose the normal bounds.## Alternatives-### Keep delta IPC and add request identifiers--Rejected. Request identifiers can reject stale replies but do not remove the-circular geometry ownership or the post-release layout jump.--### Let Electron own the complete three-column layout--Rejected. Main does not know renderer sidebar state or content constraints, and-moving split-pane layout across IPC would add latency and duplicate DOM truth.--### Keep native right-edge ownership for the work panel--Rejected. Edge-source inference is not reliable across frameless windows,-display scaling, macOS window chrome, and Wayland.--## References--- `docs/spec/03-runtime/01-ipc-protocol.md`-- `docs/spec/04-ux/01-ui-ia.md`-- `docs/spec/04-ux/07-ui-design-system.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/04-ux/09-interaction-patterns.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-056)-- `docs/spec/08-meta/decisions-log.md` (D156)+- Keep delta IPC with request identifiers: rejects stale replies but keeps the+ circular ownership and the post-release jump.+- Let Electron own the three-column layout: Main does not know renderer sidebar+ state, and layout over IPC would add latency.diff --git a/docs/adr/0030-turn-boundary-context-checkpoint-compaction.md b/docs/adr/0030-turn-boundary-context-checkpoint-compaction.mdindex 38f5d5299..43f7a95bb 100644--- a/docs/adr/0030-turn-boundary-context-checkpoint-compaction.md+++ b/docs/adr/0030-turn-boundary-context-checkpoint-compaction.md@@ -1,88 +1,59 @@# ADR 0030: Turn-boundary context checkpoint compaction-- Status: Accepted; soft-boundary, model-tool, and visibility clauses- superseded in part by ADR 0061, then partly restored by ADR 0064+- Status: Accepted; soft-boundary, model-tool, and visibility clauses superseded in+ part by ADR 0061, then partly restored by ADR 0064- Date: 2026-07-28-- Last amended: 2026-08-06-- Amended by: ADR 0049 (failure recovery), ADR 0061 (background compaction;- removes the soft-boundary nudge, the `CompactContext` tool, and the- visibility of compaction activity), ADR 0064 (Codex parity; compaction is- inline again, the model-facing tool and budget reminders return, and every- compaction is visible)+- Related: D158, ADR 0049, ADR 0061, ADR 0064## Context-A long pi agent run can contain many model/tool turns before `agent_end`.-Compacting only between user prompts or after the run is already terminal does-not protect the next provider request inside that loop.+One pi agent run can contain many model/tool turns before `agent_end`, and compacting+only between user prompts or after the run is terminal does not protect the next provider+request inside that loop: an observed request exceeded the provider maximum and was+rejected before any recovery point existed. The context helpers pi-agent-core once+exported were removed, so the desktop runtime has to own projection, estimation, and+summary generation while pi keeps the loop and its stable agent types.## Decision-PI-Desktop owns its context projection, estimation, compaction preparation and-summary generation, and independently implements the desktop-specific-controller. pi-agent-core supplies the agent loop and stable agent types.--- The controller runs after every `turn_end` and before pi starts another- provider request.-- Budgeting uses the pi-ai model context/output limits.-- At the soft boundary, a transient system instruction asks the model to call- `CompactContext` with the active-task focus.-- `CompactContext` bypasses the Rust tool/permission bridge because it changes- model context, not the workspace.-- At the hard boundary, the runtime generates a checkpoint deterministically.-- A final tool-result batch is kept with its assistant tool-call carrier.-- An exact provider overflow is a final safety net.-- Automatic protection is enabled by default.-- Protocol v6 adds a host-owned `session.appendCompaction` operation and- compaction lifecycle events.-- Only the newest valid checkpoint rebuilds model context.+PI-Desktop owns context projection, estimation, compaction preparation, and summary+generation, and the controller runs after every `turn_end` — the model and tool turn+boundary — before pi starts another provider request. Budgeting uses pi-ai model context+and output limits, with request headroom of the configured reserve, the model output+allowance, or a share of the window, bounded so reserve and retained tail each stay below+half the hard budget (ADR 0064 derives both from the model window and retains only recent+user messages; ADR 0061 removed the soft-boundary nudge and the `CompactContext` tool, and+ADR 0064 restored the tool as `new_context` with budget notices instead of a transient+instruction). At the hard boundary the runtime generates a checkpoint deterministically+and re-estimates before persistence and before continuation, and a failed summary or+ineffective checkpoint first tries ADR 0049's retained-tail recovery before the loop stops+with `CONTEXT_COMPACTION_FAILED`. A final tool-result batch stays with its assistant+tool-call carrier, and an atomic batch that reaches the hard budget becomes a+checkpoint-only bounded copy keeping each result's tool identity and error envelope plus+an explicit truncation marker, while durable messages and the visible transcript stay+complete. An exact provider overflow is the last safety net: the failed assistant leaves+model context, one checkpoint is created, the request is retried once, and a second+overflow is terminal. Protocol v6 adds a host-owned `session.appendCompaction` operation+and compaction lifecycle events, so the host appends a typed checkpoint line to the session+JSONL and never deletes, rewrites, or hides visible messages; only the newest valid+checkpoint rebuilds model context, transcript rewrites keep it only while its boundary+remains, forks copy and remap it only when the fork includes that boundary, and stored+`enabled: false` values are ignored because protection is always on.## Consequences-- Long tool loops receive context checks at the only boundary that can protect- the next request without interrupting an active model or tool call.-- The deterministic hard guard does not depend on the model obeying a reminder.-- Restart and model changes retain compacted working context without changing- the human-readable conversation.-- Compaction itself is one extra provider request and can fail.-- A checkpoint may retain a shortened model-facing copy of an oversized atomic- tool-result batch.+- Long tool loops get a context check at the only boundary that protects the next request+ without interrupting an active call, and the deterministic hard guard does not depend on+ the model obeying a reminder.+- Compaction costs one extra provider request and can fail: automatic failure has a durable+ retained-tail recovery, while manual `/compact` stays fail-fast for an idle session.+- A checkpoint may keep a shortened model-facing copy of an oversized tool-result batch, so+ future model detail is lost under pressure but every call/result pair survives, and+ provider token accounting on retained assistant messages is cleared when a checkpoint is+ reconstructed.## Alternatives-### Integrate OpenCode DCP directly--Rejected because it targets OpenCode's plugin hooks and persistence model and is-AGPL-3.0.--### Use pi compaction only at `agent_end`--Rejected because no `agent_end` occurs between tool turns in one long run.--### Rely only on a model reminder--Rejected because the model may ignore, postpone, or repeat the request.--### Delete older visible transcript messages--Rejected because context management must not destroy user history, revision-families, fork inputs, searchability, or diagnostics.--## References--### Implementation note (2026-10-03)--The accepted ownership boundary is unchanged, but pi-agent-core removed its-experimental harness/compaction exports. Agent Runtime now owns the context-projection, conversion, estimation, cut-point preparation, and summary request-adapter; pi-agent-core remains the agent loop and stable type dependency.--- `docs/spec/03-runtime/01-ipc-protocol.md`-- `docs/spec/03-runtime/02-agent-runtime.md`-- `docs/spec/03-runtime/04-data-storage.md`-- `docs/spec/03-runtime/06-host-rpc-protocol.md`-- `docs/spec/04-ux/04-builtin-commands.md`-- `docs/spec/04-ux/06-settings-ia.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `docs/spec/08-meta/decisions-log.md` (D158)-- `https://github.com/Opencode-DCP/opencode-dynamic-context-pruning`+- Compact only at `agent_end`: no `agent_end` occurs between tool turns.+- Rely on a model reminder alone: the model may ignore it, so the hard boundary stays the+ enforcement point.diff --git a/docs/adr/0031-icon-free-composer-prompt-row.md b/docs/adr/0031-icon-free-composer-prompt-row.mdindex b1ef144d8..99e39f5e4 100644--- a/docs/adr/0031-icon-free-composer-prompt-row.md+++ b/docs/adr/0031-icon-free-composer-prompt-row.md@@ -2,53 +2,34 @@- Status: Accepted- Date: 2026-07-28-- Related: [01-ui-ia](../spec/04-ux/01-ui-ia.md) ·- [07-ui-design-system](../spec/04-ux/07-ui-design-system.md) ·- [08-component-spec](../spec/04-ux/08-component-spec.md) · decision D160+- Related: D054, D094, D160## Context-D054 introduced a visible cue beside an empty draft, and D094 standardized that-cue as the canonical PI-Desktop logo in the thread-docked composer. The home-composer later removed the cue, leaving the two prompt rows visually-inconsistent.+D054 and D094 put the canonical PI-Desktop logo beside an empty draft in the+thread-docked composer while the home composer dropped the cue, so the two prompt+rows disagreed and the leftover mark spent input width on no navigation, status,+or runtime meaning.## Decision-1. Home and thread-docked composer prompt rows render no leading brand icon.-2. Draft text and placeholder ink begin at the input row's standard content- gutter; no layout space is reserved for a removed mark.-3. The renderer `BrandLogo` component continues to use the canonical asset for- the home hero, expanded/collapsed sidebar, and startup splash.-4. Session-creation controls retain their dedicated message-plus icon.-5. This decision supersedes only D054's leading brand-cue requirement and D094's- docked-composer logo placement.+Home and thread-docked prompt rows render no leading brand icon, and draft text+and placeholder ink start at the input row's standard content gutter with no+reserved space. The renderer `BrandLogo` component keeps the canonical asset for+the home hero, sidebar, splash, Dock, application menu, and About identity, and+session-creation controls keep their message-plus icon. This supersedes only+D054's leading brand cue and D094's docked-composer logo placement; naming and+the remaining brand-asset requirements are unchanged.## Consequences- Home and transcript composers share one icon-free prompt-row boundary.-- The textarea gains the width previously occupied by the 15px logo and gap.-- Removing the renderer node also removes the associated theme-specific CSS.-- Brand recognition continues through the surrounding shell without repeating- the product mark inside a text-entry surface.+- The textarea gains the width the logo and its gap took.+- Brand recognition moves to the surrounding shell, not a text-entry surface.## Alternatives-### Keep the docked 15px logo--Rejected. It preserves the historical branding contract but keeps inconsistent-input-row anatomy and consumes space without conveying state or an action.--### Add the logo back to the home composer--Rejected. Repeating the mark in both text-entry surfaces adds decorative chrome-instead of simplifying the prompt path.--## References--- `docs/spec/00-baseline.md`-- `docs/spec/04-ux/01-ui-ia.md`-- `docs/spec/04-ux/07-ui-design-system.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-046, US-UI-37)-- `docs/spec/08-meta/decisions-log.md` (D054, D094, D160)+- Keep the docked logo: preserves inconsistent input-row anatomy for no state or+ action.+- Add the logo to the home composer: repeats decorative chrome in both+ text-entry surfaces.diff --git a/docs/adr/0032-reserve-native-width-for-the-docked-work-panel.md b/docs/adr/0032-reserve-native-width-for-the-docked-work-panel.mdindex c379185e1..7c78f981b 100644--- a/docs/adr/0032-reserve-native-width-for-the-docked-work-panel.md+++ b/docs/adr/0032-reserve-native-width-for-the-docked-work-panel.md@@ -11,73 +11,63 @@## ContextADR 0029 removed a circular ownership model in which work-panel changes and-native resize events rewrote each other. It made the panel a responsive column-inside the existing client area.+native resize events rewrote each other, leaving the panel a responsive column+inside the client area: no races, but opening the panel consumed chat width,+collapsing it expanded chat again, and a native edge resize could compress the+panel.++The intended docked behavior is closer to Codex: the panel has a committed width+of its own, the window reserves native width for it while visible, and native+edges resize the conversation rather than the tool surface.## Decision-Renderer panel layout and Electron window geometry remain separate owners, but-they coordinate through an idempotent target-state reservation:+Renderer panel layout and Electron window geometry stay separate owners that+coordinate through an idempotent target-state reservation:1. The renderer owns one committed preferred panel width in the inclusive- `364..720` range.-2. The preload exposes only `window/setWorkPanelReservation({ width: 0 |- 364..720 })`.-3. In normal window state, Main derives visible bounds from persisted base- bounds plus the target reservation.-4. Opening the visible panel requests its committed width.-5. When the work area can supply the complete target, panel visibility and- divider commits do not change chat width.-6. While a reservation is active, native edge resizing changes base window- bounds and therefore chat width only.-7. Maximized and fullscreen windows record the latest requested target but defer- reservation geometry.-8. Moving the window to another display or changing display work-area geometry- reconciles the same target against the new available width.-9. Persisted normal bounds are base bounds with the active reservation width and- reservation-induced x shift removed.-10. Only the currently visible session context may set the reservation.--The divider's anchored pointer math, frame-coalesced preview, commit-on-release,-and cancellation rollback from ADR 0029 remain in force. Live preview remains a-renderer layout operation; only a successful commit changes the native target.+ `364..720` range; an open panel renders at that width, and viewport, sidebar,+ and native-edge changes never clamp or rewrite it.+2. The preload exposes only+ `window/setWorkPanelReservation({ width: 0 | 364..720 })`, and Main returns+ `{ requested, reserved }` — the normalized target and the native width added+ for it — so repeating a target has no cumulative effect.+3. In normal window state Main derives visible bounds from persisted base bounds+ plus the target reservation, expanding right first and shifting left only as+ far as the display work area requires, with `reserved` capped by available+ work-area width.+4. Opening requests the committed width; collapsing or closing the final+ resource requests zero and symmetrically removes the added width and any+ x shift. A committed divider change retargets the reservation, and only the+ visible session context may set it.+5. When the work area can supply the full target, visibility and divider commits+ do not change chat width; otherwise the panel keeps its committed width and+ chat absorbs the unavoidable `requested - reserved` shortfall.+6. Native edge resizing changes base bounds and therefore chat width only, while+ maximized and fullscreen windows record the target and reconcile it on return+ to normal state or on a display or work-area change.+7. Persisted normal bounds exclude reservation width and x shift, so relaunch+ never restores a panel-expanded shell.++ADR 0029's anchored pointer math, frame-coalesced preview, commit-on-release, and+cancellation rollback stay in force; only a successful commit changes the native+target.## Consequences-- Opening and collapsing a panel preserve the conversation width whenever the- display work area has enough unused width.-- Native edge gestures have one predictable effect: they resize the conversation- while the panel remains fixed.-- Small displays can make chat narrower than its 360px readability target, but- never silently compress the panel or corrupt its committed preference.-- Main owns a narrow, allowlisted geometry capability rather than an arbitrary- delta resize channel.-- Window-state persistence and maximize/fullscreen transitions must distinguish- base bounds from temporary reservation geometry.+- Opening and collapsing preserve conversation width whenever the work area has+ unused width, and native edge gestures resize only the conversation.+- Small displays can narrow chat below its 360px readability target, but never+ compress the panel or corrupt its committed preference.+- Main holds a narrow allowlisted geometry capability rather than an arbitrary+ delta channel, and window-state persistence must keep base bounds distinct+ from temporary reservation geometry.## Alternatives-### Keep all columns inside the current client area--Rejected because panel open/collapse would continue to resize the conversation,-and native edge gestures could continue to compress the panel.--### Restore renderer-supplied resize deltas--Rejected because deltas are not idempotent and recreate the stale-request,-double-resize, and persistence ambiguity removed by ADR 0029.--### Force the full reservation outside the display work area--Rejected because a fixed panel must not move native chrome off screen.--## References--- `docs/adr/0029-separate-window-and-panel-resize-ownership.md`-- `docs/spec/03-runtime/01-ipc-protocol.md`-- `docs/spec/04-ux/01-ui-ia.md`-- `docs/spec/04-ux/07-ui-design-system.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/04-ux/09-interaction-patterns.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-056)-- `docs/spec/08-meta/decisions-log.md` (D163)+- Keep all columns inside the client area: rejected, open/collapse would keep+ resizing the conversation and edge gestures could compress the panel.+- Restore renderer-supplied resize deltas: rejected, deltas are not idempotent+ and recreate the stale-request and double-resize races ADR 0029 removed.+- Force the full reservation outside the work area: rejected, a fixed panel must+ not push native chrome off screen.diff --git a/docs/adr/0033-internal-dock-work-panel.md b/docs/adr/0033-internal-dock-work-panel.mdindex 37ee7c48c..6b9de3ee3 100644--- a/docs/adr/0033-internal-dock-work-panel.md+++ b/docs/adr/0033-internal-dock-work-panel.md@@ -10,21 +10,53 @@## Context-ADR 0032 made the work panel a docked flex column but, to keep the chat width-stable, reserved *native window width* equal to the panel's committed width.+ADR 0032 made the work panel a docked flex column but reserved native window+width equal to the panel's committed width, so Main grew the OS window and+placed the browser `WebContentsView` in the extended region. Opening the panel+therefore grew the whole application window, reading as a separate expansion+rather than space taken inside the existing window.-- The former interactive terminal tab did not use a native view; ADR 0108- removes that surface entirely.-- Native `WebContentsView`s (the host browser guest and plugin views) are- positioned from the **renderer-measured** panel rect via `setBounds` (see- `BrowserPane.setBounds` and `PluginViewTab`).+ChatGPT and WorkBuddy keep the window fixed and let the panel take space from the+client area, pushing the conversation left.++The expansion turned out to be only a room-making mechanism. The former+interactive terminal tab used no native view and is removed by ADR 0108, and+native views are positioned from the renderer-measured panel rect via+`setBounds`, which lands inside a fixed window anyway.## Decision1. The work panel is a fixed-width in-flow flex column inside the **fixed**- client area. Opening it reflows `MainChat` to the left; it never expands the- OS window.+ client area; opening it reflows `MainChat` left and never expands the OS+ window.+2. The renderer always requests a native reservation of `0`+ (`api.setWorkPanelReservation(0)`), and Main returns+ `{ requested: 0, reserved: 0 }`. The `window/setWorkPanelReservation` IPC is+ retained as a stable seam.+3. Native `WebContentsView`s keep being positioned from the renderer-measured+ panel rect via `browserSetBounds`, which needs no window expansion.+4. The default committed width is **420px** within the `364..720px` clamp.+ *(Superseded by decision D167: the default is 280px inside a `244..720px`+ clamp; every other clause here stands.)* *(Amended by ADR 0238: the clamp+ becomes the live three-column budget — 244px minimum, no fixed maximum,+ MainChat floor 360px.)*+5. Native window-edge resize changes `MainChat` only, by plain reflow.## Consequences-Superseded (Superseded by ADR 0122; internal-dock direction restored by ADR 0151). The full record is in git history.+- The OS window size is stable across open, collapse, and divider commit; only+ `MainChat` reflows, matching ChatGPT / WorkBuddy.+- On small windows `MainChat` can be squeezed below its 360px readability target+ at a wide panel width — the trade-off ChatGPT accepts.+- Reservation machinery is retained but inert, so the renderer→Main IPC surface+ and its tests stay valid, and persisted bounds are simply the user's window+ size.+- Exit animation and native view detach-before-exit logic are unchanged.++## Alternatives++- Keep ADR 0032: rejected, expanding the window is the behavior being removed,+ and it disconnects the panel from the in-window layout.+- Clip the native view with a separate overlay window: rejected, it adds a second+ window with focus and occlusion complexity for no benefit over measuring the+ in-flow rect.diff --git a/docs/adr/0034-merge-command-palette-into-global-search.md b/docs/adr/0034-merge-command-palette-into-global-search.mdindex 3be95b179..52ab4880c 100644--- a/docs/adr/0034-merge-command-palette-into-global-search.md+++ b/docs/adr/0034-merge-command-palette-into-global-search.md@@ -4,64 +4,39 @@- Date: 2026-07-30- Related: [08-component-spec §16](../spec/04-ux/08-component-spec.md) ·[09-plugin-command-palette](../spec/07-plugins/09-plugin-command-palette.md) ·- [04-builtin-commands](../spec/04-ux/04-builtin-commands.md) ·- [04-e2e-test-plan](../spec/06-delivery/04-e2e-test-plan.md) · decision D014-- Updates: removes the standalone command palette surface described in- [08-component-spec §16](../spec/04-ux/08-component-spec.md)+ decision D014## Context-The app shipped two overlapping "find anything" surfaces:--- A **command palette** (Cmd/Ctrl+Shift+P) that lists built-in and plugin- commands, opened from a dedicated top-bar button and a separate overlay.-- A **global search** (Cmd/Ctrl+K) that lists sessions, pages, and settings.+The app shipped two overlapping "find anything" overlays with the same+interaction model: a command palette (Cmd/Ctrl+Shift+P) listing built-in and+plugin commands, and a global search (Cmd/Ctrl+K) listing sessions, pages, and+settings. Keeping both meant duplicated maintenance, a second top-bar button,+and a split mental model for users.## Decision-1. Remove the standalone command palette overlay (`CommandPalette.tsx`) and its- top-bar button.-2. Render the command list (built-in + plugin commands) as a **Commands**- section inside the existing global search dialog (`SearchDialog.tsx`), using- the same `role="listbox"` / `role="option"` semantics and flat option-index- navigation as the other result groups.-3. The `openCommandPalette` shortcut (Cmd/Ctrl+Shift+P, per D014) now opens the- global search dialog, which contains the Commands section.-4. Remove the redundant "Command Palette" entry from the application View menu- (the View menu already has "Search").-5. The command data path is unchanged: `api.searchCommands` and- `runPaletteCommand` (built-in + plugin bridge) are reused by the search- dialog.+Remove the standalone command palette overlay and its top-bar button, and render+the built-in plus plugin command list as a Commands section inside the existing+global search dialog, using the same listbox/option semantics and flat+option-index navigation as the other result groups. The `openCommandPalette`+shortcut (Cmd/Ctrl+Shift+P, per D014) now opens that dialog and is retained so+the keyboard-shortcuts page and plugin command discovery keep working, while+`api.searchCommands` and `runPaletteCommand` remain the unchanged data path. The+redundant View-menu entry goes away because the menu already has Search.## Consequences-- One searchable surface covers sessions, pages, settings, and commands.-- The top bar loses a button; search is the single entry point for discovery.-- `Cmd/Ctrl+Shift+P` still works and now lands on the unified search with the- command list available; muscle memory is preserved.-- `CommandPalette.tsx`, its CSS surface, and the `paletteOpen` state are- removed.-- Plugin command discovery (E2E-023) and disable-removes-contributions (E2E-025)- are re-expressed against the global search.+- One searchable surface covers sessions, pages, settings, and commands, and+ muscle memory for Cmd/Ctrl+Shift+P still lands on commands.+- The top bar loses a button and the palette surface, CSS, and `paletteOpen`+ state are deleted.+- Plugin command discovery and disable-removes-contributions scenarios are+ re-expressed against global search.## Alternatives-### Keep two separate surfaces--Rejected: duplicates interaction logic and UI, adds a second top-bar button, and-forces users to decide which surface holds what.--### Hide commands behind a query in global search--Rejected: the command palette was reachable with an empty query-(Cmd/Ctrl+Shift+P showed all commands).--## References--- `apps/desktop/src/components/SearchDialog.tsx` (Commands section)-- `apps/desktop/src/components/ConversationTopbar.tsx` (button removed)-- `apps/desktop/src/App.tsx` (`openCommandPalette` → opens search)-- `apps/desktop/electron/main/application-menu.ts` (menu item removed)-- `apps/desktop/src/lib/api.ts` (`searchCommands` reused)-- `apps/desktop/src/lib/commands.ts` (`runPaletteCommand` reused)-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-023, E2E-025 updated)+- Keep two surfaces: rejected, it duplicates interaction logic and forces users+ to remember which surface holds what.+- Show commands only for a non-empty query: rejected, the palette listed all+ commands with an empty query, so the Commands section renders then too.diff --git a/docs/adr/0035-surface-os-locale-via-preload.md b/docs/adr/0035-surface-os-locale-via-preload.mdindex 501eea9f1..de9e12eaa 100644--- a/docs/adr/0035-surface-os-locale-via-preload.md+++ b/docs/adr/0035-surface-os-locale-via-preload.md@@ -2,65 +2,36 @@- Status: Accepted- Date: 2026-07-30-- Related: [04-ux/06-settings-ia](../spec/04-ux/06-settings-ia.md) ·- [04-ux/02-i18n-english-first](../spec/04-ux/02-i18n-english-first.md) ·- [04-e2e-test-plan](../spec/06-delivery/04-e2e-test-plan.md) · E2E-091-- Updates: the `window.piDesktop` preload contract in- [api.ts](../..//apps/desktop/src/lib/api.ts)+- Related: [04-ux/06-settings-ia](../spec/04-ux/06-settings-ia.md) · [04-ux/02-i18n-english-first](../spec/04-ux/02-i18n-english-first.md) · [04-e2e-test-plan](../spec/06-delivery/04-e2e-test-plan.md) · E2E-091## Context-The Settings → Basics → Language control offers an **Auto** option that should-follow the user's OS display language. The original implementation resolved-"auto" from the renderer's `navigator.language`.+The Settings → Basics → Language **Auto** option follows the OS display+language, but it resolved "auto" from the renderer's `navigator.language`. In+Electron that value is the embedded browser locale and reports `en-US` even on a+Simplified Chinese system, so Auto chose English and seeded the first paint with+the wrong language. Only the main process can read the real OS locale.## Decision-1. Expose the authoritative OS locale from the preload bridge as a synchronous- field `window.piDesktop.locale`.-2. Add optional `locale?: string` to the `window.piDesktop` type in `api.ts`;- non-Electron contexts do not receive a window creation argument.-3. Resolve "auto" language through a new `resolveOsLocale()` helper in- `lib/app-language.ts` that prefers `window.piDesktop.locale` and falls back- to `navigator.language` / `userLanguage` for non-Electron contexts (e.g.- tests).-4. Seed the initial i18n `lng` in `main.tsx` from `resolveOsLocale()` instead of- `navigator.language`.--This keeps OS-fact resolution in the main process and requires no new IPC-channel (the value is available before first paint, like `platform`).+Expose the authoritative locale through the preload bridge as a synchronous+`window.piDesktop.locale` field: main resolves `app.getLocale()` at window+creation and passes it through `webPreferences.additionalArguments`, which+sandboxed preload reads without importing `app`. `api.ts` types the field as+optional because non-Electron contexts receive no window argument. A new+`resolveOsLocale()` helper in `lib/app-language.ts` prefers the bridge field and+falls back to `navigator.language`, and `main.tsx` seeds i18n `lng` from it. No+IPC channel is needed, and the value is available before first paint like+`platform`.## Consequences-- "Auto" language now matches the real OS display language (e.g. Simplified- Chinese on a Chinese system), and the Auto card shows the detected language- inline ("当前:简体中文").-- Initial i18n language on first paint is correct for the OS locale.-- The `window.piDesktop` preload contract grows one read-only string field.-- Non-Electron contexts (unit tests, potential web builds) fall back to- `navigator.language` and remain functional.+- Auto matches the real OS language, and the Auto card shows the detected one.+- First paint starts in the correct language.+- The `window.piDesktop` contract gains one read-only string; unit tests and web+ builds keep working through the `navigator.language` fallback.## Alternatives-### Keep using `navigator.language`--Rejected: it is the root cause of the misdetection and cannot see the OS-language from the renderer in Electron.--### Add an async IPC call for the OS locale--Rejected: an async round-trip would delay first paint of the correct language-and complicate the synchronous pre-paint setup that already uses `platform`.--## References--- `apps/desktop/electron/main/index.ts` (passes `app.getLocale()` through- `additionalArguments`)-- `apps/desktop/electron/preload/index.ts` (reads the locale argument without- importing `app`)-- `apps/desktop/src/lib/api.ts` (`window.piDesktop.locale` type)-- `apps/desktop/src/lib/app-language.ts` (`resolveOsLocale`,- `resolveAppLanguage`)-- `apps/desktop/src/main.tsx` (initial `lng` from `resolveOsLocale`)-- `apps/desktop/src/pages/SettingsPage.tsx` (Auto card shows detected language)-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-091 added)+- Keep `navigator.language`: it is the root cause and cannot see the OS locale.+- Async IPC call: delays the first paint that a pre-paint value avoids.diff --git a/docs/adr/0036-settings-ia-ai-and-shortcuts-tabs.md b/docs/adr/0036-settings-ia-ai-and-shortcuts-tabs.mdindex 9b507baf4..aaf5ec82c 100644--- a/docs/adr/0036-settings-ia-ai-and-shortcuts-tabs.md+++ b/docs/adr/0036-settings-ia-ai-and-shortcuts-tabs.md@@ -2,89 +2,39 @@- Status: Accepted- Date: 2026-07-30-- Deciders: PI-Desktop core-- Related: D090, D133, ADR 0013, ADR 0026+- Related: D090, D133, D166, ADR 0013, ADR 0026## Context-ADR 0026 froze the Settings directory at five destinations: Basics, Model-configuration, Import, Project archive, and Info. Over time Basics accumulated-six unrelated cards — Appearance, Defaults, Permissions, Context management,-Keyboard shortcuts, and Developer — making the single page long to scan and-burying two conceptually distinct concerns:--1. **Global AI behavior** (the permission mode that governs how autonomously the- agent acts, and context management that governs how the agent compacts its- context) is an AI-runtime concern, not a look-and-feel basic.-2. **Keyboard shortcuts** is a self-contained, frequently referenced surface- that benefits from its own destination, especially now that the global search- dialog and command palette route users to shortcut configuration.+ADR 0026 froze a five-destination Settings directory, but Basics accumulated six unrelated+cards — Appearance, Defaults, Permissions, Context management, Keyboard shortcuts,+Developer — burying global AI behavior, which is a runtime concern, beside theme and+language.## Decision-Keep the full-page Settings shell, Back to app action, search control, rail-metrics, content cards, and theme behavior unchanged. Replace the five--destination rail with seven destinations in this exact order:--1. **Basics** (`general`, Lucide `SlidersHorizontal`) — Appearance and Defaults-2. **全局 AI / AI** (`ai`, Lucide `Sparkles`) — Permissions and Context management-3. **Shortcuts** (`shortcuts`, Lucide `Keyboard`) — Keyboard shortcuts-4. **Model configuration** (`agent`, Lucide `Bot`) — provider studio and default- model-5. **Import** (`import`, Lucide `Download`) — session import-6. **Project archive** (`projects`, Lucide `Archive`) — durable project index-7. **Info** (`about`, Lucide `Info`) — versions, logs, updates, and Developer--Content moves only; no setting is added, removed, or renamed:--- Permissions and Context management cards move from Basics to the new **AI**- destination.-- The Keyboard shortcuts card moves from Basics to the new **Shortcuts**- destination.-- The Developer card moves from Basics to **Info**.-- Basics keeps only Appearance and Defaults.-- Model configuration, Import, Project archive, and their contents are- unchanged.+Keep the Settings shell, Back to app action, search control, rail metrics, content cards,+and theme behavior unchanged, and replace the five-destination rail with seven in this+order: Basics (`general`), AI (`ai`), Shortcuts (`shortcuts`), Model configuration+(`agent`), Import (`import`), Project archive (`projects`), Info (`about`). Permissions and+Context management move from Basics to AI, the Keyboard shortcuts card to Shortcuts, and+Developer to Info, so Basics keeps only Appearance and Defaults and no setting is added,+removed, or renamed. `ai` and `shortcuts` join the `settingsTab` state union and the shared+`SETTINGS_NAV` search index, so Settings search and deep links resolve them and relocated+rows are indexed under their new destination, while provider setup deep links still target+Model configuration.## Consequences-- Basics is shorter and focused on look-and-feel; AI behavior, shortcuts, and- developer controls are each one click away without scrolling a single long- page.-- The frozen five-destination count and order from D133/ADR 0026 is superseded- for the destination count and ordering only; no IPC, host RPC, database,- security, or project-activation contract changes.-- Specs and E2E scenarios that assert the exact five-item rail order must be- updated to the seven-item order, including the assertion that there is "no- Keyboard destination" (now reversed).-- Developer mode moves from Basics to Info; Settings search and the developer-- tools gating behavior are unchanged.-- The shared `settingsTab` union and `SETTINGS_NAV` index grow by two entries;- existing persisted/default tab (`general`) is unaffected.+- Basics is short and look-and-feel only; AI behavior, shortcuts, and developer controls+ are one click away.+- D133/ADR 0026 is superseded for destination count and order only; no IPC, host RPC,+ storage, or security contract changes.+- Specs and E2E scenarios asserting the five-item rail order, including the reversed "no+ Keyboard destination" assertion, must adopt the seven-item order.## Alternatives-### Keep all six cards in Basics--Rejected because the single page is long to scan and groups unrelated concerns-(appearance alongside AI permission policy and shortcut recording).--### Merge AI behavior into Model configuration--Rejected because Model configuration owns *which* provider/model to use (a-connection/identity concern), while permission mode and context compaction are-*runtime behavior* concerns.--### Move Developer to a dedicated Advanced destination--Rejected because a one-card destination is not worth a rail row; Info already-groups system/advanced surfaces (versions, logs, updates) and is the natural-home for developer-tool gating.--## References--- `docs/spec/00-baseline.md`-- `docs/spec/04-ux/01-ui-ia.md`-- `docs/spec/04-ux/06-settings-ia.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `docs/spec/08-meta/decisions-log.md` (D166)+- Keep all six cards in Basics: a long page mixing appearance with AI policy.+- Merge AI behavior into Model configuration: that page owns connection identity, not+ runtime behavior.diff --git a/docs/adr/0037-project-instruction-chain.md b/docs/adr/0037-project-instruction-chain.mdindex 440b93faa..5aa33bb5f 100644--- a/docs/adr/0037-project-instruction-chain.md+++ b/docs/adr/0037-project-instruction-chain.md@@ -8,40 +8,45 @@## Context-PI-Desktop initially loaded only `<project root>/AGENTS.md` at runtime creation.-That omits directory-specific rules in monorepos and provides no compatibility-path for projects that use `CLAUDE.md`.+Loading only `<project root>/AGENTS.md` omits directory-specific rules in+monorepos and offers no path for `CLAUDE.md` projects, while letting the+model-driven sidecar scan the workspace would weaken the boundary that keeps+workspace file access in Electron main and host-core.## Decision1. Electron main resolves instructions only inside the session-bound project- root; it never follows an instruction file whose canonical path escapes that- root.-2. The global file `~/.pi/agent/AGENTS.md` is loaded before all project entries.-3. For every project directory, the first non-empty candidate wins in this- order: `AGENTS.override.md`, `AGENTS.md`, `CLAUDE.md`, `.claude/CLAUDE.md`.-4. Sources are concatenated from root to target directory.-5. The root chain is loaded when the runtime is created.-6. Electron main passes the session-bound project root with runtime launch- metadata and registers it before each prompt or compaction request.+ root and never follows a file whose canonical path escapes it. The global+ `~/.pi/agent/AGENTS.md` loads first: Settings manages that fixed path, and a+ project's `AGENTS.md` is managed from its Projects list-menu action over an+ IPC that accepts only a host-core-registered project root.+2. Per project directory the first non-empty candidate wins:+ `AGENTS.override.md`, `AGENTS.md`, `CLAUDE.md`, `.claude/CLAUDE.md`.+3. Sources concatenate from root to target directory under independent 32 KiB+ UTF-8 budgets for the global file and the project chain, so an oversized+ global file never removes project instructions. A file cut at its budget keeps+ whole UTF-8 characters and gets a notice naming the source with loaded and+ total byte counts, and project files after a truncated one are not loaded.+4. The root chain loads at runtime creation. Before a file-path tool executes,+ the sidecar may request a path-specific chain through the Electron-owned+ `project.instructions.resolve` local proxy and never reads instruction files+ directly. Main registers the session-bound project root before each prompt or+ compaction request, so the proxy resolves against that binding rather than a+ per-file `session.get` RPC.## Consequences-- Repository-wide rules load without a recursive workspace scan.-- Global defaults are editable without a project; project instructions remain- reviewable and versionable in the repository root.-- Nested rules become available only when an agent accesses a matching path.-- Path-specific resolution is best-effort and bounded at two seconds.-- Path preflight records its own duration and cache/fallback markers so- `hostRttMs` continues to describe the actual host tool call.+- Repository-wide rules load without a recursive scan, global defaults stay+ editable without a project, and nested rules appear only when a file tool+ touches a matching path and replace the active chain, so sibling rules cannot+ leak into later calls.+- Path-specific resolution is best-effort and bounded at two seconds; an+ unavailable resolver falls back to the base chain, and preflight keeps its own+ duration and markers so `hostRttMs` still describes the host tool call.## Alternatives-### Load every nested instruction file at startup--Rejected. Large monorepos could inject unrelated rules and consume the model-context before the task identifies a relevant directory.--### Let the sidecar scan the workspace--Rejected. The sidecar executes model-directed paths.+- Load every nested file at startup: rejected, monorepos would inject unrelated+ rules before the task identifies a directory.+- Let the sidecar scan the workspace: rejected, discovery stays in main so+ containment is explicit for model-directed paths.diff --git a/docs/adr/0038-plugin-mcp-bridge.md b/docs/adr/0038-plugin-mcp-bridge.mdindex ec1947784..a8020334f 100644--- a/docs/adr/0038-plugin-mcp-bridge.md+++ b/docs/adr/0038-plugin-mcp-bridge.md@@ -2,71 +2,65 @@- Status: Accepted- Date: 2026-07-31-- Related: [Plugin manifest schema](../spec/07-plugins/02-plugin-manifest-schema.md),- [Plugin security](../spec/07-plugins/04-plugin-security.md),- [ADR 0008](0008-plugin-runtime-isolation-target.md),- [ADR 0142](0142-allow-non-loopback-http-mcp.md)+- Related: [Plugin manifest schema](../spec/07-plugins/02-plugin-manifest-schema.md), [Plugin security](../spec/07-plugins/04-plugin-security.md), [ADR 0008](0008-plugin-runtime-isolation-target.md), [ADR 0142](0142-allow-non-loopback-http-mcp.md)## Context-The plugin roadmap listed an "MCP plugin type" with nothing behind it. A plugin-that wanted to expose an MCP server's tools had to reimplement each one as a-plugin agent tool and proxy the traffic itself — duplicated work, and the-proxying happened in plugin code the host cannot inspect.+The plugin roadmap listed an "MCP plugin type" with nothing behind it, so a plugin+that wanted an MCP server's tools had to reimplement each one as a plugin agent+tool and proxy the traffic inside plugin code the host cannot inspect. The agent+already routes plugin tools through the permission gate and audit path, and MCP+servers are two different things under one name: a local executable we spawn and a+remote endpoint we send arguments to, which fail and leak differently.## Decision-1. MCP servers are **declared in the manifest**, never opened at runtime.-2. The two transports carry **separate permissions**: `mcp.server.local` for- stdio, `mcp.server.remote` for HTTP.-3. The client lives in `apps/desktop/electron/main/plugin-mcp.ts` and speaks- protocol `2025-06-18`: `initialize`, `tools/list`, `tools/call`.-4. Discovered tools register into the **existing** plugin tool map as- `plugin_<pluginIdSafe>_<serverId>_<toolName>`, so no new routing exists- anywhere between the model and the server.-5. Every discovered tool is registered at `risk: "medium"`.-6. Credentials resolve **only** from the plugin's own settings through `{- "setting": "<key>" }` (D018).+1. MCP servers are declared in the manifest, never opened at runtime:+ `contributes.mcpServers` carries `{ id, label?, transport }` plus exactly one+ transport's fields, `command` / `args` / `env` for `stdio` or `url` / `headers`+ for `http`, and a manifest that mixes them fails validation in both host-core+ and the SDK validator.+2. The transports carry separate permissions, `mcp.server.local` for stdio and+ `mcp.server.remote` for HTTP, because running a local binary and shipping+ arguments to a third party are different consents.+3. The client lives in Electron main and speaks MCP `2025-06-18` through+ `initialize`, `tools/list`, and `tools/call`, using NDJSON over stdio pipes or+ streamable HTTP with SSE responses. Handshake, call, line, server-count,+ tool-count, page, and traversal budgets are bounded, and a server that breaks a+ bound is refused rather than truncated; host-core's dispatch deadline covers the+ whole leg, so the client reports its own timeout first. Connections are lazy and+ teardown follows unload.+4. Discovered tools register into the existing plugin tool map as+ `plugin_<pluginIdSafe>_<serverId>_<toolName>`, so no new routing exists between+ the model and the server.+5. Every discovered tool registers at `risk: "medium"`, because a risk level+ declared by the inspected third-party server is not evidence.+6. Credentials resolve only from the plugin's own settings through+ `{ "setting": "<key>" }` (D018). A stdio child receives the declared values,+ `PI_PLUGIN_ID`, and a fixed set of temp, locale, and toolchain variables rather+ than the host environment that holds provider keys, with the Unix PATH taken+ from the login shell (D600). Bare `npx` / `uvx` resolve to real binaries, and a+ Windows bare `python` skips the Microsoft Store alias (D624, issue #789).+ `command` must be a bare PATH name or stay inside the plugin directory, and+ `url` may use `http` or `https`, with non-loopback HTTP subject to ADR 0142 and+ the plugin network allowlist.## Consequences-- A plugin ships an MCP server as a manifest entry, and its tools appear to the- agent with correct namespacing, auditing, and timeouts.-- Reviewing what a plugin can reach means reading its manifest: every endpoint- and executable is declared text, not a runtime decision.-- Catalog size is a protocol guard, not a prompt budget: a server with 300 tools- contributes all 300, because MCP tools reach the model as deferred on-demand- entries behind `ToolSearch` and only the prompt block that advertises them is- capped.-- Because MCP tools sit in the same map as hand-written plugin tools, disabling- the plugin removes both, and a crashed plugin loses both.-- A remote server sees tool arguments.+- A plugin ships an MCP server as a manifest entry, and its tools reach the agent+ with correct namespacing, auditing, and timeouts.+- Reviewing what a plugin can reach means reading its manifest, where every+ endpoint and executable is declared text rather than a runtime decision.+- Catalog size is a protocol guard, not a prompt budget, because MCP tools reach+ the model as deferred on-demand entries behind `ToolSearch`.+- Disabling or crashing the plugin removes its MCP tools as well, and a remote+ server still sees every argument sent to it.## Alternatives-### stdio only--Rejected. Hosted MCP endpoints are common, and stdio-only would push plugin-authors to wrap them in a local shim process — an extra process plus an-unreviewable proxy, which is worse on both counts than a declared HTTP(S) URL.--### A separate `type: "mcp"` plugin kind--Rejected. It would need its own lifecycle, its own management UI, and its own-tool routing.--### Let the plugin process own the MCP connection--Rejected. The connection would then live behind the plugin's own code, outside-the broker's view, so the host could neither cap the tool set nor keep-credentials out of the plugin's reach.--### Trust the server's declared tool risk--Rejected. Risk drives host-core's confirmation flow.--## Amendment: stdio launcher resolution--GUI launches inherit a PATH that may not include fnm/nvm/uv shims. Windows `npx`-from the official Node installer is `npx.cmd` (plus a Git-Bash `npx` script),-which `spawn({ shell: false })` cannot start.+- stdio only: rejected, hosted endpoints are common and would push authors into+ extra local shim processes the host cannot review.+- A separate `type: "mcp"` plugin kind: rejected, it would duplicate lifecycle,+ management UI, and tool routing.+- Let the plugin process own the connection: rejected, the host could then neither+ cap the tool set nor keep credentials out of the plugin's reach.diff --git a/docs/adr/0039-plugin-skills-activation-and-devkit.md b/docs/adr/0039-plugin-skills-activation-and-devkit.mdindex 9a6dacf9f..b200ad80c 100644--- a/docs/adr/0039-plugin-skills-activation-and-devkit.md+++ b/docs/adr/0039-plugin-skills-activation-and-devkit.md@@ -2,76 +2,46 @@- Status: Accepted- Date: 2026-07-31-- Related: [Plugin developer experience](../spec/07-plugins/10-plugin-devex.md),- [Plugin permissions matrix](../spec/07-plugins/13-plugin-permissions-matrix.md),- [ADR 0008](0008-plugin-runtime-isolation-target.md),- [ADR 0037](0037-project-instruction-chain.md),- [ADR 0040](0040-plugin-resident-services-and-message-bus.md)+- Related: D174, ADR 0008, ADR 0037, ADR 0040## Context-`contributes.skills` has been part of manifest v1 since R1: `validateManifest`-accepts it and `examples/plugins/hello` ships a skill file. Nothing read it.+`validateManifest` accepted `contributes.skills` since manifest v1, but nothing+read it, so declaring a skill had no effect, and a `.piplug` could be installed but+not produced — no templates, no pre-install validation, no packaging loop. Users+were asked to write plugins without scaffold, run, inspect, and package.## Decision-1. **Skills reach the model as a permission-gated catalog it can load from.**- `PluginRuntime` indexes each declared skill file at load time, only for- plugins granted `agent.prompt.inject`, and only through the same containment- guard as the gated `fs` APIs.-2. **Prompt order is host skills, then plugin skills, then project- instructions.** Later text carries more weight, so a user's own instruction- files keep the last word and an installed plugin can refine the built-in- guidance but never the reverse.-3. **Catalog changes update an idle runtime's skills section.** The- chronological system-transcript decision supersedes the original digest-based- retirement: enabling a plugin, revoking `agent.prompt.inject`, or renaming a- skill appends a section update before the next request.-4. **Plugin authoring ships as a first-party devkit, not as a plugin.**- `@pi-desktop/plugin-devkit` owns scaffold, check and pack; three surfaces- share that one implementation — the `pi-plugin` CLI, the `PluginScaffold` /- `PluginCheck` / `PluginPack` agent tools served from Electron main, and the- plugins-page template action.-5. **The built-in plugin-development skill activates only for plugin- workspaces** — a `manifest.json` at the workspace root, or a loaded plugin- directory inside it.-6. **Hot reload may not widen a permission set.** A watched development plugin- reloads on save, but the reload reads the manifest first: permissions outside- the set approved when the folder was picked stop the reload with an error- telling the user to load the plugin again.+`PluginRuntime` indexes each declared skill file at load time, only for plugins+granted `agent.prompt.inject` and through the gated `fs` containment guard, and the+system prompt carries a `# Skills` section of one line per skill (id, name,+applicability) whose bodies the model pulls on demand with the `Skill` tool served+from Electron main, so a 128 KiB document costs nothing until it is read (D174).+Prompt order is host skills, plugin skills, then project instructions, so project+rules keep the last word, and enabling a plugin, revoking `agent.prompt.inject`, or+renaming a skill appends a section update to an idle runtime. Authoring ships as+`@pi-desktop/plugin-devkit` — scaffold, check, pack — shared by the `pi-plugin`+CLI, the `PluginScaffold` / `PluginCheck` / `PluginPack` agent tools, and the+plugins-page template action, and its built-in development skill activates only for+a workspace holding a `manifest.json` or a loaded plugin. A hot reload reads the+manifest first, so permissions beyond the set approved when the folder was picked+stop it with an error asking the user to load the plugin again, while grants still+follow the manifest downwards.## Consequences-- A skill file is now executable surface.-- `check` passing implies install will pass, because the devkit reproduces the- rules host-core enforces (store-only entries, 2000 files, 50 MB, no symlinks,- no `.git`/`node_modules`).-- Skill files are read when the model asks for one rather than every prompt, so- an edit takes effect on the next `Skill` call and a session that needs no- skill reads nothing.-- A failed hot reload leaves the plugin unloaded but still watched, so the next- save recovers it. host-core's registry still reports `ready` in that window:- it has no RPC for a runtime-side load failure, so the reload reports itself- through a toast and `pluginChanged`, exactly as a plugin crash does.-- Skill front-matter parsing lives in the plugin SDK (`parseSkillFrontmatter`),- shared by the runtime registry, the built-in skills and the devkit's `check`.+- A skill file is executable surface: `agent.prompt.inject` is the only, high-risk+ gate, and install review shows it.+- `check` reproduces the host rules, so passing implies install will pass; those+ limits live in TypeScript and Rust and must move together.+- Bodies apply on the next `Skill` call while catalog metadata is indexed at load+ time, so a rename needs a reload, and a failed reload leaves the plugin unloaded+ but watched, reporting through a toast and `pluginChanged` like a crash.## Alternatives-### Ship plugin authoring as a bundled plugin--Rejected. A plugin cannot produce a `.piplug`: there is no archive API in-`HOST_API_ALLOWLIST` and adding one would hand every plugin a zip writer.--### Inject the plugin-development skill into every session--Rejected. A plugin-authoring primer in every system prompt is pure waste for-users who will never write one.--### Share the 32 KiB instruction-chain budget with skills--Rejected. Skills come from third-party code and instructions come from the user.--### Reload with the previously granted permissions regardless of the manifest--Rejected. The grant set was approved against a specific manifest.+- Authoring as a bundled plugin: no archive API in `HOST_API_ALLOWLIST`, and+ scaffolding would need `fs.write.workspace`.+- Share the instruction-chain budget with skills: plugin content could displace a+ project's own rules.diff --git a/docs/adr/0040-plugin-resident-services-and-message-bus.md b/docs/adr/0040-plugin-resident-services-and-message-bus.mdindex 14ab5429b..ad832c398 100644--- a/docs/adr/0040-plugin-resident-services-and-message-bus.md+++ b/docs/adr/0040-plugin-resident-services-and-message-bus.md@@ -3,87 +3,44 @@- Status: Accepted- Date: 2026-07-31- Related: [Plugin lifecycle](../spec/07-plugins/05-plugin-lifecycle.md),- [Plugin IPC and host services](../spec/07-plugins/12-plugin-ipc-and-host-services.md),[ADR 0008](0008-plugin-runtime-isolation-target.md)## Context-Two roadmap items were blocked on the same missing pieces.+A plugin could only work when something called into it, so watchers, pollers,+and sync workers had no supported home, and the host could neither report nor+restart timers started inside `onLoad`. Inter-plugin messaging was equally+missing: `pi.events.on` / `off` were no-ops, and the wire protocol carried only+request/response frames initiated by the child.## Decision-### One new frame--The broker gains a one-way parent→child frame:--```text-{ t: "event", event, ... } // no reply, no backpressure-```--`bus.message` is its first user. The same frame finally implements-`pi.events.on` / `off`, which now sees the raw event stream.--### Resident services--1. A service is **declared** (`contributes.services`, at most 4 per plugin) and- gated on `background.service`.-2. The **broker decides when it runs**: `start` after `onLoad` completes (5s- budget), `stop` before `onUnload`.-3. A service lives in the plugin's `utilityProcess` (ADR 0008), so a crash takes- it down with the process.-4. After the last attempt the plugin stays `failed`.-5. Manual enable / disable outranks the supervisor: an explicit user action- cancels the pending timer and clears the attempt counter.--### Message bus--1. Traffic is **declared in the manifest**: `contributes.bus.publish` lists- concrete topics, `contributes.bus.subscribe` lists patterns.-2. Topics are dot-separated segments (`[a-zA-Z0-9][a-zA-Z0-9_-]*`, ≤8 segments,- ≤128 chars).-3. **Routing lives in the broker.** A message carries `topic`, `from`,- `payload`, and a host-assigned `at`.-4. Caps: 64KB per payload, 16 subscriptions per plugin, 100 publishes per- rolling 10s window; over-cap calls fail `LIMIT_EXCEEDED` / `RATE_LIMITED` and- are audited with the topic.-5. A payload is **data, never capability**.+The broker gains a one-way parent→child `event` frame, which carries the message+bus and finally implements `pi.events.on` / `off`. A resident service is+declared in `contributes.services`, gated on `background.service`, and run by+the broker: started after `onLoad`, stopped before `onUnload`, living in the+plugin's `utilityProcess`, where a crash restarts the whole plugin under+supervised backoff until it stays `failed`. Bus traffic must be declared in+`contributes.bus.publish` / `contributes.bus.subscribe`, since a granted+`bus.publish` or `bus.subscribe` permission alone routes nothing, and topics are+dot-separated pattern segments. The broker alone routes messages by `topic`,+excluding the publisher from its own fan-out, enforces payload, subscription,+and rate caps that fail `LIMIT_EXCEEDED` / `RATE_LIMITED`, and treats a payload+as data that grants a subscriber no new capability. Manual enable and disable+outrank supervision by cancelling timers and clearing attempt counters.## Consequences-- A background worker is now a first-class, visible, supervised thing: the user- sees it running, sees it restart, and sees it give up.-- Restarting the plugin rather than the service is coarse — a crash re-runs- `onLoad` — but it is the only honest unit, because the crash already destroyed- the process the service lived in.-- The 5-attempt ceiling means a genuinely broken service stops retrying.-- Declared topics make plugin-to-plugin coupling reviewable, and let the host- reject undeclared traffic without knowing anything about payload semantics.-- Because the publisher is excluded from its own fan-out, a plugin cannot use- the bus as an internal event emitter — it must use ordinary function calls,- which is what it should have done anyway.+- A background worker becomes visible and supervised: the user sees it run,+ restart, or give up, with per-service state over `plugin/services`.+- Restarting the plugin rather than the service is coarse, but the crash that+ killed the service already destroyed its process.+- Declared topics keep plugin coupling reviewable, and any subscriber with a+ matching pattern sees the topic, so secrets do not belong on the bus.## Alternatives-### Let plugins start their own timers and call it a service--Rejected. That is the status quo.--### Restart the service in place instead of the plugin--Rejected. The service runs inside the plugin's process; if it crashed the-process, there is no in-place to restart into.--### Unlimited restarts--Rejected. A crash loop with backoff still burns CPU forever and hides the-failure behind a chip that flickers between `starting` and `failed`.--### An open pub/sub with permissions only--Rejected. `bus.publish` would then mean "talk to every plugin about anything",-which is unreviewable.--### Direct plugin-to-plugin RPC--Rejected. It creates hard dependencies between independently installable,-independently versioned plugins, and it hands one plugin a handle on another.+- Let plugins start their own timers: rejected, the host cannot stop, report, or+ restart work it does not know about.+- An open pub/sub with permissions only: rejected, a grant would mean "talk to+ every plugin about anything" and be unreviewable.diff --git a/docs/adr/0041-bounded-host-runtime-and-persistence-outbox.md b/docs/adr/0041-bounded-host-runtime-and-persistence-outbox.mdindex 0ad6a6189..a5abff643 100644--- a/docs/adr/0041-bounded-host-runtime-and-persistence-outbox.md+++ b/docs/adr/0041-bounded-host-runtime-and-persistence-outbox.md@@ -5,37 +5,40 @@## Context-The Rust host previously spawned an unbounded Tokio task for every RPC and could-start an unbounded number of shell processes. During a local burst this produced-`Resource temporarily unavailable`, followed by concurrent host restarts and-writes to a destroyed stdio pipe.+The Rust host spawned an unbounded Tokio task per RPC and unbounded shell+processes. A local burst produced `Resource temporarily unavailable`, concurrent+restarts, and writes to a destroyed stdio pipe, so persistence errors hid the+original failure.## Decision-Host-core owns a bounded admission budget for RPC and tool execution. Tool-classes have independent global limits, every session has a limit, and the queue-is finite.--Electron host supervision is single-flight and generation-aware. A stale host-generation cannot issue notifications or accept new RPC writes.+Host-core bounds RPC and tool admission: independent global limits per tool+class, a per-session limit, a finite queue, bounded backoff on transient spawn+failures, no retry of started commands, and reaping of timed-out children before+permits are released.++Electron supervision is single-flight and generation-aware, so a stale generation+cannot notify or accept RPC writes. Appends pass through an Electron-main-owned+file-backed outbox flushed sequentially after a successful handshake, and the+handshake **awaits** that drain before the host is ready, so a cold `session.get`+cannot race a queued row (D327). Append is idempotent by message id, and a+colliding id owned by another session is remapped to `{sessionId}:{id}` before+the JSONL write (D444). `UNIQUE constraint failed: messages.id` is an ack, a+`PERMISSION_DENIED:` append is dropped (D597), and an unclassifiable refusal is+retried on bounded backoff and then quarantined into an application-owned+dead-letter file (D656).## Consequences-- A burst is rejected or backpressured instead of exhausting process resources.-- One failed host does not create a restart storm or hundreds of stale-pipe- errors.-- SQLite ownership remains exclusively in host-core.-- The application data directory gains one small recovery outbox file.-- A missing sessions row is restored from the live JSONL (or created as a stub- under the same id) so a queued outbox can drain; `session.delete` drops that- session's outbox entries so a stub cannot resurrect a deleted conversation- (D318).+- A burst is backpressured instead of exhausting process resources, and one+ failed host no longer causes a restart storm.+- SQLite ownership stays in host-core; the data directory gains one small outbox+ file, and a missing sessions row is restored from the live JSONL or created as+ a stub that `session.delete` clears (D318).-## Alternatives rejected+## Alternatives-- Raising the restart count: masks the resource leak and amplifies the crash- loop.+- Raise the restart count: masks the leak and amplifies the crash loop.- A semaphore only around `Bash`: leaves RPC, plugin, read, and persistencefan-out unbounded.-- In-memory-only persistence buffering: loses messages if Electron exits before- host recovery.+- In-memory-only buffering: loses messages if Electron exits before host recovery.diff --git a/docs/adr/0042-message-scoped-inline-review-cards.md b/docs/adr/0042-message-scoped-inline-review-cards.mdindex 46cf78e21..a768a2a30 100644--- a/docs/adr/0042-message-scoped-inline-review-cards.md+++ b/docs/adr/0042-message-scoped-inline-review-cards.md@@ -2,24 +2,24 @@- Status: Superseded by ADR 0043- Date: 2026-08-02-- Related: [01-ui-ia](../spec/04-ux/01-ui-ia.md) ·- [08-component-spec](../spec/04-ux/08-component-spec.md) ·- [09-interaction-patterns](../spec/04-ux/09-interaction-patterns.md) ·- [E2E-057](../spec/06-delivery/04-e2e-test-plan.md)+- Related: [01-ui-ia](../spec/04-ux/01-ui-ia.md) · decision D451 · E2E-057- Supersedes: D140's global transcript Review changes entry## Context-The transcript previously rendered one session-owned Review changes command at-the bottom of the chat.+One session-owned Review changes command summarized the whole dirty working+tree, detached from the Write/Edit row that caused the change.## Decision-1. A successful workspace Write/Edit row may render one compact- `InlineReviewCard` immediately after the row inside the same activity- disclosure. The card is scoped by the workspace path returned in that tool- result, so unrelated files and other sessions cannot appear beside it.+Render one compact `InlineReviewCard` after a successful workspace Write/Edit+row, scoped by the workspace path in that tool result and fed by the existing+bounded Git diff, with no new renderer-owned diff or ownership map.## Consequences-Superseded (Superseded by ADR 0043). The full record is in git history.+- Review stayed next to the operation that produced it, without a panel tab.+- A card tracked the live working-tree diff for its path.++Superseded by [ADR 0043](0043-message-owned-review-snapshots-and-rollback.md),+which made review state message-owned.diff --git a/docs/adr/0043-message-owned-review-snapshots-and-rollback.md b/docs/adr/0043-message-owned-review-snapshots-and-rollback.mdindex 65ebe4473..301e7ef58 100644--- a/docs/adr/0043-message-owned-review-snapshots-and-rollback.md+++ b/docs/adr/0043-message-owned-review-snapshots-and-rollback.md@@ -3,62 +3,56 @@- Status: Accepted- Date: 2026-08-02- Amended: 2026-10-22-- Related: [03-tools-and-permissions](../spec/03-runtime/03-tools-and-permissions.md) ·- [04-data-storage](../spec/03-runtime/04-data-storage.md) ·- [06-host-rpc-protocol](../spec/03-runtime/06-host-rpc-protocol.md) ·- [08-component-spec](../spec/04-ux/08-component-spec.md) ·- [E2E-057](../spec/06-delivery/04-e2e-test-plan.md)- Supersedes: ADR 0042's Git-dependent review source, D098, and D179-- Amended by: [ADR 0087](0087-line-anchored-edit-contract.md) (`Edit` may now- record a move as two entries, and a rollback invalidates session edit- snapshots for the path)+- Amended by: [ADR 0087](0087-line-anchored-edit-contract.md)+- Related: [03-tools-and-permissions](../spec/03-runtime/03-tools-and-permissions.md) · [06-host-rpc-protocol](../spec/03-runtime/06-host-rpc-protocol.md) · [E2E-057](../spec/06-delivery/04-e2e-test-plan.md)## Context-The previous Review implementation reconstructed each card from the current Git-working tree. A commit therefore removed the evidence for an earlier tool-message, and a later edit to the same path could make an old message appear to-describe work it never performed.+The previous Review implementation rebuilt each card from the current Git working+tree, so a commit removed the evidence for an earlier tool message and a later+edit to the same path could make an old message describe work it never performed.+There was no safe way to restore one message's previous file content, and review+is a conversation feature, so its evidence must belong to the message that+produced it.## Decision-1. After normal path authorization, before any `Write` or `Edit`, host-core+1. After normal path authorization and before any `Write` or `Edit`, host-corecaptures the previous file bytes in a session-scoped snapshot outside the- workspace.-2. The renderer derives `ReviewChangeCard` and the Review panel's chronological- history from persisted tool messages only.-3. `review.rollback({sessionId, snapshotId})` is a host-owned operation.-4. Snapshot storage is bounded and session-owned:- `<data_dir>/review-changes/<sessionId>/<snapshotId>/{before,meta.json}`.-5. Failed, denied, sensitive, or unresolvable operations do not create review- records.+ workspace, and a successful workspace, scratch, visualization, or approved+ external mutation writes bounded `details.review` evidence into the tool+ result with snapshot and message ids, path, operation, status, counts, hunks,+ rolled-back state, and reversibility.+2. The renderer derives `ReviewChangeCard` and the Review panel history from+ persisted tool messages only, never from a current Git diff, and a+ review-backed `Write`/`Edit` renders as one tool-level row that stays visible+ after commit, workspace switching, and restart.+3. `review.rollback({sessionId, snapshotId})` is host-owned: it verifies that the+ current file hash equals the recorded post-tool hash, returns `conflict`+ without touching the file otherwise, restores the previous bytes or removes a+ created file, and persists `state: "rolledBack"`.+4. Snapshots are session-owned and bounded, removed with the session and swept at+ startup for missing sessions, while forked transcripts keep their evidence but+ mark rollback unavailable.+5. Failed, denied, sensitive, or unresolvable operations create no record, and+ non-workspace snapshots are readable evidence rather than path grants, so they+ are non-reversible.## Consequences-- Committing after a tool no longer makes its review number or card disappear.-- Every visible diff is tied to the exact message that produced it, including- additions, deletions, and modifications.+- Committing no longer makes a review number or card disappear, and every diff+ is tied to the message that produced it.- Rollback is explicit, idempotent, and refuses to overwrite later work.-- Review no longer promises to describe unrelated shell mutations; structured- Write/Edit results are the durable review boundary.-- Snapshot bytes add host-owned local storage, bounded by file and diff caps.--## Alternatives rejected--- **Keep reading Git HEAD:** commits erase the evidence and cannot identify the- message responsible for a later same-path edit.-- **Store only a renderer patch:** the renderer cannot safely restore files, and- the patch would be lost on restart or session reload.-- **Rollback unconditionally:** it could overwrite a user's later edit or an- external change, so the post-tool hash guard is mandatory.+- Review covers structured `Write`/`Edit` results rather than unrelated shell+ mutations, and snapshot bytes add bounded host-owned storage.## Round review reader amendment-The native Review panel additionally groups persisted changes by user-conversation round and execution root/path. Latest means the newest user round-with recorded changes, not the most recently arriving tool result.--New snapshots retain bounded 1/3/5-line context hunks next to the existing-`before` rollback snapshot and optional execution-root metadata.-`review.context` reads these immutable hunks only; no full after-image cache is-created.+The native Review panel groups persisted changes by user conversation round and+execution root, where latest means the newest user round with recorded changes+and not the most recently arriving tool result, and delegate ancestry plus the+Host message-turn index preserve ownership of late results. New snapshots retain+bounded context hunks read through `review.context`, and the execution root is+provenance rather than permission, so rollback cannot write into another+checkout.diff --git a/docs/adr/0044-session-bound-project-instruction-preflight.md b/docs/adr/0044-session-bound-project-instruction-preflight.mdindex 4b46d6c43..fdef0cc54 100644--- a/docs/adr/0044-session-bound-project-instruction-preflight.md+++ b/docs/adr/0044-session-bound-project-instruction-preflight.md@@ -2,42 +2,30 @@- Status: Accepted- Date: 2026-08-02-- Related: [ADR 0037](0037-project-instruction-chain.md) ·- [Agent runtime](../spec/03-runtime/02-agent-runtime.md) ·- [Logging](../spec/03-runtime/09-logging-and-observability.md)+- Related: [ADR 0037](0037-project-instruction-chain.md)## Context-Path-scoped instruction loading ran before every file tool. The resolver lived-in Electron main, but it first called host-core `session.get` to rediscover the-project root.+Path-scoped instruction loading ran before every file tool. Its resolver lived in+Electron main but first called host-core `session.get` to rediscover the project+root, so a slow or congested host delayed an otherwise local file operation inside+the generic host round-trip measurement.## Decision-1. Electron main derives the project root from the host-owned session record- during runtime launch and passes it as launch metadata.-2. Electron main registers that root on the sidecar wrapper before each prompt- or compaction request.-3. The sidecar keeps a per-prompt claim map keyed by the registered root and- target directory.-4. Tool timing reports instruction preflight separately from `hostRttMs`, with- cache-hit and base-fallback markers.+Electron main derives the project root from the host-owned session record at runtime+launch and registers it on the sidecar wrapper before each prompt or compaction+request. A reverse `project.instructions.resolve` request uses that binding and+ignores any root supplied by sidecar payload. The sidecar keeps a per-prompt claim+map keyed by the registered root and target directory, reuses both successful+results and the best-effort fallback for later tools in the same prompt, and clears+the map before the next prompt so edits stay visible across messages. Tool timing+reports preflight separately from `hostRttMs`.## Consequences-- File-tool preflight no longer adds a host-core `session.get` round trip.-- Repeated file tools in one directory avoid duplicate resolver IPC and file- discovery while preserving cross-message freshness.-- The main-process containment boundary from ADR 0037 remains explicit: the- sidecar selects only a target path, while Electron main owns the root.-- A resolver timeout or host failure remains best-effort and falls back to the- base chain without carrying a sibling directory's instructions.--## Alternatives rejected--- **Cache instruction chains across all prompts:** risks stale rules after an- instruction file changes and requires file-watch or stat invalidation.-- **Trust a project root sent by the sidecar:** weakens the session-bound- containment boundary and lets model-directed input choose the scan root.-- **Keep the per-file `session.get`:** preserves an avoidable host dependency on- the hottest file-tool preflight path.+- Preflight no longer adds a `session.get` round trip, and repeated tools in one+ directory skip duplicate resolver IPC.+- The ADR 0037 boundary holds: the sidecar picks only the target path.+- A resolver timeout still falls back to the base chain without borrowing a sibling+ directory's instructions.diff --git a/docs/adr/0045-bash-inherits-user-login-path.md b/docs/adr/0045-bash-inherits-user-login-path.mdindex 7310f9751..79fc97071 100644--- a/docs/adr/0045-bash-inherits-user-login-path.md+++ b/docs/adr/0045-bash-inherits-user-login-path.md@@ -2,53 +2,37 @@- Status: Accepted (amended 2026-09-20, D600 / issue #571)- Date: 2026-08-02-- Related: [D084](../spec/08-meta/decisions-log.md) ·- [D181](../spec/08-meta/decisions-log.md) ·- [Tools and permissions](../spec/03-runtime/03-tools-and-permissions.md)+- Related: D084, D181## Context-The Bash tool runs agent commands through `bash -lc` (D084). A login bash-sources only the bash profile, so on macOS — where the default shell is zsh and-toolchains like nvm, pnpm, and Homebrew are initialized in `~/.zshrc` /-`~/.zprofile` — commands cannot resolve `node`, `npm`, `pnpm`, or anything else-that only the user's own shell exports.+The Bash tool runs agent commands through `bash -lc` (D084), which sources only+the bash profile. On macOS, where zsh initializes nvm, pnpm, and Homebrew in+`~/.zshrc` / `~/.zprofile`, commands cannot resolve anything only the user's own+shell exports, and a Finder/Dock launch reduces the environment to a minimal GUI+PATH.## Decision-1. On Unix, the first Bash call probes the user's login shell for its PATH:- `$SHELL` (fallback `/bin/zsh` → `/bin/bash` → `/bin/sh`) runs `-lic 'printf- %s "$PATH"'` — `-l` sources login files, `-i` sources the interactive rc —- with a 5s bound so a wedged rc cannot stall the tool.-2. The probed PATH is cached per process (`OnceLock`) and injected into every- Bash subprocess via `cmd.env("PATH", ...)`.-3. The probe is strictly best-effort: on failure (no `$SHELL`, non-executable,- non-zero exit, timeout) the host PATH is used unchanged.-4. Agent commands remain POSIX bash; only the child environment's `PATH` is- enriched.+On Unix the first Bash call probes the user's login shell for its PATH — `$SHELL`+(fallback `/bin/zsh` → `/bin/bash` → `/bin/sh`) running+`-lic 'printf %s "$PATH"'` under a time bound, keeping only the last stdout line+— and caches it per process, injecting it into every Bash subprocess via+`cmd.env("PATH", ...)`. The probe is best-effort: any failure leaves the host PATH+unchanged, and Windows keeps `bash -c` with the host environment. Agent commands+remain POSIX bash; only the child PATH is enriched.## Consequences- `node`/`npm`/`pnpm`, Homebrew tooling, and other login-shell exports resolve- inside Bash tool calls, matching what a fresh terminal offers.-- `bash -lc` still re-runs the bash profile at startup; conda/brew hooks may- prepend, dedupe, or reorder entries — the injected login PATH remains the base- the user's bash profile builds on.-- One bounded subprocess per process lifetime (the probe) is the entire- overhead; every later Bash call is cache-only.-- A slow or interactive-only user rc degrades gracefully to the previous- behavior instead of failing the tool.-- Stdio MCP servers spawned from Electron main use the same login-shell PATH- (D600 / issue #571), because they share the Finder/Dock GUI PATH problem and- cannot reuse the host-core probe.--## Alternatives rejected--- **Run commands in `$SHELL` instead of bash:** breaks the D084 contract that- agent commands are POSIX bash; zsh differences (`$path` array, echo/glob- semantics) would silently fork behavior.-- **Source rc files from the wrapper command:** fragile — the command line would- have to special-case every shell's rc grammar, and injected prefixes would- appear in every result.-- **Bundle a default PATH in the host:** cannot know the user's toolchain;- replicates the Finder-launch problem in disguise.+ inside Bash calls, matching a fresh terminal.+- `bash -lc` still re-runs the bash profile, so conda/brew hooks may reorder+ entries on top of the injected login PATH.+- Stdio MCP servers from Electron main use the same login-shell PATH (D600 /+ issue #571), since they share the Finder/Dock GUI PATH problem.++## Alternatives++- Run commands in `$SHELL`: breaks the D084 POSIX-bash contract.+- Source rc files from the wrapper command: each shell's rc grammar would need a+ special case.diff --git a/docs/adr/0046-categorized-process-logs.md b/docs/adr/0046-categorized-process-logs.mdindex 259e61faa..df7992b52 100644--- a/docs/adr/0046-categorized-process-logs.md+++ b/docs/adr/0046-categorized-process-logs.md@@ -2,45 +2,35 @@- Status: Accepted; timing-specific clauses superseded by ADR 0212- Date: 2026-08-02-- Related: [D082](../spec/08-meta/decisions-log.md) ·- [D182](../spec/08-meta/decisions-log.md) ·- [D183](../spec/08-meta/decisions-log.md) ·- [ADR 0212](0212-remove-diagnostic-timing-log-streams.md) ·- [Logging and observability](../spec/03-runtime/09-logging-and-observability.md)+- Related: D082, D182, D183, ADR 0212## Context-The M5 logger reduced unbounded growth by keeping app, host, and agent output in-three rotating files. In practice, normal session activity, tool timing,-provider diagnostics, and lifecycle noise still accumulated in the same file,-which made a single failure expensive to trace.+The M5 logger bounded growth by splitting app, host, and agent output into three+rotating files, but session activity, tool timing, provider diagnostics, and+lifecycle noise still shared one file, so tracing a single failure meant scanning+everything. Child stderr also arrived in arbitrary chunks and Rust tracing colors+were persisted as escape sequences.## Decision-1. Keep `app`, `host`, and `agent` as the top-level local log channels, but- write each channel to a directory of focused category files:- `logs/<channel>/<category>.log`.-2. Main-process call sites declare an explicit category.-3. Add the category to every NDJSON record.-4. Apply the existing 5 MB / two rotated files policy independently to every- category file.+Keep `app`, `host`, and `agent` as top-level channels but write each into+`logs/<channel>/<category>.log`, with main-process call sites declaring an+explicit category, host and agent stderr classified by marker, timing records+under `timing`, and unknown output under `runtime`. Every NDJSON record carries+the category, child stderr is buffered by line, UTF-8 is decoded at the stream+boundary, and ANSI is stripped before writing; the 5 MB / two rotated files+policy applies per category file, rotation and disk failures stay non-fatal, and+legacy flat files are left readable but receive no new records.## Consequences-- A diagnostic investigation can open only the relevant session, tool, timing,- provider, or lifecycle stream instead of scanning a mixed file.-- Timing records remain easy to grep at stable paths: `host/timing.log` and- `agent/timing.log`.-- The logs folder contains more files, but each file has a bounded size and a- stable purpose.-- Older `app.log`, `host.log`, and `agent.log` files remain readable as legacy- history, but new records are written only to the categorized layout.--## Alternatives rejected--- **Keep one file per channel and rely on the `category` field:** preserves the- scan problem that motivated this change.-- **Create one file per session:** produces unbounded file counts and leaves- boot, provider, and process failures without a natural session owner.-- **Delete or migrate legacy files on startup:** risks losing diagnostic history- and makes a logging improvement capable of failing application boot.+- Investigations open only the relevant stream, and timing records stay+ greppable at `host/timing.log` and `agent/timing.log`.+- The folder holds more, smaller single-purpose files.++## Alternatives++- One file per channel relying on the `category` field: keeps the scan problem.+- One file per session: unbounded counts, and boot, provider, and process+ failures have no session owner.diff --git a/docs/adr/0047-context-usage-inspector.md b/docs/adr/0047-context-usage-inspector.mdindex 0c3174743..00ef4b4e3 100644--- a/docs/adr/0047-context-usage-inspector.md+++ b/docs/adr/0047-context-usage-inspector.md@@ -1,58 +1,49 @@# ADR 0047: Context usage inspector with exact and estimated token sources-- Status: Accepted+- Status: Accepted (amended by D225, D244, D347, D355)- Date: 2026-08-02-- Amended by: D225 (click-toggled panel), D244 (compact summary presentation),- D347 (composer toolbar placement), and D355 (last-request occupancy)-- Related: [D103](../spec/08-meta/decisions-log.md) ·- [D183](../spec/08-meta/decisions-log.md) ·- [D184](../spec/08-meta/decisions-log.md) ·- [IPC protocol](../spec/03-runtime/01-ipc-protocol.md) ·- [Component spec](../spec/04-ux/08-component-spec.md)+- Related: D103, D183, D184## Context-The first context-usage ring exposed only a percentage and a small aggregate-breakdown. It did not answer why a turn became large, which tool contributed the-most context, or how quickly the model generated its output.+The first context-usage ring showed a percentage and a small aggregate breakdown,+so it could not explain why a turn became large or which tool contributed most of+the context. Providers report usage but expose no exact per-tool allocation.## Decision-1. Replace the standalone ring with a compact Codex-style context inspector- trigger.-2. Keep provider-reported input/output/cache/reasoning usage authoritative and- show aggregate output throughput as `outputTokens / responseDurationMs` on- completed turns only; active streams do not render a live estimate.-3. Estimate each tool's argument and result footprint with the existing- pi-agent-core token heuristic.-4. Carry `responseDurationMs` on assistant messages for throughput, plus- `providerWaitMs` and `modelStreamDurationMs` for session timing.-5. Preserve additive compatibility: missing fields use the renderer fallback- estimate or omit throughput when no stream duration is available.-6. Render the inspector panel through `document.body` as a fixed viewport- overlay.-7. Aggregate repeated tool rows by their exact tool name, preserving the- first-seen order.-8. Resolve the context-window total from the same `pi-ai` model record that- Electron passes to the agent sidecar, and enrich cached/discovered model rows- with that value.+1. A compact Codex-style inspector trigger replaces the standalone ring and+ toggles one scrollable, non-modal panel by click or keyboard activation (D225).+2. Provider-reported input, output, cache, and reasoning usage stays+ authoritative. Aggregate throughput is `outputTokens / responseDurationMs` on+ completed turns only, never a live estimate.+3. Each tool's argument and result footprint is estimated with the pi-agent-core+ token heuristic, persisted on the tool message, and marked as estimated; it is+ never added to the provider total.+4. Assistant messages carry `responseDurationMs` plus `providerWaitMs` and+ `modelStreamDurationMs`, tool messages carry `toolUsage` and `toolDurationMs`,+ and `tool_end` gains optional `toolUsage`, so live, persisted, and restored+ transcripts agree. The change is additively compatible: a missing field falls+ back to the renderer estimate or omits throughput.+5. Repeated tool rows aggregate by exact tool name in first-seen order, with call+ count and summed estimates.+6. The panel renders through `document.body` as a fixed overlay with+ collision-aware placement, and its dismissal is independent of the transcript+ scroll container.+7. The context-window total comes from the same `pi-ai` model record Electron+ passes to the sidecar, with a conservative default only when the model is+ absent from the catalog.## Consequences-- Users can inspect exact model usage and see each tool type's relative context- footprint without opening logs, while repeated calls stay compact and- auditable through their call counts.-- Historical tool rows remain useful through a deterministic fallback estimate.-- The session timing breakdown separates request-to-first-response wait from- streamed thinking/answer time and top-level tool execution.-- Tool estimates are transparent but cannot claim billing precision.-- The transcript protocol and storage shape gain optional fields, while the- existing protocol version remains compatible.+- Users see exact model usage and each tool type's footprint without opening logs,+ with repeated calls compact and auditable by count.+- Session timing separates provider wait from streamed generation and top-level+ tool execution; nested delegate timings are excluded.+- The protocol and storage shape gain optional fields while the version stays+ compatible.## Alternatives-- Keep the ring-only UI: rejected because it hides the source of large turns.-- Claim exact per-tool provider usage: rejected because the provider response- does not contain that attribution.-- Calculate throughput from wall-clock turn time: rejected because tool wait and- provider wait would distort model generation speed.+- Keep the ring-only UI: hides the source of large turns.+- Claim exact per-tool provider usage: providers carry no such attribution.diff --git a/docs/adr/0048-lazy-per-turn-tool-activation.md b/docs/adr/0048-lazy-per-turn-tool-activation.mdindex ddf492b41..bb68f1bb5 100644--- a/docs/adr/0048-lazy-per-turn-tool-activation.md+++ b/docs/adr/0048-lazy-per-turn-tool-activation.md@@ -1,73 +1,48 @@# ADR 0048: Lazy per-turn tool activation-- Status: Accepted+- Status: Accepted (amended 2026-09-27: Agent keeps `Glob`/`Grep` in its initial schema)- Date: 2026-08-02## Context-PI-Desktop currently registers the product tools, plugin tools, skills, and-plugin-development helpers before the first provider request. The complete JSON-schemas are then serialized into that request even when the prompt is a greeting-or a read-only task.+PI-Desktop registered product tools, plugin tools, skills, and plugin-development+helpers before the first provider request and serialized every JSON schema into+it, even for a greeting, so the first input was disproportionately large. A+turn-boundary context replacement lets only the requested schemas reach the+provider.## Decision-PI-Desktop keeps a complete sidecar-local tool registry but sends an active-subset to the provider:--- Agent starts with `Read`, `Bash`, `Edit`, and `Write`, matching pi's- coding-agent core.-- Chat starts with `Read`, `Glob`, and `Grep`.-- A local `ToolSearch` tool remains active when deferred capabilities exist.-- Agent-mode `Glob` and `Grep`, `BrowserPreview`, plugin tools, `Skill`, and- plugin-development helpers are deferred until requested.--The base prompt contains a bounded `# On-demand tools` catalog with names and-compact one-line descriptions, never the deferred JSON parameter schemas. The-model calls `ToolSearch` with an exact name or a short capability query.+Keep a complete sidecar-local tool registry and send only an active subset: Agent+starts with `Read`, `Bash`, `Edit`, `Write`, `Glob`, and `Grep`, Chat with `Read`,+`Glob`, and `Grep`, and `BrowserPreview`, plugin tools, `Skill`, and+plugin-development helpers stay deferred until requested. A local `ToolSearch` tool+stays active while deferred capabilities exist (ADR 0061 dropped the always-active+`CompactContext` tool; ADR 0064 restores it as `new_context`, active in every+mode), and the base prompt carries a bounded `# On-demand tools` catalog of names+and one-line descriptions, never deferred parameter schemas. The model calls+`ToolSearch` with a name or short capability query; the sidecar ranks matches,+activates at most four, returns them in `addedToolNames`, and rebuilds the context+before the next request, where native deferred-tool search may serialize the new+schemas while other adapters get them through the ordinary tool list. The deferred+set is cleared at every user prompt and rebuilt from successful activation evidence+in effective context, restored only for names still in the mode's catalog, and the+marker stays in the persisted tool result so a restarted runtime reuses an eligible+capability. `ToolSearch` never calls host-core and bypasses no permission,+workspace containment, timeout, or audit rule.## Consequences-- Simple first turns no longer pay for every optional tool schema.-- Core coding workflows keep pi's Read/Bash/Edit/Write set without an extra- discovery call; file enumeration and search remain one ToolSearch away.-- A task that needs an ancillary capability incurs one explicit ToolSearch turn- before that capability is available.-- ToolSearch is a normal model tool activity row, so the discovery step is- visible and durable rather than an opaque side effect.-- Provider compatibility remains centralized in pi-ai: native deferred search is- an optimization, while the active-context fallback works for every adapter.+- Simple first turns stop paying for every optional schema, while core coding+ workflows need no discovery call.+- An ancillary capability costs one explicit `ToolSearch` turn, visible and durable+ as a normal tool activity row.+- Provider compatibility stays centralized in pi-ai: native search is an+ optimization, the active-context fallback covers every adapter.## Alternatives-### Send every schema on every request--Rejected because it wastes first-turn context on capabilities the model does not-need and grows with the plugin registry.--### Activate tools from a prompt-text heuristic--Rejected because user wording and project instructions are not a reliable-capability classifier, and a missed heuristic would hide a valid tool.--### Use only provider-native tool search--Rejected because not every configured provider supports it.--## References--- `docs/spec/03-runtime/02-agent-runtime.md`-- `docs/spec/03-runtime/03-tools-and-permissions.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-008a)-- `https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/core/system-prompt.ts`-- `https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/extensions.md`--## Amendment — 2026-09-27: keep workspace search in Agent's initial schema--Routine file discovery should not require a separate `ToolSearch` turn. Agent-now includes `Glob` and `Grep` alongside `Read`, `Bash`, `Edit`, and `Write` in-its initial provider request.--This supersedes only ADR 0048's initial-set and Glob/Grep-deferral bullets and-the corresponding first-turn consequences; successful activation restoration,-provider compatibility, permissions, and host policy are unchanged.+- Send every schema on every request: wastes first-turn context and grows with the+ registry.+- Activate from a prompt-text heuristic: wording is no capability classifier, and a+ miss hides a valid tool.diff --git a/docs/adr/0049-context-compaction-failure-recovery.md b/docs/adr/0049-context-compaction-failure-recovery.mdindex 477859116..9230a0082 100644--- a/docs/adr/0049-context-compaction-failure-recovery.md+++ b/docs/adr/0049-context-compaction-failure-recovery.md@@ -4,60 +4,47 @@- Date: 2026-08-04- Amends: ADR 0030 / D158- Amended by: ADR 0061 (the fallback stays reserved for the blocking hard- boundary; a failed background build is discarded silently) / ADR 0064 (there- is no background build left to discard, and the `fresh_window` family issues- no summary request, so this path cannot trigger there) / ADR 0282 (the- summary request retries transient failures and the preflight guard sizes- the serialized prompt, with one reduced pass, before this fallback runs) /- ADR 0302 (the fallback keeps the real recent window rather than one user+ boundary) / ADR 0064 (no background build is left to discard, and the+ `fresh_window` family never reaches this path) / ADR 0282 (the summary+ request retries transient failures and a preflight guard sizes the serialized+ prompt before this fallback runs) / ADR 0302 (the fallback keeps the real+ recent window)## Context-The turn-boundary context guard correctly prevents an oversized provider-request, but an LLM summary request can fail after the session has already-reached the hard boundary. Treating every automatic summary failure as a-terminal turn leaves the complete transcript durable but forces the next user-message to recover the session manually.+The turn-boundary guard stops an oversized provider request, but an LLM summary+can fail after the session already reached the hard boundary, turning a+transient summarizer failure into a terminal turn. Since the visible transcript+and the model-facing context are separate, a durable checkpoint can keep a+provider-valid recent tail even when no new summary exists.## Decision-For automatic `threshold` and `overflow` compaction only, PI-Desktop uses a-three-outcome controller:--1. Preflight the summary input against the provider model window.-2. If summary generation fails, or a generated checkpoint remains above the safe- budget, prepare a deterministic fallback checkpoint.-3. Append the fallback through host-core and re-estimate the model context.--Manual `/compact` never silently falls back. Durable append failures, missing-transcript boundaries, and fallback checkpoints that remain oversized emit-`CONTEXT_COMPACTION_FAILED` and block the guarded provider request.+For automatic `threshold` and `overflow` compaction only, a three-outcome+controller applies. It first preflights the summary input against the model+window and skips a doomed summary request. If summary generation fails, or a+generated checkpoint stays above the safe budget, it prepares a deterministic+fallback checkpoint that reuses the previous summary, adds a recovery marker,+keeps a bounded recent tail, and records `details.fallback = "retained_tail"`.+The fallback is appended through host-core and re-estimated; success emits+`compaction_end` with `fallback: "retained_tail"` and the run continues with a+renderer warning.++Manual `/compact` never falls back. Durable append failures, missing transcript+boundaries, and still-oversized fallbacks emit `CONTEXT_COMPACTION_FAILED` and+block the provider request. The full transcript is never deleted or rewritten;+the fallback is only the model-context view rebuilt after restart.## Consequences-- Automatic compaction failures no longer terminate a run when a safe durable- retained tail can be installed.-- The model may lose older task details when summary generation fails; the- warning and checkpoint metadata make that degradation explicit.-- Host persistence and hard-budget validation remain mandatory, so recovery- cannot trade a better UX for an unsafe provider request.-- Manual compaction remains an explicit user action with fail-fast semantics.-- The event and checkpoint metadata provide a stable diagnostic signal without- persisting provider error text that may contain sensitive endpoint details.+- Automatic failures no longer end a run when a durable retained tail is safe.+- Older task detail may be lost; the warning and checkpoint metadata make that+ degradation explicit.+- Host persistence and hard-budget validation stay mandatory.## Alternatives-### Continue without a checkpoint--Rejected because the next provider request would bypass the hard guard and could-reproduce the provider context-limit failure.--### Delete visible transcript history--Rejected because it destroys searchability, diagnostics, fork inputs, and the-user's complete conversation.--### Retry the summary indefinitely--Rejected because a long or incompatible provider failure can hold the session-busy indefinitely.+- Continue without a checkpoint: rejected; the next request would bypass the+ hard guard.+- Delete visible transcript history: rejected; it destroys search, diagnostics,+ and fork inputs.diff --git a/docs/adr/0050-bounded-provider-stream-recovery.md b/docs/adr/0050-bounded-provider-stream-recovery.mdindex 433cf4511..f5841fdf5 100644--- a/docs/adr/0050-bounded-provider-stream-recovery.md+++ b/docs/adr/0050-bounded-provider-stream-recovery.md@@ -1,80 +1,51 @@# ADR 0050: Bounded provider stream recovery and diagnostics-- Status: Accepted (amended by D259 and D378, see below)+- Status: Accepted (amended by D259 and D378 / ADR 0206, which replaced the retry+ arithmetic below with one shared bounded budget; classification per D186)- Date: 2026-08-04-## Amendment (D259, 2026-09)--Decision D259 supersedes the retry arithmetic in points 2 and 3 of this ADR. The-"one provider-level retry" during request setup and the "retry once after a 750-ms backoff" after a stream has started were replaced by one shared, bounded-budget for non-429 transient failures: four retries after the initial attempt-(five provider attempts in total), drawn from the same pool whether the failure-lands during request setup or mid-stream, with a deterministic 1 s / 2 s / 4 s /-8 s schedule capped at 8 s and `retry-after` headers honoured first.-## Context-The provider retry layer covers failures while establishing a request, but a-provider can also terminate after the assistant stream has started. The previous-runtime classified the common `terminated` message as a generic-`PROVIDER_ERROR`, ended the turn, and left regenerate to create a new runtime-and reseed the transcript.+The provider retry layer covered failures while establishing a request, but a+provider can also terminate after the assistant stream has started: the runtime+classified the common `terminated` message as a generic `PROVIDER_ERROR`, ended+the turn, and left regenerate to build a new runtime and reseed the transcript.+Repeated mutation failures had a related cost, as the model could keep repairing+an obsolete patch instead of taking a fresh snapshot of the target file.## Decision-PI-Desktop applies the following bounded recovery strategy:-1. Classify `terminated`, premature stream closure, and equivalent incomplete- stream messages as retryable `STREAM_FAILED` errors.-2. Configure pi-ai request setup with one provider-level retry and an- interruptible delay capped at 8 seconds.-3. When a transient `STREAM_FAILED`, `NETWORK_ERROR`, or `TIMEOUT` occurs after- a stream has started, retry once in the same turn after a 750 ms abortable- backoff.+ stream messages as retryable `STREAM_FAILED`, preserving only safe,+ low-cardinality provider status/code fields in `AppError.details`.+2. Configure pi-ai request setup with a provider-level retry and an interruptible+ delay, forwarding the durable session id for adapters with request affinity.+3. After a stream has started, retry transient `STREAM_FAILED`, `NETWORK_ERROR`,+ or `TIMEOUT` in the same turn after an abortable backoff: the failed assistant+ leaves the next model context with its visible message id reused, so partial+ content is replaced rather than duplicated; a further failure is terminal.4. Attach `phase`, `providerWaitMs`, `streamMs`, provider status/code, and- `retryAttempt` when available.+ `retryAttempt` as diagnostics only — redacted, bounded, and never carrying+ credentials or raw provider bodies.5. Mutation instructions select `Edit` for one small unique replacement and- `Write` for a coherent whole-file rewrite.+ `Write` for a coherent whole-file rewrite; after a mismatch the agent follows+ the line-anchored contract's fresh-read or complete-reveal recovery, and the+ third counted failed `Edit` or shell patch command returns pi-agent-core's+ terminating tool hint with the exact mismatch.## Consequences-- A single transient stream termination no longer forces regenerate or a new- transcript/runtime boundary.-- The renderer sees one assistant bubble and one terminal lifecycle for a- recovered turn.-- Provider errors remain diagnosable from agent timing and app session logs- without exposing secrets.-- The retry budget is finite: persistent outages, authentication errors, context- failures, and the second stream failure remain visible and actionable instead- of entering an unbounded loop.-- Mutation recovery is deterministic and bounded.+- One transient stream termination no longer forces regenerate or a new+ transcript/runtime boundary; a recovered turn keeps one assistant bubble and+ one terminal lifecycle.+- Provider errors stay diagnosable from agent timing and session logs without+ exposing secrets.+- Persistent outages, authentication errors, context failures, and repeated+ stream failures stay visible and actionable instead of looping.## Alternatives-### Retry every provider error in the same turn--Rejected because authentication, model-selection, malformed-request, and context-errors are not fixed by replaying the same request.--### Retry stream failures indefinitely--Rejected because it hides persistent outages, consumes provider quota, and-prevents the user from regaining control of the session.--### Create a new assistant bubble for every stream attempt--Rejected because partial and failed attempts would look like multiple answers-and would complicate durable transcript reconciliation.--### Keep patch repair entirely prompt-driven--Rejected because wording alone does not reliably bound a model's retry loop.--## References--- `docs/spec/03-runtime/02-agent-runtime.md`-- `docs/spec/03-runtime/03-tools-and-permissions.md`-- `docs/spec/03-runtime/08-error-codes.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- Decision D186+- Retry every provider error in the same turn: authentication, model-selection,+ and context errors are not fixed by replaying the request.+- Create a new assistant bubble per attempt: partial attempts would look like+ multiple answers and complicate transcript reconciliation.diff --git a/docs/adr/0051-host-rpc-stdio-resource-isolation.md b/docs/adr/0051-host-rpc-stdio-resource-isolation.mdindex 8834e297a..249aaddb1 100644--- a/docs/adr/0051-host-rpc-stdio-resource-isolation.md+++ b/docs/adr/0051-host-rpc-stdio-resource-isolation.md@@ -5,55 +5,44 @@## Context-The host already bounds RPC tasks, tool classes, shell processes, and queued-work. A parallel Bash burst could nevertheless end the host with `Resource-temporarily unavailable (os error 35)`.+The host already bounded RPC tasks, tool classes, shell processes, and queued work,+yet a parallel Bash burst could still end it with+`Resource temporarily unavailable (os error 35)`, which Electron mapped to+`HOST_UNAVAILABLE`. The remaining risk was host-core's use of `tokio::io::stdin()`+and `tokio::io::stdout()`, which Tokio implements through its blocking pool: when the+OS refuses another worker thread the non-mandatory blocking spawn panics instead of+returning an I/O error, and the host exits with tool requests in flight. The Unix+login-shell PATH probe shared the problem through `std::thread::spawn` (D187).## Decision-1. Host-core's NDJSON stdin reader runs on one named thread created with- `std::thread::Builder`.+1. Host-core's NDJSON reader runs on one named `std::thread::Builder` thread and its+ writer on a second; the async dispatcher talks to them through channels, so request+ and tool tasks never call Tokio stdio adapters.2. The control threads retry `EINTR` and transient `EAGAIN`/`EWOULDBLOCK`- (`errno` 11 or 35) with a short bounded delay.-3. Failure to create a control thread is returned as a host startup error.-4. The login-shell PATH probe also uses `thread::Builder`; if that optional- helper cannot start, Bash falls back to the inherited host PATH.+ (`errno` 11 or 35) with a short bounded delay; the reader keeps partial input until+ a complete line arrives and the writer tracks partial writes so a retry cannot+ duplicate bytes.+3. Failure to create a control thread is a host startup error, and a closed or+ unrecoverable pipe ends the normal lifecycle under Electron's generation-aware+ supervision instead of becoming an unhandled thread-spawn panic.+4. The login-shell PATH probe also uses `thread::Builder`; if that optional helper+ cannot start, Bash falls back to the inherited host PATH. Admission limits are+ unchanged.## Consequences-- Temporary OS thread pressure no longer reaches Tokio's panic-on-no-worker- stdio path, removing the observed host exit cause behind `HOST_UNAVAILABLE`.-- The host has two long-lived control threads instead of creating a blocking- pool worker per stdio operation.-- NDJSON framing, response ordering, request concurrency, and overload codes- remain unchanged.-- A genuinely unavailable stdin/stdout pipe still ends the host and is handled- by the existing Electron restart/fatal-degradation policy.+- Thread pressure no longer reaches the panic-on-no-worker stdio path, removing the+ observed cause behind `HOST_UNAVAILABLE`, and the host holds two long-lived control+ threads instead of a blocking-pool worker per stdio operation.+- NDJSON framing, response ordering, request concurrency, and overload codes are+ unchanged, and a genuinely unavailable pipe still ends the host under the existing+ restart policy.## Alternatives-### Increase the Tokio blocking-pool limit--Rejected. It raises the number of threads competing for the same exhausted OS-resource and leaves the panic-on-thread-creation path intact.--### Keep Tokio stdio and catch the panic--Rejected. Catching a panic around the async runtime would be brittle and would-not make partial NDJSON writes or shutdown ordering explicit.--### Remove concurrency limits instead--Rejected. Admission limits remain necessary for tools and subprocesses; they do-not solve the independent control-pipe dependency on dynamic blocking-pool-workers.--## References--- `crates/host-core/src/rpc/mod.rs`-- `crates/host-core/src/tools/shell.rs`-- `docs/spec/03-runtime/05-host-core-rust.md`-- `docs/spec/03-runtime/06-host-rpc-protocol.md`-- `docs/spec/03-runtime/07-process-model.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- Decision D187+- Raise the blocking-pool limit: adds threads competing for the same exhausted+ resource and keeps the panic path.+- Catch the panic: brittle, and leaves partial writes and shutdown ordering implicit.+- Remove concurrency limits: they remain necessary for tools and subprocesses and do+ not address this control-pipe dependency.diff --git a/docs/adr/0052-plan-operating-state-and-approval-boundary.md b/docs/adr/0052-plan-operating-state-and-approval-boundary.mdindex 9a46977fd..2652f2bbb 100644--- a/docs/adr/0052-plan-operating-state-and-approval-boundary.md+++ b/docs/adr/0052-plan-operating-state-and-approval-boundary.md@@ -2,26 +2,35 @@- Status: Superseded by ADR 0053- Date: 2026-07-30-- Baseline: `0.4.13`-- Protocol: v7-- Storage schema: v8--ADR 0053 replaces this checkpoint with immutable unique host-written-`.pi/plan/*.md` artifacts, approve/reject-only resolution, the existing-`plan_approvals` artifact/execution fields, and a startup interruption fence-with no replay. The structured proposal/request-changes details below remain-historical context for the superseded design.+- Related: ADR 0061, ADR 0064, D188## Context-PI-Desktop's former product selector treated Chat and Agent as two tool-profiles.+The former product selector described Chat and Agent as two tool profiles, which+left planning ambiguous: a plan could read as a second agent, a planner model, or+a read-only permission mode. The workflow needed one pi Agent that inspects a+task, submits a structured plan, waits for a separate user decision, and only then+continues.## Decision-The product selector is exactly `Agent | Plan`. There is one pi Agent per-session.+The selector became exactly `Agent | Plan` over one Agent per session, with the+durable session mode `agent | plan` owned by Rust host-core. Plan exposed `Read`,+`Glob`, `Grep`, `BrowserPreview`, permission-mode-governed `Bash`, and+`ExitPlanMode`, and denied `Write`, `Edit`, and every plugin tool. Approval was a+separate host-owned `plan_approvals` transaction driven by the `plans.pending` and+`plans.resolve` RPCs, shipped with a schema v8 migration and protocol v7.++ADR 0053 supersedes this checkpoint. It keeps one Agent and a durable mode but+replaces the structured proposal and request-changes flow with immutable+host-written `.pi/plan/*.md` artifacts, approve/reject-only resolution, the+existing `plan_approvals` artifact and execution fields, and a startup+interruption fence with no replay. Context compaction left the Plan tool list+under ADR 0061 and returned as `new_context` under ADR 0064.## Consequences-Superseded (Superseded by ADR 0053). The full record is in git history.+- Renderer or sidecar mode state could never authorize a tool; Rust owned the+ durable transition.+- The migration, protocol, and pending-approval details are historical; current+ Plan behavior follows ADR 0053.diff --git a/docs/adr/0053-plan-checkpoint-artifact-and-execution-epoch.md b/docs/adr/0053-plan-checkpoint-artifact-and-execution-epoch.mdindex c80805be8..11d600394 100644--- a/docs/adr/0053-plan-checkpoint-artifact-and-execution-epoch.md+++ b/docs/adr/0053-plan-checkpoint-artifact-and-execution-epoch.md@@ -2,153 +2,97 @@- Status: Accepted for implementation- Date: 2026-07-31+- Related: ADR 0061, ADR 0064, D189- Supersedes: ADR 0052 and D188-- Baseline: `0.4.14`-- Protocol: v9-- Storage schema: v10## ContextThe previous Plan contract used an in-memory approval waiter around a structured-proposal and allowed request-changes feedback. It did not give the user one-exact, inspectable plan artifact or define how an approved execution could be-interrupted without replay.+proposal with request-changes feedback, so there was no single inspectable plan+artifact and no defined way to interrupt an approved execution. Approval must+survive a renderer reload, while a host restart must never replay work created by+an older host process.## Decision### 1. One Agent and one Plan submission tool-The product selector remains `Agent | Plan`, with Agent as the default and one-pi Agent per session. Plan is the same Agent in planning state.--The input is exactly:--```ts-type SubmitPlanInput = {- title: string;- markdown: string;- question: string;-};-```+The selector stays `Agent | Plan` with Agent as the default and one pi Agent per+session, where Plan is that same Agent in planning state exposing `Read`, `Glob`,+`Grep`, `BrowserPreview`, `Bash`, `EnterPlanMode`, and `SubmitPlan` while Write,+Edit, and plugin tools stay host-denied. The input is exactly `title`, `markdown`,+and `question`, with no `ExitPlanMode`, structured step schema, `proposedCommands`,+or `request_changes`, so a revision is a new `SubmitPlan` after rejection or+expiry.### 2. Immutable host-written plan artifacts-For a project-bound session, host-core writes the submitted Markdown bytes-unchanged to a new artifact under:--```text-<workspaceRoot>/.pi/plan/<unique-name>.md-```--The directory and filename are host-owned. Each submission gets a unique file;-an accepted submission never replaces an earlier artifact.+For a project-bound session host-core writes the submitted Markdown bytes+unchanged to a new uniquely named artifact under `.pi/plan/` in the workspace and+records the workspace-relative path, SHA-256, and byte size in the same approval+record, leaving `title` and `question` as structured fields without wrapping,+normalizing, or replacing the bytes. A path escape, symlink ambiguity, or write+failure creates no approval or execution descriptor.### 3. Approval and permission selection-The approval card displays the structured title and question, an opener for the-host-created artifact, the absolute expiry, and the current status. Opening the-artifact reads the immutable Markdown file; the card does not need to inline the-Markdown or display its hash or byte size.--The approval deadline is an absolute 30-minute deadline from host creation.-Renderer reload preserves the original deadline while the host remains alive.+The card shows the structured title and question, an opener for the host-created+artifact, the absolute expiry, and the current status, and offers only Approve and+Reject, where Approve requires an explicit `ask`, `accept-edits`, or `auto`+execution mode defaulting to `ask` and Reject grants nothing. The deadline is an+absolute 30-minute deadline from host creation that survives a renderer reload,+expires as `PLAN_APPROVAL_TIMEOUT`, never extends when the card reopens, and never+approves through timeout, reload, scheduled task, or stale renderer.-### Historical display amendment (issue #933)--The live approval card remains unchanged. Completed submission rows additionally-render read-only historical cards.+Completed submissions additionally render read-only historical cards, joining+returned submission call IDs to the existing approval table without rewriting the+original tool result. This is an additive read projection with no schema+migration and no execution grant.### 4. Process-epoch fence and recovery-The host process has an internal boot epoch, but it is not serialized in the-database and is not a protocol field. The single `plan_approvals` row carries-both approval status and execution fields:--```text-status: pending -> approved | rejected | expired | interrupted-execution_state: queued -> running -> completed | interrupted-```--Approval atomically changes the session to Agent with the selected permission-mode, records `execution_id`, and sets `execution_state = queued`; the same-Agent then starts the execution turn. Only one Plan approval may be pending and-only one execution may be queued or running for a session.+The single `plan_approvals` row carries `status` (`pending` → `approved` |+`rejected` | `expired` | `interrupted`) and `execution_state` (`queued` →+`running` → `completed` | `interrupted`), and approval atomically switches the+session to Agent with the selected permission mode, records `execution_id`, and+queues the execution turn; only one approval may be pending and one execution+queued or running per session. Before serving any RPC after startup, host-core+marks all prior pending approvals and queued or running executions as+`interrupted` and aborts their turns, so no approval, provider call, or tool+execution is replayed.### 5. Turn and configuration boundaries-Each session has one active turn. A second prompt, second Plan submission,-mode/provider/model/permission/shell configuration change, or second Plan run is-rejected while that turn or Plan run is active.+A session has one active turn, so a second prompt, second submission, second Plan+run, or a mode, provider, model, permission, or shell change is rejected while+that turn or run is active, and configuration is accepted only while idle.### 6. Scheduled Plan policy-Scheduled or unattended Plan execution is rejected before provider work,-artifact creation, approval, or queue insertion with-`PLAN_REQUIRES_INTERACTIVE_SESSION`. A scheduled task must be explicitly changed-to Agent before it can run unattended.+Unattended Plan execution is rejected before any provider work, artifact,+approval, or queue insertion with `PLAN_REQUIRES_INTERACTIVE_SESSION`, so a+scheduled task must be switched to Agent to run unattended.### 7. Versioned contracts-Protocol v9 carries `SubmitPlan`, the unique artifact path and metadata,-approve/reject responses, absolute expiry, execution state, shell selection, and-streamed command output. Storage schema v10 continues the single-`plan_approvals` checkpoint table with structured title/question, artifact-fields, execution ID/state, and the persisted default shell setting while-preserving existing transcript and session data.+Protocol v9 carries `SubmitPlan`, the artifact path and metadata, approve and+reject responses, the absolute expiry, execution state, shell selection, and+streamed command output, and storage schema v10 keeps the single `plan_approvals`+table with title, question, artifact fields, execution state, and the persisted+default shell through one transactional migration.## Consequences-### Positive--- Every submitted proposal has its own host-owned file with verifiable bytes.-- Renderer reload is recoverable without making a host restart replay work.-- The Agent/Plan boundary and post-approval Agent state are explicit.-- Shell choice, output, timeout, and cancellation can share the same host audit- and turn boundaries.--### Tradeoffs--- Rejecting a plan is terminal; revisions require another model turn and a new- artifact.-- A host restart interrupts even an approved queued or running execution.-- Plan artifacts accumulate under `.pi/plan/`; they are immutable and are not a+- Every proposal has its own host-owned file with verifiable bytes, and reload is+ recoverable without a restart replaying work.+- Rejecting is terminal, so a revision costs another model turn and another+ artifact; restart interrupts even an approved queued execution.+- Plan artifacts accumulate immutably under `.pi/plan/` and are not arenderer-owned draft store.-## Alternatives rejected--### Request-changes approval--Rejected for this checkpoint because it mixed plan editing with the approval-boundary.--### Replay a durable queue after host restart--Rejected because a persisted execution request can outlive the process state,-tool identity, shell identity, and user intent that created it.--### Renderer-owned or sidecar-written plan files--Rejected because the host must own the workspace write, path validation, hash,-size, and approval identity.--## Related docs+## Alternatives-- `docs/adr/0054-selectable-command-shell-catalog.md`-- `docs/spec/00-baseline.md`-- `docs/spec/03-runtime/01-ipc-protocol.md`-- `docs/spec/03-runtime/02-agent-runtime.md`-- `docs/spec/03-runtime/03-tools-and-permissions.md`-- `docs/spec/03-runtime/04-data-storage.md`-- `docs/spec/03-runtime/05-host-core-rust.md`-- `docs/spec/03-runtime/06-host-rpc-protocol.md`-- `docs/spec/03-runtime/07-process-model.md`-- `docs/spec/03-runtime/08-error-codes.md`-- `docs/spec/03-runtime/10-session-state-machine.md`-- `docs/spec/04-ux/03-permission-ux.md`-- `docs/spec/04-ux/06-settings-ia.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/04-ux/09-interaction-patterns.md`-- `docs/spec/05-security/01-security.md`-- `docs/spec/06-delivery/02-acceptance-criteria.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `docs/spec/08-meta/decisions-log.md` (D189)+- Request-changes approval: rejected because it mixed plan editing into the+ approval boundary.+- Replay a durable queue after restart: rejected because the persisted request can+ outlive the process, tool, shell, and user intent behind it.diff --git a/docs/adr/0054-selectable-command-shell-catalog.md b/docs/adr/0054-selectable-command-shell-catalog.mdindex f8fc99c4a..57ca6e8d8 100644--- a/docs/adr/0054-selectable-command-shell-catalog.md+++ b/docs/adr/0054-selectable-command-shell-catalog.md@@ -2,99 +2,65 @@- Status: Accepted for implementation (timeout bounds in §4 amended by ADR 0167 / D329; the PowerShell 7 entry is added by ADR 0209 / D381)- Date: 2026-07-31-- Baseline: `0.4.14`-- Protocol: v9-- Storage schema: v10+- Related: ADR 0053, D190## Context-The Bash tool currently resolves one Bash implementation per process. That-prevents users from choosing the command language that matches their project and-makes a changed executable hard to detect.+The Bash tool resolved one Bash implementation per process, which kept users from+choosing a command language that matches their project and made a changed+executable hard to detect. Shell selection had to become explicit and+host-authoritative while the `Bash` tool vocabulary stayed stable.## Decision### 1. Host-owned shell catalog-Host-core exposes a platform-aware catalog with stable IDs:--| ID | Shell | Discovery |-|---|---|---|-| `windows-powershell` | in-box Windows PowerShell 5.1 | `powershell.exe`/native PowerShell on Windows |-| `windows-pwsh` | PowerShell 7+ (side-by-side install) | `pwsh.exe` under `%ProgramFiles%\PowerShell\7` or on PATH |-| `cmd` | Windows Command Prompt | `cmd.exe` on Windows |-| `git-bash` | Git for Windows Bash | Git for Windows installation and PATH |-| `bash` | Unix Bash | `/bin/bash`, `/usr/bin/bash`, or an approved PATH entry on macOS/Linux |--The Windows catalog contains `windows-powershell`, `windows-pwsh`, `cmd`, and-`git-bash`; the Unix catalog contains `bash`. The catalog does not accept an-arbitrary renderer- or sidecar-supplied executable path.+Host-core exposes a platform-aware catalog of stable IDs — `windows-powershell`,+`windows-pwsh`, `cmd`, `git-bash` on Windows and `bash` on Unix — discovered only+through documented install locations or PATH. It never accepts an arbitrary+executable path from the renderer or the sidecar. Windows PowerShell 5.1 stays the+platform default and `windows-pwsh` is never selected implicitly, so choosing it+cannot surprise an existing user. Settings accept only an available ID for the+current platform; a persisted ID that later becomes unavailable falls back to the+first available shell with `fallback: true`, and an empty catalog fails with+`SHELL_NOT_FOUND`.### 2. Persisted default and stable identity-The host persists one `defaultCommandShell` ID in app settings. Selection is-allowed only from the available catalog and only while the affected session is-idle.+One `defaultCommandShell` ID is persisted in app settings and may change only+while the affected session is idle. At turn launch the runtime pins the effective+shell ID and dialect, and host-core re-resolves the catalog before spawn,+rejecting a changed identity with `COMMAND_SHELL_CHANGED`. The check covers+catalog selection, not executable path hashing, and no fallback happens after the+turn is pinned.### 3. Stable Bash protocol contract-The Agent tool and host method remain `Bash` and `tools.execute`; shell choice-is data on the request, not a new `PowerShell`, `Cmd`, or `GitBash` tool name.-The command runs non-interactively in the originating session workspace with the-selected shell's documented invocation form.--Host-core streams stdout and stderr as separate ordered output events. The final-tool result remains bounded and records whether either stream was truncated.+The Agent tool stays `Bash` and the host method stays `tools.execute`; the shell is+request data rather than a separate tool name. The command runs+non-interactively in the originating session workspace using the selected shell's+documented invocation form. Host-core streams stdout and stderr as separate+ordered events, the final result stays bounded and records truncation, and no+chunk may carry secrets or another session's output.### 4. Timeout and cancellation-Every Bash execution has a mandatory 60-second default timeout. A caller may-request a host-validated override only from 1 second through 300 seconds;-missing values use exactly 60 seconds, and out-of-range values are rejected.+Every execution has a mandatory default timeout with a host-validated override+range, and out-of-range values are rejected (bounds amended by ADR 0167). Timeout+and abort terminate the whole process tree through a Unix process group or a+Windows job/process-tree boundary, then close the stream and return+`TOOL_TIMEOUT` or `TURN_ABORTED` without leaving an orphan.## Consequences-- Users can choose the command language once and keep that default across- sessions and restarts.-- A changed effective shell selection cannot receive commands under stale- assumptions, while a persisted unavailable preference can recover through the- intentional catalog fallback.-- Streaming makes long commands observable without weakening final result- limits.-- The stable Bash protocol avoids multiplying tool schemas and compatibility- paths.--## Alternatives rejected--### Always use Bash--Rejected because it excludes native Windows command workflows and makes the-user's shell preference invisible.--### Let the caller provide an arbitrary executable path--Rejected because it bypasses catalog policy and makes identity validation and-security review unreliable.--### Create one protocol tool per shell--Rejected because it breaks existing Bash skills and expands the permission and-audit matrix without adding authority.--## Related docs--- `docs/adr/0053-plan-checkpoint-artifact-and-execution-epoch.md`-- `docs/spec/03-runtime/01-ipc-protocol.md`-- `docs/spec/03-runtime/03-tools-and-permissions.md`-- `docs/spec/03-runtime/05-host-core-rust.md`-- `docs/spec/03-runtime/06-host-rpc-protocol.md`-- `docs/spec/03-runtime/07-process-model.md`-- `docs/spec/03-runtime/08-error-codes.md`-- `docs/spec/03-runtime/09-logging-and-observability.md`-- `docs/spec/03-runtime/16-tool-result-limits.md`-- `docs/spec/04-ux/06-settings-ia.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/04-ux/09-interaction-patterns.md`-- `docs/spec/05-security/01-security.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `docs/spec/08-meta/decisions-log.md` (D190)+- Users pick a command language once and keep it across sessions and restarts.+- A stale shell assumption cannot receive commands, while an unavailable+ persisted preference recovers through the intentional catalog fallback.+- The single `Bash` schema keeps skills, permissions, and auditing unchanged.++## Alternatives++- One protocol tool per shell: breaks existing Bash skills and grows the+ permission matrix without adding authority.+- Caller-supplied executable path: bypasses catalog policy and makes identity+ validation unreliable.diff --git a/docs/adr/0055-agent-only-mode.md b/docs/adr/0055-agent-only-mode.mdindex efa07817b..349fd69b9 100644--- a/docs/adr/0055-agent-only-mode.md+++ b/docs/adr/0055-agent-only-mode.md@@ -1,35 +1,29 @@# ADR 0055: Agent-only mode; Chat becomes an internal read-only profile-- Status: Superseded by ADR 0052 / ADR 0053+- Status: Superseded by ADR 0052 / ADR 0053, which reintroduced the mode concept+ as the Plan operating state- Date: 2026-08-05--> Superseded. The mode concept this ADR removed returned as the Plan-> operating state (ADR 0052, superseded in turn by ADR 0053), so the product-> again exposes an `Agent | Plan` selector and `chat` migrates to `plan`, not-> `agent`. Retained because the reasoning about a negative permission gate and-> about failing closed on an unknown `mode` value still holds, and because it-> records why the toggle was removed before it was reintroduced with a-> different contract.+- Related: D003, D004, D115, D119, D185, D188, D189, D191## Context-Since D003/D004 a session carried one of two tool profiles.--1. A user who switched to Chat and later removed the toggle from their muscle- memory could leave a session permanently unable to write files.-2. Every tool, prompt-composition, and permission change had to be reasoned- about twice, and the lazy tool-activation core sets (D185) forked on mode.-3. The mode chip competed for space with the controls users do change — model,- thinking level, permission mode.+Since D003/D004 a session carried an `agent` profile with the full coding surface+or a `chat` profile with a read-only subset (`Read`, `Glob`, `Grep`) that+host-core hard-denies past every permission mode (D115). `chat` was never a+destination, yet the UI advertised it as a peer choice, and the profile could not+simply be deleted because imported and older rows carry `mode` values the current+UI does not produce.## Decision-1. **`agent` is the only mode the product exposes.** The top-bar segmented- toggle, the Settings default-mode row, both palette commands and their slash- aliases, the `.ct-mode*` styles, and the `settings.mode*` i18n keys are- removed. `newSession` always requests `agent`, and boot normalizes a stored- `defaultMode` that is not `agent`.--## Consequences--Superseded (Superseded by ADR 0052 / ADR 0053). The full record is in git history.+`agent` became the only exposed mode and `chat` was renamed `read-only`+(`Mode = "read-only" | "agent"`), with a negative gate — `PermissionManager`+denies when `mode != "agent"` and the tool is outside `read_only_mode_allows` —+so a legacy `mode` fails closed rather than gaining Write, Edit, or Bash.+Error codes became `BASH_DISABLED_IN_READ_ONLY` and+`WRITE_DISABLED_IN_READ_ONLY`, and `chat` rows migrated to `agent` at open.++ADR 0052 / ADR 0053 supersede this record: the product again exposes an+`Agent | Plan` selector, `chat` migrates to `plan` rather than `agent`, and the+reasoning about a negative gate and about failing closed on an unknown `mode`+value still holds.diff --git a/docs/adr/0056-extension-activation-scope.md b/docs/adr/0056-extension-activation-scope.mdindex f344b8013..23ffa2077 100644--- a/docs/adr/0056-extension-activation-scope.md+++ b/docs/adr/0056-extension-activation-scope.md@@ -2,164 +2,102 @@- Status: Accepted (capability storage and UI portions superseded by ADR 0112)- Date: 2026-08-05+- Related: ADR 0038, ADR 0039, ADR 0112, D015, D174, D192, D193, D194## Context-Until now the only way to add an MCP server or a skill to PI-Desktop was to-write a plugin. ADR 0038 gave plugins an `mcp` contribution point that Electron-main bridges over stdio or HTTP; ADR 0039 (as revised by D174) gave them a-`skills` contribution point that publishes model-invoked catalog entries behind-the `Skill` tool.--- Every MCP server in the wild is distributed as a JSON snippet — a `mcpServers`- block from a README.-- A skill is one Markdown document.+Adding an MCP server or a skill meant writing a plugin, through the `mcp` point of+ADR 0038 or the `skills` point of ADR 0039 / D174. That is the wrong shape for a+JSON `mcpServers` snippet or a single Markdown document. Reach was the second gap:+`enabled` was one boolean per plugin, so an extension was on everywhere or+nowhere, and toggling by hand when switching projects left tools visible that the+model still tried to call.## Decision### 1. One activation shape for all three extension kinds-`packages/shared/src/activation.ts` defines `ActivationScope = { mode: "global"-| "projects"; projects: string[] }`, stored **alongside** `enabled: boolean`-rather than encoded into it. Plugins, user MCP servers and user skills all carry-the pair, so one control renders all three and one predicate filters all three.--The three-state control the UI shows (`off` / `projects` / `global`) is derived-by `activationState`, not stored. Keeping `enabled` separate is what lets a user-narrow an extension to two projects, switch it off, and switch it back on-without re-picking the projects.--- Path comparison is case-insensitive and trailing-separator-insensitive,- because macOS and Windows both hand us case-varying spellings of one- directory, and a scope that silently stops matching reads as a bug.-- A scoped path also matches its subdirectories, so scoping to a monorepo root- covers sessions opened on a package inside it.-- A `projects`-mode extension is **inactive** in a session with no project at- all.-- A missing or unrecognized scope resolves to global, which is what every- extension installed before this change was.--### 2. Scope is enforced at catalog assembly **and** at dispatch--Filtering the catalog is not sufficient: a session outlives the prompt that-listed its tools, so re-scoping an extension mid-session has to take effect-immediately. Every surface therefore checks twice:--- Plugin tools, skills and commands: `pluginActiveInProject` filters the- per-turn catalog and re-checks in `tools.execute`, in the command palette, and- in command execution.-- User MCP tools: `UserMcpRuntime.toolsForProject` filters, and `callTool`- refuses with `TOOL_NOT_FOUND` and "not active for this session" when the- record no longer applies.-- User skills: `skills.active` filters, and `loadUserSkillBody` re-reads the- record and throws if the scope has narrowed.--Themes are deliberately **not** scoped: appearance is an app-wide preference,-not a per-project capability.+`packages/shared/src/activation.ts` defines+`ActivationScope = { mode: "global" | "projects"; projects: string[] }`, stored+alongside `enabled: boolean` rather than encoded into it, so plugins, user MCP+servers, and user skills share one control and one predicate. The UI three-state+control (`off` / `projects` / `global`) is derived by `activationState`, which lets+a user narrow an extension, switch it off, and switch it back on without+re-picking projects.++`isActiveInProject` is the single matching rule: comparison is case-insensitive+and trailing-separator-insensitive, a scoped path also matches its+subdirectories, a `projects`-mode extension is inactive in a session with no+project, and a missing or unrecognized scope reads as global.+`normalizeProjectPath` mirrors host-core's `normalize_project_path` so a path+chosen in the picker compares equal to the `projects` table.++### 2. Scope is enforced at catalog assembly and at dispatch++A session outlives the prompt that listed its tools, so every surface checks+twice. Plugin tools, skills, and commands filter the per-turn catalog through+`pluginActiveInProject` and re-check in `tools.execute`, the command palette, and+command execution. User MCP tools filter through+`UserMcpRuntime.toolsForProject`, and `callTool` refuses with `TOOL_NOT_FOUND`+once the record no longer applies. User skills filter through `skills.active`, and+`loadUserSkillBody` re-reads the record and throws when the scope narrowed. Themes+stay unscoped because appearance is app-wide. Agent-facing surfaces filter on the+session's `projectPath`; app-facing surfaces filter on the active window's+project.### 3. User MCP servers are a host-core registry, not plugins-`crates/host-core/src/mcp_servers.rs` owns one `McpServerRecord` JSON file under-`~/.agents/servers` or `<project>/.agents/servers`, minus the plugin. Activation-state is app-local under `<data>/agent-capabilities/mcp.json`.--Electron main owns the processes and sockets in `UserMcpRuntime`, reusing-`McpServerClient` from the plugin bridge rather than a second client:--- A server connects the first time a session that can see it is assembled, and- its tool list is cached, so a second session on the same project costs- nothing.-- A server that fails its handshake stays failed until the user edits it or- presses Test, so session assembly never pays the connect timeout twice.-- Saving an edit that changes **what the server is** (transport, command, args,- env, url, headers) drops the connection; changing label, description or scope- does not.-- The active-process cap is 16, the width the app already uses for per-owner- resource caps; over-cap servers are logged and skipped rather than queued.-- Each server keeps the plugin bridge's own 64-tools-per-server ceiling.+`crates/host-core/src/mcp_servers.rs` owns `McpServerRecord` files under+`~/.agents/servers` or `<project>/.agents/servers`, with activation state in+app-local `<data>/agent-capabilities/mcp.json`, exposed as `mcp.list`,+`mcp.active`, `mcp.upsert`, `mcp.remove`, and `mcp.setEnabled`. Electron main owns+the processes in `UserMcpRuntime`, reusing the plugin bridge's `McpServerClient`:+a server connects when a session that can see it is assembled, a failed handshake+stays failed until the user edits or tests it, and an edit that changes transport,+command, args, env, url, or headers drops the connection while label,+description, or scope do not. Tool names carry the `mcp_` prefix+(`userMcpToolName`), distinct from the bridge's `plugin_`, so an audit line names+the registry that served a call. `commandPolicy` is `trusted` with the child's cwd+in the user's home directory, because no plugin owns the server; spawn-time+resolution of `npx` and `uvx` is shared with the plugin bridge (ADR 0038 / D624).### 4. A pasted `mcpServers` block is the primary way to add one-`parseMcpImport` in `packages/shared` accepts what users actually have on the-clipboard: the `mcpServers` document, the `servers` spelling, a bare map, or a-single server object. It infers `http` from the presence of a `url` because half-the configs in the wild omit `type`; coerces non-string env and header values;-drops non-string args; honours `disabled: true`; and caps an import at 32-servers.--A malformed entry is **reported, not fatal** — the import returns what it-understood plus a per-entry reason for what it skipped, because a fifteen-server-paste with one bad entry should not be all-or-nothing.+`parseMcpImport` in `packages/shared` accepts the `mcpServers` document, the+`servers` spelling, a bare map, or a single server object; it infers `http` from a+`url`, coerces non-string env and header values, honours `disabled: true`, and+caps one import. A malformed entry is reported per entry rather than failing the+whole paste.### 5. User skills are one Markdown document each-`crates/host-core/src/user_skills.rs` scans Markdown documents under-`~/.agents/skills` or `<project>/.agents/skills`. Activation state is app-local-under `<data>/agent-capabilities/skills.json`; no registry or enabled field is-written into a skill document.--The delivery contract is D174's unchanged: the description is what enters the-prompt, the body is fetched only when the model invokes `Skill`, and a document-is capped at 128 KiB. This is why the editor requires a description and places-it above the body — the description is the part that has to earn its context-cost, and it is the only part the model sees until it asks.+`crates/host-core/src/user_skills.rs` scans Markdown under `~/.agents/skills` or+`<project>/.agents/skills`, with activation state in app-local+`<data>/agent-capabilities/skills.json` and RPCs `skills.list`, `skills.active`,+`skills.create`, `skills.import`, `skills.update`, `skills.read`, `skills.remove`,+and `skills.setEnabled`. D174's delivery contract is unchanged: only the+description enters the prompt, the body arrives when the model invokes `Skill`,+and the editor therefore requires a description above the body. User skill ids are+bare while plugin skill ids contain `/`, so `loadUserSkillBody` rejects a slash and+falls through to the plugin catalog.## Consequences-- Adding an MCP server is a paste, and writing a skill is typing Markdown into a- sheet.-- Plugin `enabled` semantics are unchanged for anything that never sets a scope,- so no migration is needed: an absent scope reads as global.-- Extensions remains a two-tab (`installed`, `market`) plugin surface.-- A project-scoped extension contributes nothing to a session with no workspace.-- Two registries now live outside SQLite as JSON files.+- Adding an MCP server is a paste and writing a skill is Markdown; neither needs a+ manifest, package, or signature.+- An absent scope reads as global, so existing plugins need no migration and+ `SCHEMA_VERSION` is unchanged.+- Capability management is three independent Settings > Agent pages while+ Extensions keeps its installed and market tabs, and two registries live as+ hand-editable JSON outside SQLite.+- A project-scoped extension contributes nothing to a session with no workspace,+ which is intended but can surprise a user once.## Alternatives-### Keep requiring a plugin wrapper--Rejected. It is the status quo, and it prices the two most common extensions — a-JSON snippet and a Markdown file — at the cost of publishing software.--### Encode "off" as a third activation mode--Rejected. `mode: "off"` would have to carry the project list anyway to survive a-round trip through off, and every consumer would then have to remember that-`projects` is meaningful in a mode named `off`.--### One merged "Extensions" list across all capability kinds--Rejected. Plugins are installed, MCP servers are configured, skills are written,-and subagents are global prompt documents.--### Filter only the catalog, not dispatch--Rejected. A tool the model can see is a tool it will try to call, and a session-assembled before the user narrowed a scope still remembers the name.--### Scope by session rather than by project--Rejected. Users think about extensions in terms of the codebase they are working-in, not the individual conversation, and a per-session choice would have to be-made again on every new session in the same project.--### Let a project-scoped extension apply to project-less sessions--Rejected as a "safe" default that is the opposite of safe: it would make-`projects` mode wider than it reads, and the sessions it would silently widen-into are the ones with no workspace boundary to contain them.--## References--- `packages/shared/src/activation.ts`, `packages/shared/src/mcp-import.ts`-- `packages/plugin-sdk/src/index.ts` (`userMcpToolName`)-- `crates/host-core/src/mcp_servers.rs`, `crates/host-core/src/user_skills.rs`-- `crates/host-core/src/plugins.rs`, `crates/host-core/src/rpc/mod.rs`-- `apps/desktop/electron/main/user-mcp.ts`,- `apps/desktop/electron/main/index.ts`-- `apps/desktop/src/pages/PluginsPage.tsx`,- `apps/desktop/src/components/extensions/*`-- `apps/desktop/src/styles/extensions.css`-- `docs/spec/07-plugins/01-plugin-system.md`,- `docs/spec/07-plugins/03-plugin-api.md`-- Decisions D192, D193, D194; extends D015, D174, ADR 0038, ADR 0039+- Keep requiring a plugin wrapper: prices a JSON snippet and a Markdown file at+ the cost of publishing software.+- Encode "off" as a third mode: `mode: "off"` would still carry the project list,+ and consumers would have to remember it stays meaningful.+- Filter only the catalog: a session assembled before re-scoping still remembers+ the tool name, so the gap before the next prompt stays open.diff --git a/docs/adr/0057-permission-gated-external-paths-and-portable-search.md b/docs/adr/0057-permission-gated-external-paths-and-portable-search.mdindex 81e8d2ff0..1839abfbf 100644--- a/docs/adr/0057-permission-gated-external-paths-and-portable-search.md+++ b/docs/adr/0057-permission-gated-external-paths-and-portable-search.md@@ -2,86 +2,51 @@- Status: Accepted for implementation (amended by D315)- Date: 2026-08-05-- Baseline: `0.4.14`-- Protocol: v9-- Storage schema: v10## Context-Read/search tools were classified as low risk before their path resolver ran. An-absolute path outside the session workspace therefore bypassed the normal-permission card and failed later as `PATH_OUTSIDE_WORKSPACE`.+Read/search tools were classified as low risk before their path resolver ran, so+an absolute path outside the workspace skipped the permission card and failed+later as `PATH_OUTSIDE_WORKSPACE`, which looked like a broken Plan turn. The host+already had bounded Rust `Read`/`Glob`/`Grep` implementations, but the sidecar+schemas exposed only part of their scoping controls.## Decision### 1. Explicit outside paths are permission-gatedFor `Read`, `Glob`, `Grep`, `Write`, and `Edit`, the host classifies an explicit-path against the session workspace and scratch roots before applying the normal-risk matrix:--- Auto executes the explicit outside path without a card.-- Ask and Accept edits emit the existing inline permission request.-- Allow once covers only the current call; Allow for session uses the existing- tool-name grant scope.-- Deny, timeout, and cancellation return `TOOL_DENIED` without execution.-- Relative parent traversal and symlink escapes use the same rule as absolute- paths.--After approval, host-core resolves the path with the same canonicalized-ancestor-logic used for contained paths. It never turns the external location into a new-workspace root, and implicit Bash cwd or recursive walks do not gain this-exception.+path against the workspace and scratch roots before the risk matrix. Auto+executes it, Ask and Accept edits emit the inline permission request, Allow once+covers one call while Allow for session uses the existing tool-name grant, and+deny, timeout, or cancellation return `TOOL_DENIED`. Relative parent traversal+and symlink escapes follow the same rule, canonicalized resolution is reused, and+the external location never becomes a workspace root. Plan's hard deny for+Write/Edit/plugin/unknown tools still applies.### 2. Native search is the portable default-The runtime exposes the host's complete bounded search contract:--- `Read`: `offset` and `limit`;-- `Glob`: `path` and `limit`;-- `Grep`: `path`, `include`, `outputMode`, `headLimit`, and `caseInsensitive`.--`outputMode` exposes exactly `content`, `filesWithMatches`, and `count` in the-schema. The host also normalizes `files_with_matches` and `files-with-matches`-as compatibility aliases before execution.+The runtime exposes the full bounded contract: `Read` takes `offset` and+`limit`, `Glob` takes `path` and `limit`, `Grep` takes `path`, `include`,+`outputMode`, `headLimit`, and `caseInsensitive`. `outputMode` accepts+`content`, `filesWithMatches`, and `count`, with `files_with_matches` and+`files-with-matches` normalized as compatibility aliases. Grep may exec a+user-installed `rg` (D181 / D315) as an implementation backend without a shell,+keeping budgets and the same JSON shape, and falls back to the in-process+searcher when `rg` is missing or fails.## Consequences-- A Plan inspection outside the project can wait for a clear user decision- instead of failing at the resolver boundary.-- Auto remains suitable for fully automated sessions, while Ask and Accept edits- preserve an explicit consent boundary for external data and mutations.-- Search requests can narrow scope and output before execution, reducing shell- fallbacks, invalid output-mode retries, and context growth.-- External reads and searches are visible through absolute paths; external- mutations do not create workspace Review or artifact records.-- The security denylist remains the default.+- Plan inspection outside the project waits for a user decision instead of+ failing at the resolver.+- Auto still suits fully automated sessions; Ask and Accept edits keep an+ explicit consent boundary.+- Search narrows scope and output before execution, reducing shell fallbacks+ and context growth; the security denylist and host-core authority remain.## Alternatives rejected-### Keep returning `PATH_OUTSIDE_WORKSPACE`--Rejected because the agent cannot distinguish a user-denied request from a-missing permission opportunity, and Plan loses a legitimate inspection path.--### Treat all low-risk reads as Auto--Rejected because a low-risk operation can still disclose data from an unrelated-directory.--### Use shell-specific search commands--Rejected because command availability and quoting differ across macOS, Linux,-and Windows, and unbounded shell output was a measured source of context-exhaustion.--## Related docs--- `docs/spec/03-runtime/03-tools-and-permissions.md`-- `docs/spec/03-runtime/05-host-core-rust.md`-- `docs/spec/03-runtime/06-host-rpc-protocol.md`-- `docs/spec/03-runtime/08-error-codes.md`-- `docs/spec/03-runtime/15-workspace-ignore-rules.md`-- `docs/spec/03-runtime/16-tool-result-limits.md`-- `docs/spec/04-ux/03-permission-ux.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-019/E2E-019e)+- Keep returning `PATH_OUTSIDE_WORKSPACE`: rejected; a denied request is+ indistinguishable from a missing permission opportunity.+- Treat all low-risk reads as Auto: rejected; a low-risk read can still disclose+ data from an unrelated directory.diff --git a/docs/adr/0058-extensions-page-density-and-button-contrast.md b/docs/adr/0058-extensions-page-density-and-button-contrast.mdindex 060c2767f..dd178e1c2 100644--- a/docs/adr/0058-extensions-page-density-and-button-contrast.md+++ b/docs/adr/0058-extensions-page-density-and-button-contrast.md@@ -1,39 +1,34 @@# ADR 0058: Extensions Page Density and Theme-Readable Button Surfaces-- **Status:** Accepted (IA amended by ADR 0112)-- **Date:** 2026-08-05-- **Decision:** D196+- Status: Accepted (IA amended by ADR 0112)+- Date: 2026-08-05+- Related: D196, ADR 0112## Context-The Extensions destination is a focused two-tab plugin surface: Installed and-Marketplace. MCP, Skills, and Subagents are managed independently under Settings-> Agent.+The Extensions destination is a two-tab plugin surface (Installed, Marketplace)+whose four-counter overview band repeated state the tabs, groups, and update+alerts already showed, and the shared button primitive leaned on gray-scale+aliases and transparent fills that left secondary actions weak in dark mode.## Decision-1. Remove the numeric overview band and its four derived counters from the- Extensions page.-2. Define shared primary and secondary buttons with semantic theme tokens:- primary buttons use `--ds-accent` and `--ds-bg-primary`; secondary buttons- use `--ds-bg-secondary`, `--ds-text-primary`, and `--ds-border-default`.-3. Treat this as a renderer presentation change only.+Remove the overview band and its four derived counters, keeping the two tabs with+counts, installed state groups, and pending-update alerts as the hierarchy. Define+primary and secondary buttons on semantic tokens — `--ds-accent` over+`--ds-bg-primary`, `--ds-bg-secondary` with `--ds-text-primary` and+`--ds-border-default`, hover on `--ds-accent-hover` and `--ds-bg-tertiary`. This+is a renderer presentation change only: no plugin, MCP, skill, marketplace,+permission, host, protocol, or storage contract changes.## Consequences-- The page header and segmented control reach the useful content sooner and- preserve more space for extension rows, cards, and editors.-- The source of truth for counts remains close to the surface it describes.-- Primary and secondary actions have an opaque, theme-correct surface and a- visible semantic edge in both dark and light themes.-- Any future overview summary must introduce a distinct action or decision point- rather than repeating tab or group state.--## Alternatives considered--- Keep the overview band and reduce it to two cards: rejected because it still- duplicates state and leaves the four-tab hierarchy uneven.-- Fix only the Extensions page buttons: rejected because the shared `Button`- primitive is used across the app and the contrast defect is systemic.-- Add hard-coded per-theme colors: rejected because it would bypass the semantic- token contract and make future theme changes harder.+- The header and segmented control reach content sooner, with counts next to the+ surface they describe.+- Actions gain an opaque theme-correct surface and a visible semantic edge in+ both themes.++## Alternatives++- Keep the band narrowed to two cards: still duplicates state.+- Hard-code per-theme colors: bypasses the semantic token contract.diff --git a/docs/adr/0059-composer-clipboard-files-in-session-scratch.md b/docs/adr/0059-composer-clipboard-files-in-session-scratch.mdindex 140c3859a..cc7f158c0 100644--- a/docs/adr/0059-composer-clipboard-files-in-session-scratch.md+++ b/docs/adr/0059-composer-clipboard-files-in-session-scratch.md@@ -1,83 +1,57 @@# ADR 0059: Persist Composer Clipboard Files in Session Scratch-- Status: Accepted+- Status: Accepted (amended 2026-09-14, issue #138, which replaced the clipboard+ selection rule)- Date: 2026-08-05-- Deciders: PI-Desktop core-- Related: D197, D209, ADR 0024 (composer commands and @ file references), ADR 0070 (compact reference display), D114 (session scratch directory), D119 (transcript file store)+- Related: D114, D119, D197, D209, ADR 0024, ADR 0070, ADR 0131## Context-The composer is a controlled textarea. Chromium exposes pasted operating-system+The composer is a controlled textarea: Chromium exposes pasted operating-systemfiles and screenshots as `File` objects, while the native picker exposes files-that may live outside the active workspace.+that may live outside the active workspace. The text-only prompt contract has no+binary `ImageContent` channel, an attached file must remain available to the+agent after the prompt is sent, and writing the bytes into the project would+dirty git state.## Decision-The [directory-reference amendment](composer-pasted-directory-references.md)-keeps native directories as path references. This regular-file byte contract-continues to apply to files and images only.--1. The renderer intercepts paste only when the clipboard contains one or more- `File` objects.-2. The renderer transfers bounded file bytes plus the browser-provided name and- MIME type to Electron main through `composer/pasteFiles`, together with the- durable session id.-3. Electron main validates that the session exists, limits the request to 20- files, 64 MiB per file, and 128 MiB total, strips directory components and- unsafe name characters, and writes unique files with exclusive-create- semantics below:-- ```text- <data_dir>/scratch/<sessionId>/pasted/- ```--4. Main returns each UUID-backed absolute path plus its sanitized original leaf- name.-5. Pasted files follow the existing scratch lifecycle: deleting the session or- the orphan/stale startup sweep removes them.--## Security and boundary notes--- The renderer cannot select the destination directory; the session id is- checked in main and the output root is constructed from the host data dir.-- Renderer names are reduced to a basename and sanitized.-- The bridge is Electron-only.--## Alternatives considered--- **Insert the browser file name only:** loses the bytes and gives the agent no- usable path.-- **Write into the workspace:** makes a normal paste dirty the project and- breaks session scratch isolation.-- **Send binary inline with the prompt:** changes the text-only prompt contract,- inflates context, and requires provider-specific attachment handling.-- **Use an Electron file picker for paste:** does not support screenshots and- adds an extra interaction for the common clipboard workflow.+Native directories stay path references, per the+[directory-reference amendment](composer-pasted-directory-references.md); this+byte contract covers files and images only.++1. The renderer intercepts paste only when the clipboard holds `File` objects;+ text-only paste stays native textarea behavior. It prefers editable text when+ that text is not whitespace-only and every accompanying file is `image/*`+ resolving to no native path; any native path, non-image file, or absent or+ whitespace-only text keeps the attachment flow.+2. The renderer transfers bounded bytes plus name and MIME type to Electron main+ through `composer/pasteFiles` with the durable session id; native picker+ selections use `composer/importFiles`.+3. Main validates the session, bounds the payload, strips directory components+ and unsafe name characters, and writes unique files with exclusive-create+ semantics below `<data_dir>/scratch/<sessionId>/pasted/`; the renderer cannot+ choose the destination and picker paths resolve through `realpath` to regular+ files only.+4. Main returns each UUID-backed absolute path plus its sanitized leaf name, which+ ADR 0070 renders as a compact chip and serializes into the prompt as an `@`+ reference, so prompt and transcript carry paths, never clipboard bytes.+5. Pasted files follow the existing scratch lifecycle and never change project+ git status; text above ADR 0131's `largePasteThreshold` likewise becomes a+ session scratch `text/plain` reference.++The bridge is Electron-only: it adds no host RPC method and exposes no arbitrary+filesystem write access to the renderer.## Consequences-- File and image paste works from both home and docked composers without a- project file mutation.-- The visible draft gains compact leaf-name references; the dispatched prompt- gains the same normal `@absolute/path` references, so existing Read/Glob/Grep- behavior handles the materialized files.-- Large or malformed clipboard payloads fail visibly in the composer and do not- partially write because bytes are validated before the first write.--## Amendment (2026-09-14): clipboard text representation for mixed Word pastes+- File and image paste works from home and docked composers without a project+ file mutation, with leaf-name chips in the draft and `@absolute/path`+ references in the dispatched prompt.+- Large or malformed payloads fail visibly and write nothing.-Issue #138: Microsoft Word can place non-whitespace `text/plain` together with-an `image/*` copy of the same selection on the clipboard, so the `File`-only-rule of decision 1 discarded editable text and materialized the image instead.-This amendment replaces that selection rule; the remaining decisions are-unchanged.+## Alternatives-- The renderer selects the clipboard representation before the attachment flow.-- Any native file path, any non-image file, absent or whitespace-only text, and- image-only pastes keep the file and image attachment flow of decision 1.-- Selected text follows ADR 0131's existing `largePasteThreshold`: text at or- below the threshold stays editable inline, and larger text becomes a session- scratch `text/plain` reference.-- Short multiline text is escaped and inserted as text plus generated line- breaks, so paragraphs, blank and trailing lines, the replaced selection, the- surrounding text, the caret, and native undo all survive.+- Insert the browser file name only: loses the bytes and gives no usable path.+- Send binary inline with the prompt: changes the text-only contract and needs+ provider-specific attachment handling.diff --git a/docs/adr/0060-regenerate-branch-archive-under-the-rpc-lock.md b/docs/adr/0060-regenerate-branch-archive-under-the-rpc-lock.mdindex 67a185657..0668955dd 100644--- a/docs/adr/0060-regenerate-branch-archive-under-the-rpc-lock.md+++ b/docs/adr/0060-regenerate-branch-archive-under-the-rpc-lock.md@@ -2,62 +2,66 @@- Status: Accepted- Date: 2026-08-06-- Deciders: PI-Desktop core- Related: D119 (transcript file store), D109 (regenerate history pager),ADR 0041 (decoupled message persistence)## ContextTurn completion in Electron main archived the finished regenerate branch with a-read-modify-write across four host calls: `session.get`,-`session.listRevisions`, `session.saveRevision`, then `session.replaceMessages`-to stamp pager metadata (`revisionRootId` / `revisionCount` / `activeRevision`)-on the user root.+read-modify-write across `session.get`, `session.listRevisions`,+`session.saveRevision`, and `session.replaceMessages`, while assistant and tool+messages reached SQLite asynchronously through the app-owned+`PersistenceOutbox` (ADR 0041). The paths raced: a snapshot taken before the+outbox drained was rewritten as the truth, deleting the message appended in+between, and the rewrite also stripped `turn_id` from every reinserted index+row. An idempotent metadata stamp could therefore destroy a transcript message.## Decision-1. Turn completion calls one new host method, `session.saveActiveRevision`,- which performs read, archive, and stamp inside a single RPC while holding the- host state lock.-2. The pager stamp rewrites exactly one transcript line- (`transcripts::update_message`), copying every other line through verbatim.-3. Electron main drains the persistence outbox before calling, and skips the- archive (with a warning) when the outbox cannot be drained.-4. `session.replaceMessages` keeps each surviving message's owning `turn_id`- across the rewrite.-5. `session.replaceMessages` is documented as safe only for a caller that owns- the whole transcript for the duration of the call.-6. The new method is additive and the protocol version stays at 9.--## Quit-time lifecycle correction (2026-10-07)--An archive can outlive `activeTurns` and an empty append outbox. Previously,-quitting in that interval disposed host-core while `session.saveActiveRevision`-was pending.+### 1. One host call owns read, archive, and stamp-## Alternatives considered+Turn completion calls `session.saveActiveRevision`, which performs all three+inside a single RPC while holding the host state lock, so no transcript snapshot+crosses a process boundary.++### 2. The stamp rewrites one line++The pager stamp updates exactly one transcript line through+`transcripts::update_message`, copying the other lines verbatim and re-reading+the file inside the call, so a line appended after the caller's read survives.++### 3. Archiving skips rather than runs on stale state++Electron main drains the persistence outbox first and skips the archive with a+warning when the drain fails, because an incomplete archived branch stays wrong+forever once a user pages back to it.++### 4. Transcript rewrites keep turn attribution-- **Await the outbox and keep the four-call rewrite:** narrows the window but- does not close it.-- **Stamp through a targeted `session.updateMessage` RPC and keep the archive in- Electron:** still two host calls with the archive reading a snapshot from- outside the lock, so the archived branch can miss the final message even- though the live transcript survives.-- **Make `session.replaceMessages` merge unknown newer messages:** an implicit- merge in a method whose contract is "this is the transcript" would make- regenerate truncation unable to delete anything.-- **Bump the protocol version to 10:** buys no negotiation because handshake- already requires exact equality between components that ship together, and- forces edits to five unrelated frozen-contract guards.+`session.replaceMessages` preserves each surviving message's owning `turn_id`,+and is documented as safe only for a caller that owns the whole transcript for+the duration of the call; read-modify-write from Electron main is unsupported.++### 5. The change is additive++The new method keeps the protocol at version 9: host and Electron ship in one+artifact, and a host without the method fails the call, which the caller already+logs as a skipped archive. A quit-time correction (2026-10-07) makes Electron+track terminal event writes and drain them within the existing quit budget+before host disposal, so a pending archive is not disposed mid-flight.## Consequences-- A turn that completes after a regenerate can no longer lose its final- assistant message, and archived branches contain the whole turn.-- `turn_id` survives transcript rewrites, so per-turn queries and diagnostics- stay accurate after regenerate and tool review updates.-- Electron main holds less transcript logic: the branch root search, the- revision index arithmetic, and the stamp now live in host-core with unit- tests, including one that appends a message after the archive's read.-- Data already lost to the previous behavior is not recoverable; the message is- absent from both the rewritten transcript and the archived revision payload.+- A turn completing after a regenerate can no longer lose its final assistant+ message, and archived branches hold the whole turn.+- `turn_id` survives transcript rewrites, keeping per-turn queries accurate.+- Transcript logic shrinks in Electron main: root search, revision arithmetic,+ and stamping now live in host-core. Data lost before this change is not+ recoverable.++## Alternatives considered++- Await the outbox and keep the four-call rewrite: rejected; it narrows the+ window instead of closing it.+- Merge unknown newer messages inside `session.replaceMessages`: rejected; an+ implicit merge would stop regenerate truncation from deleting anything.diff --git a/docs/adr/0061-imperceptible-background-context-compaction.md b/docs/adr/0061-imperceptible-background-context-compaction.mdindex aa213eca0..2e5175b6f 100644--- a/docs/adr/0061-imperceptible-background-context-compaction.md+++ b/docs/adr/0061-imperceptible-background-context-compaction.md@@ -2,116 +2,75 @@- Status: Accepted (clauses 2, 4, 6, 7, 8 amended by ADR 0064)- Date: 2026-08-06-- Deciders: PI-Desktop core-- Amends: ADR 0030 / ADR 0049 / D158+- Related: ADR 0030, ADR 0047, ADR 0049, ADR 0064, D158, D200## Context-The turn-boundary guard from ADR 0030 is correct: no provider request is issued-above the hard budget, and ADR 0049 gives every automatic failure a durable-retained-tail recovery. What it is not is invisible.--- every successful automatic compaction raised an info toast;-- `compaction_start` set `isRunning`, so the run state and spinner jumped while- nothing the user asked for was running;-- the soft boundary injected a transient instruction asking the model to call- `CompactContext`, which spent a model turn and left a tool-activity row in the- transcript;-- compaction ran only at `tokens >= hardLimit`, so it always happened at the- moment the user was waiting for a reply, with a summary input close to the- whole window in the worst case;--> Corrected by ADR 0064: this section originally added "Codex also has no-> model-side compaction tool at all — the host decides and executes." That is-> wrong. Codex has `new_context`-> (`tools/handlers/new_context_window_spec.rs`), gated by-> `Feature::TokenBudget`, and neither of the two ideas above is Codex's default:-> `BodyAfterPrefix` is opt-in and Codex has no pre-computation to grade a-> trigger for.+The turn-boundary guard of ADR 0030 correctly refuses provider requests above the+hard budget, and ADR 0049 gives automatic failures a durable retained-tail+recovery, but none of it was invisible. Compaction raised a toast, flipped the run+state and spinner, spent a model turn on a `CompactContext` nudge, ran only at the+hard limit while the user was already waiting for a reply, and exposed tuning+knobs in Settings. Its fixed `reserveTokens` and `keepRecentTokens` defaults also+applied the same absolute counts to a 32k and a 1M window.## Decision-Compaction becomes a host-owned background activity that the user cannot-perceive. The blocking hard boundary is unchanged and remains the safety net.--1. **Tiered budget, derived from the model window.** `contextBudget()` keeps- `hardLimit` and `requestHeadroom` exactly as ADR 0030 defined them, and adds- `backgroundLimit = floor(hardLimit * 0.7)` as the pre-computation trigger.-2. **Incremental trigger scope.** Background pre-computation requires both- `tokens >= backgroundLimit` and growth of at least `keepRecentTokens` since- the baseline recorded when the newest checkpoint was installed.-3. **Generation is separated from installation.** `buildCheckpoint()` runs the- preparation, budget preflight, and summary request without persisting- anything or touching `activeCompaction`.-4. **Provider-idle windows only.** Background summary requests are started from- exactly two places: `tool_execution_start`, where the model stream has ended- and the next request has not been issued, and the `finally` of `prompt()`,- where the user is reading the result.-5. **Staleness is checked at install, and failure is silent.** A pre-computed- checkpoint is consumed at the next turn boundary or user prompt only if the- checkpoint it was based on is still active, its `throughMessageId` anchor is- still present in `fullEntries`, and it still fits the *current* model's- budget.-6. **No model-facing compaction.** `CompactContext`, the `<context_management>`- nudge, and the `"CompactContext"` entry in the host-core no-confirmation- allowlist are removed.-7. **Silence.** `compaction_start` and `compaction_end` carry an optional- `phase?: "background" | "blocking"` (absent means `blocking`; additive per- ADR 0047, so the protocol version does not change).-8. **The context inspector is the only visible trace.** `compaction_end` carries- `status: { generation, summaryTokens }`, and the durable- `SessionDetail.compaction` provides the same on session open or fork.-9. **No settings.** The Settings compaction card, its search keywords, its i18n- keys, and the main-process passthrough are removed.--Manual `/compact` is unchanged and remains fail-fast.+Compaction becomes host-owned background work the user cannot perceive. The+blocking hard boundary is unchanged and remains the safety net.++1. The budget is tiered and derived from the model window. `contextBudget()` keeps+ `hardLimit` and `requestHeadroom` as ADR 0030 defined them, adds+ `backgroundLimit` as the pre-computation trigger, and derives+ `keepRecentTokens` from the hard budget. The soft boundary and its `softGap`+ are deleted.+2. The background trigger is incremental: it fires only when usage exceeds+ `backgroundLimit` and has grown by `keepRecentTokens` since the baseline of the+ newest checkpoint. The hard boundary keeps measuring the total, because that is+ the provider's actual constraint.+3. Generation is separated from installation. `buildCheckpoint()` runs the+ preparation and summary request without persisting anything or touching+ `activeCompaction`, while `installCheckpoint()` re-estimates, appends through+ host-core, updates the anchor, and emits `compaction_end`. The blocking path+ composes both back to back, so threshold, overflow, and manual behavior are+ unchanged.+4. Background requests start only in provider-idle windows, from+ `tool_execution_start` and the `finally` of `prompt()`. They never share the+ connection with a streaming turn, and they leave `compactionInProgress` unset+ because that flag feeds `getStatus().isRunning`.+5. A pre-computed checkpoint is installed only if its base checkpoint is still+ active, its `throughMessageId` anchor is still present, and it fits the current+ model's budget. Any miss discards it and falls back to the blocking path; a+ failed background build is dropped without persisting, without an event, and+ without the ADR 0049 fallback, which belongs to the hard boundary.+6. No model-facing compaction remains. `CompactContext`, the+ `<context_management>` nudge, and its no-confirmation allowlist entry are+ removed, so triggering is fully deterministic and host-driven.+7. The lifecycle events carry an optional `phase?: "background" | "blocking"`+ field, additive per ADR 0047. A successful automatic compaction notifies+ nobody: toasts remain only for a retained-tail fallback, an overflow retry, and+ a manual `/compact` result.+8. The inspector is the only visible trace. `compaction_end` carries+ `status: { generation, summaryTokens }`, and `SessionDetail.compaction`+ provides the same on session open or fork. The generation counter rides inside+ the checkpoint's opaque persisted `details`, so no record schema changes.+9. The Settings compaction card and its passthrough are removed, and persisted+ `contextCompaction` values are ignored, because a user who once disabled the+ guard would have no switch left. The type survives only as a+ construction-time override for tests.## Consequences-- In the common case the user never waits for compaction.-- Summary inputs are smaller and cheaper, because 0.7 of the hard limit is a- much smaller history than the hard limit itself.-- A session that crosses the background limit pays for a summary it might not- have needed. 0.7 is the cost trade: past that point reaching the hard limit is- close to inevitable, so the tokens are rarely wasted, while a lower ratio- would bill short sessions for summaries they never use.-- Small-window and large-window models now get proportionate budgets instead of- one pair of absolute token counts.-- Losing the model-side tool removes a class of wasted turns and a transcript- artifact, and removes the possibility of the model ignoring, deferring, or- repeating the request.+- In the common case nobody waits for compaction: the summary overlaps a tool+ execution or an idle session and the turn boundary installs a finished+ checkpoint.+- Small and large windows get proportionate budgets, and losing the model-side+ tool removes a class of wasted turns and a transcript artifact.+- Compaction is no longer auditable from the transcript, which is an accepted+ reversal of ADR 0030, and users can no longer disable the guard.## Alternatives-### Compact concurrently with the streaming turn--Rejected. It would remove the last of the latency, but two simultaneous requests-on one provider connection invite rate limiting (observed on Bedrock) and double-the visible cost of a single user action.--### Keep the soft-boundary nudge alongside background compaction--Rejected. With deterministic pre-computation the nudge adds only the failure-modes it always had — a spent turn, a transcript row, and a model free to ignore-it.--### Keep the settings knobs but hide them behind a developer toggle--Rejected. The values are now derived from the model window; an override would be-a way to reintroduce the small-window/large-window defect, and a hidden switch-to disable a safety guard is worse than no switch.--### Show a subtle inline indicator while compacting--Rejected. Any persistent indicator makes the user aware of a mechanism they-cannot act on.--## References--- `docs/spec/03-runtime/01-ipc-protocol.md`-- `docs/spec/03-runtime/02-agent-runtime.md`-- `docs/spec/03-runtime/03-tools-and-permissions.md`-- `docs/spec/04-ux/06-settings-ia.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `docs/spec/08-meta/decisions-log.md` (D158, D200)-- `codex-rs/core/src/session/context_window.rs` (behavioral reference)+- Compact during the streaming turn: two requests on one connection invite rate+ limiting and double the visible cost.+- Keep the soft-boundary nudge: it adds only the failure modes it always had.diff --git a/docs/adr/0062-bounded-subagents-behind-a-task-tool.md b/docs/adr/0062-bounded-subagents-behind-a-task-tool.mdindex ac4bb1c2e..9fa8e25d9 100644--- a/docs/adr/0062-bounded-subagents-behind-a-task-tool.md+++ b/docs/adr/0062-bounded-subagents-behind-a-task-tool.md@@ -5,126 +5,97 @@opt-in parent-tool inherit amended by ADR 0246; resumable delegations amendedby ADR 0279; report spillover amended by RFC #1196)- Date: 2026-08-06-- Deciders: PI-Desktop core-- Related: D201, ADR 0041 (persistence outbox), ADR 0048 (lazy per-turn tool- activation), ADR 0053 (plan checkpoint and execution epoch), D123 (prompt- template documents), D138 (session-scoped inline permission requests),- D198 (contract modes), ADR 0112 (capability roots and Settings IA), ADR 0119- (event-driven subagent timeouts), D265 (one delegation reads as a card too),- ADR 0246 (opt-in `tools: inherit`), ADR 0279 (resumable delegations)+- Related: ADR 0041, ADR 0048, ADR 0053, ADR 0112, ADR 0119, ADR 0246,+ ADR 0279, D123, D138, D198, D201, D265## Context-A single agent loop pays for everything it reads. Wide searches, long build logs-and multi-file surveys are separable work whose intermediate output is worthless-once the conclusion is known, yet all of it lands in the session's context-window and stays there for the rest of the task.+A single agent loop pays for everything it reads: wide searches, long build logs,+and multi-file surveys land in the session context and stay there for the rest of+the task, and compaction can only recover space afterwards. Delegation runs the+separable piece in its own context and returns a report, so the open questions+are the boundaries: where definitions come from, what a delegate may do to the+workspace, how its rows relate to the parent, and what happens when several+delegates need the user at once.## Decision### 1. Definitions are Markdown documents, builtin plus global user documents-A subagent definition is frontmatter plus a Markdown body that becomes the-delegate's system prompt, mirroring prompt templates (D123):--```text-~/.agents/subagents/<name>.md-```--PI-Desktop ships three builtins inline in `agent-runtime` (`explorer`,-`code-reviewer`, `test-runner`). User documents under `~/.agents/subagents` are-combined with the builtins by name.+A definition is frontmatter plus a Markdown body that becomes the delegate's+system prompt (D123), stored as `~/.agents/subagents/<name>.md`. Three builtins+(`explorer`, `code-reviewer`, `test-runner`) ship inline in `agent-runtime` and+merge with the global user catalog by name at each session launch, capped at+`MAX_SUBAGENT_DEFINITIONS`, with a malformed document degrading to a launch+diagnostic.### 2. A definition declares its tools, and is read-only when it does not-`tools` may only name file, search and shell tools (`SUBAGENT_ASSIGNABLE_TOOLS`:-Read, Glob, Grep, BrowserPreview, Bash, Edit, Write). Plugin, skill, mode and-meta tools are out of reach: a delegate is a bounded worker, not a second full-session.--Every delegate tool call goes through the same `tools.execute` host path as the-parent's, so containment, permission modes and hard denies are unchanged. A-delegate cannot ask the model-facing questions the parent can: no plan or goal-submission, no mode transition, no nested `Task`.+`tools` may only name `SUBAGENT_ASSIGNABLE_TOOLS` — file, search, and shell+tools — so plugin, skill, mode, and meta tools stay out of reach; omitting+`tools` grants `Read, Glob, Grep`, and `tools: "*"` expands to the assignable+set. Calls pass through the same `tools.execute` path, and a delegate cannot+submit a plan, change mode, or nest a `Task`.### 3. A definition may pin its own provider and model-`model: <provider>/<model>` binds a delegate to a specific model regardless of-the session's. Pins are resolved once per launch in Electron main, where-credentials and the pi model catalog live, and are capped at-`MAX_SUBAGENT_PROVIDERS` (8) distinct providers.--An unresolvable pin (no matching provider, no API key) is left out of the-binding map instead of falling back to the session provider, and the `Task` call-fails with a tool error naming the pin. A definition that asks for a cheap model-must never silently spend the expensive one.+`model: <provider>/<model>` binds a delegate regardless of the session model,+resolved once per launch in Electron main and capped at+`MAX_SUBAGENT_PROVIDERS` distinct providers, matching on id, vendor key, or+display name. An unresolvable pin is left out of the binding map and the `Task`+call fails with a tool error naming it, so a cheap definition never silently+spends the expensive model.### 4. Delegation is one Agent-mode tool, and parallel by construction-Proposed amendment: [parallel file batches](parallel-read-batches.md) allows-Read/Glob/Grep/Write/Edit candidates, isolates delegate path-instruction-preparation, keeps a batch that mixes Task with those file tools sequential, and-holds a read or search ordered after a writable Task behind the delegate-completion boundary. The original only-Task batch policy below is historical.--The `Task` tool takes `agent`, `task` and an optional short `description`. The-catalog of available delegates rides in the tool description rather than the-system prompt, because the two change together.+`Task` takes `agent`, `task`, and an optional `description`, carries its+delegate catalog in the tool description, and executes only in Agent mode, where+Plan and Goal keep their Task-family schemas declared but deny execution before+a delegate exists (D198). Concurrency comes from pi's execution modes, so only+an all-`Task` batch fans out, bounded by `MAX_SUBAGENT_CONCURRENCY`, with a+sidecar `PathMutex` serializing same-path mutations and the parent's bounded+retry policy applied to every delegate.### 5. The parent's context gains the report, and only the report-A `SubagentRun` is a second pi `Agent` in the same sidecar process. Its final-message, bounded to `MAX_SUBAGENT_REPORT_CHARS` (12k), becomes the `Task` tool-result, with `agent`, `status`, `turns`, `toolCalls` and `usage` as structured-details.--When a delegate's completed report exceeds `MAX_SUBAGENT_REPORT_CHARS`, the-runtime preserves the full, unclipped report in the session scratch directory-(`<data_dir>/scratch/<sessionId>/delegations/<parentToolCallId>/report.md`; an-opaque ID containing path separators is encoded before it is used as a path-component) and returns a compact pointer notice (`Complete subagent report (N-characters) was saved to: <path>`) alongside `scratchReportPath` in the-structured result. If scratch persistence fails, it degrades gracefully to-bounded head/tail clipping with a truncation marker.+The delegate's final message becomes the `Task` result, capped at+`MAX_SUBAGENT_REPORT_CHARS`, with `agent`, `status`, `turns`, `toolCalls`, and+`usage` as details; an oversized report is preserved under the session scratch+`delegations/<parentToolCallId>/report.md` and returned as a pointer notice.+Delegate rows persist with `parentToolCallId` and `agentName` for review but are+skipped when model context is rebuilt, so only the report reaches the parent and+a delegate's termination collapses into the tool result.### 6. Attribution is persisted, and the transcript derives its topology from ithost-core stores `parentToolCallId` and `agentName` in the message `meta`-object, so a reloaded session nests identically to a live one. The renderer-groups every attributed row under the `Task` row that spawned it and renders-them one level in; the turn stream and the minimap see only the parent's rows.--Every `Task` call in an activity group is drawn as a delegation summary, a lone-one included (D265). Consecutive `Task` starts are the only rows in that group-(D319): parent thinking, workspace tools, and lifecycle rows stay in ordinary-processing groups around the card.+object, so a reloaded session nests exactly like a live one, with attributed+rows rendered one level in under the spawning `Task` row while the turn stream+and minimap see only parent rows. Every `Task` call draws as a delegation+summary (D265) whose header derives counts and status from those tool messages,+and live and reloaded views derive the same topology from the persisted ids+without adding a graph record, edge, IPC field, or storage schema.### 7. Permission requests queue per session-The renderer used to hold one pending permission per session. Parallel delegates-break that: two delegates can each be waiting on a `Bash` call.+Pending requests become a per-session queue, oldest first, where only the head is+answerable, answers match by request id, a host-expired request is removed by+tool call id, and an abort denies the whole queue. The card names the delegate+that asked and how many requests wait behind it.-## Alternatives considered+## Consequences-- **Serial delegates in v1.** Simpler, and it would have avoided the path lock- and the permission queue.-- **Inherit the session model always.** Cheaper to reason about.-- **Let delegates inherit the parent's tools.** Rejected for silent, always-on- inherit: it makes every delegation as dangerous as the session, and a- definition is the only place a reader can see what a delegate may do.-- **A separate process per delegate.** Real isolation, but it duplicates the- host connection, provider setup and event plumbing for a bounded worker that- already runs under host-core containment.+- Wide searches, reviews, and command runs leave the session context at the price+ of one report each, and a user can add a delegate under `~/.agents/subagents`+ without a rebuild.+- Two capability surfaces exist for the same tools: a delegate can be strictly+ weaker than its session, never stronger.+- Delegate rows lengthen transcripts on disk but stay collapsed and out of model+ context, while review and rollback still see them.-## Consequences+## Alternatives considered-- Wide searches, reviews and command runs move out of the session's context at- the price of one report each.-- A user can add a delegate under `~/.agents/subagents`; no rebuild, no settings- change, effective on the next prompt when enabled locally.-- Two capability surfaces now exist for the same tools: the session's mode and a- definition's `tools` list.-- The permission UX must handle more than one waiting request, which is visible- to any user of parallel delegates.-- Delegate rows make transcripts longer on disk; they stay collapsed and out of- model context, but review and rollback still see them.+- Serial delegates in v1: rejected; fanning out a survey is most of the value,+ and retrofitting concurrency would redo the transcript and permission work.+- Feed delegate messages back into the parent's context: rejected; that is+ exactly the cost delegation removes.diff --git a/docs/adr/0063-subagent-management-ui.md b/docs/adr/0063-subagent-management-ui.mdindex d0a6508a1..7dadb5d0c 100644--- a/docs/adr/0063-subagent-management-ui.md+++ b/docs/adr/0063-subagent-management-ui.md@@ -7,49 +7,41 @@## Context-ADR 0062 shipped subagents without a renderer surface. A user could create a-personal delegate only by placing a Markdown document in an implementation--specific location, and the shipped catalog was not visible in Settings.+ADR 0062 shipped subagents without a renderer surface: a personal delegate meant+placing a Markdown document in an implementation-specific location. The surface must+not write tracked project files or invent a project-level source that differs from+the runtime contract.## Decision### 1. Global documents are the only user-managed subagent source-User-owned definitions are Markdown files in:--```text-~/.agents/subagents/<id>.md-```--There is no project-level subagent directory. The application does not scan or-write `.pi/agents` for capability management.+User definitions are `~/.agents/subagents/<id>.md`; there is no project-level+subagent directory and the application never scans or writes `.pi/agents`.+`id == name` stays the model's `Task` handle, duplicate names are rejected.### 2. Activation is app-localThe document owns prompt metadata (`name`, `description`, `tools`, `model`,-`thinkingLevel`, and `maxTurns`) but never owns `enabled`. The enabled state is-stored in `<data>/agent-capabilities/subagents.json`.+`thinkingLevel`, `maxTurns`) but never `enabled`, which lives in+`<data>/agent-capabilities/subagents.json`; scanning removes state for deleted+documents.### 3. The Settings page is global-only-Settings > Agent > Subagents is one fixed-height global list. It has no project-picker, project column, or add/import action in this surface.--Skills and MCP have separate Settings destinations and are not tabs inside-Extensions. Extensions itself contains only Installed and Marketplace.+Settings > Agent > Subagents is one fixed-height global list with no project picker+or import action; each row shows the frontmatter summary and an app-local enable+switch. Skills and MCP keep separate destinations, and Extensions holds only+Installed and Marketplace.### 4. The runtime remains the source of truth-Electron supplies the global user documents to `loadSubagentDefinitions` on the-next prompt. The renderer does not reimplement catalog precedence or invent a-project source.+Electron supplies the global documents to `loadSubagentDefinitions` on the next+prompt; the renderer reimplements no precedence.## Consequences-- Personal delegates follow the user across projects without modifying a- repository.-- Teams that need a repository-specific prompt must use the project's normal- instruction mechanism; `.pi/agents` is not a capability source.-- The UI can show and persist local enablement without changing Markdown files.-- There is no project-scoped subagent toggle, so project precedence applies to- Skills and MCP only.+- Personal delegates follow the user across projects, while teams needing a+ repository-specific prompt use the project instruction mechanism.+- Enablement persists outside the Markdown, and project precedence applies to Skills+ and MCP only.diff --git a/docs/adr/0064-codex-parity-context-compaction.md b/docs/adr/0064-codex-parity-context-compaction.mdindex f1cff59bf..ca03caeb3 100644--- a/docs/adr/0064-codex-parity-context-compaction.md+++ b/docs/adr/0064-codex-parity-context-compaction.md@@ -2,163 +2,97 @@- Status: Accepted (automatic trigger amended by D623 / issue #970)- Date: 2026-08-06-- Deciders: PI-Desktop core- Amends: ADR 0061 / ADR 0030 / D158 / D200; amended by ADR 0136+- Related: [08-meta/decisions-log](../spec/08-meta/decisions-log.md) (D203)## Context-ADR 0061 made compaction imperceptible and cited Codex as the reference for-doing so. Reading the Codex sources afterwards showed that four of its clauses-are the opposite of what Codex actually does, and that one factual claim in its-Context section is wrong:--| Codex | ADR 0061 |-| --- | --- |-| Compaction is synchronous only; there is no pre-computation anywhere | Checkpoints are pre-computed in provider-idle windows (clause 4) |-| The auto-compact threshold scope defaults to the whole context; `BodyAfterPrefix` is opt-in | The background trigger measures the increment since the last checkpoint (clause 2) |-| Every compaction emits a `ContextCompaction` turn item **and** an `EventMsg::Warning` | A successful compaction notifies nobody and leaves no row (clauses 7, 8) |-| `new_context` is a real model-facing tool, gated by `Feature::TokenBudget` | "Codex also has no model-side compaction tool at all" (line 31); the tool is removed (clause 6) |-| After compaction the model context keeps recent **user** messages (≤20k tokens) plus the summary | The retained tail keeps whole recent turns, assistant and tool messages included |-| Two families: LLM-summary compaction and a no-summary rollover into a fresh window | One family, always summarized |-| Two-tier budget reminders (`TokenBudgetReminder`, then `AutoCompactFallbackPrompt`), each once per window | No model-facing nudge at all (clause 6) |--- `core/src/compact.rs` — `COMPACT_USER_MESSAGE_MAX_TOKENS = 20_000`;- `build_compacted_history_with_limit()` walks history newest-first keeping only- user messages, truncates the one that crosses the limit, `reverse()`s back- into order, then appends the summary; `:384` raises `EventMsg::Warning` after- every compaction.-- `core/src/compact_token_budget.rs` — the no-summary path runs the same- compaction lifecycle, emits the same `ContextCompaction` turn item, and then- calls `start_new_context_window()`.-- `session/mod.rs:3665 start_new_context_window()` — history is cleared to the- initial context plus the turn context item, with `message: String::new()`.-- `session/turn.rs:423` — `should_roll_over = needs_follow_up &&- (take_new_context_window_request() || token_limit_reached)`: the trigger is- evaluated at a turn boundary, inline.+ADR 0061 made compaction imperceptible and cited Codex as its reference, but+reading the Codex sources showed that four of its clauses describe the opposite of+what Codex does: Codex compacts synchronously with no pre-computation, measures the+whole context rather than an increment, announces every compaction with a turn item+and a warning, and keeps a model-facing `new_context` tool. The user was told that+parity reverses the imperceptibility goal and reaffirmed the request.## DecisionCompaction follows Codex's mechanism. ADR 0030's hard boundary, ADR 0049's-retained-tail recovery, ADR 0061's model-window-derived budgets, and ADR 0061's-`buildCheckpoint` / `installCheckpoint` split all stay; ADR 0061 clauses 2, 4,-6, 7, and 8 are replaced.--1. **Inline only.** All background pre-computation is deleted:- `pendingBackgroundCheckpoint`, `backgroundCompaction`, `backgroundAbort`,- `checkpointBaselineTokens`, `backgroundLimit`, and the three call sites in- `tool_execution_start`, `prompt()`, and the run `finally`.-2. **Codex's retained shape.** `codexShapedPreparation()` keeps- `prepareCompaction()`'s cut point (and therefore its turn-boundary and- split-turn handling), then folds `turnPrefixMessages` and `retainedTail` back- into `messagesToSummarize` so the summary covers the entire compacted range,- and rebuilds the retained tail as user messages only:- `selectRetainedUserMessages()` walks the compacted range plus the previous- checkpoint's retained users newest-first up to- `COMPACTION_RETAINED_USER_MESSAGE_MAX_TOKENS = 20_000` (capped at half the- hard budget so retention alone cannot fill a small window), truncates the- message that crosses the limit instead of dropping it, and reverses back into- chronological order.-3. **Two families behind an internal switch.** `CompactionStrategy = "summary" |- "fresh_window"` resolves from a construction option, then- `PI_DESKTOP_COMPACTION_STRATEGY`, defaulting to `"summary"`.-4. **`new_context` is back.** The tool is parameterless and carries Codex's- description verbatim; executing it only sets `pendingModelCompaction` and- returns the family's rollover message.-5. **Two-tier reminders, once each per window.** With `remaining = hardLimit -- tokens`: tier one at `remaining <= clamp(hardLimit * 0.15, 8k, 32k)` states- the remaining budget and asks the model to start closing out; tier two at- `remaining <= 2_000` tells it to write down now whatever must survive.-6. **The whole checkpoint chain is durable.** `read_compactions()` and- `write_transcript_with_compactions()` replace their latest-only predecessors;- `sessions.rs` validates, forks, and remaps every record and adds- `compactions: Vec<CompactionRecord>` to the session detail payload, keeping- `compaction` as its last element.+retained-tail recovery, and ADR 0061's model-window budgets and `buildCheckpoint` /+`installCheckpoint` split stay; ADR 0061 clauses 2, 4, 6, 7, and 8 are replaced.++1. **Inline only.** All background pre-computation is deleted, and `prompt()` plus+ `prepareNextTurn()` re-estimate at their pre-request boundaries and compact+ synchronously once the estimate reaches the soft threshold, while `hardLimit`+ remains the safety guard no request may cross.+2. **Codex's retained shape.** Preparation keeps its cut point and turn-boundary+ handling, folds the prefix and retained tail into the summarized range so the+ summary covers everything compacted, and rebuilds the retained tail as user+ messages only, truncating the message that crosses the retention cap. Dropping+ assistant messages also drops their tool calls, so no orphaned `tool_use`+ reaches the provider.+3. **Two families behind an internal switch.** `CompactionStrategy` of `"summary"`+ or `"fresh_window"` resolves from a construction option and then+ `PI_DESKTOP_COMPACTION_STRATEGY`, where `fresh_window` issues no summary request+ and installs a checkpoint with an empty tail and a fixed rollover marker through+ the identical lifecycle. The switch reaches neither `AppSettings`, Settings, nor+ i18n.+4. **`new_context` is back.** The parameterless tool only sets the pending+ compaction and returns the rollover message, and its name is synchronized across+ `activeTools()`, `isCoreTool()`, the contract-mode allowlists, and the host-core+ no-confirmation allowlist.+5. **Two-tier reminders, once each per window.** A remaining-budget reminder asks+ the model to close out and a second tells it to write down what must survive,+ both claims reset when a checkpoint is installed, and the reminder is appended to+ the turn's system prompt and restored afterwards, so it never enters the+ transcript or durable history.+6. **The whole checkpoint chain is durable.** Transcript reads and writes cover+ every record, session detail carries `compactions` with `compaction` as its last+ element, and forks validate and remap every record.7. **One transcript row per compaction, and a warning every time.**- `compaction_end` carries `mark?: ContextCompactionMark` (`id`,- `throughMessageId`, `generation`, `summaryTokens`, `summarized`) instead of- ADR 0061's `status`, and drops `phase` entirely; the durable records supply- the same marks on session open or fork.+ `compaction_end` carries `mark?: ContextCompactionMark` instead of a status and+ drops `phase`, a `kind: "compaction"` entry follows its anchor message, and a+ successful compaction always raises a warning toast.-Manual `/compact` is unchanged and remains fail-fast. Settings still exposes no-compaction controls and still ignores persisted `contextCompaction` values (ADR-0061 clause 9).+Manual `/compact` stays fail-fast, and Settings still exposes no compaction+controls.### Deliberate deviations from Codex-- **Summary position.** Codex appends the summary after the retained user- messages.-- **Task boundary.** ADR 0136 narrows the retained tail: an active turn may- retain only its latest user message, while a completed-turn checkpoint has an- empty tail so the next prompt cannot be mistaken for a continuation of- completed work.-- **`hardLimit` derivation.** Codex compacts at 90% of the window; we keep ADR- 0030's "window − output reserve".-- **Tool registration.** Codex gates `new_context` behind- `Feature::TokenBudget`, so it exists only for the no-summary family.-- **Reminder thresholds and text.** Codex reads both from per-model metadata.-- **Reminder delivery.** Codex injects synthetic history items.+- **Summary position.** pi-agent-core emits the summary before the retained tail,+ and that order is not ours to choose.+- **Task boundary.** ADR 0136 narrows the retained tail, so an active turn keeps+ only its latest user message and a completed-turn checkpoint has an empty tail.+- **`hardLimit` derivation.** We keep ADR 0030's window-minus-reserve number,+ because we have no separate full-window guard and an oversized request is a hard+ provider error.+- **Tool registration and reminders.** `new_context` is registered in both+ families, and reminder thresholds derive from `hardLimit` with our own wording,+ delivered as a per-turn system-prompt append rather than synthetic history.## Consequences-- Compaction is paid for at the moment the user is waiting again.-- Model context after a compaction is much smaller and much lossier: no- assistant reasoning and no tool output survives except through the summary.-- The summary input covers the entire compacted range rather than the range- minus the tail, so each summary request remains larger than under ADR 0061.-- The 90% safety trigger intentionally pays for some additional summaries to- reduce provider-side context overflows; `hardLimit` remains the fail-closed- backstop.+- Compaction is paid for while the user waits, so ADR 0061's zero-wait property is+ gone and model context after a compaction is much smaller and lossier, while the+ visible transcript stays untouched.- Compaction is auditable from the transcript again, restoring ADR 0030's- visibility property that ADR 0061 reversed.+ visibility, and every compaction interrupts the user with a warning.+- The model may ignore the reminders, and the no-summary family ships unreachable,+ existing so the mechanism is complete and testable.## Alternatives-### Keep background pre-computation and add the visible row and warning--Rejected. The user asked for Codex's mechanism, not a superset of it, and a-pre-computed checkpoint that installs at an unrelated turn boundary makes the-row's position arbitrary.--### Filter the retained tail to user messages without folding it into the summary--Rejected as a correctness bug: `prepareCompaction()` summarizes only below the-cut point, so the dropped assistant and tool messages inside the tail would be-covered by nothing.--### Set `keepRecentTokens: 0` and let `prepareCompaction()` produce an empty tail--Rejected. When the last entry is a tool result, `findCutPoint()` falls back to-the earliest valid cut point, which discards far more than intended.--### Expose the family switch in Settings--Rejected. Codex does not expose it, and no user can judge "no summary at all"-against "one summary request" from a settings row.--## References--### Implementation note (2026-10-03)--The desktop runtime now owns the compaction preparation and context projection-described here because pi-agent-core removed its experimental harness APIs.-Cut-point, split-turn, retained-tail, and summary behavior remain governed by-this ADR and the runtime specification; durable checkpoint ownership remains-with Rust host-core.--- `docs/spec/03-runtime/01-ipc-protocol.md`-- `docs/spec/03-runtime/02-agent-runtime.md`-- `docs/spec/03-runtime/03-tools-and-permissions.md`-- `docs/spec/03-runtime/04-data-storage.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/04-ux/09-interaction-patterns.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `docs/spec/08-meta/decisions-log.md` (D158, D200, D203)-- `codex-rs/core/src/compact.rs`, `compact_token_budget.rs`,- `session/token_budget.rs`, `tools/handlers/new_context_window_spec.rs`- (behavioral reference)+- Keep background pre-computation and add the row and warning: rejected, a+ pre-computed checkpoint installs at an unrelated turn boundary.+- Filter the retained tail without folding it into the summary: rejected as a+ correctness bug, because the dropped content would be covered by nothing.+- Expose the family switch in Settings: rejected, no user can judge "no summary"+ against "one summary request".## Amendment (2026-09-23, D623 / issue #970): Earlier inline compaction trigger-The inline-only lifecycle is unchanged. Automatic compaction now starts at 90%-of the derived safe budget from both new-prompt preflight and in-run-turn-boundary checks.+The inline-only lifecycle is unchanged, and automatic compaction now starts at 90%+of the derived safe budget from both new-prompt preflight and in-run turn-boundary+checks, leaving a deterministic margin for estimator drift during the preceding+turn. A failed soft-trigger compaction may proceed only while the context stays+below `hardLimit`, and no settings, background work, host protocol, or storage+semantics are added.diff --git a/docs/adr/0065-smooth-shell-layout-and-stream-feedback.md b/docs/adr/0065-smooth-shell-layout-and-stream-feedback.mdindex d4b390e98..4fce43d7b 100644--- a/docs/adr/0065-smooth-shell-layout-and-stream-feedback.md+++ b/docs/adr/0065-smooth-shell-layout-and-stream-feedback.md@@ -2,55 +2,44 @@- Status: Accepted for implementation- Date: 2026-08-07-- Deciders: PI-Desktop core- Related: ADR 0033, ADR 0122, D146, D163, D255## Context-The shell's sidebar and work panel already used enter/exit keyframes, but the-keyframes changed only opacity and a small transform. Their flex allocations-changed to the final width as soon as the element mounted, so MainChat moved-before the first visible frame and moved back after the exit animation.+Sidebar and work-panel keyframes changed only opacity and a small transform+while the flex allocation jumped to its final width on mount, so MainChat moved+before the first visible frame. Agent streams also applied every+`message_update` and `tool_update` immediately, spending frames on historical+transcript work, and the docked composer painted a full-width gradient veil that+carried no state.## Decision-1. Sidebar and work-panel mount/exit animations animate both `width` and- `flex-basis` from zero to the committed dock width, in addition to the- bounded opacity/transform feedback.+1. Sidebar and work-panel mount/exit animations animate `width` and `flex-basis`+ from zero to the committed dock width alongside the opacity/transform+ feedback, keeping the panel an in-flow fixed-width column.2. The renderer coalesces high-frequency `message_update` and `tool_update`- events by stream target until the next animation frame.-3. `ChatTranscript` uses React's deferred value for the heavy grouped-entry- projection and minimap input.-4. The docked composer uses a transparent outer dock with bottom space reserved- by the transcript; the composer shell remains the only elevated surface.-5. An activity group only receives terminal failure styling after its active run- settles.+ events per stream target until the next animation frame, applying only the+ newest event; any control or terminal event flushes the batch first.+3. `ChatTranscript` defers the heavy grouped-entry projection through React's+ deferred value while permission, running, and terminal state stay+ synchronous.+4. The docked composer keeps a transparent outer dock with space reserved by+ the transcript, so the composer shell remains the only elevated surface.+5. A group takes terminal failure styling only after its active run settles, so+ an intermediate error row does not make a retrying run look finished.## Consequences-- Opening and closing auxiliary columns now reflows MainChat continuously over- the bounded motion duration instead of jumping before the animation.-- A stream may display the newest partial content one paint later when events- arrive faster than the display refreshes, but redundant intermediate payloads- are discarded and terminal events are never delayed.-- Long transcripts still need a future true virtualization pass; this decision- reduces update pressure without changing message persistence or grouping.-- Removing the dock veil makes the transcript surface visually quieter and keeps- the composer separation dependent on its measured layout and elevation.+- Auxiliary columns reflow MainChat continuously instead of jumping first.+- Newest partial content can appear one paint later, but redundant payloads are+ dropped and terminal events are never delayed.+- Long transcripts still need real virtualization; this reduces update pressure+ without changing persistence or grouping.## Alternatives considered-### Transform-only dock animation--Rejected because it leaves the flex allocation at its final value before the-first painted frame, which is the source of the visible layout jump.--### Overlay the work panel above MainChat--Rejected for this change because the current frozen shell contract is a docked-third column with a fixed committed width.--### Debounce all agent events--Rejected because lifecycle, permission, planning, and terminal events need-immediate ordering.+- Transform-only dock animation: rejected; the flex allocation still jumps+ before the first painted frame.+- Debounce all agent events: rejected; lifecycle, permission, and terminal+ events need immediate ordering.diff --git a/docs/adr/0066-empty-home-direct-bottom-composer.md b/docs/adr/0066-empty-home-direct-bottom-composer.mdindex c965ba055..5690837c5 100644--- a/docs/adr/0066-empty-home-direct-bottom-composer.md+++ b/docs/adr/0066-empty-home-direct-bottom-composer.md@@ -2,58 +2,35 @@- Status: Accepted for implementation- Date: 2026-08-07-- Deciders: PI-Desktop core- Amends: D111- Amended by: ADR 0067 (starter-grid presentation only; superseded by D206)## Context-The empty chat home placed contextual prompt buttons between the hero and the-composer. Those controls added an extra decision before the first task and made-the composer part of the scrollable content stack.+The empty chat home placed contextual quick actions between the hero and the+composer, adding a decision before the first task and letting optional+onboarding content push the primary task-entry surface away from the bottom of+the chat area.## Decision-1. Remove the former empty-home contextual quick-action row and its- project-opening buttons.-2. Keep the hero and optional onboarding checklist inside `.home-scroll`, the- only vertical overflow surface for empty-home content.-3. Render the home composer in a sibling `.home-composer-wrap` after the- scroller.-4. Preserve the checklist's existing inline actions and dismissal behavior.+Remove the empty-home quick-action row and its project-opening buttons, along+with the developer starter grid from ADR 0067 (D206). The hero and the optional+onboarding checklist stay inside `.home-scroll`, the only vertical overflow+surface, and the composer renders in a sibling `.home-composer-wrap` that is+flex-fixed at the bottom of `home-main-content` with the existing content width+and bottom spacing. Checklist inline actions and dismissal behave as before;+short windows scroll the checklist but never let the composer cover it.## Consequences-- Empty home has one direct task-entry path and a quieter, purpose-built- guidance surface above it.-- The composer remains stable at the bottom in both empty-home and transcript- states.-- Optional onboarding remains reachable without an overlay or a second scroll- surface.-- The former prompt-template row, quick-action styling, and developer starter- cards are not part of the renderer surface.+- Empty home has one direct task-entry path with a quieter guidance surface.+- The composer stays at the bottom in both empty-home and transcript states.+- Onboarding stays reachable without an overlay or a second scroll surface.## Alternatives considered-### Keep the quick-action row and only move the composer--Rejected. The requested surface is direct task entry; retaining the buttons-would preserve the extra decision layer and its unused prompt-prefill path.--### Keep the composer inside the scroller and align it with `margin-top: auto`--Rejected. Optional checklist growth would still move the composer, and a-short-window overflow could make the primary input less predictable.--### Absolute-position the home composer over the scroller--Rejected. A bottom overlay can cover checklist rows unless every content block-reserves and tracks the composer's changing multi-line height.--## References--- `docs/spec/04-ux/01-ui-ia.md`-- `docs/spec/04-ux/07-ui-design-system.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-063, US-UI-31, US-UI-64)-- `docs/spec/08-meta/decisions-log.md` (D111, D131, D204, D206)+- Keep the quick-action row and only move the composer: rejected; the row keeps+ the extra decision layer.+- Position the composer absolutely over the scroller: rejected; the overlay+ covers checklist rows unless every block tracks the composer height.diff --git a/docs/adr/0067-chatgpt-inspired-empty-home-starters.md b/docs/adr/0067-chatgpt-inspired-empty-home-starters.mdindex 4af5ca006..16de4374e 100644--- a/docs/adr/0067-chatgpt-inspired-empty-home-starters.md+++ b/docs/adr/0067-chatgpt-inspired-empty-home-starters.md@@ -2,24 +2,21 @@- Status: Superseded by D206- Date: 2026-08-07-- Deciders: PI-Desktop core-- Amends: D204 and the card-specific clause of ADR 0066--> This historical decision is retained for traceability. The starter grid was-> removed after review; D206 restores the empty home to the hero, optional-> onboarding checklist, and direct bottom composer.+- Related: ADR 0066, D204, D205, D206## Context-The direct bottom composer introduced by D204 fixed the empty-home layout, but-left the center of the conversation surface visually sparse.+The direct bottom composer introduced by D204 fixed the empty-home layout but+left the conversation surface sparse, so new users had to invent a prompt.## Decision-1. Add a four-card starter grid between the empty-home hero and optional- onboarding checklist: Explore a codebase, Build a feature, Fix a bug, and- Review a change.+Add a four-card starter grid between the hero and the onboarding checklist, whose+cards stay compact, monochrome, localized, and developer-specific, and whose+activation only prefills and focuses the composer.## Consequences-Superseded (Superseded by D206). The full record is in git history.+Superseded by D206, which removed the grid after review and restored the hero,+the optional checklist, and the direct composer. The cards were renderer-local+presentation and copy, with no IPC, storage, or protocol change.diff --git a/docs/adr/0068-work-panel-keyboard-entry.md b/docs/adr/0068-work-panel-keyboard-entry.mdindex 019fd63ca..da7ddfd4c 100644--- a/docs/adr/0068-work-panel-keyboard-entry.md+++ b/docs/adr/0068-work-panel-keyboard-entry.md@@ -2,66 +2,43 @@- Status: Accepted for implementation- Date: 2026-08-07-- Deciders: PI-Desktop core- Amends: D128, D142- Amended by: [ADR 0085](0085-work-panel-shortcut-toggle.md) (the shortcut is atoggle; the rejected toggle alternative below no longer holds);- [ADR 0195](0195-viewport-fixed-work-panel-toggle.md) (pointer equivalent of- the shortcut)+ [ADR 0195](0195-viewport-fixed-work-panel-toggle.md) (pointer equivalent)- Amended in part by: [ADR 0108](0108-remove-built-in-interactive-terminal.md)- Related: [01-ui-ia](../spec/04-ux/01-ui-ia.md) ·- [08-component-spec §5](../spec/04-ux/08-component-spec.md) ·- [09-interaction-patterns §1](../spec/04-ux/09-interaction-patterns.md) ·- E2E-056+ [09-interaction-patterns §1](../spec/04-ux/09-interaction-patterns.md)## Context-D128 made the work panel artifact-only and explicitly removed a global shortcut.-That keeps startup quiet, but it leaves a user with no direct way to return to a-session's retained panel after collapsing it or closing its last resource.+D128 made the work panel artifact-only and removed a global shortcut, so a user who+collapses the panel or closes its last resource has no direct way back to the+session's retained panel. The header already offers the resource chooser, so the+missing capability is panel entry, not another resource protocol.## Decision-1. Add the shared `openWorkPanel` shortcut with a default `Cmd/Ctrl + J`- binding.-2. When an active session exists, the shortcut sets that session's retained- panel context to open at its committed width without creating or activating a- resource tab.-3. The empty panel header remains the manual resource chooser for the Review- row, Browser, and in-scope plugin views.-4. The shortcut is ignored while Settings is active and is a no-op without an- active session.+Add the shared `openWorkPanel` shortcut with a default `Cmd/Ctrl + J` binding,+overridable and resettable through the existing shortcut settings. With an active+session it reopens that session's retained panel at its committed width without+creating or activating a tab, leaving existing tabs and resources unchanged. The+empty header stays the manual chooser, Review opens only on explicit user action+(D451), a plan or goal approval artifact still creates or activates a tab in its+originating session (D452), and the shortcut is ignored in Settings and is a no-op+without an active session.## Consequences-- Users can reopen the work panel without waiting for another artifact.-- Opening the panel no longer implies that a resource exists; the empty header- is an intentional chooser state.-- The change remains renderer-local and preserves session-scoped ownership,- width reservation, and startup reset behavior.-- macOS application menus remain unchanged; the shortcut is discoverable and- editable in Settings → Shortcuts.+- Users can reopen the panel without waiting for another artifact.+- An open panel no longer implies a resource exists; the empty header is a+ deliberate chooser state.+- The change stays renderer-local and preserves session-scoped ownership and width+ reservation.-## Alternatives considered+## Alternatives-### Keep artifact-only entry--Rejected. A collapsed or last-resource-closed panel could not be reopened-directly even though its session context remained valid.--### Make `Cmd/Ctrl + J` a toggle--*(Amended by ADR 0085: the shortcut now toggles.)* Rejected at the time.--### Create Review on shortcut--Rejected. A shortcut should reveal the work surface without fabricating a-workspace change resource or imposing a default tool choice.--## References--- `docs/spec/04-ux/01-ui-ia.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/04-ux/09-interaction-patterns.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-056)-- `docs/spec/08-meta/decisions-log.md` (D128, D142, D207)+- Keep artifact-only entry — rejected: a collapsed panel with a valid context+ stayed unreachable.+- Create a Review resource on the shortcut — rejected: it would fabricate a+ workspace change and impose a tool choice.diff --git a/docs/adr/0069-recoverable-native-tool-path-errors.md b/docs/adr/0069-recoverable-native-tool-path-errors.mdindex c7c91ab7a..6b3e0350d 100644--- a/docs/adr/0069-recoverable-native-tool-path-errors.md+++ b/docs/adr/0069-recoverable-native-tool-path-errors.md@@ -2,72 +2,56 @@- Status: Accepted for implementation- Date: 2026-08-10-- Deciders: PI-Desktop core- Amends: D185, D192- Amended by: [ADR 0087](0087-line-anchored-edit-contract.md) (§2's byte-faithful`Read` content is replaced by line-numbered, tagged output)-- Related: [02-agent-runtime](../spec/03-runtime/02-agent-runtime.md) ·- [03-tools-and-permissions](../spec/03-runtime/03-tools-and-permissions.md) ·- [08-component-spec §9](../spec/04-ux/08-component-spec.md) · E2E-019e ·- E2E-083 · E2E-095## Context-Recent durable sessions showed a repeated path-shape mismatch between the model-and the native tools. `Read` was called with a directory after a guessed file-name did not exist, and `Grep.path` was repeatedly given one explicit file even-though the host accepted only directories.+Recent durable sessions showed repeated path-shape mismatches between the model+and the native tools: `Read` received a directory after a guessed file name did+not exist, and `Grep.path` was repeatedly given one explicit file even though the+host accepted only directories. Both were recoverable inspection mistakes reported+as generic execution failures. The transcript compounded this by deriving a+terminal failure for the activity group from any child error, so a recovered turn+could still read as failed.## Decision-1. Preserve D185's Agent core and deferred-tool boundary.-2. Enforce and advertise one portable path contract:- - `Read.path` accepts an existing regular text file, never a directory.- - `Glob.path` accepts a directory.- - `Grep.path` accepts either one file or a directory tree.-3. A directory passed to `Read` returns public `INVALID_ARGUMENT`, not- `TOOL_FAILED`.+1. Preserve D185's Agent core and deferred-tool boundary: `Glob` and `Grep` stay on+ demand, and a new Agent prompt activates `Glob` through `ToolSearch` when a+ directory must be listed or a file name is uncertain.+2. Enforce and advertise one portable path contract: `Read.path` accepts an+ existing regular text file and never a directory, `Glob.path` accepts a+ directory, and `Grep.path` accepts either one file or a directory tree, with+ `include` still filtering a file's basename.+3. A directory passed to `Read` returns public `INVALID_ARGUMENT` rather than+ `TOOL_FAILED`, with `suggestedTool: "Glob"` and bounded `suggestedArgs` carrying+ the original path and `pattern: "**/*"` so the model can correct itself.4. Host definitions, runtime TypeBox schemas, main-Agent guidance, and subagent- guidance carry the same path semantics.-5. A tool error remains visible and auto-expanded on its own ToolCallRow.--No host protocol or storage-schema version changes. The existing tool result is-already a structured JSON value, and the Grep input shape remains a string.+ guidance carry the same semantics; subagents, which never receive+ `ToolSearch`, are told only about tools their definition has.+5. A tool error stays visible and auto-expanded on its own ToolCallRow, and the+ activity group covers duration and step containment only. Terminal agent+ errors, the TurnOutcomeCard, sidebar state, and notifications remain the single+ turn-outcome surfaces.++No host protocol or storage-schema version changes; the tool result is already+structured JSON and the Grep input shape stays a string. The 2026-09-27 amendment+to ADR 0048 ships `Glob` and `Grep` in the first request, superseding decision 1's+deferral only.## Consequences-- Common single-file Grep calls stop failing on a directory-only contract.-- A mistaken directory Read receives an actionable, non-retriable correction- rather than an ambiguous execution failure.-- Recovered turns no longer look terminally failed, while the original failed- call remains auditable in the expanded transcript.-- Deferred search keeps the measured first-request context reduction from D185;- the prompt must make the per-user-prompt activation boundary explicit.--## Alternatives considered--### Put Glob and Grep back in the Agent core--Rejected. It reverses D185's bounded first-request context decision, and the-observed failure can be corrected without paying both schemas on every prompt.--### Silently execute Glob when Read receives a directory--Rejected. It would make the audited tool name disagree with the executed-operation and return a result shape outside Read's contract.--### Keep Grep directory-only--Rejected. A direct file path is unambiguous, cheaper than walking its parent,-and common across coding-agent tool conventions.--### Mark the activity group failed after the turn settles--Rejected. Settlement does not mean every intermediate tool call succeeded; the-dedicated terminal outcome surfaces already own turn failure.+- Single-file Grep calls stop failing on a directory-only contract.+- A mistaken directory Read yields an actionable correction, not an ambiguous+ execution failure.+- Recovered turns no longer look terminally failed while the failed call stays+ auditable in the expanded transcript.-## Amendment — 2026-09-27: Agent search tools start active+## Alternatives-`Glob` and `Grep` now ship in the first Agent request alongside `Read`, `Bash`,-`Edit`, and `Write`, as recorded in the amendment to ADR 0048. This supersedes-Decision 1's deferral instruction and the deferred-search consequences above.+- Return `Glob` and `Grep` to the Agent core: rejected because it reverses D185's+ bounded first-request context.+- Silently run Glob when Read receives a directory: rejected because the audited+ tool name would disagree with the executed operation.diff --git a/docs/adr/0070-separate-composer-file-reference-display-from-prompt.md b/docs/adr/0070-separate-composer-file-reference-display-from-prompt.mdindex b21dadcb4..897ab6408 100644--- a/docs/adr/0070-separate-composer-file-reference-display-from-prompt.md+++ b/docs/adr/0070-separate-composer-file-reference-display-from-prompt.md@@ -2,52 +2,53 @@- Status: Accepted for implementation- Date: 2026-08-10-- Deciders: PI-Desktop core- Related: D124, D197, D209, ADR 0024, ADR 0059## Context-Workspace autocomplete and clipboard paste both produce canonical file paths-that the agent must receive as plain-text `@` references. Rendering those paths-directly in the controlled composer textarea exposes long workspace paths and,-for pasted files, UUID-backed absolute scratch paths.+Workspace autocomplete and clipboard paste both produce canonical file paths the+agent must receive as plain-text `@` references, but rendering them inline+exposes long workspace paths and UUID-backed scratch paths that wrap and crowd+out the task. A native textarea cannot display one substring differently, and a+shortened value cannot be expanded back by basename because duplicate leaf names+and scratch paths are both valid.## Decision1. A completed file selection and each materialized clipboard file become a- renderer-owned, transient composer reference.-2. Each reference stores its canonical path and a compact leaf label.-3. The composer renders references as compact removable chips above the- textarea.-4. Immediately before the existing submit dispatcher runs, the renderer appends- references in stable addition order and serializes each with the existing- `formatFileInsert` quoting rules.-5. Reference-only drafts are sendable.-6. Stopping before assistant text, thinking, or a tool row begins removes the- just-sent user row and restores the structured snapshot.+ renderer-owned transient reference while the textarea keeps only ordinary+ text; directory autocomplete stays literal.+2. Each reference stores its canonical path and a compact leaf label, keeping the+ full relative index path for workspace files and the UUID-backed scratch path+ for pastes while displaying the sanitized leaf name from `composer/pasteFiles`.+3. References render as compact removable chips above the textarea that show only+ the leaf label, with the canonical path in the tooltip and accessible name;+ duplicate labels stay separate references.+4. Immediately before the submit dispatcher runs, references are appended in+ stable addition order and serialized with the existing `formatFileInsert`+ quoting rules, so the prompt stays plain text with the exact+ `@relative/path` or `@absolute/path`.+5. Reference-only drafts are sendable, references follow visible text so slash+ templates and `/agent-mode`, `/plan-mode`, and `/goal-mode` stay recognizable,+ and rejected or failed dispatch keeps the draft.+6. A session- and turn-scoped snapshot of pre-serialization text and references+ is restored when a stop happens before assistant text, thinking, or a tool row+ begins; once a reply starts, abort keeps the partial transcript and restores+ no draft.7. References are scoped by durable session id and cleared when their workspace- changes.-8. `ComposerPastedFile.name` is the sanitized original leaf display name.--## Alternatives considered--- **Insert only the basename into the prompt:** rejected because duplicate names- and external scratch files would no longer resolve reliably.-- **Overlay shortened text on a transparent textarea:** rejected because the- displayed and native text lengths diverge, breaking caret, selection,- wrapping, IME, and accessibility behavior.-- **Replace the textarea with `contenteditable`:** rejected for this focused- change because it would reopen the complete IME, selection, undo, paste, and- accessibility contract.-- **Parse serialized `@path` tokens back out of an unanswered user message:**- rejected because user-authored references and renderer-appended references are- indistinguishable, and the persisted text no longer carries the original- display label or duplicate-reference identity.+ changes, and `ComposerPastedFile.name` is the sanitized leaf name while `path`+ carries the UUID storage name. No IPC, host RPC, or storage field is added.## Consequences- Long and UUID-backed paths no longer occupy the visible prompt row.-- Canonical references remain exact in persisted messages and model context.-- The renderer owns transient reference state in addition to textarea text.-- Clipboard storage containment, limits, cleanup, and security boundaries are- unchanged from ADR 0059.+- Canonical references stay exact in persisted messages and model context.+- The renderer owns transient reference state beside textarea text, with+ clipboard containment and limits unchanged from ADR 0059.++## Alternatives++- Insert only the basename into the prompt: rejected, duplicate names and scratch+ files would not resolve reliably.+- Overlay shortened text on a transparent textarea: rejected, displayed and+ native lengths diverge and break caret, selection, IME, and accessibility.diff --git a/docs/adr/0071-apple-inspired-global-corner-hierarchy.md b/docs/adr/0071-apple-inspired-global-corner-hierarchy.mdindex 9155a5532..b29d0dd7d 100644--- a/docs/adr/0071-apple-inspired-global-corner-hierarchy.md+++ b/docs/adr/0071-apple-inspired-global-corner-hierarchy.md@@ -2,66 +2,41 @@- Status: Accepted for implementation- Date: 2026-08-11-- Deciders: PI-Desktop core- Related: D072, D210## Context-PI-Desktop enforced a shared radius-token scale, but that scale preserved a-collection of historical 5/6/7/8/10/12/14/16/18/22px values. The one-pixel steps-at the compact end were difficult to distinguish, and the shared button-primitive used a capsule even though most of its 28–32px actions belong to a-dense desktop interface.+The shared radius-token scale preserved historical values whose one-pixel steps at+the compact end were hard to distinguish, and the shared button primitive used a+capsule even though most actions belong to a dense desktop interface. Apple's+guidance separates fixed rounded rectangles, capsules, and concentric shapes and+derives a child radius from its container, which matters more than one radius+applied everywhere. The packaged Chromium runtime could not render+`corner-shape: squircle`.## Decision-1. Replace the fixed-radius ladder with 4/6/8/10/12/14/16/18/20/24px values.-2. Standard compact and medium controls use fixed rounded rectangles.-3. Pills, badges, segmented selections, switches, tracks, status dots, and- equal-width circular icon controls keep their explicit capsule or circle- geometry.-4. Surfaces increase radius with size and elevation.-5. Full-width structural shell surfaces remain square at the window edge.-6. The composer aliases its established 20px radius to `--radius-xl`, keeping- the visible composer geometry while bringing it into the global ladder.-7. D072's token-only lint enforcement remains unchanged; only the frozen pixel- values and shared primitive assignments are amended.+Replace the fixed-radius ladder with a coarser, evenly perceivable scale while+keeping `--radius-full` for capsules and `--radius-round` for circles. Compact and+medium controls use fixed rounded rectangles, with the shared button and field+primitives on `--radius-sm`; pills, badges, segmented selections, switches, tracks,+status dots, and circular icon controls keep their explicit capsule or circle+geometry. Surfaces increase radius with size and elevation, a child corner near and+parallel to a container corner follows the concentric relation+`outer radius = inner radius + inset`, and full-width structural shell surfaces stay+square at the window edge. The composer aliases its established radius to+`--radius-xl`, and D072's token-only lint enforcement is unchanged.## Consequences-- The interface has a more legible small-to-large corner hierarchy, while- compact macOS controls no longer look uniformly pill-shaped.-- Existing token consumers receive the revised values globally without- component-local literals.-- Designers and implementers must choose pill or circle tokens intentionally- instead of treating them as a default radius.-- True continuous-corner rendering remains unavailable until the packaged- Chromium runtime supports `corner-shape`; the compatible fallback is the- standardized fixed-radius ladder.+- Small-to-large corners read as one hierarchy instead of a pill default.+- Token consumers pick up the revised values globally, without component literals.+- Continuous corners stay deferred: the 2026-08-14 addendum records that later+ Chromium packaging removed the runtime blocker without changing this decision.-## Alternatives considered+## Alternatives-### Make every component a capsule--Rejected because Apple retains rounded rectangles for compact macOS controls and-uses capsules selectively for emphasis and specific control families.--### Add `corner-shape: squircle` now--Rejected because the packaged Chromium 138 runtime does not support it.--### Keep the historical values and change individual components--Rejected because the request is global, and retaining closely spaced 5/6/7/8px-steps would continue to make the hierarchy hard to perceive and maintain.--## Addendum (2026-08-14): the `corner-shape` blocker is gone--The Context and Alternatives above are left as recorded. Their runtime premise-no longer holds: the shell moved to Electron 43, which bundles Chromium 150, and-`CSS.supports("corner-shape", "squircle")` returns `true` in the packaged-renderer.--This addendum does not change the decision. The fixed-radius ladder stays as-specified; adopting continuous corners is a design change that needs its own-decision, not a side effect of a dependency bump.+- Make every component a capsule: rejected because Apple keeps rounded rectangles+ for compact controls and reserves capsules for emphasis.+- Keep historical values and change components individually: rejected because the+ change is global and the close steps stay imperceptible.diff --git a/docs/adr/0072-global-plugin-launcher.md b/docs/adr/0072-global-plugin-launcher.mdindex f703feeb3..5f695c611 100644--- a/docs/adr/0072-global-plugin-launcher.md+++ b/docs/adr/0072-global-plugin-launcher.md@@ -1,53 +1,46 @@# ADR 0072: Add a global plugin launcher-- Status: Accepted for implementation+- Status: Accepted for implementation (ADR 0080 supersedes the first-use lazy+ window creation)- Date: 2026-08-11-- Deciders: PI-Desktop core-- Related: D211 · [Settings IA](../spec/04-ux/06-settings-ia.md) ·- [Interaction patterns](../spec/04-ux/09-interaction-patterns.md) · E2E-120+- Related: D211, D219, ADR 0080## Context-Installed plugin panels are reachable from the Plugins destination, but opening-one interrupts the user's current work and requires pointer navigation. A-system-wide shortcut needs a dedicated native window: the normal renderer cannot-receive keys while PI-Desktop is unfocused, and the existing plugin panel host-should remain the only authority that opens plugin UI.+Installed plugin panels are reachable only from the Plugins destination, so+opening one interrupts the current task. A system-wide shortcut needs its own+native window, because the renderer cannot receive keys while PI-Desktop is+unfocused and the existing panel host should stay the only authority that opens+plugin UI.## Decision-1. Add the shared, customizable `openPluginLauncher` shortcut, defaulting to- `Alt+Space`.-2. Electron main owns one centered, frameless 620×440 utility window on the- display nearest the pointer.-3. The sandboxed launcher renderer uses the existing preload and the additive- Electron-only toggle, dismiss, and shown channels.-4. Only enabled, ready plugins with a panel are candidates.+1. Add the customizable `openPluginLauncher` shortcut, defaulting to `Alt+Space`,+ registered with `globalShortcut` after boot; because Windows reserves that+ chord for the active window's system menu, host-core also installs a narrow+ low-level keyboard hook for the exact default binding, keeping the focused+ main window as a last-resort fallback.+2. Electron main owns one centered, frameless utility window on the display+ nearest the pointer — warmed after boot per ADR 0080, non-resizable, absent+ from the taskbar, always on top while visible, hidden on blur or Escape.+3. The sandboxed launcher renderer uses the existing preload plus additive+ Electron-only toggle, dismiss, and shown channels, lists plugins through the+ existing plugin API, and opens a result through the existing sandboxed panel+ host, changing no plugin permission or host-core boundary.+4. Only enabled, ready plugins with a panel are candidates; search normalizes+ name, id, and description and derives tone-free full pinyin and initials from+ the display name, and IME composition never dispatches. Successful opens are+ remembered in renderer-local device storage (D219).## Consequences-- A plugin panel can be opened without navigating away from the current task.-- The shortcut remains visible and resettable in Settings → Shortcuts.-- `pinyin-pro` is bundled into renderer output rather than shipped as a runtime- package tree.-- A custom shortcut continues to use Electron's global shortcut API.-- The renderer IPC additions remain Electron-local and additive; the native- fallback adds one host method/notification without changing protocol v9 or- storage schema v11.+- A plugin panel opens without navigating away from the current task, and the+ shortcut stays resettable in Settings → Shortcuts.+- A hook installation failure is logged and the focused-window fallback stays+ usable.-## Alternatives considered+## Alternatives-### Reuse global search--Rejected. Global search is part of the main renderer and cannot appear while the-application is unfocused without first restoring the entire main window.--### Open plugins directly from a native menu--Rejected. A static menu cannot provide Chinese/pinyin fuzzy search and would-need to be rebuilt for every plugin lifecycle change.--### Put pinyin aliases in plugin manifests--Rejected. It makes search quality depend on every plugin author and duplicates-data that can be derived consistently at query time.+- Reuse global search: it lives in the main renderer and cannot appear while the+ application is unfocused.+- Put pinyin aliases in manifests: makes search quality depend on every author.diff --git a/docs/adr/0073-next-turn-composer-configuration-and-stopped-throughput.md b/docs/adr/0073-next-turn-composer-configuration-and-stopped-throughput.mdindex b0d7d3948..8838c9420 100644--- a/docs/adr/0073-next-turn-composer-configuration-and-stopped-throughput.md+++ b/docs/adr/0073-next-turn-composer-configuration-and-stopped-throughput.md@@ -2,51 +2,46 @@- Status: Accepted for implementation- Date: 2026-08-11-- Deciders: PI-Desktop core- Amends: D189-- Related: D212 · [Agent runtime](../spec/03-runtime/02-agent-runtime.md) ·- [Component spec](../spec/04-ux/08-component-spec.md) · E2E-120+- Related: D212## Context-The composer previously made its draft, mode, thinking, and permission controls-read-only for an entire agent run. That prevented preparing the next prompt and-next-turn configuration while preserving the correct safety rule: host-core must-not mutate the configuration pinned by an in-flight turn.+The composer made draft, mode, thinking, and permission controls read-only for a+whole run, so users could not prepare the next prompt, while the real safety rule+is only that host-core must not mutate configuration pinned by an in-flight turn.+A user Stop could also arrive before final provider usage, leaving stopped answers+without stream duration or output counts.## Decision-1. During an active turn, the composer draft and mode, thinking, and permission- selectors remain editable.-2. The renderer stores the latest full session configuration per running session- and projects it optimistically.-3. Runtime terminal messages preserve `responseDurationMs`.-4. Rust transcript conversion persists both optional fields in message metadata.+1. During an active turn the draft and the mode, thinking, and permission+ selectors stay editable; Send alone is disabled, Stop stays available, and a+ pending Plan/Goal approval keeps blocking the draft and configuration controls.+2. The renderer keeps the latest full session configuration per running session+ and, on `agent_end`, `error`, or compaction completion, submits it through the+ existing idle-only `session/configure` API, newer selections replacing queued+ ones without touching the running runtime.+3. Runtime terminal messages preserve `responseDurationMs`, and an aborted+ response without positive provider output usage gets an estimated optional+ `responseOutputTokens` counted at four code points per token over visible+ thinking plus answer text.+4. Rust transcript conversion persists both optional fields in message metadata,+ exact provider usage wins over the estimate, the estimate stays labeled, and+ records without either field remain valid.## Consequences-- Users can prepare the next request and adjust its operating profile without- waiting for the current answer, but cannot send a concurrent prompt.-- Host idle-only admission, one-turn-per-session, Plan/Goal approval, and- permission enforcement remain unchanged.-- Stopped partial answers show a stable approximate tokens-per-second value and- retain it after reload; complete answers continue to use exact provider usage.-- `responseOutputTokens` is an additive shared field stored inside existing- message metadata, so neither protocol v9 nor storage schema v11 changes.+- Users prepare the next request and its operating profile without sending+ concurrently.+- Idle-only admission, one turn per session, Plan/Goal approval, and permission+ enforcement are unchanged.+- Stopped answers show a stable approximate tokens-per-second value after reload,+ and the additive field changes neither protocol v9 nor storage schema v11.-## Alternatives considered+## Alternatives-### Configure the host immediately while running--Rejected. It would either violate idle-only admission or risk changing the-permission/tool/model configuration already pinned for the active turn.--### Keep controls disabled but allow only draft typing--Rejected. Mode, thinking, and permission are part of preparing the next prompt;-making only text editable leaves the workflow unnecessarily serialized.--### Hide throughput when final usage is missing--Rejected. The visible partial output and measured stream interval provide a-useful estimate, and the UI can distinguish it from provider-reported usage.+- Configure the host while running: rejected because it breaks idle-only+ admission or mutates pinned turn configuration.+- Hide throughput without final usage: rejected because output and stream interval+ already support a labeled estimate.diff --git a/docs/adr/0074-native-notification-permission-for-plugins.md b/docs/adr/0074-native-notification-permission-for-plugins.mdindex e4a24e353..68f2ebc91 100644--- a/docs/adr/0074-native-notification-permission-for-plugins.md+++ b/docs/adr/0074-native-notification-permission-for-plugins.md@@ -5,43 +5,36 @@## Context-The plugin `notify` capability currently exposes only an in-app Toast.-PI-Desktop already uses Electron's native notification API for terminal task-outcomes, but that surface is intentionally owned by the application and backed-by the durable task notification inbox.+The plugin `notify` capability exposed only an in-app Toast, while native+notifications already existed for terminal task outcomes behind the+application-owned task inbox. Plugins need OS notification access without+gaining Electron objects or the inbox, but Electron offers no cross-platform+read-only permission query and no separate request method, so native delivery+can only report success through the notification lifecycle.## Decision-Keep `pi.ui.notify` as the backwards-compatible in-app Toast. Add three-permission-gated APIs under `pi.ui`:+Keep `pi.ui.notify` as the backwards-compatible in-app Toast and add three+permission-gated APIs under `pi.ui`: `getNotificationPermission()` returning+`granted`, `denied`, `unknown`, or `unsupported`; `requestNotificationPermission()`+running a short native probe and returning the best-effort result;+`showNativeNotification({ title, body? })` returning `{ shown, permission }`.+All three use the existing low-risk manifest `notify` permission, the Electron+main process owns the native objects and length limits, and plugin+notifications never create inbox rows or session activation on click.-- `getNotificationPermission()` returns `granted`, `denied`, `unknown`, or- `unsupported`.-- `requestNotificationPermission()` performs a short native notification probe- and returns the best-effort result.-- `showNativeNotification({ title, body? })` sends a native notification and- returns `{ shown, permission }`.+## Consequences-All three APIs use the existing low-risk manifest `notify` permission. The-Electron main process owns the native objects, limits title/body lengths, and-keeps plugin notifications separate from the durable task inbox.+- Plugins can send OS-level reminders while staying behind the existing+ permission review, and existing plugins keep their Toast behavior.+- A plugin must handle `unknown`, `denied`, and `unsupported` instead of assuming+ a banner was delivered.+- The task inbox stays application-owned and cannot be used as plugin+ persistence or navigation.-## Consequences+## Alternatives-- Plugins can provide OS-level reminders and status updates while remaining- behind the existing plugin permission review.-- Existing plugins keep their Toast behavior and source compatibility.-- A plugin must handle `unknown`, `denied`, and `unsupported` without assuming- that a native banner was delivered.-- The task notification inbox remains application-owned and cannot be used as a- plugin persistence or navigation channel.--## Alternatives considered--- Replacing `pi.ui.notify` with native delivery: rejected because it silently- changes existing plugin behavior and conflates Toasts with OS notifications.-- Adding a platform-specific permission package: rejected for this API revision;- it would add platform-specific dependencies without a common Electron- permission contract.-- Allowing plugins to construct Electron `Notification` objects: rejected by the- plugin isolation boundary.+- Replace `pi.ui.notify` with native delivery: it silently changes existing+ plugin behavior and conflates Toasts with OS notifications.+- Let plugins construct Electron `Notification` objects: rejected by the plugin+ isolation boundary.diff --git a/docs/adr/0075-manual-development-plugin-reload.md b/docs/adr/0075-manual-development-plugin-reload.mdindex e43a5fe88..576ad227c 100644--- a/docs/adr/0075-manual-development-plugin-reload.md+++ b/docs/adr/0075-manual-development-plugin-reload.md@@ -5,33 +5,29 @@## Context-Development plugins are watched and hot-reloaded from their local folders. The-watcher intentionally refuses a manifest that adds permissions beyond the-ceiling approved when the folder was loaded.+The development-plugin watcher refuses a manifest that adds permissions beyond the+ceiling approved when the folder was loaded, so the developer had to re-pick the+folder to resume.## Decision-Add a renderer-to-main `pi-desktop/plugin/reload` invoke channel. Electron main-resolves the plugin id through the host registry, loads the registered path with-the registry's current permissions, and re-arms the development watcher after a-successful load.+Add a renderer-to-main `pi-desktop/plugin/reload` invoke channel: Electron main+resolves the plugin id through the host registry, loads the registered path with the+registry's current permissions, and re-arms the development watcher after a+successful load. Only `source: "dev"` rows expose it.-The automatic watcher remains conservative: it cannot widen the permission-ceiling. A manual reload is an explicit developer action that acknowledges the-current manifest and makes its declared permissions the new ceiling for later-automatic reloads.+The watcher stays conservative and cannot widen the ceiling; a manual reload is an+explicit developer action that makes the current manifest's permissions the new+ceiling.## Consequences-- Developers can recover from permission-gated hot reloads without re-picking a- folder.-- Installed and marketplace plugins do not gain a manual reload control.-- The existing watcher, plugin runtime, and host-core storage contracts remain- unchanged; the new channel is an additive Electron IPC surface.+Developers recover without re-picking a folder, other plugin sources gain no such+control, and the channel is an additive Electron IPC surface with unchanged watcher,+runtime, and storage contracts.-## Alternatives considered+## Alternatives-- Reusing the folder picker: rejected because it repeats path selection and- makes recovery needlessly disruptive.-- Allowing automatic reloads to widen permissions: rejected because file edits- must not silently grant new capabilities.+- Reuse the folder picker: rejected, it repeats path selection.+- Let automatic reloads widen permissions: rejected, file edits must not grant+ capabilities.diff --git a/docs/adr/0076-windows-reserved-global-shortcut-fallback.md b/docs/adr/0076-windows-reserved-global-shortcut-fallback.mdindex 4e9bfb915..2cfe9d470 100644--- a/docs/adr/0076-windows-reserved-global-shortcut-fallback.md+++ b/docs/adr/0076-windows-reserved-global-shortcut-fallback.md@@ -2,31 +2,23 @@- Status: Accepted- Date: 2026-08-12-- Deciders: PI-Desktop core-- Related: D211 · ADR 0072 · E2E-120+- Related: D211, ADR 0072, E2E-120## Context-Windows reserves `Alt+Space` for the active window system menu. Electron's-`globalShortcut` may therefore reject the plugin launcher's default binding, and-a renderer `before-input-event` fallback only works while PI-Desktop is focused.+Windows reserves `Alt+Space` for the active window's system menu, so Electron's+`globalShortcut` may reject the launcher's default binding.## DecisionHost-core installs a narrow Windows `WH_KEYBOARD_LL` hook for the default-`Alt+Space` binding. It consumes the matching keydown, emits the existing-JSON-RPC notification transport with `keyboard.shortcut`, and lets Electron-toggle the plugin launcher.--The hook does not inspect or persist text, and it does not expose a new renderer-or plugin capability. If hook installation fails, the focused-window fallback-remains available and the failure is logged.+`Alt+Space` binding, consumes the keydown, and emits `keyboard.shortcut` over the+existing JSON-RPC notification transport; `keyboard.setGlobalShortcut` enables the+hook only while that binding is effective on Windows, and other platforms and+custom bindings keep Electron's global shortcut path. The hook reads no text,+grants no capability, and leaves the focused-window fallback in place on failure.## Consequences-- The default Windows launcher chord works while another application is- foregrounded and does not open that application's system menu.-- The host binary owns a small platform-specific input integration, while- Electron remains responsible for window creation and plugin-panel access.-- Protocol version and storage schema remain unchanged because the method and- notification are additive and Electron is the only consumer.+- The default chord works while another application is foregrounded.+- One small host-side platform integration; no protocol or schema change.diff --git a/docs/adr/0077-asktool-interactive-multi-question-flow.md b/docs/adr/0077-asktool-interactive-multi-question-flow.mdindex 0fd5bc8a6..73221fb4c 100644--- a/docs/adr/0077-asktool-interactive-multi-question-flow.md+++ b/docs/adr/0077-asktool-interactive-multi-question-flow.md@@ -1,39 +1,35 @@# ADR 0077: Add an interactive multi-question asktool-- Status: Accepted for implementation+- Status: Accepted for implementation (amended 2026-09-27: question and option+ text render as Markdown for display only)- Date: 2026-08-12-- Deciders: PI-Desktop core- Related: E2E-123## ContextThe model needs a structured way to collect several user decisions without-turning them into chat prose or permission approvals. The user may answer one-question at a time, choose multiple options, provide custom text, skip a-question, or decline the complete prompt.+drafting chat prose or permission requests. The user may answer one question at a+time, select multiple options, add custom text, skip, or decline the prompt, and+an unanswered call still needs a stable tool output.## Decision-1. Add a built-in `asktool` to every operating mode.-2. The request carries an ordered array of question text, option labels, and an- optional multi-select flag.-3. The renderer owns draft selection state and displays one question at a time.-4. The runtime formats the resolved values as normal tool content: each line is- `question:answer`, multiple questions use `\n---\n`, and null answers use an- empty value after the separator.+1. A built-in `asktool`, available in every operating mode, emits a typed+ `asktool_request` event and pauses the runtime until the renderer resolves it+ through `pi-desktop/agent/askTool/resolve`.+2. The request carries ordered question text, option labels, and an optional+ multi-select flag; the renderer adds a custom text-input option and shows one+ question at a time.+3. Skip and decline resolve to `null`, answers carry selected labels and custom+ text, and there is no timeout.+4. Resolved values become tool content: `question:answer` per line, `\n---\n`+ between questions, empty for null answers.-## Consequences--- The model receives a deterministic, compact tool result rather than UI state.-- The interactive wait is outside host permission policy and cannot grant a- workspace capability.-- The request is additive to the existing agent event envelope and does not- require a protocol version bump.-- Aborting a turn completes the outstanding tool call with skipped values so a- pending card cannot strand the runtime.+Question and option text may use CommonMark or GFM, projected as safe phrasing+content; selection and tool output keep the normalized source strings.-## Amendment — 2026-09-27: Render asktool content as Markdown+## Consequences-`question`, selectable option text, and optional option descriptions may use-CommonMark/GFM. The renderer uses a safe phrasing-content projection: raw HTML-is ignored, links are non-interactive, and images do not load.+- The model receives a compact, deterministic tool result.+- The wait sits outside host permission policy and cannot grant a capability.+- Aborting a turn completes the pending call with skipped values.diff --git a/docs/adr/0078-cross-platform-tray-resident-minimize.md b/docs/adr/0078-cross-platform-tray-resident-minimize.mdindex 9b8073803..a4ca0f0f4 100644--- a/docs/adr/0078-cross-platform-tray-resident-minimize.md+++ b/docs/adr/0078-cross-platform-tray-resident-minimize.md@@ -2,38 +2,38 @@- Status: Accepted for implementation (amended by ADR 0117, ADR 0123, and ADR tray-session-shortcuts)- Date: 2026-08-12-- Deciders: PI-Desktop core-- Related: D216, D252, D256, E2E-124, ADR 0117, ADR 0123+- Related: D216, D252, D256, ADR 0117, ADR 0123## Context-PI-Desktop already has custom window controls on Windows/Linux and native-traffic-light controls on macOS. Their minimize actions currently use native-window minimization, which makes the app disappear into different OS window-surfaces and does not provide a consistent way to keep background work resident.+Minimize used native window minimization on every platform, so the app disappeared+into different window surfaces with no consistent way to stay resident for+background work. Electron Main already owns window lifecycle and shutdown.## Decision-1. Electron Main creates one tray icon on every supported desktop platform.-2. Main intercepts the `minimize` event for the main window and hides it to the- tray only for macOS traffic-light minimization.-3. Tray click and double-click, the Show menu item, and macOS app activation- restore and focus the existing window.-4. The tray menu contains localized Show PI-Desktop and Quit PI-Desktop items.+Electron Main creates one tray icon per supported platform, using the product PNG on+Windows/Linux and a transparent monochrome template asset on macOS. Only macOS+traffic-light minimize hides the window to the tray; Windows/Linux minimize stays+ordinary OS minimization so the taskbar entry remains, and hiding never closes the+window or disposes a backend. Tray click and double-click, the Show item, and macOS+app activation restore and focus the existing window or create one through the+existing factory, and Quit goes through `app.quit()` and `before-quit`.++[ADR tray-session-shortcuts](tray-session-shortcuts.md) extends the restore and+menu clauses with bounded session groups and opens the macOS menu on single-click.## Consequences-- macOS keeps its tray-resident minimize behavior, while Windows/Linux use the- normal taskbar minimize/restore affordance for explicit minimize actions.-- The renderer needs no new privileged IPC surface.-- A tray icon is a required packaged resource; a missing icon is logged and the- app remains usable rather than crashing during boot.-- Window bounds persistence remains unchanged because a hidden window retains- its normal bounds and is not treated as a new window state.+- macOS keeps tray-resident minimize while Windows/Linux keep taskbar+ minimize/restore; close-to-tray remains a configurable close behavior.+- No new privileged IPC surface is added, and a missing tray asset is logged rather+ than fatal.+- Window bounds persistence is unaffected because a hidden window keeps its bounds.-## Session-menu amendment+## Alternatives-[ADR tray-session-shortcuts](tray-session-shortcuts.md) extends clauses 3–4 with-bounded session groups and makes macOS single-click open the menu without-restoring the main window. Open, double-click, and Quit retain their lifecycle-behavior.+- Leave minimize entirely native — rejected: background work then has no resident+ surface and macOS loses its traffic-light behavior.+- Hide to tray on every platform — rejected: Windows/Linux users lose the taskbar+ affordance.diff --git a/docs/adr/0079-vitepress-documentation-site.md b/docs/adr/0079-vitepress-documentation-site.mdindex 71f53967c..05871aba5 100644--- a/docs/adr/0079-vitepress-documentation-site.md+++ b/docs/adr/0079-vitepress-documentation-site.md@@ -1,43 +1,37 @@# ADR 0079: Use VitePress for the bilingual documentation site-- **Status:** Accepted; the Chinese companion scope is amended by- [ADR chinese-docs-entry-points-only](chinese-docs-entry-points-only.md)-- **Date:** 2026-08-13+- Status: Accepted+- Date: 2026-08-13## Context-The repository has a growing set of specifications, ADRs, project notes, and-plugin authoring material. Plain Markdown files are easy to review, but the-current directory has no shared navigation, local search, responsive reading-experience, or clear language entry point.+`docs/` holds specifications, ADRs, project notes, and plugin authoring material+as plain Markdown. Review stays easy, but readers get no shared navigation, local+search, responsive reading layout, or language entry point.## Decision-Make `docs/` a standalone VitePress project in the pnpm workspace. Keep the-existing Markdown files in place as the source of truth and add a custom,-responsive theme with local search, English and Simplified Chinese locale entry-points, and curated navigation.--The English site is complete and remains canonical. The Chinese site provides a-translated orientation, topic map, and a complete path-for-path companion for-every specification.+Make `docs/` a standalone VitePress project in the pnpm workspace, keeping the+Markdown files as the source of truth and adding a responsive custom theme with+local search, English and Simplified Chinese entry points, and curated+navigation. English stays canonical; the Chinese site provides a translated+orientation, a topic map, and a path-for-path companion for every specification,+preserving code and protocol identifiers, linking back to the English source, and+sharing the generated sidebar so coverage gaps are detectable. One centered+layout serves landing, guide, specification, ADR, project, and plugin pages, with+reading width bounded independently of the sidebar and outline rails.## Consequences-- Contributors can run, build, and preview the docs with `pnpm docs:*` commands.-- Documentation has a stable static site shape without adding a server runtime.-- New user-visible documentation behavior must be covered in the E2E test plan.-- English remains the canonical language for specs, ADRs, protocol terms, and- code-facing documentation.-- A behavior-changing English specification edit must update its Chinese- companion in the same logical change.--## Alternatives considered--- Keep plain Markdown only: preserves the smallest toolchain, but does not solve- navigation, search, responsive presentation, or bilingual entry points.-- Translate only orientation and topic landing pages: lowers maintenance cost,- but makes Chinese navigation switch back to English precisely when a reader- reaches the technical detail and leaves locale coverage impossible to verify.-- Use a hosted docs platform: adds an external publishing dependency and makes- local preview less representative of the repository source.+- Contributors preview and build docs with `pnpm docs:*`; VitePress becomes a+ development dependency of a new workspace package.+- Documentation gets a static site shape without adding a server runtime.+- A behavior-changing English specification edit updates its Chinese companion in+ the same change.++## Alternatives++- Keep plain Markdown only: rejected because it solves none of navigation, search,+ or bilingual entry.+- Hosted docs platform: rejected because it adds an external publishing+ dependency and makes local preview less representative.diff --git a/docs/adr/0080-prewarm-global-plugin-launcher.md b/docs/adr/0080-prewarm-global-plugin-launcher.mdindex 742632922..ed8c45ff8 100644--- a/docs/adr/0080-prewarm-global-plugin-launcher.md+++ b/docs/adr/0080-prewarm-global-plugin-launcher.md@@ -1,41 +1,35 @@# ADR 0080: Prewarm the global plugin launcher after boot-- **Status:** Accepted-- **Date:** 2026-08-13-- **Related:** D211 · D217 · ADR 0072 · E2E-120+- Status: Accepted+- Date: 2026-08-13+- Related: ADR 0072, D211, D217## ContextThe global plugin launcher was created lazily on the first Option/Alt+Space-invocation. That path had to allocate a second Electron `BrowserWindow`, start-its sandboxed renderer, load the shared renderer bundle, mount React, and only-then reveal the launcher.+invocation, so that press paid for a second `BrowserWindow`, a sandboxed renderer,+the shared renderer bundle, and React mount before anything appeared.## Decision-As soon as Electron is ready, before backend/plugin boot completes, Electron-starts creating and loading the launcher window in the background while keeping-it hidden. This work runs in parallel with primary startup.--Window creation is represented by one shared in-flight promise. A shortcut-received while warm-up is still loading joins that promise, preventing a blank-window, a lost shown event, or duplicate renderer creation.+Once Electron is ready, and in parallel with backend and plugin boot, Main starts+creating and loading the launcher window hidden. One shared in-flight promise+represents that creation, so a shortcut arriving during warm-up joins it instead of+raising a blank window or a duplicate renderer. A failed warm-up is logged,+destroys the incomplete window, clears the promise, and leaves the shortcut path+able to retry. Invocations still set display bounds, show, and focus the retained+window, and the launcher still refreshes its plugin catalog on every show, with no+IPC, host RPC, permission, protocol, or storage change.## Consequences-- The first post-boot shortcut no longer pays BrowserWindow and renderer load- latency on its visible path; warm-up starts early enough to overlap backend- startup.-- One hidden sandboxed renderer remains resident after boot, trading a bounded- memory cost for consistent launch latency.-- Application boot is not blocked on launcher warm-up, and warm-up failure does- not prevent a later shortcut from retrying.--## Alternatives considered--- Keep first-use lazy creation: preserves the smallest idle footprint but keeps- the reported first-launch delay.-- Await warm-up as part of application boot: guarantees readiness before the app- is marked booted but lengthens the primary window's critical startup path.-- Reuse the main renderer: avoids a second renderer but cannot provide the- independent system-wide utility window while PI-Desktop is unfocused.+- The first post-boot shortcut no longer pays window and renderer load time.+- One hidden sandboxed renderer stays resident for consistent latency.+- Boot never blocks on warm-up, and failure does not disable later launches.++## Alternatives++- Keep first-use lazy creation: rejected because it keeps the reported first-launch+ delay.+- Reuse the main renderer: rejected because a system-wide utility window must work+ while PI-Desktop is unfocused.diff --git a/docs/adr/0081-host-owned-plugin-panel-chrome.md b/docs/adr/0081-host-owned-plugin-panel-chrome.mdindex 3aa8550b1..5e14a4b88 100644--- a/docs/adr/0081-host-owned-plugin-panel-chrome.md+++ b/docs/adr/0081-host-owned-plugin-panel-chrome.md@@ -2,62 +2,41 @@- Status: Accepted- Date: 2026-08-13-- Deciders: PI-Desktop core- Related: D118, D129, D218, ADR 0021, ADR 0025## Context-Plugin panels run in separate sandboxed `BrowserWindow` instances and load-plugin-owned HTML. Those windows previously used Electron's default frame, so-their titlebar did not match the main PI-Desktop window and differed materially-between macOS, Windows, and Linux.+Plugin panels run in separate sandboxed `BrowserWindow` instances that load+plugin-owned HTML, so they kept Electron's default frame: their titlebar did not+match the main window and differed across macOS, Windows, and Linux. The panel page+cannot be trusted with the main renderer preload, and the host chrome must not+depend on plugin CSS.## Decision-1. Plugin panels use the same platform split as the main window: macOS uses- `hiddenInset` with traffic lights at `{x:16,y:16}`, while Windows and Linux- use a frameless window with renderer-drawn controls.-2. The existing sandboxed plugin-panel preload installs a host-owned 46px- titlebar in a closed Shadow DOM.-3. Windows/Linux expose minimize, maximize/restore, and close through one- Electron-local fixed action tuple.-4. The public `window.pluginBridge` surface does not gain window primitives.-5. Controls carry localized accessible names, visible keyboard focus, theme-- aware light/dark surfaces, and reduced-motion behavior.-6. Development panels receive a host-only titlebar reminder for the 46px safe- area.+Panels follow the main window's platform split: macOS uses `hiddenInset` with inset+traffic lights, while Windows and Linux use a frameless window with renderer-drawn+controls. The existing sandboxed plugin-panel preload injects a host-owned titlebar+into a closed Shadow DOM, renders the manifest panel title, offsets the plugin body+by the titlebar height on top of its computed padding, and publishes+`--pi-plugin-titlebar-height` for fixed or sticky plugin UI. Windows and Linux send+minimize, maximize/restore, and close as one Electron-local fixed action tuple that+Main accepts only from a live plugin panel. `window.pluginBridge` gains no window+primitives, and the session partition, sandbox, context isolation, and+permission-checked bridge stay unchanged. Controls keep localized accessible+names, visible focus, theme-aware surfaces, and reduced motion.## Consequences-- Plugin panels visually align with the main application chrome on all three- release platforms without granting plugins broader Electron access.-- Plugin CSS cannot style the closed titlebar tree, although a plugin can still- replace its own document and therefore remove the preload-injected visual- element.-- The host reserves 46px above plugin content.-- The private window-control channel remains outside host-core protocol v9.+- Panels align with the application chrome on all three release platforms without+ widening plugin access.+- Plugin CSS cannot style the closed titlebar tree, though a plugin can replace its+ own document and drop the injected element without gaining a capability.+- Fixed-content panels must respect `--pi-plugin-titlebar-height`, and the private+ window-control channel stays outside host-core protocol v9.## Alternatives-### Keep Electron's default panel frame--Rejected because it preserves inconsistent product chrome and leaves-Windows/Linux panels visually detached from the main application.--### Expose the main window-control API to plugin JavaScript--Rejected because the plugin bridge should remain limited to declared plugin-capabilities and must not acquire generic native-window authority.--### Host plugin content inside the main renderer DOM--Rejected because it would weaken the existing separate-window, separate--partition isolation model for a visual-only change.--## References--- `docs/spec/03-runtime/01-ipc-protocol.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-024D)-- `docs/spec/07-plugins/01-plugin-system.md`-- `docs/spec/07-plugins/04-plugin-security.md`+- Keep the default panel frame: preserves inconsistent chrome across platforms.+- Expose the main window-control API: would give plugins generic native-window+ authority beyond their declared capabilities.diff --git a/docs/adr/0082-localized-plugin-panel-chrome.md b/docs/adr/0082-localized-plugin-panel-chrome.mdindex ac3f7e32d..60366e07d 100644--- a/docs/adr/0082-localized-plugin-panel-chrome.md+++ b/docs/adr/0082-localized-plugin-panel-chrome.md@@ -1,28 +1,25 @@# ADR 0082: Localized and page-adaptive plugin panel chrome-## Status--Accepted+- Status: Accepted## Context-Plugin panels are hosted in their own Electron windows. Their titlebar was given-a single string from the manifest and the preload chrome defaulted to a dark-surface.+A plugin panel's titlebar took a single manifest string and the preload chrome defaulted to+a dark surface, splitting the panel from the active UI language and giving light plugin+pages a black header.## Decision-1. `ui.title` accepts either the existing string form or a localized object- containing both `en` and `zh-CN` strings.-2. The host passes the active light/dark theme to the panel window.-3. The titlebar remains in the closed preload-owned Shadow DOM.-4. Existing string manifests and existing panel dimensions remain compatible.+`ui.title` accepts the existing string form or a localized object holding both `en` and+`zh-CN`, resolved against the active UI locale and falling back to the other label, then the+manifest name. The host passes the active light/dark theme, and the preload samples the+document's computed body background and foreground for the titlebar, using the host theme+when the page is transparent. The titlebar stays in the closed preload-owned Shadow DOM, so+plugin CSS cannot restyle host controls.## Consequences-- Plugin authors can ship one manifest with English and Simplified Chinese panel- titles.-- Panel chrome remains visually coherent with custom plugin pages and the host's- explicit theme preference.-- A panel whose colors change after first paint is not continuously inspected;- plugins should set their page surface before `DOMContentLoaded`.+- Authors ship one manifest with English and Simplified Chinese titles, and chrome stays+ coherent with custom pages and the host theme.+- A panel that recolors after first paint is not re-inspected; string manifests and panel+ dimensions stay compatible.diff --git a/docs/adr/0083-custom-global-ui-font.md b/docs/adr/0083-custom-global-ui-font.mdindex 8e959552b..0cb843698 100644--- a/docs/adr/0083-custom-global-ui-font.md+++ b/docs/adr/0083-custom-global-ui-font.md@@ -2,99 +2,57 @@- Status: Superseded in part by ADR 0298- Date: 2026-08-14-- Baseline: `0.4.16`-- Protocol: v9 (one additive Electron-main IPC channel; host RPC unchanged)-- Storage schema: v10 (optional `AppSettings.fontFamily` JSON field)+- Storage: optional `AppSettings.fontFamily` field## Context-The shell typography is a single hardcoded token stack (`--font-sans`). Users-want to choose a global UI font from Settings — including open-licensed fonts-that are safe for commercial use — similar to the font picker in the dbx desktop-client, which enumerates system fonts and bundles an OFL family.+The shell typography was a single hardcoded token stack, and users wanted to+choose a global UI font in Settings. The renderer is sandboxed behind the+preload IPC allowlist and the font source must stay local, with no CDN or CSS+font service.## Decision### 1. Settings picker and persistence-Settings → Basics → Appearance gains a **Font** row with a searchable picker.-Selections persist as `AppSettings.fontFamily`, a CSS `font-family` stack-string.--The picker menu portals to `document.body` as a fixed body-level floating layer-(measured against the trigger and clamped to the viewport), so the settings-card's `overflow` cannot clip or squeeze it; it follows the body-level-floating-layer contract in the component spec.+Settings → Basics → Appearance gained a searchable **Font** row whose selection+persists as `AppSettings.fontFamily`, a CSS `font-family` stack string, where an+absent or empty value means the built-in stack and **System default** persists+`fontFamily: ""` rather than removing the key, because `settings.set` merges+supplied fields and an omitted key cannot clear a stored override.### 2. Bundled open-licensed families (superseded by ADR 0298)-*(Historical. [ADR 0298](0298-remove-bundled-fonts.md) removed every bundled-family, so the picker offers System default plus installed system families and-nothing is loaded from disk.)*--Four families shipped with the app as `woff2`, all under the SIL Open Font-License 1.1 (free for commercial use and redistribution; license texts were-shipped under `apps/desktop/src/assets/fonts/licenses/`):--| Family | Script coverage | Source |-|---|---|---|-| Geist | Latin (variable) | vercel/geist-font |-| Inter | Latin (variable) | rsms/inter |-| Noto Sans SC | CJK (variable) | google/fonts (Source Han Sans lineage) |-| LXGW WenKai | CJK kai (regular) | lxgw/LxgwWenKai |--0298. The mono stack (`--font-mono`) is unchanged.+[ADR 0298](0298-remove-bundled-fonts.md) removed every bundled family, so the+picker offers System default plus installed families and loads nothing from+disk.### 3. System font enumeration in Electron main-Electron main resolves installed system font families using platform tooling-only (no native modules), so the main bundle stays self-contained:--- macOS: `osascript` JXA bridging `CTFontManagerCopyAvailableFontFamilyNames` —- the same CoreText query `font_kit::all_families()` uses, returning canonical- CSS family names in tens of milliseconds — with `system_profiler- SPFontsDataType -json` kept as a fallback when osascript is unavailable-- Windows: PowerShell `[Windows.Media.Fonts]::SystemFontFamilies`-- Linux: `fc-list -f "%{family[0]}\n"`--Results are deduplicated, filtered (hidden `.`-prefixed families excluded),-sorted, and cached for 60 seconds per process. The renderer reaches them through-one new allowlisted IPC channel, `pi-desktop/app/systemFonts`.+Electron main resolves installed families with platform tooling only and+without native modules — an `osascript` JXA bridge on macOS, PowerShell on+Windows, `fc-list` on Linux — deduplicates, sorts, and caches the result, and+exposes it to the renderer through one allowlisted IPC channel.### 4. ApplicationThe renderer overrides `--font-sans` on `document.documentElement` from-`AppSettings.fontFamily`; `body` and every `var(--font-sans)` consumer pick it-up without a reload. *(Superseded by [ADR 0298](0298-remove-bundled-fonts.md):-the `@font-face` rules, `apps/desktop/src/styles/fonts.css`, and its `@import`-in `globals.css` are deleted, so a stored stack resolves through installed-families.)*+`AppSettings.fontFamily`, so `body` and every `var(--font-sans)` consumer+follow without a reload.## Consequences-- Users pick a global UI font once; it persists across restarts and renders- offline from installed families ([ADR 0298](0298-remove-bundled-fonts.md)- ships no font files).-- CJK coverage stays correct for every option via the appended fallback tier.-- macOS enumeration resolves through the fast CoreText path in tens of- milliseconds (the previous `system_profiler` path took 2–5 s and is now only a- fallback); the result is cached 60 s per process and returns canonical family- names such as `PingFang SC` rather than system_profiler's localized aliases- such as `苹方-简`.-- The installer carried roughly 16 MB of bundled font files; ADR 0298 removed- them, so `out/renderer` emits no application font face and only KaTeX's- `woff2` glyphs remain (see `06-delivery/06-release-runbook.md`).-- `@font-face` `font-weight` descriptors are exempted from the style-token guard- because they describe font files, not UI typography.+- Users pick a global UI font once; it persists across restarts and resolves+ through installed families, since [ADR 0298](0298-remove-bundled-fonts.md)+ ships no font files.+- CJK coverage stays correct because every stack appends a system CJK fallback+ tier, and the mono stack is unchanged.+- Enumeration no longer pays the multi-second `system_profiler` cost on macOS,+ and the installer no longer carries bundled font files.## Alternatives-- **`font_kit` in host-core** (dbx's approach): fast native enumeration, but- adds a host RPC method and widens the host protocol surface for a- renderer-only preference; Electron main reaches the same CoreText family list- through an `osascript` JXA bridge without widening the protocol.-- **`font-list` npm package**: clean API, but its internal directory- `require("./libs/core")` does not survive electron-vite main bundling, and its- macOS helper is a prebuilt binary that would need asar unpacking.-- **`queryLocalFonts()` (Local Font Access API)**: permission-gated in the- sandboxed renderer and still experimental in Electron.+- `font_kit` in host-core: fast, but widens the host RPC surface for a+ renderer-only preference.+- The `font-list` npm package: its internal `require` does not survive+ electron-vite main bundling.diff --git a/docs/adr/0084-deferred-new-task-session-creation.md b/docs/adr/0084-deferred-new-task-session-creation.mdindex 361e6a322..4876c0b77 100644--- a/docs/adr/0084-deferred-new-task-session-creation.md+++ b/docs/adr/0084-deferred-new-task-session-creation.md@@ -1,48 +1,36 @@# ADR 0084: Defer new-task session creation until the first message-- **Status:** Accepted-- **Date:** 2026-08-14-- **Related:** D220 · D088 · D093 · E2E-011b · E2E-011d+- Status: Accepted+- Date: 2026-08-14+- Related: D088, D093, D220## Context-Clicking New Task created a session immediately, so the sidebar history gained a-default-titled `新建任务` / "New task" row even when the user never typed a message.-A reuse rule (D088/D093) kept at most one empty draft per project or temporary-scope, but the first empty row still appeared and remained visible until the-user sent a prompt that renamed it.+New Task created a session immediately, so sidebar history gained a+default-titled `新建任务` / "New task" row even when nothing was typed. The reuse+rule (D088/D093) kept at most one empty draft per project or temporary scope, but+that row was visible at once and the draft also persisted in the host database.## Decision-New Task opens an unpersisted draft instead of creating a session:--- `newSession()` resets the renderer to the home empty state (keeping the- requested project scope) and no longer calls `session.create` nor reuses a- legacy empty draft.-- The first message (`sendPrompt`) or pasted files (which must attach to a- session) materialize the draft through a shared `materializeDraftSession`- helper that creates the session, applies any retained toolbar configuration,- and commits the same navigation/run state the eager path used.-- Composer and top-bar model toolbar choices made on the draft are retained in a- new `draftConfiguration` store slice and applied at materialization time- instead of materializing a session on a toolbar-only interaction.-- The sidebar history filter now drops sessions whose title is still a default- untitled value, hiding legacy empty drafts and any accidentally empty session- as a defense in depth.+New Task opens an unpersisted draft instead of creating a session: `newSession()`+resets the renderer to the home empty state, keeping the requested project scope,+leaving `activeSessionId` unset, and no longer calling `session.create` or+reusing a legacy empty draft. The first message, or a pasted file, materializes+the draft through a shared `materializeDraftSession` helper that applies retained+toolbar configuration from a `draftConfiguration` store slice before committing+the same navigation and run state the eager path used. The sidebar history filter+drops sessions whose title is still a default untitled value, hiding legacy empty+drafts as defense in depth.## Consequences-- The sidebar history only records tasks that actually carry input; abandoned- New Task drafts leave no row and no persisted session.-- No new empty sessions accumulate in the host database; legacy empty drafts- remain on disk but are hidden from history.-- The renderer store, Composer, and Sidebar change; protocol v9, host RPC, and- storage schema v11 are untouched, so older renderers remain compatible.+- History only records tasks that carry input, and no new empty sessions+ accumulate in the host database.+- Only the renderer store, Composer, and Sidebar change; host RPC and the storage+ schema are untouched, so older renderers stay compatible.-## Alternatives considered+## Alternatives-- Keep eager creation and only hide empty drafts in the sidebar: smaller change,- but leaves invisible sessions on disk and keeps the reuse machinery alive for- rows the user should never see.-- Create the session on the first draft keystroke: would still create rows for- messages that are never sent, which is what the request asks to avoid.+- Hide empty drafts but keep eager creation: leaves invisible sessions on disk.+- Create the session on the first keystroke: still creates rows for unsent text.diff --git a/docs/adr/0085-work-panel-shortcut-toggle.md b/docs/adr/0085-work-panel-shortcut-toggle.mdindex b73798619..1077e61e9 100644--- a/docs/adr/0085-work-panel-shortcut-toggle.md+++ b/docs/adr/0085-work-panel-shortcut-toggle.md@@ -1,64 +1,42 @@# ADR 0085: Make the work panel shortcut a toggle-- Status: Accepted for implementation+- Status: Accepted for implementation; amends ADR 0068 and D207, and is amended+ by [ADR 0195](0195-viewport-fixed-work-panel-toggle.md) (the viewport-fixed+ toggle is the pointer equivalent; the header chevron no longer collapses)- Date: 2026-08-14-- Deciders: PI-Desktop core-- Amends: ADR 0068, D207-- Amended by: [ADR 0195](0195-viewport-fixed-work-panel-toggle.md) (the- viewport-fixed toggle is the pointer equivalent; the header chevron is no- longer a collapse control)-- Related: [01-ui-ia](../spec/04-ux/01-ui-ia.md) ·- [08-component-spec §5](../spec/04-ux/08-component-spec.md) ·- [09-interaction-patterns §1](../spec/04-ux/09-interaction-patterns.md) ·- E2E-056+- Related: D128, D142, D221, ADR 0068, ADR 0195## Context-ADR 0068 made `Cmd/Ctrl + J` an open-only action and rejected a toggle on the-grounds that the panel header already owns collapse and that a toggle risks-hiding the panel while the user is trying to reveal it. In use the asymmetry-reads as a broken shortcut instead of a safeguard: the same chord that reveals-the panel does nothing on the second press, so a keyboard-first user has to move-to the header control to put the panel away.+ADR 0068 made `Cmd/Ctrl + J` open-only, because the panel header already owned+collapse and a toggle might hide the panel mid-reveal. In use the asymmetry reads+as broken: the chord that reveals the panel does nothing on a second press, while+every other shell chord (`Cmd/Ctrl + B` for the sidebar) toggles. The risk is+small because collapsing is immediately reversible.## Decision-1. `openWorkPanel` becomes a toggle.-2. Collapsing via the shortcut retains the session's context exactly as the- header control does — tabs, active resource, Browser resource, and committed- width are preserved, so a second press restores the previous surface.-3. The shortcut id stays `openWorkPanel` so existing user keybinding overrides- keep working; only the Settings → Shortcuts label changes to describe- toggling.-4. The no-active-session and Settings no-op contexts from 0068 are unchanged, as- are artifact-driven resource creation, session ownership, and- background-event isolation.+1. `openWorkPanel` becomes a toggle: an open visible panel collapses through the+ same path as the header control, and a closed panel reveals the active+ session's retained context at its committed width without creating a resource+ tab.+2. Collapsing retains tabs, active resource, Browser resource, and committed+ width, so a second press restores the previous surface.+3. The shortcut id stays `openWorkPanel` so existing keybinding overrides keep+ working; only the Settings → Shortcuts label changes.+4. The no-active-session and Settings no-op contexts from ADR 0068 are unchanged,+ as are artifact-driven resource creation, session ownership, and background+ event isolation; no host protocol, IPC channel, or menu command is added.## Consequences-- One chord both reveals and puts away the work panel, matching the sidebar.-- The header collapse control remains for pointer users and is now one of two- equivalent entry points to the same store action.-- ADR 0068's "Make `Cmd/Ctrl + J` a toggle" rejected alternative no longer- holds; 0068's remaining clauses stay in force.+- One chord both reveals and puts away the panel, matching the sidebar, while the+ header control remains a pointer entry point.+- ADR 0068's toggle-rejection alternative no longer holds; its remaining clauses+ stay in force.-## Alternatives considered+## Alternatives-### Keep open-only and add a separate close chord--Rejected. A second binding spends scarce chord space on the inverse of an-existing one and still leaves the first chord feeling inert.--### Toggle only when the panel has no tabs--Rejected. Behavior that depends on invisible tab state is less predictable than-a plain toggle, and the retained context makes collapsing a populated panel-non-destructive anyway.--## References--- `docs/adr/0068-work-panel-keyboard-entry.md`-- `docs/spec/04-ux/01-ui-ia.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/04-ux/09-interaction-patterns.md`-- `docs/spec/08-meta/decisions-log.md` (D128, D142, D207, D221)+- Open-only plus a separate close chord: spends scarce chord space on the inverse+ of an existing binding.+- Toggle only when the panel has no tabs: depends on invisible state.diff --git a/docs/adr/0086-macos-regular-activation-policy.md b/docs/adr/0086-macos-regular-activation-policy.mdindex 8b9fd3efa..fc6475dca 100644--- a/docs/adr/0086-macos-regular-activation-policy.md+++ b/docs/adr/0086-macos-regular-activation-policy.md@@ -2,40 +2,46 @@- Status: Accepted- Date: 2026-08-14-- Deciders: PI-Desktop core-- Related: D223, E2E-127, ADR 0072, ADR 0078, ADR 0080+- Related: ADR 0072, ADR 0078, ADR 0080, D223## Context-The global plugin launcher (ADR 0072) is a frameless always-on-top panel that-should appear over whatever the user is doing, so its window asked Electron for-`setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true })`. On macOS that-option is not a per-window flag: Electron implements it by calling-`TransformProcessType(kProcessTransformToUIElementApplication)` on the whole-process, because macOS 10.14 and later only let accessory applications float-windows above another app's fullscreen Space.+The global launcher (ADR 0072) asked Electron for+`setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true })`, which on macOS is+a process-wide `TransformProcessType` call: the app became a UIElement app and+disappeared from the Dock and Cmd+Tab. ADR 0080 then moved creation into boot+warm-up, so this ran on every launch, and because macOS emits Electron's+`activate` only from `applicationShouldHandleReopen:`, a tray-hidden window had no+keyboard route back.## Decision-1. PI-Desktop is a regular (foreground) macOS application for its entire- lifetime.-2. The launcher keeps its collection behavior: it joins every regular Space and- floats above PI-Desktop's own fullscreen window.+1. PI-Desktop stays a regular foreground macOS application for its lifetime. No+ code path may transform the process type: the launcher passes+ `skipTransformProcessType: true`, and `app.dock.hide()` and+ `setActivationPolicy` stay out of Main. Dock and Cmd+Tab presence is an+ invariant, not a side effect of one window's options.+2. The launcher keeps its collection behavior and floats above PI-Desktop's own+ fullscreen window, but it does not overlay another application's fullscreen+ Space, which macOS reserves for accessory apps.3. macOS activation restores the shell through `did-become-active` as well as- `activate`, gated on a booted, non-quitting app with no visible window.-4. Tests assert the launcher call shape and the activation handler, so a future+ `activate`, gated on a booted, non-quitting app with no visible window, so+ Cmd+Tab and App Exposé recover a tray-hidden window without dragging the main+ window forward when only the launcher or a plugin panel is shown.+4. Tests assert the launcher call shape and the activation handler so a futurewindow option cannot silently make the app accessory again.## Consequences- The app is always reachable from the Dock, Cmd+Tab, App Exposé, and the tray.-- The launcher cannot overlay another app's fullscreen Space.-- Panel focus is unchanged: `show()` activates the app and makes the panel key- under both policies, so ADR 0080's latency work is untouched.+- Invoking the launcher from another app's fullscreen Space activates PI-Desktop+ and switches Spaces, which is ordinary foreground behavior.+- Panel focus and ADR 0080's warm-up latency are unchanged.## Alternatives-- Toggle the policy around each launcher show (`app.dock.hide()` before,- `app.dock.show()` after).-- Drop `visibleOnFullScreen` entirely.-- Ship PI-Desktop as an `LSUIElement` tray app.+- Toggle the policy around each launcher show: rejected because it flickers the+ Dock icon, adds work to the optimized path, and strands the app as accessory if+ the restore is missed.+- Ship PI-Desktop as an `LSUIElement` tray app: rejected because it contradicts+ ADR 0078's resident main window.diff --git a/docs/adr/0087-line-anchored-edit-contract.md b/docs/adr/0087-line-anchored-edit-contract.mdindex e7e4bd263..4bacd1063 100644--- a/docs/adr/0087-line-anchored-edit-contract.md+++ b/docs/adr/0087-line-anchored-edit-contract.md@@ -2,123 +2,90 @@- Status: Implemented (phases 1–2; block ops, drift recovery, and boundary repair remain phased)- Date: 2026-08-15-- Deciders: PI-Desktop core- Amends: D186, ADR 0069 §2 (`Read` output shape), ADR 0043 §1 (review keying)- Supersedes: the `old_string` / `new_string` `Edit` contract in[03-tools-and-permissions §4d](../spec/03-runtime/03-tools-and-permissions.md)-- Related: [18-line-anchored-edit-contract](../spec/03-runtime/18-line-anchored-edit-contract.md) ·- [02-agent-runtime](../spec/03-runtime/02-agent-runtime.md) ·- [16-tool-result-limits](../spec/03-runtime/16-tool-result-limits.md) ·- [08-error-codes](../spec/03-runtime/08-error-codes.md) ·- E2E-130 … E2E-139+- Related: [18-line-anchored-edit-contract](../spec/03-runtime/18-line-anchored-edit-contract.md)## Context-`Edit` currently takes `old_string` / `new_string` and requires `old_string` to-match exactly one location in the file-(`crates/host-core/src/tools/mod.rs:1278`). `Read` deliberately returns-line-number-free bytes so that text copied out of its `content` still matches-(`crates/host-core/src/tools/mod.rs:1225`).--1. **The model must retype existing code.** Every edit's correctness depends on- reproducing bytes it saw earlier.-2. **Ambiguity is the model's problem to solve.** A duplicated fragment forces- the model to widen `old_string` until it is unique, which increases the- retyped surface and therefore the chance of retyping it wrong.-3. **Nothing proves the model read what it is editing.** A unique match on a- remembered fragment succeeds even when the model never displayed that region- in this session, and even when the file changed after the read that informed- the edit.+`Edit` takes `old_string` / `new_string` and requires an exact single match, while+`Read` returns line-number-free bytes so copied text still matches. Three failures+follow and none are fixable inside that contract: the model must retype existing+code, ambiguity becomes the model's problem to widen a fragment, and nothing+proves the model ever read the region it is editing — the failure class that+silently produces plausible, wrong edits. `Grep` already returns line numbers, but+the edit path cannot consume them.## Decision### 1. `Edit` becomes a line-anchored patch tool-`Edit` takes `path`, `tag`, and `ops`. `old_string` / `new_string` are removed;-no compatibility shim, no per-model variant selection, no second write tool.--The operation surface is the full `hashline` surface: range replace (`PUT-N.=M:`), gap insert (`PUT <N:` / `PUT >N:` / `PUT >$:`), syntactic-block replace-and sibling insert (`PUT N*:` / `PUT >N*:`), capture-and-delete (`CUT N.=M` /-`CUT N*`), register paste (`PUT <N @name` / `PUT N.=M @name`), and the-file-level `REM` / `MV DEST`. Body rows are `+`-prefixed final content; `-old`-rows and bare context rows do not exist, because the range already expresses the-deletion.+`Edit` takes `path`, `tag`, and `ops`; `old_string` / `new_string` are removed with+no compatibility shim, no per-model variant, and no second write tool, so the+permission matrix, review snapshots, artifacts, audit surface, and mutation+serialization stay single-valued. The surface is the full `hashline` one — range+replace (`PUT N.=M:`), gap insert (`PUT <N:` / `PUT >N:` / `PUT >$:`), block+replace and sibling insert (`PUT N*:` / `PUT >N*:`), capture-and-delete+(`CUT N.=M` / `CUT N*`), register paste (`PUT <N @name` / `PUT N.=M @name`), and+`REM` / `MV DEST` — with `+`-prefixed final content only, since the range already+expresses the deletion.### 2. Read and Grep mint tags; Read emits line numbers-`Read` prefixes each returned line with `N:` and prepends a `[path#TAG]` header.-This reverses ADR 0069's byte-faithful `content` decision, whose sole purpose-was to keep copied text matchable by `old_string`.+`Read` prefixes each line with `N:` and prepends a `[path#TAG]` header holding a+4-hex fingerprint of the whole normalized file, reversing ADR 0069's+byte-faithful `content` decision. `Grep` gains the same header per matched file,+and `Write` returns the post-write header so an immediately following `Edit`+needs no extra `Read`.### 3. Host-core owns a session-scoped snapshot storeA bounded in-memory store maps `(session, canonical path)` to a short history of-full-file versions, each carrying its tag and the set of line numbers a producer-actually **displayed**. This makes two guarantees enforceable that the current-contract cannot express:--- **Version.** An `Edit` whose `tag` does not hash the live file is not applied- on the model's word.-- **Provenance.** An `Edit` anchored on a line the session never displayed is- rejected, with that line's real content inlined in the error so a straight- retry can succeed without another `Read`.--The store is in-memory, per session, bounded, and dropped with the session. It-is distinct from ADR 0043's review snapshots, which are on-disk, per tool call,-and exist for rollback; the two share only the hashing primitive already in-`crates/host-core/src/review.rs`.+full-file versions, each carrying its tag and the line numbers a producer+displayed, which makes version drift and unread provenance rejectable instead of+undetectable. It is distinct from ADR 0043's on-disk review snapshots and shares+only the hashing primitive; `execute_tool_with_path_access` gains the session+identity parameter it needs.### 4. Tree-sitter is added to host-core for block resolution-`PUT N*:`, `PUT >N*:`, and `CUT N*` need the line span of the syntactic-construct opening at line `N`. host-core gains `tree-sitter` plus a bounded-grammar set. Resolution is a pure function of (text, language, line) and returns-`None` for an unsupported language, an invalid line, a line with no opener, or a-file that does not parse; the tool then rejects the block op with an actionable-message naming the plain-range alternative.--Every resolved span is echoed back in the tool result so the model can see that-it anchored the wrong opener.+`PUT N*:`, `PUT >N*:`, and `CUT N*` need the span of the construct opening at line+`N`, resolved as a pure function of text, language, and line that returns `None`+for an unsupported language, invalid line, opener-less line, or unparsed file.+Block ops degrade with a message naming the plain-range alternative, never guess,+and echo every resolved span back.### 5. Registers are session-scoped and named; anonymous registers are call-local-Cross-file moves use named registers (`CUT 1* @fn` in one call, `PUT <1 @fn` in-the next), which is `hashline`'s own sanctioned cross-call mechanism. `Edit`-stays single-path: PI-Desktop's permission gate, review snapshot, artifacts row,-and mutation permit are all keyed on one `args.path`, and multi-section patches-would fork all four.+Cross-file moves use named registers across two calls, while `Edit` stays+single-path because the permission gate, review snapshot, artifacts row, and+mutation permit are keyed on one `args.path`. The anonymous register lives only+within one call.### 6. Failure is explicit, and recovery must be provable-A stale tag attempts snapshot recovery: every anchor is remapped through-unchanged lines from the tagged snapshot to the live file, surrounding context-is validated, and all anchors must move by one consistent offset. Anything-changed, split, or ambiguous fails closed with a mismatch error carrying current-content.+A stale tag attempts snapshot recovery: anchors are remapped through unchanged+lines, surrounding context is validated, and all anchors must move by one+consistent offset. Anything changed, split, or ambiguous fails closed with a+mismatch error carrying current content, head/tail-only inserts apply with a+warning, and a no-op apply is an error.## Consequences-- The model stops retyping existing code to edit it.-- Edits against content the session never displayed become impossible instead of-- Edits against content the session never displayed become impossible instead of- being undetectable. §4d's bounded loop guard stays, now allowing three counted- failures per path before termination.-- `Read` output grows by the width of a line-number prefix, and its `content` is- no longer byte-faithful.-- host-core gains a per-session memory cost bounded by the store's caps, plus- tree-sitter and its grammars in the binary.+- The model stops retyping existing code and unread-anchored edits become+ impossible; the §4d loop guard allows three counted failures per path before a+ visible `MUTATION_RETRY_BUDGET_EXHAUSTED` end of turn.+- `Read` output grows by a line-number prefix and is no longer byte-faithful, so+ consumers must strip prefixes and the renderer's Edit diff must come from the+ review record's hunks.+- host-core pays a bounded per-session memory cost plus tree-sitter and an+ explicit grammar list, and every model must learn one new syntax with no+ fallback contract.## Alternatives rejected-- **Add a tag to the existing `old_string` contract.** Fixes version and- provenance but leaves the model retyping code, which is the larger cost.-- **Keep both contracts behind a mode switch.** Two prompts, two validators, two- renderers, two audit shapes, and a per-model exclusion list to maintain- forever, in exchange for tolerating models that cannot follow one documented- syntax.-- **Add a second, separate line-anchored write tool.** Cheapest to build and the- worst to own: two concurrent high-risk write tools fork the permission matrix,- the review snapshot boundary, the artifacts ledger, and the mutation permit.-- **Unified diff / `apply_patch`.** Requires the model to compute hunk headers- and retype context lines — both retyping and arithmetic.+- **Add a tag to the existing `old_string` contract.** It fixes version and+ provenance but still leaves the model retyping code, the larger cost.+- **Block resolution by brace counting or indentation.** Silently wrong on+ strings, comments, macros, JSX, and Markdown; declining beats usually right.diff --git a/docs/adr/0088-declared-file-scope-for-plugins.md b/docs/adr/0088-declared-file-scope-for-plugins.mdindex dffa710cf..4294a76e4 100644--- a/docs/adr/0088-declared-file-scope-for-plugins.md+++ b/docs/adr/0088-declared-file-scope-for-plugins.md@@ -2,127 +2,80 @@- Status: Accepted (Implemented 2026-08-15)- Date: 2026-08-15+- Related: ADR 0008, D009## Context-ADR 0008 put plugin main code in its own `utilityProcess`, but noted that the-process is a full Node environment: permissions gate the `pi.*` surface, not-`require("node:fs")`. Capability sandboxing is still the open half (ADR 0008,-D009).--- `fs.read.workspace` → any file in the workspace, including `.env` and- `.git/config`-- `fs.write.workspace` → any path in the workspace-- `fs.delete.workspace` → `fs.remove` with `recursive: false`, which bounds one- call and not the blast radius: `fs.glob("**/*")` followed by a loop empties a- workspace as thoroughly as `rm -rf` does**--- A **read** is dangerous when the bytes can leave.+ADR 0008 put plugin main code in a `utilityProcess`, but permissions still gate+only the `pi.*` surface, so the granularity of that gate is the whole design+until capability sandboxing (ADR 0008, D009) lands. That granularity was three+workspace-wide switches — `fs.read.workspace`, `fs.write.workspace`,+`fs.delete.workspace` — reaching `.env`, `.git/config`, and, through `fs.glob`+in a loop, the whole workspace. Lexical prefix containment let a workspace+symlink point at `~/.ssh`, and a missing grants argument auto-granted the entire+manifest. The permissions matrix had always promised confirm-on-first-use; this+record delivers it, plus recoverable deletion, because the risks of read, write,+and delete are not symmetric.## Decision### 1. `manifest.fs` declares scope; permission names stay flat strings-`permissions` remains `readonly string[]` and gains `fs.read`, `fs.write`,-`fs.delete` — "may this plugin touch files at all". A separate `fs` block says-"which files":--```json-{- "permissions": ["fs.read", "fs.write", "fs.delete"],- "fs": {- "read": { "root": "workspace", "scope": ["**/*"] },- "write": { "root": "workspace", "scope": ["docs/**", "*.md"] },- "delete": { "own": true, "scope": ["dist/**"] }- }-}-```--A separate field rather than objects inside `permissions` because permissions-are handled as strings end to end — install review, chips, grant round-trips,-catalog validation — and the marketplace catalog format is versioned separately.+`permissions` stays `readonly string[]` and gains `fs.read`, `fs.write`, and+`fs.delete` for "may this plugin touch files at all", while a sibling `fs` block+carries per-mode `root`, `scope`, and `own`. Flat strings are kept because+permissions travel as strings through install review, grants, and the separately+versioned marketplace catalog; whole-tree patterns are refused for write and+delete, and an absent scope means every access falls to the user.### 2. Four gates, in a fixed order-Every `pi.fs.*` call passes, in order:--1. `assertPermission` — is `fs.<mode>` declared **and** granted (intersection,- so a revoked permission actually stops working)-2. Containment — `realpath` on both the root and the target; for a path being- created, `realpath` of the nearest existing ancestor.-3. Unconditional deny-list — credentials and history refused under every root,- scope, and grant: `.env*`, `.npmrc`, `.netrc`, `.git-credentials`, `id_rsa*`,- `*.pem`/`*.p12`/`*.pfx`/`*.keystore`, and anything inside `.git`, `.ssh`,- `.aws`, `.gnupg`, `.kube`, `.docker`, plus the host's own data directory- (provider keys, session store)-4. Declared scope, else user consent--`pi.fs.glob` answers to the same rules: results are filtered by the read scope,-denied paths and reserved trees are omitted (a name is a read too), and-`node_modules` / `.git` / `.venv` / `__pycache__` are not walked at all.+Every `pi.fs.*` call checks the declared-and-granted permission, then realpath+containment of root and target (a path that does not exist reports `NOT_FOUND`+rather than an escape attempt), then an unconditional deny-list of credentials,+history, and the host's own data directory, and finally declared scope or user+consent. `pi.fs.glob` answers to the same rules, so a name is a read too.### 3. Deletion has two tiers, and always goes to the trash-- **`fs.delete` with `own: true`** — the host appends every successful- `fs.writeText` to a write ledger in the plugin's own data directory (path plus- mtime, host-owned, not reachable from the plugin API).-- **`fs.delete` with `scope`** — deleting somebody else's file requires the- globs up front, and they are shown to the user where the permissions are- shown.--Both tiers additionally:--- go through `shell.trashItem`, never `rm`.-- keep `recursive: false`; a non-empty directory is refused rather than emptied-- answer to a rolling brake of 50 deletes per 60s per plugin.+`own: true` deletes only paths the host recorded in a host-owned write ledger+when the plugin wrote them, falling to consent once the file's mtime has moved;+a declared `scope` covers everybody else's files and is shown with the+permissions. Both tiers use `shell.trashItem` rather than `rm`, keep+`recursive: false`, and answer to a rolling brake of 50 deletes per 60s per+plugin.### 4. Consent is a native dialog, and never more durable than the session-Out-of-scope access calls `dialog.showMessageBox`: **Deny** / **Allow once** /-**Allow this session**. A session grant covers the containing directory and dies-with the process; nothing is persisted.+Out-of-scope access asks Deny / Allow once / Allow this session; a session grant+covers the containing directory and dies with the process, and a host with no+consent service refuses.### 5. `root: "userSelected"`-`pi.fs.requestDirectory()` opens the native directory picker and returns a-handle. Inside that directory the plugin needs no manifest scope — the user just-pointed at it, which *is* the grant — while containment and the deny-list still-apply.--This is where the capability comes back. "Organize my whole photo folder", "bulk-import/export" plugins become possible with **zero standing power**, modelled on-the browser's File System Access API.+`pi.fs.requestDirectory()` returns a memory-only handle that grants that+directory without manifest scope while containment and the deny-list still+apply, which restores bulk file workflows with zero standing power.### 6. Migration is a breaking downgrade-| Legacy permission | What it is worth now |-|---|---|-| `fs.read.workspace` | `fs.read`, `scope: ["**/*"]` — unchanged, because egress is closed |-| `fs.write.workspace` | `fs.write` with an empty scope — every write asks the user |-| `fs.delete.workspace` | `fs.delete` with `own: true` — only its own output goes without asking |--Capability is reduced; no hole is left open. An explicit rule always beats the-legacy default, so an author upgrades by adding `fs`, never by renaming-anything.+Legacy `fs.write.workspace` becomes `fs.write` with an empty scope and+`fs.delete.workspace` becomes `fs.delete` with `own: true`, so capability is+reduced and no hole opens; the Plugins page marks downgraded plugins.## Consequences-- A plugin that writes or deletes outside its declared scope now prompts, and a- prompt the user denies is audited as `PERMISSION_DENIED`.-- Installed plugins that predate `manifest.fs` lose write and delete reach on- the next load.-- Reads stay generous, which keeps the interesting plugins possible.-- Deletion is recoverable through the OS trash on every platform Electron- supports it, and we store none of the user's data to achieve that — no- quarantine copy, no undo journal.-- The rate brake is per plugin and rolling, so a legitimate large cleanup is- interrupted once rather than refused.--## Alternatives considered--- **A host-owned quarantine directory with an undo UI** instead of the OS trash:- rejected.-- **Objects inside `permissions`** (`{ "name": "fs.write", "scope": [...] }`):- rejected.-- **Prompt on every file access, no manifest scope**: rejected.-- **Keeping `recursive: false` as the only delete bound**: rejected.+- Writes and deletes outside declared scope prompt, and a denial is audited as+ `PERMISSION_DENIED`; plugins predating `manifest.fs` lose write and delete+ reach on the next load, visibly rather than silently.+- Reads stay generous, which is a bet on the egress allowlist in+ `manifest.net.domains`.+- A malicious plugin can still call `node:fs` directly; this bounds the `pi.*`+ surface and leaves the sandbox case to ADR 0008 D009.++## Alternatives++- Host-owned quarantine directory with an undo UI — rejected: it copies the+ user's files to offer recovery the OS already provides.+- Objects inside `permissions` — rejected: permissions are strings end to end+ across review, grants, and catalog.diff --git a/docs/adr/0089-proactive-background-subagent-delegation.md b/docs/adr/0089-proactive-background-subagent-delegation.mdindex 48cfef14e..15e2f399f 100644--- a/docs/adr/0089-proactive-background-subagent-delegation.md+++ b/docs/adr/0089-proactive-background-subagent-delegation.md@@ -3,28 +3,16 @@- Status: Accepted for implementation (resumable delegations amended byADR 0279)- Date: 2026-08-16-- Deciders: PI-Desktop core-- Related: D201, D202, ADR 0062, ADR 0063, ADR 0048, ADR 0100, ADR 0279, E2E-142+- Related: D201, D202, ADR 0062, ADR 0063, ADR 0048, ADR 0100, ADR 0279,+ E2E-142## Context-ADR 0062 shipped delegation as context economy: `Task` runs one delegate to-completion and returns its report, and the tool description tells the model to-delegate only when a wide search or long survey would otherwise fill the parent-context. In practice the main agent almost never delegates:--- The system prompt says nothing about delegation, so the model only ever sees- the tool's defensive description ("do not delegate what you can finish in a- couple of tool calls") with no positive trigger patterns to act on.-- `Task` blocks the parent's tool loop until the delegate finishes, so from the- model's perspective delegation trades one long job for another; there is no- way to keep working while a delegate runs.-- All builtin delegates are read-only report machines, so there is nothing to- delegate implementation work to, and a write-capable delegate would hit the- session's permission prompts for every file it touches.-- The concurrency cap (4) and the fire-and-forget contract leave no room for- orchestration patterns like "review my change before I commit" or "explore- three directions in parallel, then converge".+ADR 0062 shipped delegation as context economy, and in practice the main agent+almost never delegates: the system prompt said nothing positive about it,+`Task` blocked the parent's tool loop, every builtin delegate was read-only,+and a per-batch concurrency cap of four left no room for orchestration patterns+such as reviewing a change before commit or exploring directions in parallel.## Decision@@ -33,96 +21,66 @@ every containment boundary ADR 0062 established.### 1. The delegate lifecycle is non-blocking and tool-driven-`Task` starts a delegate in the background and returns immediately with a-`delegationId`. Three new Agent-mode tools drive the lifecycle, all in the core-tool set beside `Task`:--- `TaskWait(delegationIds?, mode?, minCompleted?, timeoutSeconds?)` converges on- running delegations (all by default) and returns their reports; `mode: "any"`- + `minCompleted` converges as soon as the first N finish, and settled- delegations return immediately so reports can be re-read by id.-- `TaskList()` reports the session's delegations with status.-- `TaskStop(delegationIds?)` stops running delegations; stopped reads as- `stopped`.--The session runtime owns a delegation registry (id, agent, status, timings,-result, completion promise, abort handle). Settled records are retained for the-session (capped at 100) so `TaskWait` can re-read a report without re-running-the delegate.+`Task` starts a delegate in the background and returns a `delegationId`, and+three core tools drive the rest: `TaskWait` converges on running delegations and+returns their reports, `TaskList` reports the session's delegations with+status, and `TaskStop` stops them and reads as `stopped`. The runtime keeps a+delegation registry of id, agent, status, timings, result, completion promise,+and abort handle, retains settled records for the session so reports can be+re-read, and aborts anything still running when the run ends.### 2. The system prompt names positive trigger patterns-The base prompt gains a `## Delegation` section (only when the catalog is-non-empty) listing concrete situations: parallel exploration of independent-directions, adversarial review before commit, multi-file implementation via-`fixer`, context-economy searches, and batch sharding — plus the convergence-rules (continue working after `Task`, fill `description` for the user, never end-the turn with running delegates). The `Task` description is rewritten to lead-with these triggers and keep the old "do not" list as a single boundary line.+The base prompt gains a `## Delegation` section, present only when the catalog+is non-empty, that lists the situations worth delegating and the convergence+rules for ending a turn.### 3. New builtins: a faster `explorer` and a write-capable `fixer`-`explorer` is rewritten in the style of the omo-slim explorer prompts: tool-selection guidance (Grep for patterns, Glob for discovery, Read for files),-parallel searches, and a structured `<files>` / `<answer>` report shape.--A fourth builtin, `fixer`, implements multi-file changes from a complete spec:-`tools: [Read, Glob, Grep, Edit, Write, Bash]`, `maxTurns: 40`, with a-`<summary>` / `<changes>` / `<verification>` report shape. It is the only-write-capable builtin; the other three stay read-only.+`explorer` was rewritten around tool selection and a structured report shape,+and a fourth builtin `fixer` implements multi-file changes from a complete spec+with a summary/changes/verification report; the other three stay read-only.### 4. Definitions may declare a permission scope-Frontmatter gains `permission: inherit | ask | accept-edits | auto` (default-`inherit`). A definition with an explicit non-`inherit` scope causes the sidecar-to attach that scope to the delegate's `tools.execute` calls, and host-core-resolves each call under that mode instead of the session's effective permission-mode.+Frontmatter accepts `permission: inherit | ask | accept-edits | auto`, default+`inherit`, and an explicit non-`inherit` scope is resolved by host-core for the+delegate's `tools.execute` calls instead of the session's effective mode. It is+a permission-mode override only: the hard deny rules and the external-path gate+stay in force, and `accept-edits` auto-allows `Write`/`Edit` inside the+workspace and scratch roots while Bash keeps the session's behavior.### 5. Concurrency-`MAX_SUBAGENT_CONCURRENCY` becomes a per-session running cap of 10 (was a-per-batch cap of 4). `Task` fails with a tool error when the session already-runs 10 delegates, telling the model to wait or stop first.+The running cap becomes 10 delegates per session, and `Task` fails with a tool+error that tells the model to wait or stop first.## Consequences-- Delegation stops being "a long tool call" and becomes background- orchestration: the parent can implement while `explorer` searches and- `code-reviewer` reviews, then converge with `TaskWait`.-- Models receive positive trigger patterns in the system prompt and a full- lifecycle vocabulary, which is what makes delegation proactive rather than- permitted-but-unused.-- A write-capable delegate is bounded by its definition's `permission` scope,- not by the session's prompts; host-core stays the authority and the external- path gate is untouched.-- Old transcripts keep rendering: `Task` rows keep their delegation grouping,- and the new tools map to the same delegate presentation.-- A delegate that outlives its turn is stopped, not left running; the prompt- rule plus the turn-end abort make that the exception rather than the policy.--## Alternatives considered--- **Background tasks across turns (Proma-style).** Delegates that keep running- after the parent turn ends, with the UI showing pending background work, would- maximize parallelism but requires reworking Electron main's turn lifecycle,- completion semantics and the renderer's session-idle handling.-- **Let delegates inherit the session permission mode.** Rejected: a delegate- that needs `auto` would silently re-enable prompting or force the whole- session to `auto`; the per-definition scope keeps the relaxation explicit and- reviewable in the definition document.-- **Keep `Task` blocking and add a `wait` flag.** Rejected: a flag the model- must remember to set is a flag it forgets; a lifecycle with distinct tools- makes "start, work, converge" a sequence the model can follow and the prompt- can teach.+- Delegation becomes background orchestration: the parent implements while+ `explorer` searches and `code-reviewer` reviews, then converges with+ `TaskWait`.+- Positive prompt triggers plus a lifecycle vocabulary are what make delegation+ proactive rather than permitted-but-unused.+- A write-capable delegate is bounded by its definition's `permission` scope+ while host-core stays the authority, and old transcripts keep rendering+ through the existing delegate presentation.-## Amendment — session-owned job controls (2026-11-05)+## Alternatives++- Delegates running across turns: rejected, it would require reworking the turn+ lifecycle, completion semantics, and renderer idle handling for parallelism+ the within-turn model already delivers.+- Keeping `Task` blocking with a `wait` flag: rejected, a flag the model must+ remember to set is one it forgets.-Background Bash already belongs to Host and exposes results to the desktop, but-the model's controls only resolve runtime delegation IDs. Extending each tool-independently would duplicate target selection and risk adding permanent servers-to default delegation wait/stop sets.+## Amendment — session-owned job controls (2026-11-05)-TaskWait/List/Stop therefore share explicit typed job references. Runtime routes-delegation references to the existing delegation implementation and Bash-references to session-scoped Host RPC.+`TaskWait`, `TaskList`, and `TaskStop` share explicit typed job references, so+the model's controls resolve both runtime delegations and session-owned+background Bash, whose RPC checks ownership and keeps process supervision in+Host. Bash waits are bounded and completion-aware, cancelling a wait does not+signal the process, and output tails are repeatable and independently bounded+for stdout and stderr; completion notifications stay deferred, and unsupported+Bash controls are reported explicitly. This decision moves no delegation+reports or resumption chains into Rust.diff --git a/docs/adr/0090-user-configurable-close-behavior-close-to-tray.md b/docs/adr/0090-user-configurable-close-behavior-close-to-tray.mdindex 1b906f170..a717fe288 100644--- a/docs/adr/0090-user-configurable-close-behavior-close-to-tray.md+++ b/docs/adr/0090-user-configurable-close-behavior-close-to-tray.md@@ -2,71 +2,55 @@- Status: Accepted for implementation- Date: 2026-08-12-- Deciders: PI-Desktop core-- Related: D230, D256, ADR 0021, ADR 0025, ADR 0078, ADR 0123+- Related: ADR 0021, ADR 0025, ADR 0078, ADR 0123, D230, D256## Context-On Windows/Linux, closing the main window calls `app.quit()`-(`window-all-closed`), so the app exits and its taskbar entry disappears.-Minimizing already hides the window into the tray that D216 (ADR 0078) keeps-resident on every platform, but users with long-running chats expect closing the-window to keep the app available too.+On Windows and Linux, closing the main window runs `app.quit()` through+`window-all-closed`, so the app exits and its taskbar entry disappears, while+minimize already hides the window into the tray D216 (ADR 0078) keeps resident.+Users with long-running chats expect close to keep the app available, and other+users expect close to quit; macOS is out of scope because its Dock lifecycle+already matches.## Decision-1. Windows/Linux close behavior becomes a persisted, user-configurable- preference with three values, of which two are ever settable:- - `ask`: the transient unset state — the first close prompts once.- - `tray`: closing the window hides it under the resident D216 system-tray- icon and keeps the app running; the tray menu restores the window or quits- the app.- - `quit`: legacy behavior — closing the window exits the app.-2. The first close with an unset preference shows a themed in-app dialog (Cancel- / Close to tray / Quit).-3. The preference is stored by Electron main in `<data>/close-behavior.json`- (same ownership pattern as `window-state.json`), NOT in host-core settings:- it is app-shell lifecycle state, read and written only by the main process,- and needs no host RPC or schema change.-4. Two additive IPC channels expose it to the renderer:- `pi-desktop/window/closeBehavior/get` (returns `{ behavior, supported }`) and- `pi-desktop/window/closeBehavior/set`, which accepts only `tray` and `quit`- (`ask` and unknown values fail with `INVALID_ARGUMENT`).-5. Settings (General tab) renders a two-option radio segment — Close to tray /- Quit app — for Windows/Linux only; an unset preference shows no selection.-6. The close handler intercepts every non-macOS `close` that is not already an- approved quit; `before-quit` (`quitting`) and macOS closes always fall- through, so an explicit quit, the tray Quit item, and the automated boot- probe are unaffected.-7. The bounds watchdog (`ensureStableBounds`) skips minimized and hidden- windows, so minimize always stays minimized and a tray-hidden window is never- force-restored by the Stage-Manager shelf recovery.-8. Known limitation: on Windows system shutdown/logoff, the OS may deliver a- `close` that is intercepted while the preference is `ask` or `tray`.+The close behavior becomes a persisted user preference with three values: `ask`,+the transient unset state that prompts once, `tray`, which hides the window under+the resident tray icon and keeps the app running, and `quit`, the legacy exit. The+first close shows a themed in-app dialog (Cancel / Close to tray / Quit), a+non-cancel choice is remembered permanently, `closeBehavior/set` rejects `ask`, and+an unavailable renderer falls back to a bounded native dialog or allows Quit+rather than trapping the close.++Electron main stores the preference in `<data>/close-behavior.json` on the+`window-state.json` ownership pattern rather than in host-core settings, and+exposes it through the additive channels+`pi-desktop/window/closeBehavior/get`, returning `{ behavior, supported }`, and+`pi-desktop/window/closeBehavior/set`, which accepts only `tray` and `quit` and+fails with `INVALID_ARGUMENT` otherwise, including on macOS where `supported` is+`false` and the Settings row is hidden. Settings (General) renders a two-option+radio segment for Windows and Linux only, and the tray icon is never reconciled+with the preference because minimize-to-tray needs it either way.++The close handler intercepts every non-macOS close that is not an approved quit,+`before-quit` and macOS closes fall through, `quit` calls `app.quit()` itself, and+`window-all-closed` stays silent only under `tray`; a `tray` close without a tray+icon falls back to a real quit. Dialogs render in the main renderer, correlated by+request id after the readiness handshake, with a native fallback after ten+seconds, and the bounds watchdog skips minimized and hidden windows.-9. The first-close and explicit-quit dialogs render in the main renderer using- the existing theme.--## Alternatives considered+## Consequences-- **Store the preference in host-core settings (`AppSettings`):** rejected- because it would add a Rust schema field and host RPC surface for pure shell- lifecycle state that only Electron main consumes.-- **Renderer dialog without readiness and fallback handling:** rejected because- a missed request could block close.-- **Always close-to-tray without a choice:** rejected — it changes the meaning- of the close button for users who expect exit.-- **Tray icon reconciled with the preference:** rejected; D216 keeps one tray- icon resident on every platform for minimize-to-tray, so destroying it when- close behavior is `quit` would break an unrelated feature.+- Windows and Linux close either hides to tray or quits per a remembered choice+ that Settings can change, using the existing `@pi-desktop/i18n` catalogs.+- No host RPC, storage schema, or macOS close behavior changes.+- During Windows shutdown a close can be intercepted, but the OS still terminates+ the session without data loss.-## Consequences+## Alternatives considered-- Windows/Linux explicit minimize uses the normal taskbar transition; a close- choice of `tray` still hides the window under the resident D216 tray icon.- macOS native minimize remains tray-resident under D216.-- Close on Windows/Linux either hides to tray or quits, per user choice,- remembered across launches and changeable in Settings.-- The tray menu and the first-close dialog reuse the existing `@pi-desktop/i18n`- catalogs (English and Simplified Chinese).-- No host protocol, storage schema, or macOS behavior changes.+- Store the preference in host-core `AppSettings`: rejected; it would add a Rust+ schema field and RPC surface for pure shell lifecycle state.+- Always close to tray without a choice: rejected; it changes the meaning of the+ close button for users who expect exit.diff --git a/docs/adr/0091-rate-limit-same-turn-retry.md b/docs/adr/0091-rate-limit-same-turn-retry.mdindex 5a81c644b..6c121b050 100644--- a/docs/adr/0091-rate-limit-same-turn-retry.md+++ b/docs/adr/0091-rate-limit-same-turn-retry.md@@ -2,53 +2,53 @@- Status: Accepted- Date: 2026-08-14 (amended 2026-08-19)-- Deciders: PI-Desktop core-- Related: D233, D245, E2E-149, ADR 0050, D186+- Related: D233, D245, ADR 0050, D186## Context-A provider HTTP 429 caused by a transient rate limit can happen both before a-response is established and after a stream has already started. The old-implementation split those cases between pi-ai's one setup retry and the-runtime's one mid-stream replay.+A provider HTTP 429 can arrive before a response is established or after a stream+has started, and splitting those phases between pi-ai's setup retry and the+runtime's mid-stream replay surfaced recoverable rate limits too early and made+the effective budget depend on which phase failed. OpenCode's session retry+policy is the behavioral reference: silent finite retries, provider retry headers+ahead of client backoff, abortable waits, only the exhausted failure rendered.## Decision-1. `PROVIDER_RATE_LIMITED` owns a runtime retry budget of five retries after the- initial provider attempt.-2. Each 429 retry is silent and abortable.-3. A 429 before streaming is retried by the provider stream adapter.+1. `PROVIDER_RATE_LIMITED` owns a runtime budget of five retries after the+ initial attempt, shared by setup and stream recovery, so a turn has at most six+ provider attempts; pi-ai's nested retry is disabled on this path.+2. Each retry is silent and abortable, with delay precedence `retry-after-ms`,+ `retry-after` seconds, `retry-after` HTTP-date, then exponential backoff from+ 2 seconds with up to 25% jitter, every delay capped at 30 seconds.+3. A pre-stream 429 is retried by the provider stream adapter and a mid-stream+ 429 is replayed by the runtime after removing the failed assistant from model+ context, both through the same controller and budget; the main session and+ every builtin subagent follow this policy.4. Intermediate assistant errors, lifecycle end events, and duplicate assistant- bubbles are suppressed.-5. Authentication, model-selection, malformed-request, context, and other- non-retryable failures do not enter the 429 path.-6. After the fifth 429 retry fails, the normal assistant error and lifecycle- error are emitted once.+ bubbles are suppressed: a recovered attempt reuses the original visible+ assistant id, emits one terminal lifecycle, and is not persisted into the next+ model context.+5. Authentication, model-selection, malformed-request, and context failures stay+ terminal, and existing non-429 transient behavior keeps its separate+ one-retry bounds.+6. After the fifth retry fails, the normal assistant and lifecycle errors are+ emitted once, diagnostics keep the redacted provider error plus `phase`,+ `providerStatus`, and `retryAttempt: 5`, and aborting during a wait cancels the+ timer and any later request.## Consequences-- Short provider rate-limit bursts recover without an error card, toast, or- manual action, whether the 429 arrives during setup or streaming.-- Persistent rate limiting remains bounded: six total attempts, at most five- backoffs, and a maximum 30-second individual wait.-- Retry headers from providers such as OpenAI-compatible gateways are honored,- while malformed or excessive values cannot hold a turn indefinitely.-- Main sessions and subagents cannot drift into different rate-limit policies,- and lifecycle consumers receive one coherent assistant turn.+- Short bursts recover without an error card, toast, or manual action, whether+ the 429 arrives during setup or streaming.+- Persistent rate limiting stays bounded at six attempts and a 30-second maximum+ individual wait, with the final failure visible and actionable.+- Provider retry headers are honored, and main sessions and subagents cannot+ drift into different policies or emit split assistant turns.## Alternatives-- Keep pi-ai's setup retry and add another runtime retry.-- Retry every provider failure five times.-- Keep one same-turn retry and rely on the UI's manual action.--## References--- OpenCode session retry behavior (behavioral reference only)-- `docs/spec/03-runtime/02-agent-runtime.md` §5d-- `docs/spec/03-runtime/08-error-codes.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` E2E-149-- `docs/spec/08-meta/decisions-log.md` D245-- `packages/agent-runtime/src/provider-retry.ts`-- `packages/agent-runtime/src/runtime.ts`-- `packages/agent-runtime/src/subagent.ts`+- Keep pi-ai's setup retry and add another runtime retry: nested wrappers+ multiply attempts and make the budget phase-dependent.+- Retry every provider failure five times: credentials, model ids, and malformed+ requests are not repaired by repetition.diff --git a/docs/adr/0092-plugin-owned-panel-surface.md b/docs/adr/0092-plugin-owned-panel-surface.mdindex 28bb56f8a..5e523ea62 100644--- a/docs/adr/0092-plugin-owned-panel-surface.md+++ b/docs/adr/0092-plugin-owned-panel-surface.md@@ -2,50 +2,40 @@- Status: Accepted- Date: 2026-08-17-- Deciders: PI-Desktop core- Related: D234, ADR 0081, ADR 0082## Context-The first plugin-panel chrome revision made the host render a complete 46px-titlebar. It still split behavior by platform: macOS retained native traffic-lights, while Windows and Linux received a flat 112px control band.+The first plugin-panel chrome revision made the host render a full titlebar,+kept native traffic lights on macOS while giving Windows and Linux a flat+control band, and drew the manifest title plus a development reminder. That+chrome owns the visual hierarchy of a panel, so authors cannot build their own+toolbar without competing with the host.## Decision-1. Plugin panels use frameless `BrowserWindow` instances on macOS, Windows, and- Linux.-2. The sandboxed preload reserves a transparent 46px safe area and renders one- fixed capsule at the top-right.-3. The plugin owns its title, toolbar, background, content, and all other- visible panel UI.-4. The capsule remains in a closed preload-owned Shadow DOM.+Plugin panels use frameless windows on every platform without native traffic+lights or panel menus, and the sandboxed preload reserves a transparent 46px+safe area holding one fixed top-right capsule with minimize,+maximize/restore, and close. The plugin owns its title, toolbar, background, and+content, with normal-flow content offset automatically, fixed or sticky UI+anchored to `--pi-plugin-titlebar-height: 46px`, and drag regions opted into+through `-webkit-app-region: drag` with interactive children opting out. The+capsule stays in a closed preload-owned Shadow DOM behind a sender-validated+private window-control channel, and `window.pluginBridge` gains no window+primitives.## Consequences-- A panel presents the same compact top-right control grammar on all supported- platforms while giving each plugin complete ownership of its visible header.-- The 46px safe area remains a stable layout contract, so existing normal-flow- panels do not move behind the controls and fixed plugin toolbars have a- documented anchor.-- The manifest title remains useful as native window identity and launcher- metadata, but it is no longer a host-rendered visual element.-- Development panels no longer need a host-only reminder; the devkit and plugin- documentation must teach the safe-area variable and drag-region contract.+- Every platform shows the same compact control grammar while the plugin owns+ its entire visible header.+- The 46px safe area remains a stable layout contract for panels and fixed+ toolbars, while the manifest title survives only as window identity.+- Documentation must teach the safe-area variable and the drag-region contract.## Alternatives-### Keep native macOS controls and a host titlebar--Rejected because it keeps the platform split and reserves the plugin's primary-visual hierarchy for host chrome.--### Expose window controls to the plugin bridge--Rejected because plugin JavaScript still does not need generic native-window-authority; the preload-local, sender-validated channel is sufficient.--### Remove the safe area entirely--Rejected because a host control overlay still needs a stable hit and drag band,-and existing fixed/sticky plugin layouts would collide with the capsule.+- Keep native macOS controls plus a host titlebar: rejected, it preserves the+ platform split and spends the plugin's hierarchy on host chrome.+- Expose window controls to the plugin bridge: rejected, plugin JavaScript+ needs no generic native-window authority.diff --git a/docs/adr/0093-plugin-panel-strict-drag-band.md b/docs/adr/0093-plugin-panel-strict-drag-band.mdindex 6331f1609..55388ed3e 100644--- a/docs/adr/0093-plugin-panel-strict-drag-band.md+++ b/docs/adr/0093-plugin-panel-strict-drag-band.md@@ -2,56 +2,42 @@- Status: Accepted- Date: 2026-08-17-- Deciders: PI-Desktop core- Related: D235, ADR 0092## Context-The plugin-owned panel surface introduced a compact host capsule, but its layout-contract must remain explicit. Frameless windows still need a reliable drag-area, and the top band cannot receive plugin clicks.+Frameless plugin panels need a reliable drag area, so the top band cannot receive+plugin clicks. The host must not grow that band for a title, a platform-specific+control row, or decorative chrome, and development authors need a visible+reminder of the constraint.## Decision-1. Every plugin panel reserves exactly 46 CSS px for the transparent host drag- band.-2. The drag band uses `-webkit-app-region: drag` and blocks plugin pointer- interaction across those 46px.-3. The host renders no panel title.-4. The capsule stays fixed at the top-right inside the 46px band and remains a- minimal closed-Shadow-DOM surface: three controls, a subtle border and- page-adaptive background, with no heavy shadow or blur effect.--## Paint-through opt-in--Panels that need a full-bleed surface may declare `<meta name="pi-plugin-chrome"-content="v3">`. The host keeps the same 46px geometry and capsule, but replaces-one full-width native drag rectangle with empty-space drag segments.+1. Every panel reserves exactly 46 CSS px for the transparent host drag band;+ normal-flow content is offset by that value and fixed or sticky plugin UI uses+ `--pi-plugin-titlebar-height: 46px`.+2. The band uses `-webkit-app-region: drag` and blocks plugin pointer interaction;+ the host capsule opts out with `no-drag` so its three buttons stay clickable.+3. The host renders no panel title; development panels show a localized,+ non-interactive reminder that the top band is drag-only outside the capsule.+4. The capsule stays fixed at the top-right inside the band as a minimal closed+ Shadow-DOM surface; its sender-validated window-control channel, localized+ labels, focus, reduced-motion behavior, and `window.pluginBridge` are unchanged.+5. Panels needing a full-bleed surface declare+ `<meta name="pi-plugin-chrome" content="v3">`: the host keeps the geometry and+ capsule but swaps one full-width native drag rectangle for empty-space drag+ segments, so elements marked `data-pi-plugin-no-drag` paint and receive pointer+ events while blank space still drags; `v2` panels keep the strict band.## Consequences-- Plugin authors get a stable 46px layout and interaction contract on every- desktop platform.-- The top band is intentionally unavailable to plugin buttons except for the- host capsule; plugin toolbars should use the documented drag/no-drag rules.-- Development authors see the constraint while production panels keep the- surface quiet.-- The capsule has less visual weight and cannot extend beyond the drag band.+- Authors get a stable layout and interaction contract on every platform.+- Development panels show the constraint while production panels stay quiet, and+ the capsule cannot extend beyond the drag band.## Alternatives-### Let the drag band grow with the capsule--Rejected because a variable host band would change plugin layout and make the-same panel differ across platforms or future chrome revisions.--### Let every plugin content receive clicks in the drag band by default--Rejected for the default because frameless window dragging would become-unreliable and authors could mistake the top strip for ordinary interactive-content.--### Restore a host-rendered panel title--Rejected because the plugin owns the visible panel hierarchy; the host only-needs the three native window actions and the development constraint reminder.+- Let the band grow with the capsule: the same panel would differ across+ platforms and chrome revisions.+- Give plugin content clicks by default: frameless dragging would become+ unreliable.diff --git a/docs/adr/0094-single-instance-per-data-directory.md b/docs/adr/0094-single-instance-per-data-directory.mdindex 47c133159..1e5b04f4b 100644--- a/docs/adr/0094-single-instance-per-data-directory.md+++ b/docs/adr/0094-single-instance-per-data-directory.md@@ -2,76 +2,59 @@- Status: Accepted- Date: 2026-08-18-- Deciders: PI-Desktop core- Related: D236, D002, D216, ADR 0078, ADR 0090## Context-Nothing stopped a second PI-Desktop process from starting. Launching the app-again while it was already running — a double click on Windows or Linux, a `open--n` or a packaged app started next to a development host on macOS, or a-tray-resident session the user assumed had exited — booted a complete second-copy: another host-core over the same `pi.sqlite`, another persistence outbox-and log tree in the same data directory, another agent sidecar, another tray-icon, another global launcher shortcut registration, and another updater.+Nothing stopped a second process from starting and booting a complete second+copy: another host-core over the same `pi.sqlite`, another outbox, log tree,+agent sidecar, tray icon, launcher shortcut registration, and updater. A second+shell defeats single-writer ownership of SQLite (D002) with silent data+divergence. The data directory is what cannot be shared, but Electron's lock is+scoped to `userData`, not to `PI_DESKTOP_DATA_DIR`, and runs given their own+data directory must stay launchable.## Decision-1. Electron main takes `app.requestSingleInstanceLock()` during module- evaluation, after `app.setName` (the lock file lives under the name-derived- `userData` path) and before anything reads or writes the data directory.-2. A launch that does not get the lock calls `app.quit()` immediately and boots- nothing.-3. The instance that holds the lock handles `second-instance` by restoring and- focusing its main window through the same path as the tray's Show action,- which recreates a window that was closed or hidden into the tray.-4. The lock is requested only when `PI_DESKTOP_DATA_DIR` is unset.+Electron main takes `app.requestSingleInstanceLock()` during module evaluation,+after `app.setName` and before anything touches the data directory. A launch+that does not get the lock calls `app.quit()` immediately and boots nothing, so+it creates no window, tray, child process, or log line in the running+instance's data directory. The lock holder handles `second-instance` by+restoring and focusing its window through the tray's Show path, and requests+the lock only when `PI_DESKTOP_DATA_DIR` is unset.## Consequences-- One installation is one process: one host-core, one SQLite writer, one outbox,- one tray, one launcher shortcut binding, one updater.-- Relaunching the app is a reliable way back to a tray-hidden or closed window,- alongside the tray, the Dock, and `did-become-active` (ADR 0078, ADR 0086).-- E2E harnesses, the capture rig, and side-by-side profiles are unaffected- because they set `PI_DESKTOP_DATA_DIR`.-- Two runs that are pointed at the *same* explicit data directory are still- admitted.+- One installation is one process: one host-core, one SQLite writer, one+ outbox, one tray, one launcher binding, one updater.+- Relaunching is a reliable way back to a tray-hidden or closed window.+- E2E harnesses and side-by-side profiles are unaffected because they set+ `PI_DESKTOP_DATA_DIR`; two runs pointed at the same explicit directory are+ still admitted.## Alternatives-### Relocate `userData` under `PI_DESKTOP_DATA_DIR`--This would scope the lock to the resource that actually cannot be shared.--### Keep a lock file in the data directory--Rejected because it re-implements what Electron already provides and still has-no channel to raise the running window; a stale lock file after a crash would-also block the app with no recovery path.--### Let the second launch focus the first and stay alive--Rejected because a resident duplicate keeps a second Electron process, tray, and-shortcut registration for no purpose.--### Do nothing and document the hazard--Rejected because the failure is silent data divergence over a single-writer-database, and the user has no signal that two shells are open on one workspace.+- Relocate `userData` under `PI_DESKTOP_DATA_DIR`: rejected, it also holds+ renderer `localStorage` (D093), plugin partitions, and browser cookies, which+ would be discarded for existing profile users.+- A lock file in the data directory: rejected, it re-implements the Electron+ lock and has no channel to raise the running window.## Amendment (D599)-The alternatives below still stand: the lock is not scoped to-`PI_DESKTOP_DATA_DIR`, and `userData` is not relocated under it.--What changed is that a development build is no longer the same installation as-the packaged app. It takes `PI-Desktop Dev` in the OS application-data root and-`~/.pi-desktop-dev`, so `pnpm dev` starts while the packaged app holds its lock-and the two never share `pi.sqlite`, the outbox, or the log tree.+The lock is still scoped to `userData` and is not scoped to+`PI_DESKTOP_DATA_DIR`. A development build is now a distinct installation+(`PI-Desktop Dev` in the OS application-data root and `~/.pi-desktop-dev`), so+`pnpm dev` runs beside the packaged app without sharing `pi.sqlite`, the+outbox, or the log tree. An explicit `--user-data-dir` still wins for the E2E+harnesses, and a shipped installation keeps `PI-Desktop` and `~/.pi-desktop`,+so no existing profile moves.## Amendment: explicit storage relocation (2026-10-01)-Issue #1213 adds an explicitly confirmed, offline relocation of the complete app-and Chromium profile. The stable `userData` installation lock is retained, while-Chromium `sessionData` may follow the copied browser profile.+Issue #1213 adds an explicitly confirmed, offline relocation of the complete+app and Chromium profile: the `userData` installation lock is retained while+Chromium `sessionData` may follow the copied browser profile, with no silent+relocation or reset of existing renderer state. See+[Custom storage location](custom-storage-location.md).diff --git a/docs/adr/0095-vendor-account-oauth-login.md b/docs/adr/0095-vendor-account-oauth-login.mdindex 5fb3b589b..266cce9ea 100644--- a/docs/adr/0095-vendor-account-oauth-login.md+++ b/docs/adr/0095-vendor-account-oauth-login.md@@ -2,87 +2,70 @@- Status: Accepted for implementation- Date: 2026-08-18-- Deciders: PI-Desktop core- Related: D237, D240, ADR 0098, D028, D031, ADR 0012, ADR 0020, ADR 0027## Context-A provider row could only be authenticated one way: the user pastes an API key,-host-core encrypts it under `secret:provider:<id>:api_key`, and Electron main-reads the plaintext back on every launch so the sidecar can sign requests with a-constant `{ auth: { apiKey } }`. Users who already pay for a vendor subscription-— Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot — had to buy separate API-credit to use PI-Desktop at all.+A provider row could only be authenticated by pasting an API key, encrypted under+`secret:provider:<id>:api_key` and read back by Electron main at launch so the+sidecar could sign with a constant `{ auth: { apiKey } }`. Subscribers to Claude+Pro/Max, ChatGPT Plus/Pro, or GitHub Copilot therefore had to buy separate API+credit. pi-ai already ships the OAuth flows, the `CredentialStore` contract, and+locked refresh, but explicitly leaves login and logout orchestration to the app,+and PI-Desktop had no such half. Vendor tokens expire in about an hour and a+refresh token mints credentials on demand, so a credential resolved once at+launch was neither fresh enough nor safe enough.## Decision1. **The credential is a second secret on the same provider row.** OAuth- credentials serialize to JSON and are stored through the existing encrypted- secret store under `secret:provider:<id>:oauth`, beside — never instead of —- `secret:provider:<id>:api_key`.-+ credentials are stored through the existing encrypted secret store under+ `secret:provider:<id>:oauth`, beside — never instead of —+ `secret:provider:<id>:api_key`; `has_secret` widens to "either credential",+ `has_oauth` distinguishes them, and `auth_kind` gains `oauth`, so neither the+ host protocol version nor the storage schema changes.2. **Login orchestration lives in Electron main, in `oauth.ts`.** It implements`CredentialStore` over host-core's `secrets.*` RPC, serializing `modify` per- provider so pi-ai's locked-refresh assumption holds, and bridges pi-ai's- `AuthInteraction` to renderer events over five new invoke channels and one- event channel under `pi-desktop/providers/oauth/*`.-+ provider so pi-ai's locked-refresh assumption holds, and bridges+ `AuthInteraction` to the renderer over `pi-desktop/providers/oauth/*`+ channels, so the renderer renders whatever the vendor asked for rather than a+ per-vendor script.3. **The vendor list is derived, not enumerated.** Cards come from- `models.getProviders().filter(p => p.auth.oauth)`, so all seven vendors are- supported on day one and a vendor that gains or loses a flow in pi-ai needs- no change here.-+ `models.getProviders().filter(p => p.auth.oauth)`, and main calls+ `registerBunOAuthFlows()` once at startup because pi-ai loads flows through a+ variable dynamic import that electron-vite cannot bundle.4. **The sidecar resolves auth per request and never sees a refresh token.** An- OAuth row's launch payload carries `apiKey: ""`.-+ OAuth row's launch payload carries `apiKey: ""`; the runtime injects a+ `resolveAuth` callback answered by a new host-proxy method,+ `provider.resolveAuth`, which main answers itself against the session binding+ table and refuses for anything else, replying with a short-lived `ModelAuth`+ carrying `apiKey`, `headers`, and `baseUrl`.5. **A vendor row's identity stays stable across turns.** `matches()` compares- the provider row, whose `apiKey` is permanently `""`; a fresh `resolveAuth`- closure per launch is a function property and disappears through- `JSON.stringify`.-+ the provider row, whose `apiKey` is permanently `""`, so an OAuth session+ reuses its warm runtime instead of rebuilding it once an hour.6. **Model discovery and connection tests go through the account.** For an OAuth- row, `providers.listModels` reads the signed-in account's own model endpoint.- pi-ai `models.getAvailable` (including the vendor's `filterModels`) is the- fallback when that request fails.+ row, `providers.listModels` reads the signed-in account's own model endpoint+ with `models.getAvailable` as fallback, the connection test proves the account+ by resolving auth, and the row's `apiStyle` follows the selected model, adding+ `openai_codex_responses` and `pi_messages`. The one-row-per-vendor assumption+ is amended by ADR 0098: every login now creates an independent row and+ credential scope.## Consequences-- A subscriber signs in from Settings → Model configuration and picks models- normally; no API credit is required for the seven supported vendors.-- The privilege boundary tightens rather than loosens.-- Vendor logins depend on main being alive to answer `provider.resolveAuth`; a- host or main restart mid-turn fails the request rather than signing it with a- stale token, which is the intended failure direction.-- API-key rows are untouched: same storage, same launch payload, same resolve- path.+- A subscriber signs in from Settings → Model configuration and needs no API+ credit for the supported vendors.+- The privilege boundary tightens: a vendor row now gives the sidecar a+ revocable hour-long token for its one bound provider, and no refresh token.+- Vendor logins depend on main answering `provider.resolveAuth`, so a restart+ mid-turn fails the request instead of signing with a stale token; API-key rows+ keep the same storage, payload, and resolve path.## Alternatives-- **Resolve the credential once at launch and put it in the payload.** Rejected:- a Codex token expires in about an hour, so long sessions would break mid-turn;- refreshing would change the payload and make `matches()` miss every turn,- rebuilding the runtime and discarding warm state; and it would put a token the- user never typed into a process that runs model-directed code.-- **Give the sidecar the credential store and let pi-ai refresh in-process.**- Rejected: that hands the refresh token — the durable secret — to the least- trusted process, and contradicts the existing host-proxy allowlist rule that- the sidecar must not be able to pull secrets or mutate configuration.-- **Store OAuth credentials in a new dedicated table or file.** Rejected: the- encrypted secret store already provides the exact guarantees needed, and a- second backend would need its own lifecycle, deletion path, and audit.-- **Ship two or three vendors first.** Rejected: the list is derived from- pi-ai's catalog, so restricting it would have meant writing a hardcoded- allowlist — more code for less coverage.--## References--- `docs/spec/03-runtime/11-provider-model-system.md`-- `docs/spec/03-runtime/12-provider-config-schema.md`-- `docs/spec/03-runtime/14-secrets-storage.md`-- `docs/spec/03-runtime/01-ipc-protocol.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `apps/desktop/electron/main/oauth.ts`,- `apps/desktop/electron/main/agent-sidecar.ts`-- `packages/agent-runtime/src/provider-binding.ts`-- `crates/host-core/src/secrets.rs`, `crates/host-core/src/providers.rs`-- Decision D237, D028, D031+- Resolve the credential once at launch and put it in the payload — rejected:+ tokens expire mid-session, and refreshing would change the payload, miss+ `matches()`, and rebuild the runtime every turn.+- Give the sidecar the credential store and let pi-ai refresh in process —+ rejected: it hands the durable secret to the least trusted process and breaks+ the host-proxy allowlist.diff --git a/docs/adr/0096-flat-settings-directory-and-marketplace-context.md b/docs/adr/0096-flat-settings-directory-and-marketplace-context.mdindex 4fa8c79ba..9d2fd5d7e 100644--- a/docs/adr/0096-flat-settings-directory-and-marketplace-context.md+++ b/docs/adr/0096-flat-settings-directory-and-marketplace-context.md@@ -11,59 +11,39 @@## Context-The implemented Settings rail had grown to nine entries, including a separate-`Extensions` destination for two marketplace-source controls. The rail also-wrapped destinations in `Personal`, `Integrations`, and an implicit system-section.+The Settings rail had grown to nine entries, including a separate `Extensions`+destination for two marketplace-source controls, and wrapped destinations in+`Personal`, `Integrations`, and an implicit system section. Those headings repeated+what the labels already said, while `Extensions` carried the same visible name as the+app-shell destination that owns plugin management.## Decision-Keep the full-page Settings shell and render one flat, searchable directory in-this exact order:+Keep the full-page Settings shell and render one flat, searchable directory in this+order: Basics, AI, Shortcuts, Instructions, Model configuration, Import, Project+archive, Info. Remove the navigation group headings and the Settings `Extensions`+destination.-1. Basics-2. AI-3. Shortcuts-4. Instructions-5. Model configuration-6. Import-7. Project archive-8. Info--Remove navigation group headings and the Settings `Extensions` destination. At-the time of this decision, move the official/mirror/custom marketplace source-selector, including the custom catalog URL field and active-source status, into-the app-shell `Extensions → Marketplace` surface.+The official/mirror/custom marketplace source selector, including the custom catalog+URL field and active-source status, moved into the app-shell+`Extensions → Marketplace` surface. That selector has since been retired: the page+uses the official catalog only, host-core ignores legacy source values, and the+shared Settings search index contains only the eight destinations. No IPC, host+protocol, storage, provider, plugin permission, or project ownership contract+changes.## Consequences-- Settings has one visual hierarchy and fewer competing labels.-- The rail matches the frozen eight-destination IA and no longer duplicates the- Extensions page name.-- The marketplace-source selector described by this ADR is no longer present;- source selection is not a Settings destination or an Extensions control.-- Screenshot capture scenes and marketplace E2E steps use the fixed official- catalog.+- Settings has one visual hierarchy, the rail matches the frozen eight-destination+ IA, and it no longer duplicates the Extensions page name.+- Marketplace source selection is neither a Settings destination nor an Extensions+ control; capture scenes and E2E steps use the fixed official catalog.## Alternatives-### Keep the three group headings--Rejected because the groups do not add a second useful navigation level; they-make the rail taller and repeat the meaning of the destination labels.--### Rename Settings `Extensions` to `Marketplace`--Rejected because it would preserve a one-card Settings destination and still-split marketplace browsing from marketplace configuration.--### Remove marketplace source configuration--Rejected at the time because mirror and custom catalog sources were considered-necessary for some networks and development catalogs.--## References--- `docs/spec/04-ux/06-settings-ia.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`-- `docs/spec/07-plugins/07-plugin-marketplace.md`+- Keep the three group headings: they add no second useful level and repeat the+ labels.+- Rename Settings `Extensions` to `Marketplace`: it preserves a one-card destination+ and still splits browsing from configuration.+- Remove source configuration: rejected at the time; the official-only decision keeps+ the catalog URL fallback and a development override (ADR 0276).diff --git a/docs/adr/0097-place-global-defaults-under-ai-settings.md b/docs/adr/0097-place-global-defaults-under-ai-settings.mdindex 28141d362..6e9324bff 100644--- a/docs/adr/0097-place-global-defaults-under-ai-settings.md+++ b/docs/adr/0097-place-global-defaults-under-ai-settings.md@@ -2,56 +2,34 @@- Status: Accepted- Date: 2026-08-18-- Deciders: PI-Desktop core- Related: D166, D238, D239, ADR 0096## ContextThe flat Settings directory removed redundant navigation levels, but the Basics-page still owned a Defaults card containing the default operating mode, command-shell, and Enter-to-send preference. These controls change agent behavior rather-than application appearance, so their location made the Basics page mix visual-preferences with global AI behavior.+page still owned a Defaults card holding the default operating mode, command+shell, and Enter-to-send preference: agent behavior controls sitting beside+appearance controls.## Decision-Keep the eight-destination Settings directory unchanged. Basics owns the-Appearance card and platform-supported close behavior.--- default operating mode (Agent / Plan / Goal)-- command shell selection and its host-backed fallback status-- Enter-to-send--The Model configuration destination continues to own the default provider/model-selector because it is coupled to provider readiness and model identity. This-change only moves renderer content and Settings search ownership; persisted-settings, host APIs, runtime semantics, and deep-link contracts do not change.+Keep the eight-destination Settings directory. Basics owns Appearance and+platform-supported close behavior; the **全局 AI / AI** destination owns+Permissions and the Defaults card with default operating mode (Agent / Plan /+Goal), command shell selection with its host-backed fallback status, and+Enter-to-send. Model configuration keeps the default provider/model selector+because it is coupled to provider readiness and model identity. Only renderer+content and Settings search ownership move; persisted settings, host APIs,+runtime semantics, and deep links do not change.## Consequences- Basics has a focused visual and application-preference scope.-- Global AI presents the behavior controls users expect to affect agent turns.- Settings search routes mode, command shell, and Enter-to-send queries to AI.-- Existing persisted settings and runtime behavior remain unchanged.+- Persisted settings and runtime behavior are unchanged.## Alternatives-### Keep Defaults in Basics--Rejected because the card mixes appearance with agent execution behavior.--### Add a separate Behavior destination--Rejected because it would expand the flat directory for three closely related-controls that already have a clear owner in AI.--### Move the controls to Model configuration--Rejected because operating mode, command shell, and Enter-to-send are global-interaction behavior and do not depend on provider/model readiness.--## References--- `docs/spec/04-ux/06-settings-ia.md`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md`+- Keep Defaults in Basics: rejected, it mixes appearance with agent behavior.+- Add a Behavior destination: rejected, it expands the directory for three+ controls that already have an owner.diff --git a/docs/adr/0098-multiple-vendor-oauth-accounts.md b/docs/adr/0098-multiple-vendor-oauth-accounts.mdindex 71e529cb9..1f4395ffc 100644--- a/docs/adr/0098-multiple-vendor-oauth-accounts.md+++ b/docs/adr/0098-multiple-vendor-oauth-accounts.md@@ -2,59 +2,47 @@- Status: Accepted for implementation- Date: 2026-08-18-- Deciders: PI-Desktop core-- Related: D240, ADR 0095, D027, D028, D031+- Related: ADR 0095, D027, D028, D031, D240## ContextThe first vendor-account implementation used the pi-ai vendor id as the local-identity. Electron main kept one provider-row id and one `CredentialStore` per-vendor, so a second sign-in could only reuse the first account.+identity, so Electron main kept one provider row and one `CredentialStore` per+vendor and a second sign-in could only reuse the first account. The renderer also+showed OAuth rows both in the AI provider list and in a Vendor accounts card, and+sign-out cleared the credential but left the row. Multiple accounts for one vendor+are a real requirement, and the account boundary must be the security boundary+because tokens must never cross between accounts.## Decision-1. **The provider row id is the account identity.** Every successful login- starts with a new `authKind: "oauth"` provider row, even if another row has- the same `vendorKey`.-2. **Each account gets a scoped pi-ai collection.** Electron main creates one- `MutableModels` instance and one `CredentialStore` for each provider row.-3. **Vendor accounts own OAuth row lifecycle.** The Vendor accounts card lists- every local account, allows the vendor picker to be selected repeatedly, and- removes an account through `providers.delete`.-4. **AI services and vendor accounts are separate settings surfaces.** The AI- services list contains API-key and custom/no-auth services only.-5. **Runtime bindings use provider ids end to end.** The sidecar binding table- stores only the OAuth provider row ids allowed for a session.-6. **Ambiguous subagent aliases fail closed.** A subagent pin may use an exact- provider id.+The provider row id is the account identity: every successful login starts a new+`authKind: "oauth"` row even when another row shares the `vendorKey`, and the+credential lives only at `secret:provider:<providerId>:oauth`. Each row gets its+own `MutableModels` instance and `CredentialStore`, which accepts the builtin+vendor id only inside that instance and maps it to the row-specific secret ref;+refresh serialization is keyed by row id, so concurrent accounts cannot overwrite+each other's token. The Vendor accounts card owns the lifecycle: it lists every+local account, allows the picker to be used repeatedly, and removes an account+through `providers.delete`, which clears the row, OAuth secret, API-key secret, and+secret metadata together, while a row without a credential stays visible as+`Needs sign-in`. The AI services list holds API-key and custom or no-auth services+only; connected OAuth rows still feed the default-model selector and runtime but+are edited only from Vendor accounts. Sidecar bindings store only the row ids+allowed for a session and validate `provider.resolveAuth` against that set, and a+subagent aliased by vendor name resolves only when it names one row.## Consequences-- The account list can contain several rows for one vendor and labels duplicate- rows with a stable ordinal for scanning.-- Removing the selected default account clears or repairs the default to the- first remaining ready provider.-- Existing OAuth rows remain readable after upgrade; the next sign-in creates a- new row instead of mutating the existing one.-- The IPC host protocol and SQLite schema do not need a new table or version.+- Several rows for one vendor coexist with a stable ordinal, and removing the+ default account repairs the default to the first remaining ready provider.+- Existing OAuth rows stay readable after upgrade; the next sign-in adds a row.+- No schema version is needed: the renderer uses `providers/oauth/delete`, which+ delegates to the existing host provider deletion contract.## Alternatives-- **Keep one shared credential per vendor and add account labels.** Rejected:- the credential store and pi-ai model collection are vendor-keyed, so one- account would overwrite or refresh the other.-- **Keep OAuth rows in the generic AI services list.** Rejected: it presents two- owners for one object and makes deletion semantics unclear.-- **Clear only the OAuth secret on account removal.** Rejected: it leaves an- unusable provider row, stale default identity, and a misleading service entry.--## References--- `docs/adr/0095-vendor-account-oauth-login.md`-- `docs/spec/03-runtime/11-provider-model-system.md` §8a and §17-- `docs/spec/03-runtime/12-provider-config-schema.md` §3 and §9-- `docs/spec/03-runtime/01-ipc-protocol.md` vendor accounts-- `docs/spec/04-ux/06-settings-ia.md` Model configuration-- `docs/spec/06-delivery/04-e2e-test-plan.md` E2E-151-- `apps/desktop/electron/main/oauth.ts`-- `apps/desktop/electron/main/agent-sidecar.ts`+- Share one credential per vendor with labels: the vendor-keyed store would let one+ account overwrite the other.+- Clear only the OAuth secret on removal: leaves an unusable row and a stale+ default identity.diff --git a/docs/adr/0099-titled-settings-navigation-clusters.md b/docs/adr/0099-titled-settings-navigation-clusters.mdindex ee55e3fd1..556aee027 100644--- a/docs/adr/0099-titled-settings-navigation-clusters.md+++ b/docs/adr/0099-titled-settings-navigation-clusters.md@@ -2,50 +2,37 @@- Status: Accepted- Date: 2026-08-18-- Deciders: PI-Desktop core- Related: D238, D241, ADR 0096## Context-The Settings rail is intentionally a flat, searchable directory of eight-destinations. The rows are correct and remain in one navigation level, but the-unbroken list is visually dense.+The Settings rail is a flat, searchable directory of eight destinations whose+unbroken list is visually dense, and the previous visual-only spacing used divider+lines that were easy to lose against the dark rail and named nothing.## Decision-Keep the destination index flat and preserve its order, IDs, search behavior,-and ownership. Render four localized, non-interactive headings above the-existing row clusters:+The destination index stays flat and keeps its order, IDs, search behavior, and+ownership; four localized, non-interactive headings are rendered above the+existing row clusters, with muted typography and whitespace instead of dividers:- Personal / 个人: Basics, AI, Shortcuts- Agent / 智能体: Instructions, Model configuration- Workspace / 工作区: Import, Project archive- About / 关于: Info-Use muted typography and whitespace between clusters. Do not render divider-lines or add nested navigation.+Search still filters one flat index, and a cluster and its heading disappear when+no destination remains in it.## Consequences-- The rail gains clear scan landmarks without introducing another interactive- navigation level.-- The headings are available in both supported UI locales.-- The rail no longer depends on border contrast to communicate grouping in- either theme.-- The existing destination ordering and deep-link behavior remain stable.+- The rail gains scan landmarks without another interactive navigation level, in+ both supported UI locales.+- Grouping no longer depends on border contrast, and destination ordering and+ deep-link behavior stay stable.## Alternatives-### Keep the completely flat rail--Rejected because the compact rows remain difficult to scan as one block.--### Use divider lines between groups--Rejected because the previous rule was low-salience in dark mode and added-chrome without naming the groups.--### Add interactive nested navigation--Rejected because the Settings IA is intentionally a flat destination index and-the groups do not own additional navigation state.+- Use divider lines between groups: low-salience in dark mode and they name+ nothing.+- Add interactive nested navigation: the groups own no additional state.diff --git a/docs/adr/0100-builtin-subagents-inherit-parent-permission-mode.md b/docs/adr/0100-builtin-subagents-inherit-parent-permission-mode.mdindex 9cf49bcc4..1986c51e4 100644--- a/docs/adr/0100-builtin-subagents-inherit-parent-permission-mode.md+++ b/docs/adr/0100-builtin-subagents-inherit-parent-permission-mode.md@@ -2,50 +2,36 @@- Status: Accepted- Date: 2026-08-18-- Deciders: PI-Desktop core- Related: D115, D242, ADR 0057, ADR 0089## Context-The proactive delegation decision gave the builtin `fixer` an explicit-`permission: accept-edits` scope. That made workspace `Write` and `Edit` calls-convenient when the parent session was in `ask`, but it also replaced the-parent's effective permission mode for every other call.+Proactive delegation gave the builtin `fixer` an explicit `permission:+accept-edits` scope, which overrode the parent's mode: under an `auto` parent a+`fixer` call to `Glob` or to a `Write` outside the workspace opened a card `auto`+is meant to allow. The external-path gate stays a capability boundary, and an+explicit scope on a user-owned definition must stay meaningful.## Decision-Builtin subagent definitions use the default `permission: inherit` behavior. The-builtin `fixer` no longer declares `permission: accept-edits`; its available-tools remain `[Read, Glob, Grep, Edit, Write, Bash]` and its workspace/path-containment rules do not change.+Builtin subagent definitions use the default `permission: inherit`, so builtin+`fixer` no longer declares `permission: accept-edits` while its tools and+containment rules are unchanged. A delegate `tools.execute` call without a scope+resolves under the parent's effective mode: `ask` keeps approval for high-risk and+explicit external-path calls, `accept-edits` auto-allows only in-root `Write`/`Edit`,+and `auto` auto-allows what the parent could do. An explicit non-`inherit` scope+stays a deliberate override, and a project definition cannot escalate beyond the+session mode.-With no scope attached to a delegate `tools.execute` call, host-core resolves-the call under the parent session's effective permission mode:+## Consequences-- `ask` keeps approval for high-risk and explicit external-path calls;-- `accept-edits` auto-allows only in-root `Write`/`Edit` and keeps the other- approval boundaries;-- `auto` auto-allows the same calls the parent could make, including explicit- external paths.+- An `auto` parent uses `fixer` without an unexpected card, and delegation never+ silently widens an `ask` or `accept-edits` parent.+- Builtin `fixer` may prompt for writes under `ask`; callers wanting another+ posture use an explicit user definition scope.-## Consequences+## Alternatives-- A parent in `auto` can use builtin `fixer` without an unexpected subagent- authorization card.-- A parent in `ask` or `accept-edits` is not silently made more permissive by- delegation.-- The builtin fixer may prompt for its writes in `ask`; callers that need a- different posture can use an explicit user definition scope.-- Host-core's external-path containment and permission evaluation do not need a- special subagent exception.--## Alternatives considered--- **Keep `fixer` at `accept-edits`:** rejected because it reproduces the- observed auto-mode popup and makes a built-in delegate ignore the user's- selected permission posture.-- **Change `fixer` to `auto`:** rejected because it would bypass approval even- when the parent session is `ask`.-- **Ignore every delegate scope when the parent is `auto`:** rejected because an- explicit user-owned `ask` scope is a deliberate stricter policy and must- remain enforceable.+- Keep `fixer` at `accept-edits`: reproduces the popup and lets a builtin ignore+ the user's posture.+- Ignore delegate scopes under `auto`: an explicit user `ask` scope is deliberate.diff --git a/docs/adr/0101-model-aware-image-attachments.md b/docs/adr/0101-model-aware-image-attachments.mdindex 9bc90503c..b755485fe 100644--- a/docs/adr/0101-model-aware-image-attachments.md+++ b/docs/adr/0101-model-aware-image-attachments.md@@ -2,50 +2,48 @@- Status: Accepted- Date: 2026-08-18-- Deciders: PI-Desktop runtime and desktop UI maintainers- Amends: D197, ADR 0059, ADR 0070-- Amended by: D361 (inline bound is 10 MB, matching MiniMax's OpenAI-compatible cap), D392 / ADR 0218 (binding image-input overrides)+- Amended by: D361 (inline bound is 10 MB), D392 / ADR 0218 (binding image-input+ overrides)## Context-Clipboard images were materialized successfully, but the composer reduced every-file to `@<path>` text. A model that supports image input therefore received a-filesystem reference instead of an image block.+Clipboard images were materialized, but the composer reduced every file to+`@<path>` text, so a vision model received a filesystem reference instead of an+image block. The capability signal must come from the same model catalog pi-ai+uses to serialize provider requests, and it must stay ownerless of binary data+in the transcript.## Decision-1. Keep the composer draft compact and textual.-2. Resolve vision capability from the exact pi-ai model record.-3. Electron main remains the attachment boundary.-4. For a vision-capable model, an image within the 10 MB inline limit crosses- the sidecar only as transient base64 data and becomes a pi-ai image content- block.-5. For a non-vision model, an unknown model, or an image above the per-image- inline limit, the prompt receives a safe `@path` fallback.-6. Restored vision history has a 30 MB aggregate raw-image-byte budget in- addition to the 10 MB per-image limit.-7. The Composer shows a compact accessible status row when an image is attached:- it states whether the selected model can receive visual input.+The composer draft stays textual, with each file reference keeping kind, name,+MIME type, and source path as structured metadata, and vision capability is+resolved from the exact pi-ai model record: only `model.input.includes("image")`+enables image transport, while unknown and custom ids stay non-vision. Electron+main remains the attachment boundary, validating each source path against the+session scratch root, the session-bound project root, or the content-addressed+attachment root, storing images as `attachments/<sha256>` and persisting only+the reference and metadata in `UiMessage`. For a vision model within the 10 MB+per-image inline limit, the image crosses the sidecar as transient base64 and+becomes a pi-ai image block that is never persisted; otherwise the prompt+receives a safe `@path` fallback, with replayed content-store images copied into+the session scratch `replayed/` directory first. Restored vision history also+carries a fixed aggregate raw-image budget, newest attachments first, with+older images falling back to the path form and the current prompt row excluded+from hydration. The composer status row and the model picker expose the same+authoritative vision capability.## Consequences-- GPT/vision-capable models can inspect pasted images without requiring a- model-specific renderer implementation.-- Text-only and non-vision models retain the existing file-tool workflow.-- Image bytes are deduplicated and can survive retry, fork, and runtime- recreation without putting binary data in the transcript.-- Restored sessions preserve historical vision blocks regardless of age while- the images fit within one fixed aggregate budget; over-budget history has a- deterministic memory ceiling and a safe path fallback for older images.-- Attachment garbage collection remains a later storage task; references are- content-addressed so it can be added without changing the message contract.--## Rejected alternatives--- **Always send `@path` text:** preserves non-vision behavior but cannot satisfy- vision models.-- **Trust renderer/provider discovery flags:** can advertise a capability that- the runtime adapter cannot serialize and would make unknown models unsafe to- classify.-- **Persist base64 in messages:** makes reloads and SQLite/JSONL growth- unbounded and crosses the persistence boundary unnecessarily.+- Vision-capable models inspect pasted images with no model-specific renderer+ path, while text-only models keep the file-tool workflow.+- Image bytes are deduplicated and survive retry, fork, and runtime recreation+ without living in the transcript.+- Reference-only persistence leaves attachment garbage collection for a later+ storage task without changing the message contract.++## Alternatives++- Always send `@path` text: rejected, it cannot satisfy vision models.+- Persist base64 in messages: rejected, it makes reloads and SQLite growth+ unbounded across the persistence boundary.diff --git a/docs/adr/0102-publisher-owned-plugin-source-and-git-hosted-artifacts.md b/docs/adr/0102-publisher-owned-plugin-source-and-git-hosted-artifacts.mdindex dd543f13a..1f7117f89 100644--- a/docs/adr/0102-publisher-owned-plugin-source-and-git-hosted-artifacts.md+++ b/docs/adr/0102-publisher-owned-plugin-source-and-git-hosted-artifacts.md@@ -1,106 +1,91 @@# ADR 0102: Publisher-owned plugin source with a Git-hosted artifact store-> Amended 2026-08-19: artifacts are committed to the existing distribution-> repository rather than published as releases of the center repository. The-> ownership model and every other decision below are unchanged.--- Status: Accepted for implementation+- Status: Accepted for implementation (supersedes ADR 0006, amends ADR 0005 and+ ADR 0007; amended 2026-08-19 so artifacts are committed to the existing+ distribution repository instead of published as releases of the center+ repository, with the ownership model unchanged)- Date: 2026-08-18-- Deciders: PI-Desktop plugin and distribution maintainers-- Supersedes: ADR 0006 (marketplace postponed)-- Amends: ADR 0007 (plugin package format), ADR 0005 (user-installable plugins)+- Related: ADR 0005, ADR 0006, ADR 0007, ADR 0008## Context-The shipped marketplace stores everything in one repository.+The shipped marketplace stores everything in one repository:`vastsa/pi-desktop-plugins` holds plugin source under `plugins/<id>/`, built-packages under `packages/*.piplug`, and the `catalog.json` the client reads.--- Plugin source has no owner outside the marketplace repository.-- The marketplace repository grows binary packages forever and its Git history- becomes the artifact store by accident.-- Nothing binds a published package to the source that produced it.-- `verified` is a hand-edited catalog field.+packages under `packages/*.piplug`, and the `catalog.json` the client reads, so+publishing means a maintainer commits somebody else's source and regenerates the+catalog with a local script. That model does not survive third-party publishers:+plugin source has no owner outside the marketplace repository, the repository+grows binary packages forever, nothing binds a published package to the source+that produced it, `verified` is a hand-edited catalog field, and `download_url`+follows redirects to any host.## Decision### 1. The publisher's repository is the source of truthA publisher submits a repository coordinate — canonical HTTPS repository URL,-path, and a ref that resolves to a 40-hex commit. PI-Desktop never copies plugin-source into a project-owned repository.+path, and a ref that resolves to a 40-hex commit — and PI-Desktop never copies+plugin source into a project-owned repository, with `pluginId`, `publisherId`, the+linked repository, and the packaged `manifest.json` identity agreeing and each+published version pinned to exactly one `(repository, commit, path)` tuple.### 2. Management and distribution are separate repositories-`vastsa/pi-plugin-center` is the management plane: submissions, ownership-verification, isolated builds, review, the policy gate, and the registry that-records what has been published.--`vastsa/pi-desktop-plugins` stays the distribution repository. It keeps serving-`catalog.json` from its root and packages from `packages/`, and the CNB copy-keeps mirroring it.+`vastsa/pi-plugin-center` is the management plane — submissions, ownership+verification, isolated builds, review, the policy gate, and the registry of what+has been published — while `vastsa/pi-desktop-plugins` stays the distribution+repository serving `catalog.json` from its root and packages from `packages/`,+mirrored on CNB, with no S3, R2, or separately operated CDN.-- The publisher builds and attaches `<id>-<version>.piplug` to a release in- their own repository, or the center's isolated runner builds it from the- pinned commit.-- The center verifies the bytes, then commits the package to- `pi-desktop-plugins/packages/` together with a regenerated `catalog.json`, in- one commit.-- Package URLs stay relative, so they resolve against whichever host served the- catalog.+The publisher attaches `<id>-<version>.piplug` to a release in their own+repository or the center's isolated runner builds it from the pinned commit, and+the center verifies the bytes and commits the package with a regenerated+`catalog.json` in one commit; package URLs stay relative, so switching between+GitHub and the CNB mirror cannot send a download to the other provider or change+the checksum being verified.### 3. Catalog schema v2 is the client contract-`catalog.json` gains `schemaVersion: 2` and carries, per version: the source-repository, ref, commit and path; the builder identity; the review decision,-risk tier and policy version; `yanked` state; and an optional detached-signature. The client keeps reading v1 catalogs unchanged so the existing-marketplace repository and any custom source keep working during migration.+`catalog.json` gains `schemaVersion: 2` and carries, per version, the source+repository, ref, commit and path, the builder identity, the review decision, risk+tier and policy version, `yanked` state, and an optional detached signature, while+the client keeps reading v1 catalogs unchanged.### 4. The host restricts where a package may come fromBecause package URLs are now publisher-influenced, host-core enforces a download-host allowlist for marketplace packages: the GitHub release and raw asset hosts,-and the CNB host. Redirects are restricted to HTTPS and the final effective URL-is re-checked against the allowlist.+host allowlist for marketplace packages — the GitHub release and raw asset hosts+and the CNB host — restricts redirects to HTTPS, re-checks the final effective+URL, and lets a custom or enterprise catalog download only from the host that+served its own catalog unless the user configured additional hosts.### 5. Trust and review verdicts are center-issued, never publisher-asserted-`trust`, `review.decision`, `review.risk`, and `policyVersion` are written by-the center's policy evaluator. Publisher-submitted metadata cannot set them.+`trust`, `review.decision`, `review.risk`, and `policyVersion` are written by the+center's policy evaluator, so publisher-submitted metadata cannot set them, the+client renders `community` for anything it cannot attribute to the center, and it+never renders an unverifiable claim as `verified`.### 6. A yanked version is not installable`yanked: true` removes a version from install and update selection, keeps it-visible in version history with its reason, and marks an installed copy as-needing attention.+visible in version history with its reason, and marks an installed copy as needing+attention.## Consequences-- Third-party publishers can ship plugins without write access to any- PI-Desktop-owned repository, and can version on their own schedule.-- The default catalog URL is unchanged, so no client release and no user action- is needed to reach plugins published through the center.-- The client needs no code change for this decision: relative package URLs- already resolve against the catalog that carried them, and the download host- allowlist already covers both distribution hosts.-- Every installed marketplace plugin can be traced to a repository and commit,- and the desktop can show that provenance before install.-- Losing object storage costs WORM semantics and versioned-bucket retention.--## Rejected alternatives--- **Keep source in the marketplace repository.** Simple, already working, and- cannot support a publisher who is not a maintainer.-- **Index only; download from publisher repositories.** Removes the center from- the download path entirely, but a publisher can delete or replace a release- asset out from under a published version, and the client would need an- open-ended host allowlist.-- **Publish artifacts as releases of the distribution repository.** Keeps Git- history free of binaries and allows pruning old versions, at the cost of a- catalog that must declare an artifact base, and a CNB mirror that has to- replicate release assets separately instead of riding along with the Git- mirror that already exists.-- **Center builds every plugin from source with no publisher artifact.**- Strongest reproducibility, and makes the center responsible for every plugin's- toolchain and dependency supply chain from day one.+- Third-party publishers ship on their own schedule without write access to any+ PI-Desktop-owned repository, and every installed marketplace plugin traces to a+ repository and commit the desktop can show before install.+- The default catalog URL is unchanged, so no client release, user action, or code+ change is needed beyond tolerating two catalog schemas side by side.+- Losing object storage costs WORM semantics: the Git record is tamper-evident+ rather than tamper-proof, and committed binaries make every clone pay for every+ version ever published. Publisher signing keys stay out of scope (ADR 0008).++## Alternatives++- Keep source in the marketplace repository: cannot support a publisher who is not+ a maintainer.+- Index only and download from publisher repositories: a publisher can delete or+ replace a release asset, and the client would need an open-ended host allowlist.diff --git a/docs/adr/0103-compact-context-usage-summary.md b/docs/adr/0103-compact-context-usage-summary.mdindex 6ce6792d0..2ea8ff445 100644--- a/docs/adr/0103-compact-context-usage-summary.md+++ b/docs/adr/0103-compact-context-usage-summary.md@@ -2,49 +2,39 @@- Status: Accepted (amended by D347 / ADR 0184 and D355 / ADR 0193)- Date: 2026-08-18-- Deciders: PI-Desktop renderer and UX maintainers- Amends: D103, D184, ADR 0047## Context-The context usage inspector exposed useful token data, but its default panel-became a dense diagnostic report: stacked KPI cards, multiple source badges,-provider rows, explanatory estimate copy, and one visual row for every tool.-That made a quick capacity check compete with the conversation.+The context usage inspector held useful token data, but its default panel became+a dense diagnostic report of stacked KPI cards, source badges, provider rows,+explanatory copy, and one row per tool, so a quick capacity check competed with+the conversation.## Decision-1. Keep the existing click/keyboard trigger, remaining-capacity state,- viewport-aware body portal, outside-click dismissal, and Escape behavior.-2. Keep the panel's core summary: remaining tokens and percentage, used/window- counts, turn total, completed-turn generation speed, exact provider usage- values, aggregate tool types/calls/tokens, and the newest compaction summary- when present.-3. Render the turn and speed values as unboxed inline stats.-4. Remove per-tool rows, share bars, the provider/tool source badges, the- explanatory estimate paragraph, and the used-capacity meter from the default- panel.-5. Keep the trigger and panel accessible: localized labels, dialog semantics,- keyboard activation, focus return on Escape/outside dismissal, and collision-- aware placement remain unchanged.+Keep the existing trigger, dismissal behavior, and accessible dialog semantics,+and keep the core summary: remaining tokens and percentage, used and window+counts, turn total, completed-turn generation speed, exact provider usage, and+aggregate tool types, calls, and tokens. D355 scopes occupancy, turn total, and+provider values to the last model request, while speed and tools stay the visual+turn. Turn and speed render as unboxed inline stats, provider and tool usage as+two compact summary rows, and the `~` marker keeps signalling an estimated tool+total. Per-tool rows, share bars, source badges, the estimate paragraph, and the+used-capacity meter leave the default panel even though aggregation and+persistence are unchanged: this is renderer-only presentation work.## Consequences-- A routine context check fits in a short, scannable panel instead of a tall- diagnostic list.-- Exact provider data and aggregate tool cost remain visible, while detailed- per-tool attribution is no longer part of the default surface.-- No host protocol, storage schema, runtime accounting, or model metadata- contract changes.-- The E2E and component specifications must validate the compact summary rather- than the removed diagnostic rows.--## Rejected alternatives--- **Keep all rows and only reduce font size:** preserves the density problem and- makes the panel harder to scan.-- **Remove tool usage entirely:** loses the useful signal that tools contributed- to a large turn; the aggregate row keeps that signal at low visual cost.-- **Move every detail behind a second disclosure immediately:** adds another- interaction to a status check and is deferred until users demonstrate a need- for drill-down attribution.+- A routine context check fits a short, scannable panel.+- Exact provider data and aggregate tool cost stay visible; per-tool attribution+ is no longer a default surface.+- No host protocol, storage schema, accounting, or model metadata contract+ changes, and E2E and component specifications follow the compact summary.++## Alternatives++- Keep every row and shrink the type: rejected because the density problem and+ poor scannability remain.+- Remove tool usage entirely: rejected because the aggregate row keeps that signal+ cheaply.diff --git a/docs/adr/0104-plugin-contributed-work-panel-views.md b/docs/adr/0104-plugin-contributed-work-panel-views.mdindex 70fcdb380..f958a1de4 100644--- a/docs/adr/0104-plugin-contributed-work-panel-views.md+++ b/docs/adr/0104-plugin-contributed-work-panel-views.md@@ -2,91 +2,54 @@- Status: Accepted- Date: 2026-08-19-- Deciders: PI-Desktop core-- Related: [ADR 0019](0019-work-panel-subsystems.md) ·- [ADR 0033](0033-internal-dock-work-panel.md) ·- [ADR 0122](0122-reserve-native-width-while-work-panel-visible.md) ·- [ADR 0081](0081-host-owned-plugin-panel-chrome.md) ·- [ADR 0092](0092-plugin-owned-panel-surface.md) ·- [ADR 0105](0105-files-as-a-bundled-plugin.md) ·- [ADR 0108](0108-remove-built-in-interactive-terminal.md) ·- [07-plugins](../spec/07-plugins/README.md) ·- [04-ux/08-component-spec §5](../spec/04-ux/08-component-spec.md)+- Related: [ADR 0019](0019-work-panel-subsystems.md) · [ADR 0028](0028-session-scoped-work-panel-contexts.md) · [ADR 0033](0033-internal-dock-work-panel.md) · [ADR 0081](0081-host-owned-plugin-panel-chrome.md) · [ADR 0092](0092-plugin-owned-panel-surface.md) · [ADR 0105](0105-files-as-a-bundled-plugin.md) · [ADR 0108](0108-remove-built-in-interactive-terminal.md) · [ADR 0122](0122-reserve-native-width-while-work-panel-visible.md) · [04-ux/08-component-spec §5](../spec/04-ux/08-component-spec.md)## Context-Before ADR 0108 removed the interactive terminal, the right work panel exposed-four capabilities — Review, Terminal, Browser, Files (ADR 0019) — as a-hard-coded list in the renderer: a `HEADER_TOOLS` constant, a closed-`WorkPanelTabKind` union, and a four-way branch on tab kind in the panel body.-Adding any new surface meant changing host code.+The right work panel exposed Review, Terminal, Browser, and Files as a hard-coded+renderer list, so adding a surface meant changing host code. Plugins have a mature+but strictly bounded UI channel that only produces a separate `ui.panel` window+(ADR 0092), so a surface belonging next to the conversation either becomes a+detached window competing for screen space or does not exist.## Decision-1. **A plugin declares work panel surfaces with `contributes.views`.** Each- entry carries an `id`, a `title` (plain or `{ en, "zh-CN" }`), an optional- `icon` token, an HTML `entry` relative to the plugin, and an optional- `order`.--2. **A view is rendered as a `WebContentsView` owned by the main process**,- attached to the main window and positioned from a renderer-measured rect —- the mechanism the preview browser has used since ADR 0019/0033.--3. **The renderer is the visibility authority.** A `WebContentsView` composites- above renderer content, so the panel hides every native surface — the browser- and any plugin view alike — whenever it is not the active tab, the panel is- animating, the divider is being dragged, or a blocking overlay is open.--4. **An embedded view drops the window-control chrome.** A docked view has no- window to minimize, maximize, or drag, so the preload skips the three-button- capsule and the 46px safe area that ADR 0092 defines, and publishes- `--pi-plugin-titlebar-height: 0px` instead of `46px`.--5. **Icons are tokens from a host-owned closed list**, never plugin-supplied- markup.--6. **The view list is filtered by activation scope.** This differs deliberately- from `pluginThemes`, which is *not* scope-filtered because the selected theme- is one global app setting.--7. **Views are cached, bounded, and tied to the plugin's lifetime.** A view- survives tab switches so a plugin keeps its scroll position and in-page- state, up to four live views, evicting the least recently shown and never the- one on screen.+1. A plugin declares work panel surfaces with `contributes.views`, each entry+ carrying `id`, `title`, an optional `icon` token, an HTML `entry`, and an+ optional `order`, gated by a new `ui.view` permission parallel to `ui.panel`.+2. A view renders as a main-process-owned `WebContentsView` positioned from a+ renderer-measured rect, reusing the plugin's sandboxed preload, its persisted+ session partition, and its `net.domains` egress filter through shared helpers so+ docked and detached placements cannot drift.+3. The renderer is the visibility authority and hides every native surface+ whenever the view is not the active tab, the panel animates, the divider drags,+ or a blocking overlay is open.+4. A docked view drops the window-control chrome and publishes+ `--pi-plugin-titlebar-height: 0px` instead of the panel value, while+ `window.pluginBridge` stays identical so one entry file serves both placements.+5. Icons are tokens from a host-owned closed list, and an unknown token degrades to+ a lettered tile rather than accepting plugin markup inside host chrome.+6. The view list is filtered by activation scope, unlike the global+ `pluginThemes`, and permission, scope, and entry existence are re-checked when a+ view opens.+7. Views are cached and tied to the plugin's lifetime: a few live views survive tab+ switches with least-recently-shown eviction, while disable, uninstall, reload,+ or crash destroys them and the renderer re-opens from the lifecycle event.## Consequences-- The work panel becomes an extension point rather than a fixed set.-- A plugin's storage is one thing regardless of placement, because a view and- that plugin's detached window share a partition.-- `windowForSender` must scan windows directly instead of resolving a plugin id- first: a docked view now also resolves to a plugin id, and routing window- controls through that would let a docked view close the same plugin's separate- window.-- The z-order caveat ADR 0019 accepted for the browser now applies to every- plugin view.-- Four live `WebContentsView`s is four extra renderer processes at worst.--## Alternatives considered--### An `<iframe>` inside the host renderer--Rejected. It would z-order correctly and need no bounds syncing, but Electron-cannot give an iframe its own session partition, so the plugin page would share-the host renderer's process and storage.--### Plugin-supplied React components rendered by the host--Rejected outright. It would put third-party code in the host renderer with-access to the app's own state and IPC bridge, discarding the entire plugin trust-boundary for a rendering convenience.--### Reuse `ui.panel` and let the host decide where to show it--Rejected. A panel is one surface per plugin with a window's dimensions and-title; a view is one of several, sized by the panel column, and needs its own-menu label, icon, and order.--### Both, selected by a `isolation: "process" | "inline"` manifest field--Rejected for this change.+- The work panel becomes an extension point that third-party plugins reach by the+ same route first-party code will use.+- A view shares its plugin's session partition, so it inherits any state that+ plugin's detached window already had.+- Window-control routing must scan windows directly, so a docked view cannot close+ the same plugin's separate window.+- The z-order caveat once accepted for the browser now applies to every plugin+ view, and each live view costs an extra renderer process.++## Alternatives++- An `<iframe>` inside the host renderer: rejected, Electron cannot give it its own+ session partition, which is a weaker boundary than plugin windows have.+- Plugin-supplied React components rendered by the host: rejected, it would put+ third-party code inside the host renderer with the app's IPC bridge.diff --git a/docs/adr/0105-files-as-a-bundled-plugin.md b/docs/adr/0105-files-as-a-bundled-plugin.mdindex e6884363b..52d2e3be0 100644--- a/docs/adr/0105-files-as-a-bundled-plugin.md+++ b/docs/adr/0105-files-as-a-bundled-plugin.md@@ -2,29 +2,29 @@- Status: Superseded by [ADR 0241](0241-vendored-updatable-file-view-plugin.md)- Date: 2026-08-19-- Deciders: PI-Desktop core- Related: [ADR 0019](0019-work-panel-subsystems.md) ·[ADR 0104](0104-plugin-contributed-work-panel-views.md) ·[ADR 0108](0108-remove-built-in-interactive-terminal.md) ·- [07-plugins/13-plugin-permissions-matrix](../spec/07-plugins/13-plugin-permissions-matrix.md)--> Superseded by ADR 0241. Files is no longer a bundled first-party plugin: the-> work panel's file view is now a vendored, updatable third-party plugin-> (`pi.file-manager`). The reasoning below still holds and is what the-> replacement inherits — the view is an ordinary plugin on the public-> `contributes.views` channel, and Review stays with the transcript. The-> terminal clause was already superseded by ADR 0108.+ [ADR 0170](0170-work-panel-browser-as-bundled-plugin.md) · D451## Context-The work panel has a public extension point for plugin-contributed views.+The work panel exposes a public extension point for contributed views, so the+bundled Files browser had to exercise that public path instead of staying a+host-only view. Review stays transcript-owned by ADR 0043 and therefore has a+different boundary.## Decision-1. `pi.files` is a first-party plugin shipped from- `apps/desktop/resources/plugins/` and contributes its view through- `contributes.views` just like a third-party plugin.+`pi.files` becomes a bundled first-party plugin contributing its view through+`contributes.views`, enabled by default, uninstallable, disableable by the user,+and reading the filesystem only through public permission-gated APIs. Only the+Files tool migrates; transcript-owned `file:<path>` resources stay, and Review+opens only on explicit user action (D451). Browser chrome ships as bundled plugin+`pi.browser` over the same public API.## Consequences-Superseded (Superseded by [ADR 0241](0241-vendored-updatable-file-view-plugin.md)). The full record is in git history.+Superseded by ADR 0241, which replaced the bundled plugin with the vendored,+updatable file view plugin `pi.file-manager`; the reasoning above is what the+replacement inherits. The terminal clause was already superseded by ADR 0108.diff --git a/docs/adr/0106-core-five-builtin-commands.md b/docs/adr/0106-core-five-builtin-commands.mdindex 6c82b5bef..5bf9153d9 100644--- a/docs/adr/0106-core-five-builtin-commands.md+++ b/docs/adr/0106-core-five-builtin-commands.md@@ -2,49 +2,39 @@- Status: Accepted- Date: 2026-08-19-- Deciders: PI-Desktop core-- Related: D250, ADR 0024, ADR 0034, `04-ux/04-builtin-commands.md`+- Related: D250, ADR 0024, ADR 0034## ContextThe first-party command registry had grown to fifteen entries while the composer-`/` menu and global-search Commands section exposed several actions that already-had dedicated UI surfaces. It also retained dispatch-only aliases and-specification-only IDs that were no longer registered.+`/` menu and the global-search Commands section exposed actions that already had+dedicated UI surfaces, and it kept dispatch-only aliases and specification-only+IDs that were no longer registered.## Decision-1. Freeze the first-party registry at exactly these five IDs:- `builtin.session.new`, `builtin.agent.compact`, `builtin.mode.agent`,- `builtin.mode.plan`, and `builtin.mode.goal`.-2. Keep the matching aliases `/new`, `/compact`, `/agent-mode`, `/plan-mode`,- and `/goal-mode`.+1. Freeze the first-party registry at exactly `builtin.session.new`,+ `builtin.agent.compact`, `builtin.mode.agent`, `builtin.mode.plan`, and+ `builtin.mode.goal`.+2. Keep the matching aliases `/new`, `/compact`, `/agent-mode`, `/plan-mode`, and+ `/goal-mode`; mode aliases keep the one-shot form, switching mode first and+ sending the remaining text as the visible user turn.3. Remove the session deletion, abort, project, settings, plugin, log,session-rename, command-palette, reload-window, and DevTools entries from the- builtin registry and renderer dispatch.-4. Keep plugin command contributions and dedicated UI actions independent of- this registry.+ builtin registry and renderer dispatch, along with the legacy `newChat`,+ `openProject`, and `openSettings` dispatch aliases.+4. Keep plugin command contributions and dedicated UI actions independent of this+ registry; an old builtin ID is not a compatibility alias.## Consequences-- Global search and the composer `/` menu have a smaller, stable first-party- command surface.-- New-task, compaction, and mode switching remain keyboard- and slash-first- workflows.-- Abort, delete, project, settings, plugin, log, reload, and DevTools actions- remain available only through their dedicated controls or surfaces where those- workflows still exist; they are not discoverable as builtin commands.+- The `/` menu and global search keep a smaller, stable first-party surface; the+ removed actions remain on their dedicated controls.- Unknown former aliases fall through as ordinary slash text unless anothercommand source contributes the same name.-## Alternatives considered+## Alternatives-### Keep all app-navigation commands in the registry--Rejected: project, settings, plugin, and diagnostic actions duplicate existing-surfaces and compete with task-oriented commands in global search.--### Preserve old IDs as hidden compatibility aliases--Rejected: hidden aliases still expand the command contract and keep dead entries-executable from stale UI or copied invocations.+- Keep app-navigation commands in the registry: they duplicate existing surfaces.+- Preserve old IDs as hidden compatibility aliases: hidden aliases still expand+ the command contract.diff --git a/docs/adr/0107-atomic-viewing-context-for-task-notifications.md b/docs/adr/0107-atomic-viewing-context-for-task-notifications.mdindex 2e7dfab84..04db88f04 100644--- a/docs/adr/0107-atomic-viewing-context-for-task-notifications.md+++ b/docs/adr/0107-atomic-viewing-context-for-task-notifications.md@@ -2,43 +2,33 @@- Status: Accepted- Date: 2026-08-20-- Deciders: PI-Desktop core-- Related: D117, D135, E2E-064, E2E-065, `03-runtime/01-ipc-protocol.md`+- Related: D117, D135, E2E-064, E2E-065## Context-Task completion has two renderer-visible effects: the transcript receives an-agent lifecycle event, and Electron may receive a durable notification from-`session.endTurn`. The renderer previously treated every `agent_end` or terminal-`error` event as an unread sidebar outcome, even when the focused current chat-was already showing that result.+A finished task has two renderer-visible effects: the transcript receives an agent+lifecycle event, and Electron may receive a durable notification from+`session.endTurn`. The renderer treated every `agent_end` or terminal `error` as a+new unread sidebar outcome even when the focused chat already showed the result,+and the active viewing hint arrived through an asynchronous React effect that a+fast turn could outrun.## Decision-1. Treat unread `task.completed` and `task.failed` notification records as the- sole source of terminal sidebar marks.-2. Carry an optional `viewingSessionId` snapshot on renderer-originated- `agent/prompt` requests.-3. Keep the existing viewing-context IPC and Main-owned visibility/focus gate.+Unread `task.completed` and `task.failed` notification records are the sole source+of terminal sidebar marks; lifecycle events keep driving run state, transcript+updates, and the in-chat result card but never create an unread outcome alone.+Renderer-originated `agent/prompt` requests carry an optional `viewingSessionId`+snapshot that Electron validates as an exact match and installs before+asynchronous turn setup, and a missing, null, or mismatched snapshot clears the+hint and fails safe to notifying. The existing viewing-context IPC and Main-owned+visibility and focus gate stay: suppression applies only to the exact finishing+session in a visible, focused window.## Consequences-- A focused user who remains in a conversation sees the transcript completion- without a duplicate sidebar mark, inbox row, or native notification.-- Background and unfocused sessions retain durable and native recovery notices.-- The prompt request gains one additive optional field; older callers that omit- it fail safe rather than suppressing a result using stale renderer state.-- Sidebar outcome state becomes consistent with the notification inbox and its- read/acknowledgement lifecycle.--## Alternatives considered--### Hide the completed icon only for the selected row--Rejected: this would leave stale unread state in the store and would not prevent-durable or native notifications.--### Rely only on the React viewing-context effect--Rejected: the effect is asynchronous and can lose a race with a fast completion-or renderer navigation.+- A focused user who stays in the conversation sees the completion without a+ duplicate sidebar mark, inbox row, or native notification.+- Background, hidden, and unfocused sessions keep durable and native notices, and+ older callers that omit the field fail safe.+- Sidebar outcome state now matches the inbox and its read lifecycle.diff --git a/docs/adr/0108-remove-built-in-interactive-terminal.md b/docs/adr/0108-remove-built-in-interactive-terminal.mdindex 20b380060..f560f7b33 100644--- a/docs/adr/0108-remove-built-in-interactive-terminal.md+++ b/docs/adr/0108-remove-built-in-interactive-terminal.md@@ -14,45 +14,41 @@## Context-The work panel previously included an interactive shell backed by a PTY in-Electron Main and a terminal renderer in the work-panel UI. That surface was-separate from the agent's non-interactive `Bash` tool, but it added a native-module, renderer dependencies, terminal-specific IPC, packaging rules, and a-second shell lifecycle to the desktop application.+The work panel carried an interactive shell backed by a PTY in Electron Main and a+terminal renderer. It was separate from the agent's non-interactive `Bash` tool and+added a native module, renderer dependencies, terminal-specific IPC, packaging rules,+and a second shell lifecycle, while the product does not need to own an interactive+shell to keep Agent Bash useful.## Decision-1. Remove the work-panel interactive terminal.-2. Keep Agent Bash unchanged.-3. Delete the terminal-only Electron Main manager, renderer component and- styles, IPC invoke/event channels, shared terminal payload types, and- terminal-specific tests.-4. Do not replace the removed surface with a plugin PTY API.-5. Do not increment the frozen desktop protocol version.+1. Remove the work-panel interactive terminal. The panel keeps plugin-contributed+ views including the bundled Files and Browser views (ADR 0170), artifact file+ tabs, and the Review tab the user opens themselves (D451).+2. Keep Agent Bash unchanged: a permission-aware, non-interactive tool whose+ command, output, status, copy behavior, and `IconTerminal` presentation stay in+ the transcript, and generic lifecycle values such as `"terminal"` in plan refresh+ state remain valid.+3. Delete the terminal-only Main manager, renderer components and styles, IPC+ channels, shared payload types, and terminal tests, along with the PTY/xterm+ dependencies and their build configuration.+4. Do not replace it with a plugin PTY API — interactive shell access is delegated to+ an external terminal — and do not increment the frozen desktop protocol version,+ since the removed channels were desktop IPC additions.## Consequences-- The work panel has no interactive shell tab or terminal launcher, and its- empty state lists the Review row, Browser, and in-scope plugin views.-- Desktop packaging no longer carries the PTY native module or terminal renderer- dependencies, reducing native build and release surface.-- Interactive shell workflows require an external terminal.-- Historical D099/D249 records remain useful as history, but their terminal- implementation and retention clauses are superseded by this decision.+- The work panel has no shell tab or launcher, packaging drops the PTY native module+ and terminal renderer dependencies, and interactive shell work moves to an external+ terminal while Agent Bash remains the in-app bounded path.+- Historical D099 and D249 records remain history, but their terminal clauses are+ superseded here.-## Alternatives considered+## Alternatives-### Keep the PTY in the host--Rejected: it preserves a second shell lifecycle and native dependency for a-surface the product no longer needs to own.--### Move the PTY into a plugin--Rejected: a plugin PTY permission would grant arbitrary execution as the user,-and a bundled-only channel would create a private trust-boundary exception.--### Turn Agent Bash into an interactive terminal--Rejected: Bash is intentionally bounded, permission-aware, and transcript--owned.+- Keep the PTY in the host: a second shell lifecycle and native dependency for a+ surface the product no longer owns.+- Move the PTY into a plugin: a plugin PTY permission would grant arbitrary execution+ as the user.+- Turn Agent Bash into an interactive terminal: that changes the agent protocol and+ security model instead of removing a work-panel surface.diff --git a/docs/adr/0109-open-files-with-the-os-associated-application.md b/docs/adr/0109-open-files-with-the-os-associated-application.mdindex 53872dd95..fa1d80efb 100644--- a/docs/adr/0109-open-files-with-the-os-associated-application.md+++ b/docs/adr/0109-open-files-with-the-os-associated-application.md@@ -2,53 +2,42 @@- Status: Accepted- Date: 2026-08-20-- Deciders: PI-Desktop maintainers-- Related: [ADR 0105](0105-files-as-a-bundled-plugin.md) ·- [ADR 0088](0088-declared-file-scope-for-plugins.md) ·- [07-plugins/03-plugin-api](../spec/07-plugins/03-plugin-api.md) · E2E-153+- Related: [ADR 0105](0105-files-as-a-bundled-plugin.md) · [ADR 0088](0088-declared-file-scope-for-plugins.md) · E2E-153## Context-The bundled `pi.files` view can inspect text in its isolated viewer, but image,-document, archive, and other files are better handled by the operating system's-associated application. The existing `shell.openExternal` API intentionally-accepts only web and mail URLs, so converting a workspace path into a `file:`-URL would either weaken that boundary or give the plugin an unscoped file-opener.+The bundled `pi.files` view can inspect text in its isolated viewer, but images,+documents, and archives are better handled by the operating system's associated+application. `shell.openExternal` accepts only web and mail URLs, so converting+a workspace path into a `file:` URL would either weaken that boundary or hand+the plugin an unscoped file opener.## Decision-1. Add `pi.fs.openDefault(pathFromRoot)` and the matching panel bridge channel- `fs.openDefault`.-2. The API is covered by the existing `fs.read` permission.-3. Electron Main calls `shell.openPath` after the gate, causing the operating- system to choose the file association.-4. The bundled Files view exposes the action only from its selected-file viewer,- including for binary and image files.-5. This is an additive plugin API change; the desktop IPC and host protocol- versions do not change.+Add `pi.fs.openDefault(pathFromRoot)` and the matching panel bridge channel+`fs.openDefault`, covered by the existing `fs.read` permission. The host+resolves the root-relative path through the complete read gate (declared root,+real-path containment, protected paths, deny list, and declared scope or user+consent) and accepts existing regular files only. Electron Main then calls+`shell.openPath`, so the operating system chooses the association; the plugin+never receives an absolute path and cannot pick an executable or command line.+The bundled Files view offers the action from its selected-file viewer, and both+success and failure are audited by plugin id and root-relative path. The change+is additive, so desktop IPC and host protocol versions and the+`shell.openExternal` URL restrictions are unchanged.## Consequences-- Files can hand off content that the in-app text viewer cannot render.-- The default application may copy, transform, or sync the file according to its- own behavior; the user explicitly initiates the handoff from the viewer.-- Plugins with `fs.read` still cannot open credentials, repository internals,- protected app data, arbitrary absolute paths, or directories through this API.-- A failed OS handoff is reported to the plugin as `OPEN_FAILED` and is visible- through the Files view's error toast.+- Files can hand off content the in-app text viewer cannot render.+- The default application may copy, transform, or sync the file, at the user's+ explicit request.+- Plugins with `fs.read` still cannot open credentials, protected app data,+ arbitrary absolute paths, or directories, and a failed handoff returns+ `OPEN_FAILED`.-## Alternatives considered+## Alternatives-### Reuse `shell.openExternal` with a `file:` URL--Rejected: that API is for external links and would blur URL egress with local-file access.--### Add a private bundled-plugin IPC channel--Rejected: Files is intentionally a public plugin API consumer.--### Add a new permission separate from `fs.read`--Rejected for this action: the host does not expose an arbitrary opener.+- Reuse `shell.openExternal` with a `file:` URL: rejected, it blurs URL egress+ with local file access and weakens scope enforcement.+- A private bundled-plugin IPC channel: rejected, it recreates the exception+ ADR 0105 removed.diff --git a/docs/adr/0110-plugin-panel-chrome-spacing-contract.md b/docs/adr/0110-plugin-panel-chrome-spacing-contract.mdindex e0f4b14e1..6a9b360ed 100644--- a/docs/adr/0110-plugin-panel-chrome-spacing-contract.md+++ b/docs/adr/0110-plugin-panel-chrome-spacing-contract.md@@ -2,33 +2,29 @@- Status: Accepted- Date: 2026-08-20-- Deciders: PI-Desktop core- Related: [ADR 0092](0092-plugin-owned-panel-surface.md) ·[ADR 0093](0093-plugin-panel-strict-drag-band.md) ·- [ADR 0104](0104-plugin-contributed-work-panel-views.md) ·- [07-plugins](../spec/07-plugins/03-plugin-api.md)+ [ADR 0104](0104-plugin-contributed-work-panel-views.md)## Context-The host-owned plugin capsule reserves a strict 46px drag band. Older plugin-pages used ordinary body padding and relied on the preload to add that band.+The host-owned plugin capsule reserves a strict drag band, and older plugin pages+relied on preload-added padding while newer pages also read the host titlebar+variable. Host padding then duplicated the safe area and left blank space above+the plugin toolbar.## Decision-1. A current plugin page declares `<meta name="pi-plugin-chrome" content="v2">`.-2. The preload publishes `--pi-plugin-titlebar-height` before page layout:- `46px` for a detached panel and `0px` for a docked view.-3. v2 pages own their normal-flow spacing and must use that variable.-4. The host capsule remains a closed, page-adaptive three-control capsule in the- top-right of the 46px band; plugin pages own their title, toolbar, and- surfaces.-5. First-party examples, bundled plugins, and generated panel templates use the- neutral PI-Desktop token ramp and the v2 marker.+A current plugin page declares `<meta name="pi-plugin-chrome" content="v2">`. The+preload publishes `--pi-plugin-titlebar-height` before layout with the detached+band height or `0px` when docked, and v2 pages own their flow spacing through+that variable while the host adds no extra top padding; pages without the marker+keep the legacy additive offset. The host capsule stays a closed, page-adaptive+three-control capsule in the band, and first-party pages and generated templates+use the v2 marker with the neutral token ramp.## Consequences-- Plugin pages no longer need to guess whether the host already inserted the- safe area, and detached/docked entries can share their layout.-- Existing third-party pages continue to render while authors migrate.-- The marker is a small public HTML contract rather than a manifest schema- change, so plugins can adopt it without a package format revision.+- Detached and docked pages share one deterministic spacing contract.+- Existing third-party pages render unchanged until authors adopt the marker.+- The marker is a small HTML contract, not a manifest schema change.diff --git a/docs/adr/0111-reveal-files-in-file-manager.md b/docs/adr/0111-reveal-files-in-file-manager.mdindex d779cd070..ddaacaf6c 100644--- a/docs/adr/0111-reveal-files-in-file-manager.md+++ b/docs/adr/0111-reveal-files-in-file-manager.md@@ -2,35 +2,28 @@- Status: Accepted- Date: 2026-08-22-- Deciders: PI-Desktop maintainers-- Related: [ADR 0105](0105-files-as-a-bundled-plugin.md) ·- [ADR 0109](0109-open-files-with-the-os-associated-application.md) ·- [07-plugins/03-plugin-api](../spec/07-plugins/03-plugin-api.md) · E2E-153+- Related: ADR 0105, ADR 0109, E2E-153## Context-The bundled `pi.files` viewer previously used its header action to open the-selected file with the operating system's associated application. That handoff-is not reliable for every file type or platform, and it does not match the-primary browsing intent of locating the file in the project.+The bundled `pi.files` viewer handed the selected file to the OS-associated+application, a handoff that fails for some file types and platforms and does not+match the intent of locating a file in the project.## Decision-1. Add `pi.fs.reveal(pathFromRoot)` and the matching panel bridge channel- `fs.reveal`.-2. Gate the operation with the existing `fs.read` permission and the complete- declared file-scope checks: root containment, symlink resolution, protected- paths, deny-list, and manifest scope or consent.-3. Electron Main calls `shell.showItemInFolder` after the gate.-4. The bundled Files viewer replaces its header action with **Show in folder**- and reports a localized toast if the reveal fails.-5. Successful and failed reveals are audited with the plugin id and- root-relative path.+Add `pi.fs.reveal(pathFromRoot)` with the panel bridge channel `fs.reveal`, gated by+the existing `fs.read` permission plus the declared file-scope checks: root+containment, symlink resolution, protected paths, deny-list, and manifest scope or+consent. Only existing regular files are accepted, Electron Main calls+`shell.showItemInFolder` after the gate, the viewer replaces its header action with+**Show in folder**, and `fs.openDefault` stays an additive public API for the+associated-application handoff. Reveals are audited with plugin id and+root-relative path; no desktop IPC or host-core protocol version changes.## Consequences-- A selected file can be located without depending on a file association.-- The action cannot reveal credentials, protected app data, files outside the- workspace or selected root, or files outside the plugin's declared read scope.-- Third-party plugins can use the same bounded operation as the bundled Files- plugin; no private bundled-plugin capability is introduced.+- A file can be located without depending on a file association.+- Credentials, protected app data, and files outside the workspace or the plugin's+ declared read scope cannot be revealed.+- Third-party plugins get the same bounded operation.diff --git a/docs/adr/0112-agent-capability-management-roots-and-settings-ia.md b/docs/adr/0112-agent-capability-management-roots-and-settings-ia.mdindex 2b68c25ac..04b5cc0d8 100644--- a/docs/adr/0112-agent-capability-management-roots-and-settings-ia.md+++ b/docs/adr/0112-agent-capability-management-roots-and-settings-ia.md@@ -2,81 +2,56 @@- Status: Accepted- Date: 2026-08-20-- Deciders: PI-Desktop core- Supersedes the capability-storage and capability-IA portions of ADR 0056,ADR 0058, and ADR 0063; updates D193, D194, and D202## Context-MCP servers, skills, and subagent definitions were previously described as-registries under the application data directory, and the Extensions page grew to-contain their management surfaces. That model made capability files hard to-carry between installations, mixed configuration with app-local activation-state, and made the Extensions page responsible for unrelated authoring flows.+MCP servers, skills, and subagent definitions were described as registries under+the application data directory and managed from the Extensions page, which made+capability files hard to carry between installations and mixed configuration+with app-local activation state.## Decision### 1. `.agents` is the only capability file root-The host scans and writes only these directories:--```text-~/.agents/skills global skills-<project>/.agents/skills project skills-~/.agents/servers global MCP configuration-<project>/.agents/servers project MCP configuration-~/.agents/subagents global subagent definitions-```--There is no project-level subagent directory. `.pi/agents`, `.pi/skills`, and-`.pi/mcp` are not capability sources; the unrelated `.pi/prompts` store is-unchanged.+The host scans and writes only `~/.agents/skills` and `<project>/.agents/skills`+for skills, `~/.agents/servers` and `<project>/.agents/servers` for MCP+configuration, and `~/.agents/subagents` for subagent definitions; there is no+project-level subagent directory, and `.pi/agents`, `.pi/skills`, and `.pi/mcp`+are not capability sources while the unrelated `.pi/prompts` store is unchanged.### 2. File ownership and activation state are separate-Capability documents never contain `enabled` or a project override. host-core-stores app-local state in:--```text-<data>/agent-capabilities/skills.json-<data>/agent-capabilities/mcp.json-<data>/agent-capabilities/subagents.json-```--Global capabilities default to enabled and may have a per-project override.-Project capabilities have state for their owning project.+Capability documents never contain `enabled` or a project override; host-core+keeps app-local state under `<data>/agent-capabilities/`, with globals enabled+by default, projects carrying their own state, and scanning pruning records for+files that no longer exist.### 3. Project precedence is resolved before filtering-For the active runtime, project records shadow global records by id or-case-insensitive display name. The project record wins even when its local state-is disabled; only after shadowing does the host filter disabled records.+Project records shadow global records by id or case-insensitive display name+even when locally disabled, because only after shadowing does the host filter+disabled records.### 4. Management lives under Settings > Agent-Skills, MCP, and Subagents are three independent Settings destinations, not-tabs. Skills and MCP use fixed-height global/project columns; their project-column has a recent-project picker.--Skills expose one single-file native import action per column and physically-copy the selected document into that column's `.agents/skills` directory. MCP-create and edit reuse `McpEditorSheet`; editing locks the id, validation is-shared with the host, and same-level id or label duplicates are rejected.+Skills, MCP, and Subagents are three independent Settings destinations rather+than tabs, and Extensions keeps only Installed and Marketplace.### 5. Protocol queries are explicitCapability list, read, remove, import, and enable calls carry `level` and, when-needed, `projectPath`. A project-level request without `projectPath` is invalid.+needed, `projectPath`, and a project-level request without `projectPath` is+invalid; runtime activation merges `mcp.active` and `skills.active` for the+selected project, while subagent activation is global-only.## Consequences-- Capability files are portable, inspectable, and safe to share without copying- application-local enablement decisions.-- A project can override or disable a global capability without changing the- global file.-- The Settings IA is larger, but Extensions is a focused plugin/marketplace- surface and every capability page can expose its own affordances.-- Existing plugin activation scopes remain unchanged; they are not reused for- the file-level capability pages.-- The host retains compatibility-shaped legacy scope RPC fields as no-op inputs- where needed, but new UI state is represented by level and local state.+- Capability files stay portable and a project can disable a global capability+ without editing the global file.+- Extensions stays a focused plugin surface and each capability page exposes+ its own affordances.+- Plugin activation scopes are unchanged, and legacy scope RPC fields survive+ only as no-op inputs.diff --git a/docs/adr/0113-immediate-empty-session-slot-and-deduplication.md b/docs/adr/0113-immediate-empty-session-slot-and-deduplication.mdindex d1c766881..3f330f864 100644--- a/docs/adr/0113-immediate-empty-session-slot-and-deduplication.md+++ b/docs/adr/0113-immediate-empty-session-slot-and-deduplication.md@@ -3,49 +3,46 @@- **Status:** Accepted- **Date:** 2026-08-21- **Supersedes:** ADR 0084 / D220-- **Related:** D088 · D093 · D305 · E2E-011b · E2E-011d · E2E-011e · E2E-011g+- **Related:** D088 · D093 · D305- **Amended by:** ADR 0154 (first-frame empty reveal; reuse without a blocking list refresh)## Context-ADR 0084 deferred session creation until the first prompt. That removed-abandoned rows, but it also made the New Task action invisible in the sidebar-and removed the scoped empty-session reuse behavior.+ADR 0084 deferred session creation until the first prompt, which removed abandoned+rows but made New Task invisible in the sidebar and dropped the scoped+empty-session reuse behavior. The product now needs a real, immediately visible+empty session with one empty slot per project or Temporary group. Titles cannot+define emptiness, but the host already stores the message count in+`sessions.last_seq`.## Decision-When New Task is invoked for a project or the path-less Temporary group:+New Task sorts the group's non-archived sessions by `updatedAt` descending. If the+latest is empty — `messageCount = 0` with no live renderer rows, running turn, or+submitted draft — the renderer selects it and reveals its transcript on the first+frame, treating a click on the active row as a no-op; otherwise it reveals the+empty home, creates a session through `session.create`, and inserts the returned+summary without blocking on `session.list` / `session.get` (ADR 0154). Requests+for one group are serialized, so rapid clicks observe the first completed slot+instead of racing `session.create` calls.-1. Sort that group's non-archived sessions by `updatedAt` descending.-2. If the most recent session is empty (`messageCount = 0` and the renderer has- no live rows, running turn, or submitted draft), select it and reveal its- empty transcript on the first frame.-3. Otherwise reveal the empty home on the first frame, create a real empty- session through `session.create`, and insert the returned summary into the- sidebar.--Renderer requests for the same group are serialized. This makes rapid repeated-clicks observe the first completed empty slot instead of racing multiple-`session.create` calls.+`SessionSummary.messageCount` is added to the shared IPC/session contract as an+additive field derived from `sessions.last_seq`, keeping protocol v9 and storage+schema v11 compatible. The startup home remains an unpersisted renderer draft;+only explicit New Task creates or reuses the durable slot.## Consequences-- New sessions are visible and selectable immediately, before the first user- message.-- Repeated New Task clicks in one group are idempotent while different project- groups remain independent.-- An older empty session can remain when a newer non-empty session is the- group's latest; the rule intentionally considers only that latest session.-- Empty sessions persist until the user deletes or archives them.+- New sessions are visible and selectable before the first message, and repeated+ clicks in one group are idempotent while groups stay independent.+- Empty sessions persist until deleted or archived, and an older empty session+ can remain when the newest session in the group is non-empty.- Protocol v9 gains one additive summary field; storage schema v11 and host- ownership remain unchanged.+ ownership are unchanged.## Alternatives considered-- Keep the unpersisted draft from ADR 0084: rejected because the action has no- immediate sidebar presence and cannot provide a durable ready slot.-- Continue using a default title as the empty predicate: rejected because a- manual rename changes presentation, not transcript state.-- Add a host-side special `session.createOrReuse` RPC: rejected because the- existing renderer navigation boundary can enforce the requested grouping rule- without expanding the host method catalog.+- Keep the unpersisted draft from ADR 0084: the action has no immediate sidebar+ presence and cannot provide a durable ready slot.+- Use a default title as the empty predicate: a rename changes presentation, not+ transcript state.diff --git a/docs/adr/0114-provider-model-bindings-and-thinking-configuration.md b/docs/adr/0114-provider-model-bindings-and-thinking-configuration.mdindex fe732b39d..38e4f7ab9 100644--- a/docs/adr/0114-provider-model-bindings-and-thinking-configuration.md+++ b/docs/adr/0114-provider-model-bindings-and-thinking-configuration.md@@ -2,51 +2,34 @@- Status: Accepted- Date: 2026-08-21-- Deciders: PI-Desktop core-- Updates ADR 0020 and ADR 0027+- Related: ADR 0020, ADR 0027## Context-The provider studio previously stored one `defaultModelId` and kept context,-output, and thinking capability decisions in runtime/catalog code. That made a-provider unable to retain settings for more than one model and made custom-models indistinguishable from an unconfigured default.+The provider studio stored one `defaultModelId` and kept context, output, and+thinking capability in runtime and catalog code, so a provider could not retain+settings for more than one model and a custom model was indistinguishable from an+unconfigured default.## Decision-`ProviderPublic`, `ProviderCreateInput`, and `ProviderUpdateInput` expose a-`models: ModelBinding[]` field. A binding contains:--```ts-type ModelBinding = {- id: string- contextWindow: number- maxTokens: number- thinkingLevels: ThinkingLevel[]- defaultThinkingLevel: ThinkingLevel | null-}-```--Rust host-core persists the array under `providers.config_json.models`, which-keeps provider-specific settings additive and inside the existing storage owner.-`default_model_id` remains a compatibility field and mirrors the first binding-on new writes.--## Migration and compatibility--When a stored provider has no `config_json.models` array, host-core materializes-one binding from `default_model_id` with the custom fallback values. The-materialized binding is returned by `providers.list` / `providers.get`; the next-provider create/update writes the new array.+`ProviderPublic`, `ProviderCreateInput`, and `ProviderUpdateInput` expose+`models: ModelBinding[]`, each binding carrying `id`, `contextWindow`, `maxTokens`,+`thinkingLevels`, and `defaultThinkingLevel`; host-core persists the array under+`providers.config_json.models`, and `default_model_id` remains a compatibility+field mirroring the first binding. The pi-ai catalog stays authoritative for+known-model metadata, so Settings offers its values as initial inputs while edits+land in the binding, and unknown custom models start at 128,000 context, 8,192 max+output, no thinking levels, and a null default. A stored provider without+`config_json.models` is materialized as one binding from `default_model_id`, and+Electron main resolves `models[0]?.id` before the legacy field. Thinking levels+fall back in the order `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`,+and no thinking support is `thinkingLevels: []` with a null default, never a fake+`off`. The storage contract changes additively with no new table or migration+version.## Consequences- Multiple model configurations survive restart and provider edits.-- Thinking-level fallback is deterministic: the canonical order is `off`,- `minimal`, `low`, `medium`, `high`, `xhigh`, `max`.-- Empty thinking support is represented by `thinkingLevels: []` and- `defaultThinkingLevel: null`, rather than a fake `off` selection.-- The provider storage contract changes additively without a new SQLite table or- migration version.-- Conversation model switching and routing policies remain explicitly out of- scope; the first binding is the current runtime default.+- Known-model metadata stays pinned to pi-ai while a user override is durable;+ conversation model switching and routing stay out of scope.diff --git a/docs/adr/0115-plugin-clipboard-history-is-host-owned.md b/docs/adr/0115-plugin-clipboard-history-is-host-owned.mdindex b10de28c6..b27e0d021 100644--- a/docs/adr/0115-plugin-clipboard-history-is-host-owned.md+++ b/docs/adr/0115-plugin-clipboard-history-is-host-owned.md@@ -6,31 +6,28 @@## Context-Plugins can read and write the current clipboard, but a plugin process has no-Electron clipboard access. Clipboard-history plugins therefore used to poll-`readText()` and maintain a second store, while the host polled the native-clipboard to capture images.+Clipboard-history plugins had no Electron clipboard access, so they polled+`readText()` and kept a second store while the host polled the native clipboard+for images. That repeated work read and encoded unchanged screenshots, burned+idle resources, and still missed copies between samples. History is also more+sensitive than the current clipboard, so per-plugin recorders would duplicate+data and weaken the permission boundary.## Decision-The Electron main process maintains one rolling, in-memory history and exposes-it to plugins as `pi.clipboard.getHistory()`. The API reuses `clipboard.read`,-returns newest-first text and image entries, and audits every call with the-entry count.--The host does not poll the system clipboard. It records text written through-`writeText` and records content from the Composer's user-initiated `paste`-event.--- 30 days retention;-- 500 entries and 256 MiB total payload;-- 100 KiB of UTF-8 text or 50 MiB of PNG image bytes per entry.+The Electron main process keeps one rolling in-memory history and exposes it to+plugins as `pi.clipboard.getHistory()`, reusing the `clipboard.read` permission+and returning newest-first text and image entries. The host never polls the+system clipboard: it records text written through `writeText` and content from+the Composer's user-initiated `paste` event, whose bytes the renderer already+holds, normalizing images to PNG during that request only. Consecutive identical+content collapses with a refreshed timestamp, retention, entry count, and total+payload are bounded, and the history is cleared on application exit.## Consequences-- Idle applications do not read or encode clipboard contents, and Composer paste- handling does not perform a second native clipboard read.-- `getHistory()` contains host writes and content pasted into Composer; a copy- that is never pasted is intentionally not captured.-- The history remains host-owned, in-memory only, and protected by the existing- `clipboard.read` permission.+- Idle applications stop reading and encoding clipboard content, and a paste+ costs no second native read.+- `getHistory()` holds host writes and Composer pastes only; content copied+ before startup or never pasted is not recoverable.+- History stays host-owned, in memory, and behind the existing permission.diff --git a/docs/adr/0116-opencode-go-provider-preset.md b/docs/adr/0116-opencode-go-provider-preset.mdindex 4e7e37e2c..50048f336 100644--- a/docs/adr/0116-opencode-go-provider-preset.md+++ b/docs/adr/0116-opencode-go-provider-preset.md@@ -2,40 +2,34 @@- Status: Accepted- Date: 2026-08-24-- Deciders: PI-Desktop core- Updates ADR 0012 and ADR 0020## Context-The OpenCode Go service exposes an OpenAI-compatible Chat Completions API, but-its endpoint is service-owned and should not be edited like a generic gateway.-Users should be able to configure it without copying an endpoint from separate-documentation, while the existing provider studio must continue to support+OpenCode Go exposes an OpenAI-compatible Chat Completions API whose endpoint is+service-owned, so users should not copy it from separate documentation as they+would for a generic gateway, while the provider studio must keep supportingarbitrary OpenAI-compatible services.## Decision-Add `opencode_go` as a persisted API-style value and expose it in the custom-provider dialog. Selecting it applies these immutable connection defaults:--```text-name: OpenCode Go-baseUrl: https://opencode.ai/zen/go/v1-```--The renderer keeps the name and endpoint visible but read-only, accepts the API-key as the only editable connection field, and continues to use the normal-discovered-model selector. Save-time normalization also enforces the fixed-values so stale or manually constructed form state cannot override them.+Add `opencode_go` as a persisted API-style value selectable in the custom+provider dialog, applying immutable connection defaults (`OpenCode Go` at+`https://opencode.ai/zen/go/v1`). The renderer shows name and endpoint read-only,+accepts the API key as the only editable connection field, keeps the normal+discovered-model selector, and save-time normalization enforces the fixed+values. The runtime maps `opencode_go` to pi-ai's OpenAI Chat Completions+adapter unless a model catalog entry pins another wire API, discovers models+from `/models` with a Bearer key, and leaves secrets in the existing Rust host+secret store. Agent-runtime injects the `x-opencode-session` routing header plus+`x-opencode-client` and a PI-Desktop `User-Agent` on session, subagent,+prompt-enhancement, and plugin one-shot streams, detecting the service by+`apiStyle: opencode_go`, `opencode` / `opencode-go` vendor ids, or an+`opencode.ai` base URL.## Consequences-- OpenCode Go is recognizable in the provider row and durable configuration.-- The service cannot be accidentally pointed at a different endpoint while the- preset is selected.-- Generic OpenAI-compatible configuration remains available as a separate API- style for user-controlled gateways.-- The preset does not create a second wire adapter or constrain the service's- model list to a hardcoded catalog.-- OpenCode Go chat, subagent, and one-shot requests carry a stable session- routing header without waiting on a pi-ai change.+- The service is recognizable in the provider row and durable configuration.+- The preset cannot be pointed at another endpoint while generic+ OpenAI-compatible configuration stays a separate API style.+- Requests carry a stable session routing header without a pi-ai change.diff --git a/docs/adr/0117-windows-taskbar-native-minimize.md b/docs/adr/0117-windows-taskbar-native-minimize.mdindex 14309b92b..2093d8794 100644--- a/docs/adr/0117-windows-taskbar-native-minimize.md+++ b/docs/adr/0117-windows-taskbar-native-minimize.md@@ -2,27 +2,30 @@- Status: Accepted (amended by ADR 0123)- Date: 2026-08-24-- Deciders: PI-Desktop core-- Related: D216, D252, D256, E2E-124, ADR 0078, ADR 0123+- Related: D216, D252, D256, ADR 0078, ADR 0123## Context-The tray-resident minimize decision in D216 hides the main window from the-operating system's window list. On Windows, clicking the taskbar button of the-focused window is a native minimize/restore toggle.+The tray-resident minimize decision in D216 hides the main window from the OS+window list. On Windows, clicking the taskbar button of a focused window is a+native minimize toggle that Electron reports through the main window's+`minimize` event, and the current handler answers it with `window.hide()`, which+removes the taskbar entry and leaves the tray icon as the only restore path.## Decision-1. On Windows, the main window's native `minimize` event is not converted to- `window.hide()`.-2. The renderer-drawn Windows minimize button and the Windows native-menu- minimize action use the same native minimize transition.-3. The existing restore path continues to restore and focus the same window.+On Windows the native `minimize` event is not converted to `window.hide()`: the+OS completes the minimize and the window keeps its taskbar entry. The+renderer-drawn Windows minimize button and the Windows native-menu minimize+action use that same native transition, Linux uses it for both of its minimize+actions, and the macOS native minimize event stays tray-resident. The existing+restore path still restores and focuses the same window, so no new IPC,+storage, or host protocol contract is needed.## Consequences-- Windows has one native taskbar minimize model for both the OS taskbar toggle- and the explicit in-app minimize action.-- Windows/Linux taskbar-minimized windows remain reachable from the taskbar;- close-to-tray windows remain reachable from the resident tray icon.+- Windows has one native taskbar minimize model for the taskbar toggle and the+ in-app minimize action.+- Windows and Linux windows minimized to the taskbar stay reachable there, while+ close-to-tray windows stay reachable from the tray icon.- Background work and window bounds persistence are unchanged.diff --git a/docs/adr/0118-renderer-owned-queued-prompts.md b/docs/adr/0118-renderer-owned-queued-prompts.mdindex 6166b6f7e..b90e15ed5 100644--- a/docs/adr/0118-renderer-owned-queued-prompts.md+++ b/docs/adr/0118-renderer-owned-queued-prompts.md@@ -6,29 +6,28 @@## Context-The desktop host enforces one running turn per session. Disabling the composer-while that turn runs makes users wait or abort a useful reply before they can-provide the next instruction.+The host enforces one running turn per session, so disabling the composer+during that turn forces users to stall or abort a useful reply before giving+the next instruction. Storing a second prompt in host-core would add replay and+lifecycle ownership that a transient queue does not need.## Decision-The renderer owns an in-memory FIFO queue keyed by session id. A queued item-contains its visible prompt and composer draft snapshot, so file references-remain independently removable and can be sent through the normal prompt-channel.--The Send and Stop controls coexist while a run is active. A normal Send adds a-queue item.+The renderer owns an in-memory FIFO queue keyed by session id, where each item+holds its visible prompt and composer draft snapshot so file references stay+independently removable; the queue is never persisted and is discarded on+restart or session deletion. Send and Stop coexist while a run is active: Send+appends a queue item, the renderer drains one item at a time after the owning+session receives `agent_end` via `agent/prompt`, and Send-first moves its item+to the head and calls the additive `agent/stop` IPC, which maps to+pi-agent-core's `finishTurn` so the durable turn closes as `completed`.+Immediate abort stays separate and leaves queued items untouched.## Consequences-- Users can continue typing and queue multiple next-turn instructions while a- long model/tool run is active.-- Send now has precise next-boundary semantics without a second concurrent- durable turn or an `AGENT_BUSY` race.-- Queue contents are intentionally lost on restart and are not visible to- another session; persistence can be considered separately if a future product- requirement needs it.-- Graceful stop is only as precise as the pi-agent-core boundary: an active- provider stream is allowed to finish, while a pending permission can still- wait for its normal resolution.+- Users queue next-turn instructions during a long run, and Send gets+ next-boundary semantics without a second durable turn or an `AGENT_BUSY`+ race.+- Queue contents are lost on restart by design.+- Graceful stop is only as precise as the pi-agent-core boundary, which lets an+ active provider stream finish.diff --git a/docs/adr/0119-event-driven-subagent-timeouts.md b/docs/adr/0119-event-driven-subagent-timeouts.mdindex 50f3bfb0c..7bddf9261 100644--- a/docs/adr/0119-event-driven-subagent-timeouts.md+++ b/docs/adr/0119-event-driven-subagent-timeouts.md@@ -2,55 +2,46 @@- Status: Accepted for implementation; amended by ADR 0129- Date: 2026-08-24-- Deciders: PI-Desktop core-- Related: D254, ADR 0062 (bounded subagents), ADR 0089 (background delegation),- ADR 0129 (idle bounds silence, not slowness)--> **Amended by ADR 0129.** The event allow-list in decision 2 is superseded:-> every `AgentEvent` now re-arms the idle timer, and the idle default is 300-> seconds rather than 600. The built-ins named in decision 4 as unlimited now-> carry turn backstops. The rejection of "use only idle time" below concerns-> dropping the total-duration ceiling, which ADR 0129 keeps.+- Related: ADR 0062 (bounded subagents), ADR 0089 (background delegation),+ ADR 0129 (idle bounds silence, not slowness), D254## Context-The original delegate loop used a default turn cap. A delegate that made one or-two useful tool calls per turn could therefore be terminated while it was-actively working, and there was no way to distinguish a genuinely idle worker-from one waiting on a long-running tool.+The original delegate loop used a default turn cap, so a delegate making one or+two useful calls per turn could be terminated while actively working, and nothing+distinguished an idle worker from one waiting on a long-running tool.## Decision-1. A delegate has two independent watchdogs: 600 seconds without activity and- 21,600 seconds of total runtime.-2. Activity is any delegate turn, message, or tool lifecycle event.-3. A watchdog terminates the delegate with `timed_out` and one of- `SUBAGENT_IDLE_TIMEOUT` or `SUBAGENT_DURATION_TIMEOUT`.-4. `maxTurns` is optional.-5. Definitions may override `idle-timeout` and `max-duration`.-6. The built-in `explorer` gains `Bash` for bounded read-only inspection such as- `git log`; `code-reviewer` remains read-only.-7. The shared status contract and desktop topology expose `timed_out`; the- renderer labels it in English and Simplified Chinese and presents it as a- warning outcome.--## Alternatives considered--- **Raise the turn cap:** rejected because any fixed cap still terminates an- actively working delegate and scales poorly across models and tool density.-- **Use only a total duration:** rejected because a provider or delegate can- remain stuck indefinitely while still below the overall ceiling.-- **Use only idle time:** rejected because continuous model/tool activity could- otherwise run without a hard resource ceiling.-- **Keep Explorer read-only without Bash:** rejected because it prevents- harmless repository inspection commands that the native search tools cannot- express; the existing permission path remains authoritative for Bash.+A delegate carries two independent watchdogs: an idle timer and a total-runtime+timer that includes tool execution. Activity is any delegate turn, message, or+tool lifecycle event, and the idle timer pauses between `tool_execution_start` and+its matching `tool_execution_end`, so a long Bash call is governed by the tool+timeout instead of delegate idleness. A watchdog ends the delegate with+`timed_out` plus `SUBAGENT_IDLE_TIMEOUT` or `SUBAGENT_DURATION_TIMEOUT` and keeps+the latest partial assistant output, while provider failures, parent aborts, and+explicit turn caps keep their existing outcomes. `maxTurns` stays optional, where+omission, `none`, or `0` means unlimited and a positive value is a bounded+backstop; definitions may override `idle-timeout` and `max-duration` within+clamped ranges, and non-numeric values warn and fall back to defaults. The shared+status contract and delegation topology expose `timed_out`, labeled as a warning+outcome in each shipped locale.++ADR 0129 amends this record: every `AgentEvent` re-arms the idle timer, the idle+default drops to 300 seconds, and the built-ins described as unlimited carry turn+backstops. The total-duration ceiling stays.## Consequences-- Delegates can run past the previous 20–24 turn behavior when they remain- active, while idle and total-runtime failures remain bounded and diagnosable.-- Timeout reports are visible to `TaskWait`, `TaskList`, and the delegation- topology, including their structured error codes and timing log entries.-- A definition that explicitly sets `maxTurns` retains a deterministic hard stop- for specialized or untrusted workloads.+- Delegates run past the old turn budget while remaining active, with idle and+ runtime failures still bounded and diagnosable.+- Timeout reports reach `TaskWait`, `TaskList`, and the topology with structured+ error codes.+- An explicit `maxTurns` keeps a deterministic hard stop for untrusted workloads.++## Alternatives++- Raise the turn cap: rejected because any fixed cap still kills active work and+ scales poorly across models.+- Use only idle time: rejected because continuous activity would run without a+ hard resource ceiling.diff --git a/docs/adr/0120-bounded-session-history-windows.md b/docs/adr/0120-bounded-session-history-windows.mdindex 154656223..3c44e1772 100644--- a/docs/adr/0120-bounded-session-history-windows.md+++ b/docs/adr/0120-bounded-session-history-windows.md@@ -2,51 +2,45 @@- Status: Accepted- Date: 2026-08-24-- Deciders: PI-Desktop core-- Related: D119, ADR 0041, `03-runtime/04-data-storage.md`,- `03-runtime/06-host-rpc-protocol.md`+- Related: D119, ADR 0041, `03-runtime/04-data-storage.md`, `03-runtime/06-host-rpc-protocol.md`## Context-Opening a session previously read its complete JSONL transcript, projected every-message, and sent the complete result through host-core, Electron, and the-renderer. A single large pasted or tool-produced value could therefore make a 50-MB transcript allocation and block the desktop while a long session was being-opened.+Opening a session read its complete JSONL transcript, projected every message,+and pushed the result through host-core, Electron, and the renderer, so one+large pasted or tool-produced value could stall the desktop while a long session+opened. Mount-time virtualization did not help, because the full payload had+already crossed the process boundary.## Decision-1. Renderer-facing `session.get` supports an additive read window with- `messageBefore`, `messageLimit`, and `contentLimit`.-2. Host-core reads JSONL with a buffered sequential parser and projects only the- requested page.-3. The desktop opens sessions with the newest 100 messages and a 64 KiB- per-message display budget.-4. The uncapped default remains available to non-renderer callers, so model- reconstruction and persistence semantics do not depend on UI pagination.--The original implementation scanned the transcript sequentially to find a-requested window. It now keeps a disposable per-session layout of physical-message and compaction line offsets, with a versioned disk cache when the-filesystem provides a reliable file identity.--## Alternatives considered--- **Only virtualize the message list:** rejected because the expensive full- parse and IPC payload would still happen before rendering.-- **Store only a preview in the transcript:** rejected because it loses user- data and changes model context semantics.-- **Use a database payload table for paging:** rejected for now; the JSONL- transcript remains the lossless source and a streaming window avoids a schema- migration while fixing the boundary that caused the stall.+1. Renderer-facing `session.get` accepts an additive window with+ `messageBefore`, `messageLimit`, and `contentLimit`, and returns+ `messageStart` and `hasMoreBefore` so the renderer can page toward older+ messages while keeping the newest view.+2. Host-core parses JSONL sequentially and projects only the requested page;+ `contentLimit` truncates only the display projection, with an explicit+ marker, while the on-disk transcript and the uncapped sidecar/model path stay+ authoritative.+3. The desktop opens the newest page, fetches older pages on scroll while+ preserving scroll position, and rehydrates the complete transcript before any+ deliberate full-history rewrite so a partial window cannot delete older+ messages.+4. The uncapped default stays available to non-renderer callers, and window+ lookup uses a disposable per-session layout of message and compaction+ offsets, optionally cached on disk and rebuilt from the JSONL source whenever+ it is invalid. Format, schema, and RPC contracts are unchanged.## Consequences-- Session activation has bounded renderer memory and IPC work independent of the- total visible history, apart from the sequential scan needed to locate the- requested page.-- Older history is available on demand, and display-only truncation is clear to- the user while the complete content remains available to the agent.-- Full-history edit, delete, revision-switch, and abort operations may perform a- deliberate uncapped read before mutation; this preserves transcript data- rather than allowing a partial UI window to overwrite older messages.+- Activation cost is bounded by the window instead of the whole history.+- Older history is available on demand, and display truncation is visible while+ the agent keeps the complete content.+- Full-history edit, delete, revision switch, and abort may read uncapped before+ mutating, which protects older messages.++## Alternatives++- Only virtualize the message list: rejected, the full parse and IPC payload+ still happen first.+- Store only a preview: rejected, it loses user data and changes model context.diff --git a/docs/adr/0121-one-shot-composer-prompt-enhancement.md b/docs/adr/0121-one-shot-composer-prompt-enhancement.mdindex 8fc83ca3b..06a5acba8 100644--- a/docs/adr/0121-one-shot-composer-prompt-enhancement.md+++ b/docs/adr/0121-one-shot-composer-prompt-enhancement.md@@ -2,20 +2,22 @@- Status: Superseded by ADR 0324- Date: 2026-08-24-- Updated: 2026-10-08 (feature moved to an optional standalone plugin)- Related: Issue #14, Issue #562## Context-The Composer needs a convenient way to improve a draft without sending a-message, changing the conversation transcript, or exposing provider credentials-to the renderer.+The Composer needed to improve a draft without sending a message, changing the+transcript, or exposing provider credentials to the renderer.## Decision-Prompt enhancement is an allowlisted renderer-to-Electron IPC operation. The-renderer sends the draft and a provider/model/thinking snapshot.+Enhancement was an allowlisted renderer-to-Main IPC operation that sent the draft+with a provider/model/thinking snapshot, and Main resolved credentials and asked+agent-runtime for one completion with no session history, tools, or transcript+side effect, using an overridable user template and a built-in system prompt.## Consequences-Superseded (Superseded by ADR 0324). The full record is in git history.+Superseded by ADR 0324, which moved the feature to an optional standalone plugin,+so the typed IPC contract and its shared default templates no longer exist. Main+stayed the only owner of API keys and vendor OAuth resolution.diff --git a/docs/adr/0122-reserve-native-width-while-work-panel-visible.md b/docs/adr/0122-reserve-native-width-while-work-panel-visible.mdindex c2428cb82..6219d078d 100644--- a/docs/adr/0122-reserve-native-width-while-work-panel-visible.md+++ b/docs/adr/0122-reserve-native-width-while-work-panel-visible.md@@ -2,21 +2,22 @@- Status: Superseded by ADR 0151- Date: 2026-08-25-- Related: [01-ui-ia](../spec/04-ux/01-ui-ia.md) ·- [08-component-spec §5](../spec/04-ux/08-component-spec.md) ·- [09-interaction-patterns §8](../spec/04-ux/09-interaction-patterns.md) ·- [01-ipc-protocol](../spec/03-runtime/01-ipc-protocol.md) · decision D255+- Related: D255- Supersedes: ADR 0033; restores the native-reservation behavior from ADR 0032## Context-The work panel is correctly rendered as an in-flow flex sibling, but the-renderer had started requesting a native reservation of `0` for every state.+The work panel rendered correctly as an in-flow flex sibling, but the renderer+requested a native reservation of zero in every state, so a collapsed panel left+the window at its larger size and chat expanded into the released column.## Decision-1. Keep the work panel as a fixed-width in-flow flex column in the renderer.+Request a native reservation equal to the panel's committed width through+`window/setWorkPanelReservation` before showing it opened, keep the panel mounted+through its exit animation, then request zero width and unmount only after the+request succeeds. The Browser `WebContentsView` kept being positioned from the+renderer-measured panel rectangle, and Main kept capping the added width on a+constrained work area.-## Consequences--Superseded (Superseded by ADR 0151). The full record is in git history.+ADR 0151 supersedes this record and owns current work panel sizing.diff --git a/docs/adr/0123-native-taskbar-minimize-controls.md b/docs/adr/0123-native-taskbar-minimize-controls.mdindex d5a2b5b34..d974e14fc 100644--- a/docs/adr/0123-native-taskbar-minimize-controls.md+++ b/docs/adr/0123-native-taskbar-minimize-controls.md@@ -2,40 +2,33 @@- Status: Accepted- Date: 2026-08-25-- Deciders: PI-Desktop core-- Related: D216, D230, D252, D256, E2E-124, ADR 0078, ADR 0090, ADR 0117+- Related: ADR 0078, ADR 0090, ADR 0117, D216, D230, D252, D256## Context-Windows/Linux use a frameless window with renderer-drawn minimize, maximize, and-close controls. The minimize action was calling `window.hide()`, which removed-the window from the taskbar and made the action behave like a close-to-tray-operation.+The frameless Windows/Linux window draws its own controls, and minimize called+`window.hide()`, removing the window from the taskbar and behaving like+close-to-tray, which already has its own persisted `tray`/`quit` choice.## Decision-1. The Windows/Linux renderer window-control `minimize` action calls Electron's- native `BrowserWindow.minimize()` transition.-2. The main-window `minimize` event does not convert Windows/Linux native- minimization into `hide()`.-3. macOS keeps its existing traffic-light tray-resident minimize behavior.-4. The resident tray, close-behavior persistence, IPC action allowlists, host- protocol, and background-process lifetime do not change.+The renderer `minimize` action and the native-menu minimize action call+Electron's `BrowserWindow.minimize()` on Windows and Linux, and the main-window+`minimize` event no longer converts that into `hide()`, so the taskbar entry+survives and the same window restores. macOS keeps its tray-resident minimize,+close behavior stays owned by ADR 0090, and the tray, close-behavior+persistence, IPC action allowlists, host protocol, and background-process+lifetime are unchanged.## Consequences-- The three Windows/Linux window buttons now match the expected desktop model:- minimize goes to the taskbar, maximize toggles the window, and close follows- the user's remembered tray/quit choice.-- The tray remains available for close-to-tray and for macOS's existing minimize- behavior; no second tray lifecycle is introduced.-- No new privileged bridge or protocol version is required because the existing- `minimize` action changes only its Main-owned Electron effect.+- Minimize goes to the taskbar, maximize toggles, and close follows the+ remembered tray/quit choice.+- No second tray lifecycle and no new privileged bridge or protocol version.## Alternatives considered-- **Keep explicit minimize as hide-to-tray:** rejected because it makes the- minimize and close controls indistinguishable when close-to-tray is selected- and removes the standard taskbar restore path.-- **Remove the resident tray:** rejected because close-to-tray and macOS- minimize still need a reliable restore surface.+- Keep minimize as hide-to-tray: rejected; it makes minimize and close+ indistinguishable.+- Remove the resident tray: rejected; close-to-tray still needs a restore+ surface.diff --git a/docs/adr/0124-temporary-session-scratch-workspace.md b/docs/adr/0124-temporary-session-scratch-workspace.mdindex 9e7157990..a0edd9cd0 100644--- a/docs/adr/0124-temporary-session-scratch-workspace.md+++ b/docs/adr/0124-temporary-session-scratch-workspace.md@@ -2,44 +2,48 @@- Status: Accepted- Date: 2026-08-26-- Related: Issue #16, ADR 0059, ADR 0118+- Related: ADR 0059, ADR 0118, Issue #16## Context-Temporary sessions intentionally keep `projectPath` empty so they do not inherit-or mutate the currently visible project. That left their native tools without a-root, however, even though each session already owns a deterministic-`<data_dir>/scratch/<sessionId>` directory.+Temporary sessions keep `projectPath` empty so they neither inherit nor mutate the+visible project, which left their native tools without a root even though each+session already owns a deterministic scratch directory under the data directory.+The empty home also reused one hero copy for a temporary chat and for no session.## Decision-1. Host-core resolves a persisted path-less session's tool workspace to its own- `<data_dir>/scratch/<sessionId>` directory and creates that directory when- the binding is first resolved.-2. Read, Glob, Grep, Write, Edit, and Bash use that scratch directory as the- temporary session's workspace root.-3. Plan and Goal workspace validation continues to require a persisted project- binding, so a scratch workspace does not broaden contract-mode execution.-4. The renderer derives the empty-home hero state from the selected session:- project sessions retain the project-underlined welcome, temporary sessions- show dedicated temporary-chat copy without a project action, and no active- session shows the generic welcome.+### 1. The scratch directory is the tool workspace++Host-core resolves a persisted path-less session's tool workspace to its own+`<data_dir>/scratch/<sessionId>` directory, creating it on first resolution. The+session schema is unchanged and `projectPath` stays absent.++### 2. Native tools root at the scratch directory++Read, Glob, Grep, Write, Edit, and Bash treat that directory as the root, never the+mutable global workspace, with existing containment and permission checks intact.+A missing-session compatibility call may keep the legacy fallback.++### 3. Plan and Goal keep the project requirement++Workspace validation for Plan and Goal still requires a persisted project binding,+so a scratch workspace does not widen contract-mode execution.++### 4. The empty home reflects the selected session++Project sessions keep the project welcome, temporary sessions show temporary-chat+copy without a project action, and no active session shows the generic welcome.## Consequences-- Temporary chats can safely use native tools without touching a project or- inheriting the most recently active project.-- Relative tool paths in temporary chats are useful immediately; scratch data- remains ephemeral and follows the existing session deletion/startup sweep.-- Temporary sessions remain visibly and structurally distinct from project- sessions without introducing a new session type or persistence migration.-- Plan and Goal keep their existing project-root boundary.--## Alternatives considered--- **Inherit the visible project:** rejected because it violates the temporary- session isolation invariant and can mutate unrelated project files.-- **Add a new persisted session type:** rejected because the existing path-less- session model already provides the correct lifecycle and grouping.-- **Leave tools unavailable:** rejected because it makes temporary chats unable- to perform otherwise isolated inspection and scratch work.+- Temporary chats use native tools without touching or inheriting a project.+- Relative paths work immediately; scratch data stays ephemeral and follows the+ existing deletion and startup sweep.+- No new session type or persistence migration is introduced.++## Alternatives++- Inherit the visible project: rejected because it breaks temporary-session+ isolation.+- Leave tools unavailable: rejected because it blocks otherwise isolated work.diff --git a/docs/adr/0125-renderer-derived-brand-marks-and-minified-output.md b/docs/adr/0125-renderer-derived-brand-marks-and-minified-output.mdindex 0db7076fb..51934e03d 100644--- a/docs/adr/0125-renderer-derived-brand-marks-and-minified-output.md+++ b/docs/adr/0125-renderer-derived-brand-marks-and-minified-output.md@@ -3,42 +3,43 @@- Status: Accepted- Date: 2026-08-26- Related: ADR 0083, D079, D094-- Baseline: `0.10.8`## Context-The renderer output was 31 MiB, and three of its costs were accidental rather-than product decisions:--1. `electron-vite` hard-defaults its renderer preset to `minify: false`, unlike- plain Vite.-2. KaTeX's stylesheet declares `woff2`, `woff`, and `truetype` sources for each- of its faces.-3. D079 and D094 named `build/icon_1024.png` as the canonical brand mark, and- `BrandLogo` imported it directly.+Three costs in a 31 MiB renderer output were accidental rather than product+decisions: `electron-vite` defaults its renderer preset to `minify: false` and+the config did not override it, KaTeX declared `woff` and `truetype` sources that+the bundled Chromium never needs, and `BrandLogo` imported the 1024x1024 PNG+master to draw a 64 px mark. The Electron shell itself accounts for almost all+of the unpacked application size, so the renderer was the only part worth+tuning.## Decision-1. The renderer build sets `minify: "esbuild"` explicitly.-2. A `pi-drop-legacy-font-fallbacks` Vite plugin removes `woff` and `truetype`- `src` entries from CSS with `enforce: "pre"`, before Vite registers `url()`- values as assets.-3. `build/icon_1024.png` and `build/logo_dark.png` remain the canonical brand- masters and the source of truth for installer icons.+The renderer build sets `minify: "esbuild"` explicitly, asserted by the+packaging footprint test because the framework default would silently undo it. A+`pi-drop-legacy-font-fallbacks` Vite plugin strips comma-prefixed `woff` and+`truetype` fallback `src` entries at `enforce: "pre"` before Vite registers+`url()` values as assets, keeping a face whose only source is one of those+formats. `build/icon_1024.png` and `build/logo_dark.png` remain the canonical+brand masters; this amends D079 and D094 so the renderer imports derived 192x192+marks from `apps/desktop/src/assets/brand/`, regenerated with `sips -Z 192`+whenever the masters change, with no change to visual identity.-*(Superseded by [ADR 0298](0298-remove-bundled-fonts.md): the app ships no-fonts, so there is nothing to subset.)* The two bundled CJK faces stayed-unsubset while they existed. ADR 0083 section 2 appended `Noto Sans SC` to every-font stack so Chinese text stayed readable offline, and subsetting would have-dropped glyphs from user-supplied content; reducing those 15 MiB required-revising ADR 0083, not a build-config change.+Font subsetting is no longer part of this decision.+[ADR 0298](0298-remove-bundled-fonts.md) removed the bundled CJK faces instead,+since subsetting would have dropped glyphs from user-supplied content.## Consequences-- `out/renderer` drops from 31 MiB to 24 MiB: JavaScript 12.53 to 7.72 MiB,- legacy font fallbacks 0.78 MiB to 0, PNG brand assets 1.23 to 0.06 MiB.-- Minified renderer stack traces need the devtools source view; no sourcemaps- are emitted, which matches the previous release behavior.-- The brand marks now exist in two places.-- Stripping legacy font formats is safe only because the app runs exclusively in- the bundled Chromium.+- The renderer output drops by roughly seven MiB of JavaScript, font, and PNG+ weight, measured before [ADR 0298](0298-remove-bundled-fonts.md).+- Minified stack traces need the devtools source view; no sourcemaps are+ emitted, matching previous release behavior.+- Brand marks now exist in two places, and the packaging footprint test fails if+ the renderer imports from `build/` again.++## Alternatives++- Subset the bundled CJK faces: it would have dropped glyphs from+ user-supplied content, so ADR 0083 had to be revised instead.diff --git a/docs/adr/0126-agent-capability-workbench.md b/docs/adr/0126-agent-capability-workbench.mdindex 8c4d9cdae..902de3e52 100644--- a/docs/adr/0126-agent-capability-workbench.md+++ b/docs/adr/0126-agent-capability-workbench.md@@ -3,46 +3,49 @@- Status: Accepted- Date: 2026-08-27- Related: ADR 0063, ADR 0112, D193, D194, D202-- Baseline: `0.10.8`## Context-`d24e1ee0` moved Skills, MCP, and Subagents out of Extensions and into Settings-> Agent. The move carried the list and the enablement switch, but it deleted-`SkillEditorSheet.tsx` and `SubagentEditorSheet.tsx` along the way.--1. **The level was structure, not a filter.** Each page stacked a Global card- block and a Project card block, each with its own heading, its own resolved- path, its own count, and its own actions.-2. **One pending request locked the page.** Rows were rendered with- `busy={loading || busyKey !== null}` and `disabled={loading || busyKey !==- null}`, so toggling any one capability disabled every control on the page,- including the unrelated level's rows.-3. **A toggle flashed the skeletons.** `toggle()` awaited `load()` on success,- and `load()` set `loading` unconditionally, so a switch replaced the whole- list with skeleton rows and then rebuilt it.+Skills, MCP, and Subagents moved from Extensions into Settings > Agent, but the+move deleted `SkillEditorSheet.tsx` and `SubagentEditorSheet.tsx` while the host+side stayed intact, so `skills.create`, `skills.update`, `skills.read`,+`skills.reveal`, `subagents.create`, and `mcp.remove` still resolved end to end+with no renderer caller. The three pages then stacked separate Global and Project+card blocks, disabled every control while any one request was pending, and+replaced the list with skeletons after each toggle.## Decision-1. **One workbench per page.** Each of Skills, MCP, and Subagents renders one- toolbar above one elevated panel.-2. **The pages author.** Create, edit, and delete return to Settings for all- three capabilities, through the recovered editor sheets and the host calls- that already existed.-3. **Busy is per row, and a refresh is not a first paint.** Only the row with an- in-flight request is busy; the rest of the page stays interactive.-4. **Enablement is optimistic.** The switch flips locally, the host call- follows, and the previous position is restored only if the host refuses.-5. **`skills.reveal` takes the level.** `revealUserSkill` and the- `IPC.invoke.skillReveal` handler now accept `{ id, level?, projectPath? }`- and forward it to `skills.read`, which has always parsed both.+1. One workbench per page. Each of Skills, MCP, and Subagents renders one toolbar+ above one panel: the toolbar owns the level filter as a segmented control with+ live counts, one search field, the project picker, and the page's primary+ actions. Level becomes a filter over one list, where each level is a group+ header row (name, resolved `.agents` path, count) and every row also carries+ its own level badge.+2. The pages author again. Create, edit, and delete return through the recovered+ editor sheets and the host calls that already existed, and new capabilities+ land at the level the filter points at. Destructive row actions sit in a+ per-row overflow menu and arm before firing. This overrides D202's fixed-height+ global list for the Subagents presentation only; subagents stay global-only,+ so that page keeps no level filter and no project picker.+3. Busy state is per row, and a refresh is not a first paint. Only the row with an+ in-flight request is busy, skeletons render on the first hydration only, and+ later loads dim the existing rows while announcing the refresh to assistive+ technology.+4. Enablement is optimistic: the switch flips locally, the host call follows, and+ the previous position returns only if the host refuses, so a toggle needs no+ reload.+5. `skills.reveal` takes the level. `revealUserSkill` and the+ `IPC.invoke.skillReveal` handler accept `{ id, level?, projectPath? }` and+ forward it to `skills.read`; a bare id string still works.## Consequences-- Reading and managing capabilities happen in the same place, and the Settings- pages no longer depend on Extensions for authoring that the host already- supported.-- Revealing a project-level skill opens that project's file.-- D202's frozen page shape is superseded for presentation.-- `maxTurns` is expressible as "no limit" in the Subagents editor.-- The change is renderer-only apart from the `skillReveal` payload widening.+- Reading and managing capabilities happen in one place, and revealing a+ project-level skill now opens that project's file.+- D202's frozen page shape is superseded for presentation only; its data boundary+ (global documents under `~/.agents/subagents`, enabled state in+ `<data>/agent-capabilities/subagents.json`) is unchanged.+- An absent `maxTurns` now means unlimited rather than a hidden default, so the+ editor leaves the field empty. Renderer-only apart from the widened+ `skillReveal` payload.diff --git a/docs/adr/0127-transcript-layout-index-and-identity-truncation.md b/docs/adr/0127-transcript-layout-index-and-identity-truncation.mdindex 9086fa3cb..163345466 100644--- a/docs/adr/0127-transcript-layout-index-and-identity-truncation.md+++ b/docs/adr/0127-transcript-layout-index-and-identity-truncation.md@@ -2,59 +2,57 @@- Status: Accepted- Date: 2026-08-26-- Deciders: PI-Desktop core-- Related: ADR 0120, D119, D122, D139, `03-runtime/04-data-storage.md`,- `03-runtime/06-host-rpc-protocol.md`, `03-runtime/01-ipc-protocol.md`+- Related: ADR 0120, D119, D122, D139, `03-runtime/04-data-storage.md`, `03-runtime/06-host-rpc-protocol.md`, `03-runtime/01-ipc-protocol.md`## Context-ADR 0120 bounded what a session open sends to the renderer, but explicitly kept-"the sequential scan needed to locate the requested page". That residue is what-users experience as the remaining problem: opening a session is still linear in-the whole conversation, and it degrades as the conversation grows, because the-newest 100 messages can only be found by parsing every line before them.--- The window clamped `messageBefore` against `SessionSummary.message_count`,- which is `sessions.last_seq` — a deduplicated logical count.-- Regenerate and edit-resend sent `truncateBefore` as- `sessionHistory[sessionId].messageStart + userIndex`, adding a physical file- offset to an index into the renderer's deduplicated, display-filtered array.+ADR 0120 bounded what a session open sends to the renderer but kept the+sequential scan used to locate the requested page, so opening a session stayed+linear in the conversation and every line was deserialized merely to be+classified. Two coordinate-space bugs shared that path: the window clamped+`messageBefore` against the deduplicated `SessionSummary.message_count` instead+of physical file lines, hiding the newest messages, and regenerate sent+`truncateBefore` as a file offset plus a display index, truncating at the wrong+point. A host-side fork could also vanish from the UI when its navigation intent+was superseded after the child had been created.## Decision-1. **Layout index.** host-core maintains a per-session *transcript layout*: the- byte offset of every message and compaction line plus the `file_len` those- offsets were recorded against.-2. **Cheap classification.** Transcript lines are classified by one depth-aware- scan for the *top-level* `type` key, never by parsing the line into a value.-3. **One coordinate space.** Read-window offsets are physical message-line- positions, clamped against the layout.+1. **Layout index.** host-core keeps a per-session transcript layout with the+ byte offset of every message and compaction line and the `file_len` it was+ recorded against, so a bounded window seeks directly to its first line. The+ layout is derived data cached in memory: growth scans the tail, shrink or+ replacement rescans, every rewrite and delete path drops the entry, and a torn+ trailing line is excluded until the writer completes it.+2. **Cheap classification.** Lines are classified by one depth-aware scan for the+ top-level `type` key instead of being parsed into a value, because tool+ results and checkpoint details can nest an object with its own `type`. New+ lines write `type` first, older ordering is read by the same scan, and no+ migration is required.+3. **One coordinate space.** Window offsets are physical message-line positions+ clamped against the layout, `last_seq` is never used for them, and the+ compaction chain is still returned whole.4. **Identity-based truncation.** `agent/prompt` accepts- `truncateFromMessageId`, and the host resolves that identity against its own- transcript; an unresolvable id is rejected with `NOT_FOUND` instead of- truncating at a guessed position.-5. **Durable fork commit.** Recording a forked child (session list, cached- transcript, checkpoint marks) is unconditional, because it is already durable- on the host when the call returns.--## Alternatives considered--- **Persist the layout in SQLite:** rejected.-- **Fix the clamp by making `last_seq` authoritative for file positions:**- rejected.-- **Keep index-based truncation and always rehydrate the full history first:**- rejected.-- **Refresh the session list after a superseded fork:** rejected as a remedy for- the lost branch.+ `truncateFromMessageId`, resolved against the host transcript, with an+ unresolvable id rejected as `NOT_FOUND` instead of truncating at a guess;+ `truncateBefore` stays accepted for older callers.+5. **Durable fork commit.** Recording the forked child is unconditional because it+ is already durable on the host, and only the visible switch stays gated on the+ navigation intent still being current.## Consequences-- Opening a session, and each older page, costs the requested window rather than- the conversation length; a large tool result is no longer parsed to be- skipped.+- Opening a session and each older page costs the window rather than the history,+ and a large tool result is no longer parsed to be skipped; the first open still+ pays one index scan.- The layout is a cache with an explicit validity token, so correctness after a- crash or rewrite does not depend on it being present or fresh.-- The newest messages of a session with an unindexed file line are visible- again, and paging backwards reaches the true first message.-- Regenerating from a paged-back transcript replaces the turn the user selected.-- A branch created while the user navigates away is still listed and openable.+ crash or rewrite never depends on it.+- Newest messages of an unindexed file line are visible again, paging reaches the+ true first message, and a branch created while navigating away stays listed.++## Alternatives++- Persist the layout in SQLite: rejected, it adds a schema migration and a second+ source of truth for cheap derived data.+- Make `last_seq` authoritative for file positions: rejected, it would require+ rewriting transcripts to repair a derived index.diff --git a/docs/adr/0128-bounded-transient-provider-retry.md b/docs/adr/0128-bounded-transient-provider-retry.mdindex e32bf237a..cc0ee15d4 100644--- a/docs/adr/0128-bounded-transient-provider-retry.md+++ b/docs/adr/0128-bounded-transient-provider-retry.md@@ -2,58 +2,47 @@- Status: Accepted- Date: 2026-08-21-- Deciders: PI-Desktop core-- Related: D259, E2E-096, E2E-149, ADR 0050, ADR 0091, D186, D245+- Related: D186, D245, D259, ADR 0050, ADR 0091, E2E-096, E2E-149## Context-Upstream gateway faults are common on OpenAI-compatible endpoints. A relay that-answers `OpenAI API error (502): {"type":"api_error","message":"Upstream API-request failed."}` is reporting a momentary upstream outage, not a rejected-request: the same prompt usually succeeds on the next attempt.+OpenAI-compatible relays answer momentary upstream outages with a 502 that usually+succeeds on the next attempt, but ADR 0091 gave only HTTP 429 a shared budget and+left other transient failures on a split per-phase policy. A second 502 before+headers was terminal, a mid-stream gateway fault was never replayed, builtin+subagents required `phase === "request"`, and non-429 backoff ignored+`Retry-After`.## Decision-1. Non-429 transient provider failures share one bounded logical-turn budget of- four retries after the initial attempt, for five provider attempts total.-2. The budget admits exactly `NETWORK_ERROR`, `TIMEOUT`, `STREAM_FAILED`, and- `PROVIDER_ERROR`.-3. Retry delay honors the server first.-4. The main session, builtin subagents, and one-shot composer enhancement use- the same codes, the same budget size, and the same delay precedence.-5. Retries stay silent and abortable, and 429 keeps its own separate five-retry- budget from ADR 0091.-6. Exhaustion emits one terminal assistant error and one lifecycle error, with- `retryAttempt: 4` for a persistent non-429 transient failure.-7. Only the failed request is replayed.+Non-429 transient failures share one bounded logical-turn budget of four retries+after the initial attempt, with setup and stream delivery drawing on the same+budget so a fault moving between phases cannot reset or multiply it. The budget+admits exactly `NETWORK_ERROR`, `TIMEOUT`, `STREAM_FAILED`, and `PROVIDER_ERROR` —+the last in the stream phase as well as setup — while every other classification,+including a non-retryable `PROVIDER_ERROR` from a malformed 400/422 request, stays+terminal. Server pacing wins: `retry-after-ms`, then `retry-after` seconds, then an+HTTP date, capped at 8 seconds, with headers retained for any status that can carry+a usable delay (429, 408, 409, 5xx) and a deterministic 1, 2, 4, 8 second doubling+schedule otherwise. Main session, builtin subagents, and one-shot composer+enhancement use the same codes, budget, and delay precedence, retries stay silent+and abortable, and 429 keeps ADR 0091's separate five-retry budget. Exhaustion+emits one terminal assistant error and one lifecycle error with `retryAttempt: 4`,+and only the failed request is replayed: the failed assistant leaves the next model+context with its visible message id reused, so a retry never restarts the turn or+re-runs a completed tool call.## Consequences-- A short upstream 502/503/504 burst recovers without an error card, whether it- lands before headers or mid-stream.-- A persistent upstream outage stays bounded and visible: five attempts, at most- four backoffs totalling 15 seconds, and an individual wait capped at 8- seconds.-- Worst-case latency before a terminal non-429 error grows, bounded by four- waits (15 seconds of backoff) instead of one.-- Gateways that state their own pacing are respected, while malformed or- excessive header values cannot hold a turn.-- The three provider entry points can no longer drift into different transient- policies.+- A short 502/503/504 burst recovers without an error card, before headers or+ mid-stream.+- A persistent outage stays bounded and visible, at the cost of up to 15 seconds of+ backoff before a terminal error.+- The three provider entry points can no longer drift into different policies.## Alternatives-- Raise pi-ai's `maxRetries` instead.-- Fold non-429 transient failures into the 429 budget.-- Retry every retriable classification three times.--## References--- `docs/spec/03-runtime/02-agent-runtime.md` §5d-- `docs/spec/03-runtime/08-error-codes.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` E2E-096, E2E-149-- `docs/spec/08-meta/decisions-log.md` D259-- `packages/agent-runtime/src/provider-retry.ts`-- `packages/agent-runtime/src/runtime.ts`-- `packages/agent-runtime/src/subagent.ts`-- `packages/agent-runtime/src/prompt-enhancement.ts`+- Raise pi-ai's `maxRetries`: nested wrappers multiply attempts and reintroduce a+ non-abortable SDK sleep.+- Fold transient failures into the 429 budget: a 502 burst would consume the+ rate-limit budget.diff --git a/docs/adr/0129-idle-watchdog-bounds-silence.md b/docs/adr/0129-idle-watchdog-bounds-silence.mdindex f5f35e976..de67a95dc 100644--- a/docs/adr/0129-idle-watchdog-bounds-silence.md+++ b/docs/adr/0129-idle-watchdog-bounds-silence.md@@ -3,49 +3,43 @@- Status: Accepted for implementation (amended by ADR 0166: watchdogs no longerkill; the parent judges subagent lifetime)- Date: 2026-08-27-- Deciders: PI-Desktop core-- Related: D260 (amends D254), ADR 0119 (event-driven subagent timeouts),- ADR 0089 (background delegation)+- Related: D260 (amends D254), ADR 0119, ADR 0089## Context-ADR 0119 replaced the delegate turn cap with an idle watchdog whose timer was-re-armed by an allow-list of five event types. The list was the problem, not the-policy: it decided liveness by event *kind*, so any `AgentEvent` variant outside-it — present or future — was silently dropped, and reading the code did not-answer the question the watchdog is supposed to answer.+ADR 0119 replaced the delegate turn cap with an idle watchdog re-armed by an+allow-list of five event types, so liveness was decided by event kind: any other+`AgentEvent` variant was silently dropped and the intended contract went unstated.+The 600-second default was also never sized against what it measures — the wait+between a delegate's last streamed token and its next response — and it equalled+the `TaskWait` default, so a hung delegate could not settle inside one wait.## Decision-1. Every `AgentEvent` re-arms the idle timer, a single streamed token arriving- as `message_update` included.-2. The default idle timeout is 300 seconds, sized from the measured 174-second- p99.9 pre-token wait plus margin for the delegate's own provider retry- backoff, which is silent by design.-3. `TaskWait` expiry reports "Still running after Ns" and states that this is- not a failure and the unfinished delegates keep working.+1. Every `AgentEvent` re-arms the idle timer, a single streamed token as+ `message_update` included, so the watchdog fires on total unresponsiveness only;+ the pause between `tool_execution_start` and its matching `tool_execution_end`+ is unchanged.+2. The default idle timeout is 300 seconds, above the measured pre-token wait and+ the delegate's silent provider retry backoff and below the 600-second+ `TaskWait` default, so a stuck delegate settles as `timed_out` inside one wait.+3. `TaskWait` expiry reports "Still running after Ns" and states that this is not a+ failure and the unfinished delegates keep working.4. The built-ins carry a turn backstop sized to their job: `explorer` 60,- `code-reviewer` 50, `test-runner` 40, `fixer` 80.+ `code-reviewer` 50, `test-runner` 40, `fixer` 80, so a non-converging delegate+ ends as `truncated` with its partial report.-## Alternatives considered+## Consequences-- **Keep the event allow-list and only lower the default:** rejected because it- leaves liveness defined by an enumeration that must be revisited whenever- `AgentEvent` grows a variant, and leaves the intended contract unstated.-- **Emit synthetic activity across provider retry backoff:** rejected for now.-- **Raise the idle default to 900s and lengthen `TaskWait`:** rejected because- it inverts the relationship that matters — the idle window must be shorter- than a wait, or a hang cannot surface inside one.-- **Leave the built-ins unlimited:** rejected because the duration ceiling is a- 6-hour backstop, not a convergence signal; a looping delegate should return- its partial work in minutes.+- A slow delegate is never idle-terminated; only silence expires it, and a new+ `AgentEvent` variant no longer requires touching the watchdog.+- Extreme latency outliers and long rate-limit backoff now expire at 300s rather+ than 600s, returning `timed_out` with the latest partial report.+- A hung delegate surfaces within a single `TaskWait`.-## Consequences+## Alternatives-- A delegate that keeps producing output is never idle-terminated, however slow- its turn is.-- Two previously-survivable classes now expire at 300s instead of 600s: extreme- provider latency outliers and a long chain of rate-limit backoff.-- A hung delegate surfaces within a single `TaskWait` instead of holding the- parent for a full window and beyond.-- Adding an `AgentEvent` variant no longer requires touching the watchdog.+- Keep the allow-list and only lower the default — rejected: liveness stays an+ enumeration that must be revisited as `AgentEvent` grows.+- Raise the idle default and `TaskWait` together — rejected: the idle window must+ stay shorter than a wait.diff --git a/docs/adr/0130-bounded-mounted-transcript-window.md b/docs/adr/0130-bounded-mounted-transcript-window.mdindex c81486ce5..b0c7da100 100644--- a/docs/adr/0130-bounded-mounted-transcript-window.md+++ b/docs/adr/0130-bounded-mounted-transcript-window.md@@ -2,66 +2,92 @@- Status: Accepted- Date: 2026-08-27-- Deciders: PI-Desktop core-- Related: D261, D269, E2E-159, ADR 0120, ADR 0127, D247, D258, D108,- `04-ux/08-component-spec.md`+- Related: ADR 0120, ADR 0127, D108, D247, D258, D261, D269, E2E-159- Amended by: D269 (history continuation and boundary-driven escalation)## Context-ADR 0120 bounded the transcript payload that crosses the IPC boundary, and ADR-0127 / D258 bounded the cost of locating a page inside the JSONL file. Both-addressed session *activation*.--- React element trees for every row,-- a parsed Markdown AST per settled block,-- Shiki `LineCache` token arrays per code fence,-- the DOM nodes themselves.+ADR 0120 bounded the transcript payload crossing IPC and ADR 0127 / D258 bounded+locating a page inside the JSONL file, but neither bounded what the renderer+keeps mounted afterwards: every paged-in row stayed mounted for the session with+its React tree, Markdown AST, Shiki token arrays, and DOM. `content-visibility`+already skips layout and paint for far-offscreen rows, which is a CPU saving and+explicitly not a memory one, and the per-frame memo comparator walked every+mounted entry on each streamed token.## Decision-1. The mounted history is a **trailing window** over the loaded history, not all- of it.-2. Reaching the top **escalates in two stages**.-3. Window growth and a fetched page take the **same pre-paint message anchor**.-4. The window **resets per session** and is clamped to the loaded history, so a- grown budget inherited from the previous session for one frame cannot- over-mount.-5. The hydration spacer stays **scoped to the first commit**.-6. The conversation minimap's **message dashes** are built from the **mounted- entries** (`transcriptEntryMessages`).-6a. **Amended by D269.** Withheld history is represented explicitly instead of-silently: while loaded rows sit above the window (`hiddenAbove > 0`) or the host-reports an older page (`hasMoreBefore`), the rail stays mounted and shows one-dotted earlier-history continuation, even when the mounted tail has fewer than-two message markers or does not overflow one viewport. The continuation runs the-same two-stage escalation as clause 2, so it is always actionable; D108's-two-marker-plus-overflow rule resumes once no earlier history remains. 6b.-7. The entry projection arrays are memoized on `entries`, so a re-render that- changed no message hands `TranscriptHistory` a reference-equal array and its- comparator bails on identity instead of deep-walking the mounted rows.--No IPC, storage, host protocol, or pagination change.-`SESSION_TRANSCRIPT_PAGE_SIZE` and the `session.get` window contract are-untouched.+### 1. The mounted history is a trailing window-## Alternatives considered+`reduceTranscriptWindow` slices the loaded history per render, using+`TRANSCRIPT_INITIAL_MOUNT` rows for the first commit after a session switch and+`TRANSCRIPT_WINDOW_MIN` in steady state.++### 2. Reaching the top escalates in two stages++`growTranscriptWindow` adds cached rows in `TRANSCRIPT_WINDOW_STEP` increments+while the window is partial, and only a window covering all loaded history calls+`loadOlder`, because mounting loaded rows is cheaper than an IPC round trip.++### 3. Growth and fetched pages share one pre-paint anchor++Window growth and a fetched page both restore the visible message's viewport+offset before paint, preferring a message node over an answer-group marker, and+the anchor is owned through IO and three stable layout frames without ever owning+user input. This replaces the old `prependHeightRef` total-height delta, which+deferred DOM, tail updates, and intrinsic-size estimates made unreliable.++### 4. The window resets per session++Resetting and clamping to the loaded history stop a grown budget from the+previous session from over-mounting for a frame.++### 5. The hydration spacer is scoped to the first commit++Kept in steady state it would put a blank viewport between the user and the+growth trigger.++### 6. Minimap message dashes come from mounted entries-- **Rely on `content-visibility` alone:** rejected.-- **Full virtualization with measured row offsets:** rejected for now.-- **Unmount whole rows by distance in both directions:** rejected for the- original row window because removing addressable geometry interferes with- pinned-follow.-- **Cap the loaded history instead, discarding older pages from the store:**- rejected.+Dashes are built from `transcriptEntryMessages`, and a click resolves the+marker's `data-minimap-id` node inside the scroller, so markers for withheld rows+would render dashes that jump nowhere.++### 6a. Withheld history is represented explicitly (amended by D269)++While `hiddenAbove > 0` or the host reports `hasMoreBefore`, the rail shows one+dotted earlier-history continuation that runs the two-stage escalation of clause+2, and D108's two-marker-plus-overflow rule resumes once no earlier history+remains.++### 6b. Hard-edge escalation observes the top boundary (amended by D269)++Escalation reacts to the visibility of the top loading boundary as well as the+near-top check, because an underfilled page, a page whose rows all fall outside+the mounted window, or a window transition can each leave `scrollTop` unchanged.++### 7. The entry projection arrays are memoized on `entries`++An unchanged message list then hands `TranscriptHistory` a reference-equal array+whose comparator bails on identity instead of walking the mounted rows.++No IPC, storage, host protocol, or pagination change; the+`SESSION_TRANSCRIPT_PAGE_SIZE` and `session.get` window contract are untouched.## Consequences-- The initial row window limits cold mounting, but expands as the reader moves- backward.-- Upward travel through a long session costs one frame per growth step before- pagination resumes.-- The browser's native find-in-page reaches only mounted rows.-- Newly mounted rows briefly use the `contain-intrinsic-size` fallback height- before their real size is known, so the scrollbar thumb settles as they enter- view.+- Initial mounting is bounded and expands as the reader moves backward, but this+ is not a ceiling on retained transcript data or addressable row shells.+- Upward travel costs one frame per growth step before pagination resumes, with+ no extra IPC.+- Native find-in-page reaches only mounted rows; in-app search over the full+ transcript is unaffected.++## Alternatives considered++- Rely on `content-visibility` alone: rejected; it retains every row's React+ tree, Markdown AST, and token arrays, so it cannot bound the resource the+ low-memory report was about.+- Full virtualization with measured row offsets: rejected; content-dependent+ heights that change after mount would need a height cache and invalidation for+ all of it.diff --git a/docs/adr/0131-large-text-paste-session-reference.md b/docs/adr/0131-large-text-paste-session-reference.mdindex dd4709c60..a6b898198 100644--- a/docs/adr/0131-large-text-paste-session-reference.md+++ b/docs/adr/0131-large-text-paste-session-reference.md@@ -2,59 +2,50 @@- Status: Accepted- Date: 2026-08-28-- Deciders: PI-Desktop core- Related: Issue #20, D262, ADR 0059, ADR 0070, ADR 0124## Context-Native textarea paste is useful for short prompts, but very large pasted blocks-make the composer difficult to edit and inflate the visible prompt. The-application already has a bounded Electron-to-main paste bridge and a-session-owned scratch directory for clipboard files.+Large pasted text blocks make the composer hard to edit and inflate the visible+prompt, while the application already has a bounded Electron-to-main paste bridge+and a session-owned scratch directory. A solution must preserve the exact bytes,+work at a mid-draft caret, leave the project untouched, and stay addressable by+the existing `@path` file semantics.## Decision-1. Add the persisted `largePasteThreshold` app setting.-2. A text-only paste above the threshold is intercepted by the Composer and sent- through the existing `composer/pasteFiles` bridge as one UTF-8 `text/plain`- file.-3. The Composer inserts `@<temporary-name> ` at the original selection and- stores a renderer-only token-to-canonical-path mapping with the draft.-4. The mapping remains session-scoped, survives project/workspace switches for- its owning session, participates in draft caching and unanswered smart-Stop- restoration, and is removed when the token is removed from the text.-5. Clipboard files and images keep their existing compact chip and structured- attachment flow.+A persisted `largePasteThreshold` app setting (default 600 characters) leaves+shorter text-only pastes on native textarea behavior. A longer one is intercepted+by the Composer, sent through the existing `composer/pasteFiles` bridge as one+UTF-8 `text/plain` file under the session's scratch `pasted/` directory, and+replaced at the original selection by an inline `@<temporary-name> ` token backed+by a renderer-only token-to-canonical-path mapping held with the draft.++The mapping is session-scoped, survives project switches and unanswered smart-Stop+restoration for its owning session, is resolved in place exactly once before+dispatch rather than appended as a second reference, and is dropped with the+token. Clipboard files and images keep their existing compact chip and structured+attachment flow.## Consequences-- Large pasted blocks no longer occupy the editable prompt body; the user sees a- compact, addressable reference at the exact paste position.-- The agent can read the exact saved bytes through the canonical scratch path,- while the project tree, artifact store, and host protocol schema remain- unchanged.-- The setting is backward-compatible because older app settings gain the default- through host normalization rather than a database migration.-- The renderer must retain a small amount of draft metadata to distinguish a- generated inline token from user-authored `@` text and to avoid duplicate- serialization.+- Large blocks leave the editable prompt body and appear as a compact reference at+ the paste position, while the agent reads the exact bytes from the canonical+ scratch path.+- The project tree, artifact store, and host protocol schema are unchanged, and+ older app settings gain the default through host normalization.+- The renderer must retain draft metadata to tell a generated token from+ user-authored `@` text and to avoid duplicate serialization.## Alternatives considered-- **Keep all text inline:** rejected because large blocks remain difficult to- edit and unnecessarily enlarge prompt content.-- **Write directly into the workspace:** rejected because a paste is transient- input and must not dirty the user's project.-- **Use a chip only:** rejected because the requested affordance is an inline- reference at the paste location, and the surrounding draft must remain- readable.-- **Send the token as a basename or append a second path:** rejected because- scratch files require their canonical path and either option can be ambiguous- or duplicate the same input.--## Amendment (2026-09-14): text representation selected beside generated image copies--ADR 0059's #138 amendment can select a text representation for a paste that also-carries `image/*` copies, which is what Word supplies for a copied selection.-That selected text uses this decision's `largePasteThreshold`, so short text-stays editable inline and larger text spills into session scratch as before.+- Keep all text inline: large blocks stay hard to edit and enlarge prompt content.+- Write directly into the workspace: a paste is transient input and must not dirty+ the user's project.++## Amendment (2026-09-14)++ADR 0059's #138 amendment can select a text representation beside generated+`image/*` copies, as Word supplies for a copied selection; that text uses this+decision's `largePasteThreshold`, so short text stays inline and larger text+spills into session scratch.diff --git a/docs/adr/0132-attribute-cross-display-window-moves-to-the-user.md b/docs/adr/0132-attribute-cross-display-window-moves-to-the-user.mdindex 75acf1e5e..1ea9aa059 100644--- a/docs/adr/0132-attribute-cross-display-window-moves-to-the-user.md+++ b/docs/adr/0132-attribute-cross-display-window-moves-to-the-user.md@@ -1,80 +1,49 @@# ADR 0132: Attribute cross-display window moves to the user-- Status: Accepted+- Status: Accepted (amends ADR 0122 and the ADR 0032 reservation behavior it restored)- Date: 2026-08-28-- Related: [01-ipc-protocol](../spec/03-runtime/01-ipc-protocol.md) ·- [09-interaction-patterns §8](../spec/04-ux/09-interaction-patterns.md) ·- decision D263 · issue #18-- Amends: ADR 0122 (and the reservation behavior it restored from ADR 0032)+- Related: D263, ADR 0032, ADR 0122, issue #18## Context-ADR 0122 keeps a target-state, display-aware native reservation for the docked-work panel. Main plans the reservation from remembered *base bounds* — the-window rect without the reservation — and reconciles later native deltas against-the last rect it actually applied.+ADR 0122 keeps a display-aware native reservation for the docked work panel,+planned from remembered base bounds and reconciled against the last applied rect,+but its single `displayChanged` boolean collapsed two opposite situations. Reusing+remembered base bounds is right when the OS re-fitted bounds we asked for and wrong+when the user dragged the window there, so a drag to a second display jumped on+pointer release and the misattribution leaked into `window-state.json`, reopening on+the display the user had left (issue #18).## Decision-1. Replace the `displayChanged` boolean with an explicit `DisplayTransition` of- `none`, `os-adjusted`, or `user-moved`.-2. `os-adjusted` keeps ADR 0122's behavior unchanged: the remembered base bounds- survive an OS re-fit or a display topology change.-3. `user-moved` derives new base bounds from the window's current position, so- the drop position becomes the intent.-4. Classify the transition by whether an unaccounted native `move` stream- precedes it.-5. Never re-plan bounds mid-drag.-6. Persist base bounds for both `none` and `user-moved`, and advance the- remembered display key on `user-moved`, so relaunch restores the display the- user actually left the window on.-7. Retire an unconsumed marker on a deadline.-8. A forced bounds recovery (the Stage Manager path) clears the pending- user-move attribution, because it is not user intent.+Replace the `displayChanged` boolean with an explicit `DisplayTransition` of `none`,+`os-adjusted`, or `user-moved`, where `os-adjusted` keeps ADR 0122's behavior so+remembered base bounds survive an OS re-fit or topology change, and `user-moved`+derives new base bounds from the current position so the drop position becomes the+intent, normalizing only the origin into the target work area and preserving size+even when that work area is smaller. A transition counts as `user-moved` when an+unaccounted native `move` stream precedes it: the marker is a flag rather than a+deadline, so attribution never depends on main-process scheduling, and the `move`+handler never re-plans mid-drag but defers reconciliation until the stream goes+quiet. Base bounds persist for `none` and `user-moved` with the remembered display+key advanced on `user-moved`, `os-adjusted` still refuses to persist, an unconsumed+marker retires on a deadline that only bounds lingering, and a forced bounds+recovery clears the pending attribution because it is not user intent.## Consequences-- Dragging the window between displays keeps the position where it was dropped,- with no jump on pointer release.-- Relaunch reopens the window on the display it was last used on.-- ADR 0122's constrained-display reservation behavior is preserved verbatim for- OS-owned adjustments, including the restore path back to a roomy display.-- Display topology events clear the pending marker before reconciling, so a- display added, removed, or rescaled right after a drag is still classified as- OS-owned.-- A window dropped onto a display whose work area cannot hold it keeps its size- and is pinned to the work area's top-left.+- Dragging between displays keeps the drop position with no jump, and relaunch+ reopens on the display the window was last used on.+- Topology events clear the marker first, so ADR 0122's constrained-display+ behavior is preserved for OS-owned adjustments.+- A window dropped onto a smaller display keeps its size, pinned to the work area's+ top-left, while `planWorkPanelReservation` shrinks the reservation; no IPC,+ storage, or host protocol change, and `window/setWorkPanelReservation` keeps its+ request and response shape.## Alternatives-### Clamp the remembered base bounds into the new display--Rejected. It keeps the window on the target display but discards the drop-position, which is the reported symptom rather than a fix for it.--### Skip reservation planning entirely on a display change--Rejected. The reservation would then be sized for the previous display's work-area, so a narrower target display would leave the window wider than its work-area.--### Detect drags from pointer state instead of the move stream--Rejected for now. Electron exposes no drag-begin/drag-end pair for native window-moves, and polling the pointer during a drag costs more than the pending-move-marker it would replace.--### Attribute the drag with a time deadline--Rejected. A deadline makes correctness depend on main-process scheduling: a busy-main process, or a maximized window that defers its geometry past the deadline,-would silently fall back to the buggy OS-adjusted path.--## References--- `apps/desktop/electron/main/work-panel-window.ts`-- `apps/desktop/electron/main/index.ts`-- `apps/desktop/test/work-panel-window.test.mjs`-- `docs/adr/0122-reserve-native-width-while-work-panel-visible.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-160)-- `docs/spec/08-meta/decisions-log.md` (D263)+- Clamp remembered base bounds into the new display: keeps the window on the target+ display but discards the drop position.+- Attribute the drag with a time deadline: correctness would depend on main-process+ scheduling.diff --git a/docs/adr/0133-models-dev-primary-catalog-with-pi-fallback.md b/docs/adr/0133-models-dev-primary-catalog-with-pi-fallback.mdindex 012a79f76..34a16347c 100644--- a/docs/adr/0133-models-dev-primary-catalog-with-pi-fallback.md+++ b/docs/adr/0133-models-dev-primary-catalog-with-pi-fallback.md@@ -2,77 +2,58 @@- Status: Superseded for chat metadata by [models.dev catalog authority](models-dev-catalog-authority.md)- Date: 2026-08-29-- Deciders: PI-Desktop core- Amends: ADR 0027, D136, D243## Context-PI-Desktop's pinned `@earendil-works/pi-ai` package provides high-quality-runtime adapters and a useful built-in model catalog, but its model coverage and-release cadence do not represent the full current market. Provider settings-therefore cannot reliably offer current model names, limits, modalities, or-capability flags from the catalog users expect.+The pinned `@earendil-works/pi-ai` package offers good runtime adapters and a+useful built-in catalog, but its model coverage and release cadence do not match+the current market. Model metadata must stay outside the renderer, provider+credentials must never reach a catalog service, and custom or local providers+must remain usable when no public catalog knows them.## Decision-Use `https://models.dev/api.json` as the primary remote model catalog.--1. Electron main fetches the fixed URL with a bounded timeout and parses only- the provider/model fields needed by PI-Desktop.-2. A models.dev provider is matched by configured `vendorKey` first and by a- normalized provider API URL second.-3. Catalog precedence for a configured model is: `models.dev` → `pi-ai` →- provider endpoint discovery → generic defaults.-4. The existing `ModelBinding` remains the explicit user configuration for a- selected provider/model.-5. The remote snapshot is loaded at most once per Electron process unless an- explicit future refresh policy replaces it.-6. `ModelInfo.catalogSource` is a renderer-facing annotation only.--Models.dev reasoning options map to the canonical PI-Desktop levels: effort-values are retained when recognized (`none` becomes `off`); toggle and token-budget options use `off` plus `medium` as the enabled representative; a-reasoning record without a level list uses the conservative-`low`/`medium`/`high` set. Entries whose input or output modalities are not text-are not offered in the text agent model picker.+`https://models.dev/api.json` is the primary remote model catalog, fetched and+parsed by Electron main only with a bounded timeout and without any provider+credential.++1. A models.dev provider is matched by configured `vendorKey` first and by a+ normalized provider API URL second; an exact model ID match supplies the+ display name, context and output limits, input modalities, price hints,+ reasoning options, and the tool-call and structured-output flags.+2. Catalog precedence is `models.dev` → `pi-ai` → provider endpoint discovery →+ generic defaults, with pi-ai remaining the adapter-specific fallback and+ discovery covering custom and account-specific ids.+3. The existing `ModelBinding` stays the explicit user configuration: catalog+ data supplies defaults and capability metadata, while binding edits keep+ controlling configured limits and enabled thinking levels.+4. The snapshot loads at most once per Electron process, a failed fetch keeps+ the last successful in-memory snapshot and the Rust-owned provider cache, and+ `ModelInfo.catalogSource` records `models.dev` or `pi-ai` as a+ renderer-facing annotation only.++models.dev reasoning options map to canonical levels — recognized effort values+are kept (`none` becomes `off`), toggle and token-budget options use `off` plus+`medium`, and a reasoning record without a level list uses+`low`/`medium`/`high` — and entries whose modalities are not text are not offered+in the text agent model picker.## Consequences-- Settings and Composer can use a current broad provider/model catalog without- shipping a large static matrix in the application.-- Offline and unavailable-catalog operation remains possible through cached- provider rows, pi-ai's bundled catalog, provider discovery, and free-form- model IDs.-- The remote catalog can update names and limits independently of an app- release, so fixture-based parser and precedence tests are required.-- models.dev does not define provider wire adapters.-- A remote catalog outage is non-fatal and must not erase user-selected bindings- or credentials.+- Settings and Composer gain a current broad catalog without a large static+ matrix, and offline operation still works through cached rows, pi-ai,+ discovery, and free-form model ids.+- The catalog can change independently of an app release, so parser and+ precedence fixtures are required, and an outage must never erase+ user-selected bindings or credentials.+- models.dev defines no wire adapters: pi-ai compatibility data still governs+ request serialization, and a catalog entry cannot grant an unsupported+ transport to an unknown id.## Alternatives-### Keep pi-ai as the sole catalog--Rejected because its native catalog is narrower and can lag models.dev's market-coverage, despite remaining the best local fallback and adapter source.--### Fetch models.dev in the renderer--Rejected because catalog loading belongs to Electron main, keeps one network-boundary, and avoids mixing provider credentials or remote response handling-with renderer state.--### Replace provider discovery entirely--Rejected because custom/local endpoints and authenticated vendor catalogs can-expose models not present in a public catalog.--## References--- `apps/desktop/electron/main/models-dev-catalog.ts`-- `apps/desktop/electron/main/index.ts`-- `packages/agent-runtime/src/model-capabilities.ts`-- `docs/spec/03-runtime/11-provider-model-system.md`-- `docs/spec/03-runtime/12-provider-config-schema.md`-- `docs/spec/03-runtime/13-model-catalog-and-selection.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-066, E2E-080, E2E-154)+- Keep pi-ai as the sole catalog: its native catalog is narrower and lags+ models.dev coverage.+- Fetch models.dev in the renderer: catalog loading belongs to Electron main,+ which keeps one network boundary and remote handling out of renderer state.diff --git a/docs/adr/0134-models-dev-sole-model-metadata-source.md b/docs/adr/0134-models-dev-sole-model-metadata-source.mdindex e303b63e3..56d4cf7be 100644--- a/docs/adr/0134-models-dev-sole-model-metadata-source.md+++ b/docs/adr/0134-models-dev-sole-model-metadata-source.md@@ -1,93 +1,63 @@# ADR 0134: Use models.dev as the sole model metadata source with a local snapshot-- Status: Superseded for chat metadata by [models.dev catalog authority](models-dev-catalog-authority.md)+- Status: Superseded for chat metadata by+ [models.dev catalog authority](models-dev-catalog-authority.md); amends+ ADR 0027, ADR 0133, D136, D266- Date: 2026-08-29-- Deciders: PI-Desktop core-- Amends: ADR 0027, ADR 0133, D136, D266+- Related: D136, D266, ADR 0027, ADR 0133## ContextThe first models.dev integration still retained a second model metadata path in-pi-ai. That made it possible for a package upgrade or a provider-specific pi-record to change the model name, capabilities, limits, thinking levels, input-modes, or prices that PI-Desktop presented and sent to the sidecar.+pi-ai, so a package upgrade or a provider-specific pi record could change the+model name, capabilities, limits, thinking levels, input modes, or prices that+PI-Desktop presented and sent to the sidecar, and it did not persist the complete+public models.dev document, so model updates depended on the process staying+online.## Decision`https://models.dev/api.json` is the only model metadata/configuration source.--1. Electron main reads the bundled public document from- `resources/models.dev/api.json` in development and- `<resources>/models.dev/api.json` in packaged builds.-2. `scripts/release.mjs <version> --tag` fetches `https://models.dev/api.json`,- validates it, atomically replaces the checked-in resource, and includes that- file in the release commit before tagging.-3. On startup, Electron reads the bundled snapshot without network I/O.-4. The parser maps all supported models.dev fields into the existing `ModelInfo`- and sidecar `ModelConfig`: `id`, `name`, `description`, `family`,- `attachment`, `reasoning`, `reasoning_options`, `tool_call`,- `structured_output`, `temperature`, `knowledge`, `release_date`,- `last_updated`, `modalities.input/output`, `open_weights`, `limit.context` /- `input` / `output`, `cost` including audio/reasoning/cache/tier prices,- `interleaved`, `status`, `experimental`, and `provider`.-5. The runtime passes the models.dev `ModelConfig` to pi-ai's selected wire- adapter. pi-ai remains an implementation dependency for request- serialization, OAuth login/account availability, and stream handling only;- its builtin model catalog and model capability functions are not consulted.-6. A model absent from models.dev remains runnable through an explicit generic- text model shape with conservative limits and no reasoning/vision claims.--Models.dev reasoning mappings retain `effort` values that match the canonical-levels (`none` → `off`), map `toggle`/`budget_tokens` to `off` + `medium`, and-use `low`/`medium`/`high` when a reasoning record has no usable level list.-Input and output modality arrays retain `text`, `image`, `audio`, `video`, and-`pdf`; the current text agent picker excludes models that cannot accept and-produce text, while the raw bundled snapshot keeps those records for future-surfaces.+Electron main reads the bundled public document from+`resources/models.dev/api.json` in development and `<resources>/models.dev/api.json`+in packaged builds — part of the release artifact, not the user data directory —+and `scripts/release.mjs <version> --tag` fetches, validates, and atomically+replaces that checked-in resource before tagging. Startup reads the snapshot+without network I/O; Settings → Model configuration exposes **Refresh model+catalog**, which refetches the URL into the in-memory snapshot for the current+process only, never writing the packaged file or a user cache. The parser maps+every supported models.dev field into `ModelInfo` and the sidecar `ModelConfig`,+and provider/model matching accepts the configured vendor key, normalized API URL,+catalog provider identity, and unambiguous vendor-prefixed IDs without changing+the user-visible ID. The runtime passes the models.dev `ModelConfig` to pi-ai's+selected wire adapter, leaving pi-ai an implementation dependency for request+serialization, OAuth login and account availability, and stream handling only,+with its builtin model catalog and capability functions unconsulted. A model+absent from models.dev remains runnable through an explicit generic text model+shape with conservative limits and no reasoning or vision claims, and provider+`/models` discovery or authenticated OAuth availability may supply unlisted IDs+but cannot invent metadata.++Reasoning mappings keep `effort` values matching the canonical levels (`none` →+`off`), map `toggle` and `budget_tokens` to `off` plus `medium`, and fall back to+`low`/`medium`/`high` without a usable level list; modality arrays keep `text`,+`image`, `audio`, `video`, and `pdf`, while the text agent picker excludes models+that cannot accept and produce text.## Consequences-- Model metadata has one authoritative source and is reproducible offline from- the checked-in release resource.-- Every release refreshes the catalog before tag creation without requiring a- database or host-core schema migration.-- Settings can fetch a newer snapshot immediately for the current process; the- next app launch returns to the bundled release snapshot until a new release is- shipped.-- Provider bindings remain user-owned selections/overrides; the catalog owns+- Model metadata has one authoritative source and is reproducible offline from the+ checked-in release resource, which every release refreshes without a schema+ migration.+- Settings can fetch a newer snapshot for the current process; the next launch+ returns to the bundled release snapshot, and models.dev outages preserve the last+ local snapshot.+- Provider bindings stay user-owned selections and overrides: the catalog ownspublished model semantics and the generic fallback owns unknown IDs.-- Models.dev outages preserve the last local snapshot, provider endpoint- discovery, and explicit custom IDs.## Alternatives-### Keep pi-ai as a model metadata fallback--Rejected: it creates a second authority and allows package updates to silently-change the model configuration selected by the user.--### Keep a user-data snapshot--Rejected: the release artifact must be reproducible and the user cache would-make different installations use different model configuration.--### Fetch only when a provider dialog opens--Rejected: model capability state is also needed by Composer and runtime launch;-the bundled release snapshot gives all surfaces one deterministic baseline.--## References--- `scripts/release.mjs` (release-time catalog refresh)-- `apps/desktop/resources/models.dev/api.json` (bundled snapshot)-- `apps/desktop/electron/main/models-dev-catalog.ts` (catalog parsing and- refresh)-- `apps/desktop/electron/main/index.ts` (main-process loading and IPC)-- `apps/desktop/src/components/settings/ModelConfigPage.tsx` (settings refresh- action)-- `packages/agent-runtime/src/model-capabilities.ts`-- `packages/agent-runtime/src/provider-binding.ts`-- `docs/spec/03-runtime/11-provider-model-system.md`-- `docs/spec/03-runtime/12-provider-config-schema.md`-- `docs/spec/03-runtime/13-model-catalog-and-selection.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-066, E2E-080, E2E-154)+- Keep pi-ai as a metadata fallback: it creates a second authority and lets package+ updates silently change the configuration the user selected.+- Keep a user-data snapshot: the release artifact must be reproducible, and a user+ cache would make installations diverge.diff --git a/docs/adr/0135-retry-unchanged-edited-prompts.md b/docs/adr/0135-retry-unchanged-edited-prompts.mdindex 5879b946a..b159ef8d0 100644--- a/docs/adr/0135-retry-unchanged-edited-prompts.md+++ b/docs/adr/0135-retry-unchanged-edited-prompts.md@@ -2,54 +2,35 @@- Status: Accepted- Date: 2026-08-31-- Deciders: PI-Desktop core- Related: D137, D274, E2E-073, issue #23- Amends: D137## ContextThe user-message editor is an edit-and-resend workflow, but its primary action-was labeled Send and treated an unchanged prompt as a no-op. That made a-confirmation with the original text appear broken even though the user had-explicitly asked to replay the selected turn.+was labeled Send and treated an unchanged prompt as a no-op, so an explicit+request to replay a turn appeared inert.## Decision-1. Confirming a valid user-prompt edit always dispatches the existing- `editUserMessage` / Regenerate path, whether or not the trimmed prompt text- differs from the original.-2. The inline primary action is localized as Retry (`重试` in zh-CN); its- in-flight label is Retrying… (`重试中…`).-3. Retry retains the existing attachment handling, slash-command expansion,- identity-based truncation, and D109 revision archive.+Confirming a valid user-prompt edit always dispatches the existing+`editUserMessage` / Regenerate path whether or not the text changed, with the+inline primary action localized as Retry and Cmd/Ctrl+Enter invoking it, while+Escape and Cancel keep their cancel behavior. Retry retains the existing+attachment handling, slash-command expansion, identity-based truncation, and+D109 revision archive, and adds no IPC, storage, host-protocol, or runtime+contract change.## Consequences-- Replaying an unchanged prompt creates a fresh assistant turn and archives the- replaced answer tail in the existing revision pager, matching the action's- resend semantics.-- The inline labels distinguish retrying the selected turn from sending a new- composer prompt and from cancelling the edit.-- A user can still abandon the edit without changing the transcript through- Escape or Cancel.+- Replaying an unchanged prompt creates a fresh assistant turn and archives+ the replaced answer tail in the existing revision pager.+- The labels distinguish retrying a turn from sending a new prompt and from+ cancelling the edit.## Alternatives-### Keep unchanged edits as a no-op--Rejected. It is the behavior reported in issue #23 and makes an explicit resend-confirmation appear inert.--### Keep the primary label as Send--Rejected. The action does not append a new ordinary prompt; it replays the-selected prompt through the Regenerate path.--## References--- `apps/desktop/src/components/ChatTranscript.tsx`-- `packages/i18n/src/locales/en/index.ts`-- `packages/i18n/src/locales/zh-CN/index.ts`-- `docs/spec/04-ux/08-component-spec.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-073)-- `docs/spec/08-meta/decisions-log.md` (D274)+- Keep unchanged edits as a no-op: rejected, it is the behavior reported in+ issue #23.+- Keep the primary label as Send: rejected, the action replays the selected+ prompt through Regenerate rather than appending a new one.diff --git a/docs/adr/0136-active-task-boundary-across-compaction.md b/docs/adr/0136-active-task-boundary-across-compaction.mdindex 8f380c6ed..29f219bff 100644--- a/docs/adr/0136-active-task-boundary-across-compaction.md+++ b/docs/adr/0136-active-task-boundary-across-compaction.md@@ -2,41 +2,38 @@- Status: Accepted- Date: 2026-08-31-- Deciders: PI-Desktop core- Amends: ADR 0064 / D203## ContextCodex-shaped compaction kept several recent user prompts while dropping the-assistant and tool messages that established whether those prompts were-completed. After a completed task, the next prompt could therefore look like-another bare user message and the model could resume an old task (issue #22).+assistant and tool messages that established whether they were completed, so after+a finished task the next prompt could look like another bare user message and the+model resumed the old task (issue #22).## Decision-1. Checkpoints carry opaque `details.retainedTailMode`, either `active_turn` or- `completed_turn`.-2. An active-turn checkpoint is used when the provider must continue after a- tool result, `toolUse`, or overflow recovery.-3. A completed-turn checkpoint is used at a terminal turn boundary, before a new- prompt, and for manual compaction.-4. The `fresh_window` family remains the ADR 0064 no-summary exception and- always carries an empty tail.-5. Legacy checkpoints without this field are normalized to their latest user- message only.+Checkpoints carry an opaque `details.retainedTailMode` of `active_turn` or+`completed_turn`. An active-turn checkpoint, used when the provider must continue+after a tool result, `toolUse`, or overflow recovery, retains only the latest user+message under the existing 20,000-token cap; a completed-turn checkpoint, used at+a terminal boundary, before a new prompt, and for manual compaction, retains an+empty tail so the summary is authoritative. The `fresh_window` family stays the+ADR 0064 no-summary exception, and legacy checkpoints without the field normalize+to their latest user message, leaving the transcript and checkpoint chain+unchanged.## Consequences-- Completed user requests cannot be replayed as naked historical context after+- Completed requests cannot be replayed as naked historical context aftercompaction or restart.-- Active tool loops retain the one prompt needed to continue the current task,- while assistant/tool messages remain represented by the summary.-- Existing checkpoints remain readable without a migration, with a conservative- latest-user fallback.+- Active tool loops keep the one prompt needed to continue, with assistant and+ tool messages represented by the summary.+- Existing checkpoints stay readable without a migration.## Alternatives-- Retaining multiple recent user messages preserves more literal prompt text,- but loses the task boundary when completion messages are compacted away.-- Retaining assistant and tool messages would preserve more context but can- strand incomplete tool calls and violates the Codex-shaped checkpoint form.+- Retain multiple recent user messages: more literal prompt text, but the task+ boundary is lost once completion messages are compacted away.+- Retain assistant and tool messages: more context, but it can strand incomplete+ tool calls and breaks the Codex-shaped checkpoint form.diff --git a/docs/adr/0137-retained-session-panes.md b/docs/adr/0137-retained-session-panes.mdindex f5a100302..c9ab6b9d9 100644--- a/docs/adr/0137-retained-session-panes.md+++ b/docs/adr/0137-retained-session-panes.md@@ -2,84 +2,71 @@- Status: Accepted- Date: 2026-08-30-- Deciders: PI-Desktop core-- Related: D162, D261, D317, D324, ADR 0120, ADR 0127, ADR 0130, D142,- `04-ux/08-component-spec.md` §3.5 / §7, `04-ux/09-interaction-patterns.md` §5,- E2E-011, E2E-071d, E2E-071g, E2E-177, E2E-183+- Related: ADR 0120, ADR 0127, ADR 0130, D142, D162, D261, D317, D324- Amends: D162 (the dimmed keep-alive frame), ADR 0130 clause 4 and clause 5(per-session window reset and first-commit hydration), D162's"activation resets manual-scroll state" rule for revisits## Context-D162 already avoided the worst session-switch artifact: it kept the last settled-transcript mounted instead of tearing it down to a skeleton. The switch still-flashed, because keeping *a* transcript mounted is not the same as keeping *the-destination's* transcript mounted.--- The kept frame was **dimmed** (`opacity: .82`, `pointer-events: none`) under a- thin progress track.-- **Scroll position was not the pane's**.-- The **two-stage progressive hydration** of ADR 0130 clause 5 ran on every- switch: mount the trailing 15 rows for one frame behind a `100vh` spacer, then- expand in a rAF and re-anchor.+D162 kept the last settled transcript mounted, but the store held one `messages`+array for the active session and one `ChatTranscript` instance served every+session, so a switch replaced the array, reset scroll, window, and hydration by+hand, remounted every row, and reparsed Markdown for content already in memory.+The kept frame was dimmed behind a progress track, scroll position was never the+destination pane's own, and two-stage progressive hydration ran on every switch.## Decision-1. `ChatSurface` mounts one **`SessionPane` per retained session id**, keyed by- session id.-2. Retention is a **bounded LRU of 3 panes**: the visible one plus the two most- recently visited.-3. An inactive pane stays mounted, hidden with `visibility: hidden` +- `content-visibility: hidden`, `aria-hidden`, and non-interactive.-4. `messages` remains the **live projection of the store-active session**.-5. A **warm switch** — the destination already has a retained pane — reveals- that pane immediately from its retained content.-6. A **cold switch** — no retained pane — keeps the currently visible pane- showing its own session until the destination commits.-7. **DOM retention is per pane; reading retention is per session.** A pane still- pinned re-anchors to the bottom.-8. The **first commit is per pane and local**.-9. The **composer is mounted once** for the whole chat surface rather than once- per branch — it already carries a per-session draft cache.+1. `ChatSurface` mounts one `SessionPane` per retained session id, keyed by+ session id. A pane owns its transcript DOM, scroll position, and mounted-row+ window for its lifetime, so a switch is a visibility swap, not a rebuild.+2. Retention is a bounded LRU of three panes: the visible one plus the two most+ recently visited. `retainedSessionIds` holds that order in the store and+ eviction unmounts the oldest pane.+3. An inactive pane stays mounted, hidden with `visibility: hidden` and+ `content-visibility: hidden`, `aria-hidden`, and non-interactive. It is+ explicitly not `display: none`, which destroys the layout box that holds+ `scrollTop`.+4. `messages` remains the live projection of the store-active session, and a+ bounded `retainedTranscripts` record gives every pane its own snapshot, so no+ pane renders another session's rows.+5. A warm switch reveals the destination pane immediately from retained content,+ with no dim, skeleton, or remount, and the revalidated transcript lands in the+ same pane afterwards without a visible change. For a running session, or a+ completed reply the durable page has not caught up to, revalidation stitches+ the bounded durable page onto the live snapshot in chronological order.+6. A cold switch keeps the currently visible pane showing its own session until+ the destination commits, marked only by the thin progress track; the opacity+ dim is removed entirely.+7. DOM retention is per pane, reading retention is per session. Runtime+ bookmarks keep a message id, viewport offset, window budget, and disclosure+ choices independently of eviction or project switches, hold no message bodies+ or DOM, and are released on session deletion or renderer and app restart.+8. First-commit hydration is per pane and local, so the cross-session spacer, its+ rAF expansion, and its re-anchor are deleted, while ADR 0130's trailing window,+ two-stage escalation, and prepend anchor stay inside a pane.+9. The composer mounts once for the whole chat surface with its per-session draft+ cache, and stays non-interactive while the visible pane is not yet the+ store-active session, so a prompt cannot be sent to the session being left.-No IPC, storage, host protocol, or pagination change. Transcript reads, the-latest-wins navigation generation, and the five-snapshot transcript cache of-D162 are untouched; panes are a renderer-side presentation bound, not a second-cache.+No IPC, storage, host protocol, or pagination change; panes are a renderer-side+presentation bound, not a second cache.## Consequences-- Retained renderer memory grows by at most two extra mounted transcripts, each- itself bounded by ADR 0130's window.-- A revisit within the budget costs no Markdown parse, no Shiki tokenization,- and no scroll correction — the frame the user left is the frame they return- to.-- Deleted: the `session-switching` opacity dim, the session-loading skeleton- path, the cross-session scroll/window/hydration resets inside- `ChatTranscript`, the `100vh` hydration spacer, and the per-branch composer- mount.-- Four invariants callers must keep:- - **Cross-session events must not write the visible projection.** Background- message, tool, and completion events update their own session's snapshot- only; writing `messages` from a non-store-active session would paint another- session's rows into the visible pane.- - **Deleting a session must release its pane.** Removing a session drops its- `retainedTranscripts` entry and its `retainedSessionIds` slot, so no pane- outlives its session or holds a snapshot of deleted history.- - **Leaving the chat with no active session must drop every pane.** Switching- or clearing the project makes the retained sessions unreachable.- - **A hidden pane performs no reading work.** Follow scrolling, history- pagination, and row-position measurement all depend on a rendered scroller;- a hidden pane's scroller reports `scrollTop === 0`, which reads as "at the- top" and would page history for a session nobody is looking at.-- Per-session scroll retention **supersedes** the older rule that activation- resets inherited manual-scroll state, for revisits: a revisited pane is- expected to return to where the user left it.+- A revisit within the budget costs no Markdown parse, no tokenization, and no+ scroll correction, at the cost of at most two extra mounted transcripts, each+ bounded by ADR 0130's window.+- Callers must keep three invariants: cross-session events update only their own+ snapshot, deleting a session or leaving the project releases its pane, and a+ hidden pane performs no reading work because its scroller reports the top.+- Per-session scroll retention supersedes the older activation reset for revisits;+ an evicted session rebuilds a bounded pane but restores its reading bookmark.-## Alternatives considered+## Alternatives-- **Replace `messages` with a per-session message map:** rejected.-- **Deep-equality reuse of the cached array:** rejected.-- **Keep the dim, only skip it when the cache is warm:** rejected.-- **Retain every visited session's pane:** rejected.+- Replace `messages` with a per-session message map: rejected because a single+ transcript instance still swaps content, so remount and rebuild survive.+- Retain every visited session's pane: rejected because unbounded panes restore+ exactly the retention ADR 0130 removed.diff --git a/docs/adr/0138-subagent-peer-messaging.md b/docs/adr/0138-subagent-peer-messaging.mdindex a5e84af9f..93d018676 100644--- a/docs/adr/0138-subagent-peer-messaging.md+++ b/docs/adr/0138-subagent-peer-messaging.md@@ -2,38 +2,30 @@- Status: Superseded by ADR 0147- Date: 2026-08-31-- Deciders: PI-Desktop core-- Related: D201, D277, ADR 0062, ADR 0089, ADR 0100, ADR 0140, ADR 0147,- `03-runtime/02-agent-runtime.md` §5f / §5f.2, E2E-165+- Related: ADR 0062, ADR 0089, ADR 0100, ADR 0140, ADR 0147, D201, D277- Amends: nothing. ADR 0062's parent-only integration point and ADR 0089'sbackground delegation lifecycle are both preserved; this adds an opt-insibling channel beside them.-> Superseded by ADR 0147. The in-process `SubagentMailbox` and the peer tools-> this ADR introduced are removed and replaced by the A2A protocol stack: a-> host-core broker with durable tasks, typed message parts, agent-card-> discovery, and capability-token authorization over the existing JSON-RPC-> transport. Retained because the coordination failures it documents — stale-> premises under the path lock, disproved shared assumptions, duplicated-> searches — are exactly what the A2A stack now addresses, and because the-> invariants it froze (no forged sender, delegate-only tool, settled delegates-> leave) carry forward unchanged.-## Context-Delegation as built by ADR 0062 and ADR 0089 has exactly one integration point:-the parent.--- Two write-capable delegates discover mid-run that they need the same file.-- One delegate disproves an assumption every brief was written against.-- One delegate has already found the fact another is about to spend fifteen tool- calls searching for.+Delegates only talked to the parent, so concurrent workers could not correct a+stale premise, disprove a shared assumption, or share a fact before each of them+paid for the same search, while routing notes through the parent was blocked by+`TaskWait` and would defeat the point of delegation.## Decision-Add a **session-scoped peer mailbox** and three delegate-only tools, opt-in per-definition.+Add a session-scoped `SubagentMailbox` with three opt-in, delegate-only tools —+`PeerSend`, `PeerInbox`, and `PeerWait` — addressed by per-delegation peer id,+with the sender bound at spawn time, bounded message and send counts, destructive+draining, and membership tied to running delegates.## Consequences-Superseded (Superseded by ADR 0147). The full record is in git history.+Superseded by ADR 0147, which removed the in-process mailbox and these tools in+favor of the A2A stack: a host-core broker with durable tasks, typed message+parts, agent-card discovery, and capability-token authorization. The invariants+this record froze carry forward unchanged — no forged sender, delegate-only+tools, and departed delegates leave the mailbox — and the coordination failures it+documented are what A2A now addresses.diff --git a/docs/adr/0140-peer-tool-consolidation.md b/docs/adr/0140-peer-tool-consolidation.mdindex 47f64c83f..88e2802a0 100644--- a/docs/adr/0140-peer-tool-consolidation.md+++ b/docs/adr/0140-peer-tool-consolidation.md@@ -5,27 +5,27 @@- Deciders: PI-Desktop core- Related: D277, ADR 0138, ADR 0062, ADR 0089, ADR 0147,`03-runtime/02-agent-runtime.md` §5f, E2E-165, E2E-165b-- Amends: ADR 0138 clauses 2 and 3. The mailbox semantics, the caps, and every- boundary ADR 0138 established are unchanged; this decision only changes the- *tool surface* a delegate declares and calls.+- Amends: ADR 0138 clauses 2 and 3; the mailbox semantics, caps, and every other+ boundary ADR 0138 established stay unchanged.-> Superseded by ADR 0147. The single `Peer` tool this ADR settled on is-> replaced by the `A2A` tool (actions `discover | send | get | wait | cancel`)-> against a host-core A2A broker. Retained because the counting argument for one-> tool over three carries into the A2A tool surface, and because-> `SUBAGENT_A2A_TOOLS = ["A2A"]` is the direct successor of the-> `SUBAGENT_PEER_TOOLS = ["Peer"]` mapping this ADR defined.+> Superseded by ADR 0147, which replaces the single `Peer` tool with the `A2A`+> tool (actions `discover | send | get | wait | cancel`) against a host-core A2A+> broker. Retained because the counting argument for one tool over three carries+> into that surface, and `SUBAGENT_A2A_TOOLS = ["A2A"]` directly succeeds the+> `SUBAGENT_PEER_TOOLS = ["Peer"]` mapping defined here.## ContextADR 0138 introduced peer messaging as three delegate-only tools — `PeerSend`,-`PeerInbox` and `PeerWait` — declarable in a definition's `tools:` list.+`PeerInbox`, and `PeerWait` — so an opting-in delegate declared three names for+one capability, inflating declared tool counts and the parent's `Task` catalog.+The operations are mutually exclusive per call, which is the shape an `action`+parameter serves.## Decision-Fold the three tools into **one `Peer` tool** selected by a required `action`-parameter:--## Consequences--Superseded (Superseded by ADR 0147). The full record is in git history.+Fold them into one **`Peer`** tool selected by a required `action` of `send`,+`inbox`, or `wait`. `SUBAGENT_PEER_TOOLS` became `["Peer"]`, an omitted or+unknown `action` fell back to the never-blocking `inbox`, and the tool stayed+built per delegate, closed over the runtime-supplied peer id, and absent from+`toolCatalog`.diff --git a/docs/adr/0141-sidebar-width-resize.md b/docs/adr/0141-sidebar-width-resize.mdindex c58cf780d..9d731defc 100644--- a/docs/adr/0141-sidebar-width-resize.md+++ b/docs/adr/0141-sidebar-width-resize.md@@ -5,33 +5,25 @@## Context-The sidebar's fixed expanded width makes long project names and session titles-hard to inspect, while a permanently wider sidebar wastes space for compact-workspaces. The shell already owns sidebar layout and collapse state, so width-preference state belongs at the same renderer boundary.+A fixed expanded sidebar width makes long project names and session titles hard+to inspect, while a permanently wider sidebar wastes space in compact+workspaces.## Decision-The expanded sidebar exposes a resize handle on its right edge. Pointer motion-previews a width anchored to the pointer-down position and the main pane reflows-continuously.--The handle is an ARIA vertical separator. It supports ArrowLeft/ArrowRight with-16px steps, Home, and End.+The expanded sidebar exposes a resize handle on its right edge: pointer motion+previews a clamped width while the main pane reflows, only pointer release+persists it in the sidebar renderer preference storage, and the handle is an+ARIA vertical separator with arrow, Home, and End steps where Escape or+cancellation restores the pointer-down width.## Consequences-- Users can choose a comfortable sidebar width without changing native window- bounds or work-panel reservation behavior.-- The renderer remains the sole owner of sidebar width, avoiding a new IPC- contract and keeping native window edge resize independent.-- A small edge hit area and visible focus/hover rule add a discoverable control- without changing the dense sidebar row layout.+- Users pick a comfortable width without touching native window bounds, and the+ renderer stays the sole owner so no IPC contract is added.+- Collapsing preserves the preferred width.-## Alternatives considered+## Alternatives-- Fixed width: rejected because it prevents users from accommodating long- project/session labels or reclaiming unused sidebar space.-- Native window reservation or a second resize channel: rejected because the- sidebar is an in-flow renderer column and its width should only reflow the- main pane.+- A second resize channel from the native window: rejected, the sidebar is an+ in-flow renderer column that should only reflow the main pane.diff --git a/docs/adr/0142-allow-non-loopback-http-mcp.md b/docs/adr/0142-allow-non-loopback-http-mcp.mdindex ac216812c..a2ab400b3 100644--- a/docs/adr/0142-allow-non-loopback-http-mcp.md+++ b/docs/adr/0142-allow-non-loopback-http-mcp.md@@ -6,29 +6,30 @@## Context-Self-hosted MCP servers are often deployed on a private LAN and expose only a-plain HTTP endpoint. The existing MCP client already speaks streamable HTTP, but-validation rejects every non-loopback `http://` URL.+Self-hosted MCP servers often sit on a private LAN behind plain HTTP, and the MCP+client already speaks streamable HTTP, yet validation rejected every non-loopback+`http://` URL, including servers the user had deliberately configured. Removing+that restriction must not remove the plugin permission or the egress boundary,+because an HTTP endpoint observes credentials, tool arguments, and results without+confidentiality or integrity.## Decision1. User-owned and plugin-declared MCP servers accept absolute `http://` and- `https://` URLs.-2. The user MCP editor displays an explicit warning for non-loopback HTTP:- credentials and tool calls may be intercepted.-3. A plugin-declared HTTP MCP server still requires `mcp.server.remote` and its- host must be covered by `manifest.net.domains`.-4. The MCP HTTP client disables automatic redirect following, limits redirects- to five hops, permits only HTTP(S) redirect targets, and invokes the optional- endpoint policy for every hop.-5. Marketplace catalog and package download policy is unchanged.+ `https://` URLs; unsupported schemes and malformed URLs stay invalid.+2. The user MCP editor warns that credentials and tool calls may be intercepted,+ and saving a user-owned endpoint is that user's consent.+3. A plugin-declared HTTP MCP server still requires `mcp.server.remote` and a host+ covered by `manifest.net.domains`, with the same warning in review surfaces.+4. The MCP HTTP client follows no redirect automatically, allows five hops, only+ HTTP(S) targets, and applies the endpoint policy to every hop.+5. Marketplace catalog and package download policy is unchanged; non-loopback HTTP+ package downloads stay refused.## Consequences-- LAN-hosted self-developed MCP servers work without requiring TLS termination.-- The network allowlist remains authoritative for plugin-owned egress, including- redirect targets.-- Users and plugin reviewers can see when a connection is unencrypted, but the- host cannot make a plain HTTP server safe against network interception.-- SDK, renderer, host-core, client tests, security documentation, and E2E- scenarios must describe the same HTTP policy.+- LAN-hosted MCP servers work without TLS termination.+- The network allowlist stays authoritative for plugin egress, redirect targets+ included.+- The host can disclose an unencrypted connection but cannot make it safe, so+ trusted network placement remains an operational requirement.diff --git a/docs/adr/0143-user-renamable-session-titles.md b/docs/adr/0143-user-renamable-session-titles.mdindex 876e2a0cb..4b669e1b6 100644--- a/docs/adr/0143-user-renamable-session-titles.md+++ b/docs/adr/0143-user-renamable-session-titles.md@@ -2,39 +2,36 @@- Status: Accepted- Date: 2026-09-01+- Related: Issue #27## Context-Tasks are durable sessions, but their labels are currently controlled by the-default title and first-prompt auto-title flow. Once a task has accumulated-history, users need a stable label that is easier to recognize in the sidebar,-Project archive, topbar, and search results.+Tasks are durable sessions, but their labels come from the default title and the+first-prompt auto-title flow, so a task with accumulated history has no stable,+recognizable label in the sidebar, Project archive, topbar, or search results.## Decision-Treat a task name as session metadata and expose one shared rename dialog. The-dialog is available from the Sidebar session overflow/right-click menu and from-the Project archive task row.+Treat a task name as session metadata and expose one shared rename dialog, opened+from the Sidebar session menu and the Project archive task row. It trims input,+accepts 1–80 Unicode code points, keeps Save unavailable while empty, and the host+validates the same rules so direct IPC callers cannot persist invalid titles.Renaming updates `sessions.title` and marks its host-owned `title_source` as-`manual`. It does not modify the transcript, message count, project binding,-empty-session predicate, or `updated_at` activity timestamp.+`manual`, without touching the transcript, message count, project binding,+empty-session predicate, or `updated_at`. Auto-titles compare-and-set against the+automatic title, so a manual rename wins the race and only a `manual` title opts+out of automatic replacement.## Consequences-- Users can name a task from both primary task navigation and the project index.-- Host-side validation provides one durable contract for renderer and future- clients.-- Renaming cannot accidentally move a task in recent-activity order or alter- agent context.-- The renderer owns modal focus, error presentation, and the immediate local- title update after the host confirms the session exists.--## Alternatives considered--- Rename only from the topbar: rejected because the task can be discovered and- managed from the Sidebar or Project archive before opening it.-- Rename the project folder or project record: rejected because the request is- about an individual task/session, not the workspace identity.-- Add a command-palette command: deferred; the existing row actions are the- discoverable surface and no new global command is needed for this operation.+- A task can be renamed from both primary navigation and the project index, and the+ new title appears there after the local store update and across restart.+- Renaming cannot move a task in recent-activity order or alter agent context.+- One host-side contract serves the renderer and future clients.++## Alternatives++- Rename only from the topbar — rejected: the task is discoverable elsewhere before+ it is opened.+- Rename the project record — rejected: the request is about one task.diff --git a/docs/adr/0144-user-configurable-thinking-level-overrides.md b/docs/adr/0144-user-configurable-thinking-level-overrides.mdindex aed118fef..a409be19f 100644--- a/docs/adr/0144-user-configurable-thinking-level-overrides.md+++ b/docs/adr/0144-user-configurable-thinking-level-overrides.md@@ -2,44 +2,40 @@- Status: Accepted- Date: 2026-09-01-- Deciders: PI-Desktop core- Updates ADR 0114 and ADR 0134## Context-The provider model list combines published model metadata with a persisted-`ModelBinding`. Electron main applied the binding before returning `ModelInfo`-to Settings.+Electron main applied a persisted `ModelBinding` before returning `ModelInfo` to+Settings, so a binding with no enabled thinking levels made a models.dev reasoning+record look non-reasoning. The same intersection blocked a compatible proxy or+newly released model whose endpoint supported a level the catalog snapshot did not+publish.## Decision-Keep `ModelInfo` as the raw published models.dev record. Stored binding values-must not rewrite its published reasoning fields or capability tags.+`ModelInfo` stays the raw published models.dev record; stored binding values no+longer rewrite its published reasoning fields or capability tags, and effective+capability is resolved separately from the exact binding of the selected model.-The Settings picker always renders the seven canonical thinking levels: `off`,-`minimal`, `low`, `medium`, `high`, `xhigh`, and `max`. Published levels seed a-newly added known-model binding.+The Settings picker always renders the seven canonical levels — `off`, `minimal`,+`low`, `medium`, `high`, `xhigh`, `max` — seeded from the published levels for a+newly added known model and shown unselected with a manual-override hint for a+non-reasoning or unknown model. Explicit selections are saved unchanged, an empty+binding or one holding only `off` disables thinking, and Composer resolves the+selected model's exact binding before rendering its reasoning menu.## Consequences-- Correct models.dev reasoning metadata remains visible in Settings, including- when an older or manually cleared binding exists.-- OpenAI-compatible proxies and newly released models can opt into thinking- without waiting for a catalog update.-- Catalog metadata remains the sole source of published model facts; it only- seeds defaults and does not silently erase explicit endpoint configuration.+- Correct catalog reasoning metadata stays visible in Settings even with an older+ or manually cleared binding.+- Proxies and new models can opt into thinking without a catalog update, and the+ desktop does not claim the upstream endpoint accepts the chosen level.- No IPC, storage schema, or host protocol change is required.-- An endpoint may reject an explicitly enabled level; the desktop does not infer- or guarantee upstream support from the user's selection.## Alternatives considered-- Treat models.dev as an absolute thinking capability gate: rejected because it- made valid proxy configurations impossible and caused stored bindings to hide- published reasoning metadata.-- Mark every OpenAI-compatible model as reasoning-capable automatically:- rejected because compatibility endpoints differ and discovery must not infer- unsupported behavior.-- Add a separate per-model "Enable thinking" boolean: rejected because the- existing `thinkingLevels` set already expresses both the enabled levels and- the deterministic default.+- Treat models.dev as an absolute thinking gate: it broke valid proxy+ configurations and hid published reasoning metadata.+- Add a per-model "Enable thinking" boolean: `thinkingLevels` already expresses+ both enabled levels and the deterministic default.diff --git a/docs/adr/0145-native-macos-intel-release-lane.md b/docs/adr/0145-native-macos-intel-release-lane.mdindex 193b51fab..5940dcee6 100644--- a/docs/adr/0145-native-macos-intel-release-lane.md+++ b/docs/adr/0145-native-macos-intel-release-lane.md@@ -2,54 +2,42 @@- Status: Accepted (amended by D353, ADR 0191, D450 / ADR 0289)- Date: 2026-09-01-- Deciders: PI-Desktop core-- Related: D126, D285, D353, D354, D450, ADR 0022, ADR 0191, ADR 0289, E2E-092+- Related: ADR 0022, ADR 0191, ADR 0289, D126, D285, D353, D354, D450## Context-The tag release workflow published only Apple Silicon macOS artifacts. The-electron-builder configuration also pinned both macOS targets to `arm64`, so an-Intel build could not be selected without changing the shared package-configuration.+Tag releases published only Apple Silicon macOS artifacts, and the shared+electron-builder configuration pinned both macOS targets to `arm64`. The Rust host+sidecar is packaged from the native `target/release` output, so a cross-compiled+Electron package is unsafe unless the sidecar architecture is managed and+verified independently.## Decision-1. The release matrix publishes two native macOS lanes: `macos-15` for arm64 and- `macos-15-intel` for x64.-2. The static macOS electron-builder targets remain DMG and ZIP without a fixed- `arch`.-3. Each macOS runner builds `pi-desktop-host-core` locally and packages that- same native output.-4. Each macOS job renames its generated `latest-mac.yml` before uploading.-5. D353 originally gave the Intel x64 job target-specific artifact patterns,- publishing `PI-Desktop-<version>-Intel.dmg` and- `PI-Desktop-<version>-Intel-mac.zip`, while arm64 kept generic names.-6. macOS in-app update delivery is qualified separately by D450 / ADR 0289.+The release matrix publishes two native macOS lanes, `macos-15` for arm64 and+`macos-15-intel` for x64, each verifying `uname -m` and building+`pi-desktop-host-core` locally before packaging that same output. Static macOS+targets stay DMG and ZIP without a fixed `arch`, and the workflow passes an+explicit `--arm64` or `--x64` flag; the local signed release script defaults to the+host architecture and rejects a mismatching `MAC_ARCH`. Each job renames its+generated `latest-mac.yml` before upload and the publish job validates and merges+both feeds into one `latest-mac.yml` published next to both installers. D353's+`-Intel` suffix convention is superseded by ADR 0191: both lanes use their standard+`-arm64` and `-x64` labels, with updater URLs and checksums generated from the+final names. Updater ownership is untouched; D450 / ADR 0289 now drives in-app+macOS updates from the merged feed.## Consequences- Intel Mac users receive native DMG and ZIP artifacts from every tag release.-- The Rust host and Electron executable have a deterministic, matching- architecture on both macOS lanes.-- Release publication needs one metadata merge step because electron-builder- emits one macOS updater feed per architecture.-- Every macOS public download carries an explicit standard `arm64` or `x64`- marker, so neither architecture depends on a generic version-only name.-- Intel package footprint and native launch qualification must be recorded- separately from the existing arm64 baseline.--## Alternatives considered--- Keep macOS arm64-only: rejected because Intel users remain unable to install a- native release and the requested platform coverage is not met.-- Build Intel packages on an Apple Silicon runner: rejected because the Rust- sidecar is produced from the host's native release target and could be- mismatched with the Electron package.-- Publish separate updater feeds permanently: rejected because the current macOS- delivery mode is notify-and-link and the GitHub Release should expose one- macOS feed when a signed update channel becomes available.--## Amendment (D450 / ADR 0289)--The merged `latest-mac.yml` now drives in-app macOS updates. Architecture-coverage and native packaging in this ADR are unchanged.+- Host and Electron architectures match deterministically on both lanes, and every+ public download carries an explicit architecture marker.+- Publication needs one metadata merge step, and cross-building the other+ architecture requires the matching native runner.++## Alternatives++- Keep macOS arm64-only: rejected because Intel users still cannot install a+ native release.+- Build Intel packages on Apple Silicon: rejected because the Rust sidecar comes+ from the host's native target and could mismatch the Electron package.diff --git a/docs/adr/0146-separate-work-panel-and-chat-resize-ownership.md b/docs/adr/0146-separate-work-panel-and-chat-resize-ownership.mdindex 55b281a20..f6a2dd8af 100644--- a/docs/adr/0146-separate-work-panel-and-chat-resize-ownership.md+++ b/docs/adr/0146-separate-work-panel-and-chat-resize-ownership.md@@ -7,12 +7,16 @@## ContextThe visible work panel is an in-flow right column backed by a native width-reservation.+reservation. Giving its renderer divider and the native window's right edge the+same dimension made it impossible to adjust the panel or the conversation alone.## Decision-When the work panel is open:--## Consequences--Superseded (Superseded by ADR 0151). The full record is in git history.+With the panel open, the outer native right edge owned the panel target: Main+kept the base conversation width fixed, previewed the bounded `244..720px` panel+target to the renderer, and committed it once the native resize stream settled.+The inner renderer divider owned the base conversation width through the bounded+`window/setWorkPanelChatWidth({width})` target-state channel+(`1040..10000px`), preserving the active panel reservation, serializing requests,+and re-sending the press-time target on cancellation. Left and non-right edges+kept their existing base-window behavior, and ADR 0151 superseded the split.diff --git a/docs/adr/0147-a2a-protocol-stack.md b/docs/adr/0147-a2a-protocol-stack.mdindex 2dbe9376f..fb9eb1226 100644--- a/docs/adr/0147-a2a-protocol-stack.md+++ b/docs/adr/0147-a2a-protocol-stack.md@@ -2,31 +2,31 @@- Status: Superseded by ADR 0165- Date: 2026-09-02-- Deciders: PI-Desktop core- Related: D277, D318, D321, ADR 0062, ADR 0089, ADR 0100, ADR 0162, ADR 0164,- `03-runtime/02-agent-runtime.md` §5f.2,- `03-runtime/06-host-rpc-protocol.md` §4, E2E-165, E2E-165b, E2E-165c, E2E-165d-- Supersedes: ADR 0138 and ADR 0140. The in-process `SubagentMailbox` and the- single `Peer` tool are removed. The coordination need those ADRs identified- is preserved; the mechanism is replaced.-- Amended by: ADR 0162 lifts same-context-only addressing. ADR 0164 lets the- parent agent register as `kind: "parent"` and call `A2A` to other parents;- parents still cannot address subagents.+ E2E-165, E2E-165b, E2E-165c, E2E-165d+- Supersedes: ADR 0138 and ADR 0140+- Amended by: ADR 0162 (lifts same-context-only addressing), ADR 0164 (parents+ register as `kind: "parent"`)## Context-ADR 0138 introduced a session-scoped `SubagentMailbox` and delegate-only peer-tools; ADR 0140 folded them into one `Peer` tool with `send | inbox | wait`-actions.+ADR 0138 and ADR 0140 kept subagent coordination inside the Node sidecar, where+messages were fire-and-forget with no durable history, typed payloads,+discovery, or authorization beyond a runtime-supplied sender name.## Decision-Replace peer messaging with a real **A2A (Agent2Agent) protocol stack** whose-broker lives in the Rust host-core process. Each subagent in the agent-runtime-sidecar is an A2A **client** that reaches the broker over the existing stdio-JSON-RPC 2.0 / NDJSON transport — the same pipe the `plans.*` domain uses —-through a new `a2a.*` method domain.+Replace peer messaging with an A2A stack brokered in Rust host-core: each+subagent is an A2A client over the existing stdio JSON-RPC transport through a+new `a2a.*` method domain, with an in-memory agent card registry, durable+`a2a_tasks` state machines, typed `TextPart` / `FilePart` / `DataPart` payloads,+counterpart-based event routing, and host-minted per-agent capability tokens,+while one subagent tool `A2A` replaces `Peer`.## Consequences-Superseded (Superseded by ADR 0165). The full record is in git history.+- Coordination became durable and typed, and the forged-sender invariant held+ because the token never reached the model.+- Protocol v10 and schema v12 broke compatibility for older hosts.++Superseded by [ADR 0165](0165-withdraw-a2a-peer-stack.md).diff --git a/docs/adr/0148-explicitly-disable-keyboard-shortcuts.md b/docs/adr/0148-explicitly-disable-keyboard-shortcuts.mdindex e2b13f3dd..dbabfcf48 100644--- a/docs/adr/0148-explicitly-disable-keyboard-shortcuts.md+++ b/docs/adr/0148-explicitly-disable-keyboard-shortcuts.md@@ -2,36 +2,30 @@- Status: Accepted- Date: 2026-09-03-- Deciders: PI-Desktop core-- Related: Issue #31, E2E-072, ADR 0072, ADR 0076+- Related: ADR 0072, ADR 0076, issue #31## Context-The shared application shortcut settings supported a missing override or a-custom binding, but deleting an override always restored the default. Users-could not intentionally unbind an action, and a null-like value was treated as-invalid and then silently resolved back to the default.+Deleting a shortcut override always restored the default, so users could not+intentionally unbind an action, and a null-like value was silently resolved back to+the default.## Decision-`AppSettings.keybindings` uses three states per application shortcut:--- an absent property uses the platform default;-- a valid portable binding string overrides the default;-- an explicit JSON `null` means `Unbound` and disables dispatch.--Invalid strings continue to fall back to the default so corrupt or hand-edited-settings do not silently disable product actions. The settings UI exposes-Disable separately from Restore default, displays a localized Unbound state, and-keeps an unbound action out of conflict checks.+`AppSettings.keybindings` uses three states per shortcut: an absent property uses+the platform default, a portable binding string overrides it, and an explicit JSON+`null` means `Unbound` and disables dispatch, while invalid strings still fall back+to the default. Settings exposes Disable separately from Restore default, shows a+localized Unbound state, and keeps unbound actions out of conflict checks. An+unbound `openPluginLauncher` unregisters the global accelerator, disables the+host-core `Alt+Space` hook on Windows, and turns configurable macOS native-role+items into role-less clickable items.## Consequences-- Users can disable any built-in application shortcut without losing the ability- to restore its default or record a new binding.-- `resolveKeybinding` returns `string | null`, so all consumers must handle the+- Any built-in shortcut can be disabled without losing Restore default or a new+ binding, and macOS menu clicks stay available while a shortcut is unbound.+- `resolveKeybinding` returns `string | null`, so every consumer must handle theno-binding state explicitly.-- Existing settings retain their behavior; absent and valid string entries are- unchanged, while only newly persisted `null` values disable actions.-- macOS menu clicks remain available even when their configurable shortcut is- unbound.+- Existing settings keep their behavior; only newly persisted `null` values disable+ actions.diff --git a/docs/adr/0149-calm-transcript-running-status-motion.md b/docs/adr/0149-calm-transcript-running-status-motion.mdindex ff9ec0490..279b0fb8d 100644--- a/docs/adr/0149-calm-transcript-running-status-motion.md+++ b/docs/adr/0149-calm-transcript-running-status-motion.md@@ -3,39 +3,40 @@- Status: Accepted- Date: 2026-09-04- Amended: 2026-10-21-- Deciders: PI-Desktop core-- Related: D071, D290, E2E-053, E2E-083+- Related: D071, D290## Context-The transcript used a fast gradient shimmer clipped into the text of the-pre-stream Working indicator and active thinking/tool labels. Because the-foreground highlight moved through each glyph, the status copy changed contrast-continuously and was harder to scan during a long run.+The transcript clipped a fast gradient shimmer into the text of the pre-stream+Working indicator and active thinking/tool labels, so the status copy changed+contrast continuously and was hard to scan during a long run. The tool spinner+and streaming rail already supply motion for the concrete live states.## Decision-Running transcript copy remains a static, readable semantic text color. The+Running transcript copy keeps a static, readable semantic text color. Thepre-stream Working indicator adds a compact three-dot marker with a staggered-one-second opacity/scale pulse.+one-second opacity and scale pulse, active thinking and tool labels use one small+status marker with a one-second opacity pulse, and tool spinners, run-row status+dots, and the assistant streaming rail keep their existing feedback.-The Thinking indicator is the explicit exception: the collapsed/live Thinking-label uses a whole-run `TextShimmer` with a 1.2s sweep and 220ms fade, defined-by `turn-process-and-thinking-display` (2026-10-21). It does not move the-highlight glyph by glyph.+The Thinking indicator is the explicit exception: the collapsed live label uses+a whole-run `TextShimmer` with a 1.2s sweep and 220ms fade, defined by+`turn-process-and-thinking-display` (2026-10-21), never moving the highlight+glyph by glyph. All motion is disabled under `prefers-reduced-motion: reduce`+while the text and static marker stay visible, so state is never conveyed by+motion alone.## Consequences- Working and active tool labels stay legible at every animation frame.-- The transcript has one restrained loading language: readable copy plus a small- status marker, without a moving highlight over text.-- Tests and rendered review should verify both light/dark themes and reduced- motion, especially while a turn has not produced its first event.+- The transcript has one restrained loading language, without a moving highlight+ over text.+- No protocol, persistence, runtime, or localization contract changes.## Alternatives rejected-- Keep the text shimmer and slow it down: slower contrast changes still make the- label itself unstable and provide little additional state information.-- Replace the status with a large card or progress timeline: this would add- decorative surface and density to a transient state that needs only a wait- signal.+- Keep the shimmer and slow it down: the label itself stays unstable and gains+ little state information.+- Replace the status with a large card or progress timeline: it adds decorative+ density to a transient wait signal.diff --git a/docs/adr/0150-inline-svg-empty-home-agent-mark.md b/docs/adr/0150-inline-svg-empty-home-agent-mark.mdindex 512dff341..7671f173a 100644--- a/docs/adr/0150-inline-svg-empty-home-agent-mark.md+++ b/docs/adr/0150-inline-svg-empty-home-agent-mark.md@@ -2,20 +2,20 @@- Status: Superseded by ADR 0152- Date: 2026-09-04-- Deciders: PI-Desktop core-- Related: D291, E2E-046, E2E-099, US-UI-17+- Related: D291## Context-The empty-home hero used a raster sprite atlas with randomized pose groups,-discrete frame changes, and a hover shortcut that accelerated playback.+The empty-home hero used a randomized raster sprite atlas whose discrete frames+and hover-accelerated playback read as loud in the conversation area.## Decision-Replace the sprite with a 100px inline SVG agent mark. A thin orbit and signal-point rotate slowly around a compact core; the core breathes gently and the eyes-blink occasionally.+Replace the atlas with a decorative inline SVG agent mark in the existing 100px+slot: a slowly rotating orbit and signal point, a breathing core, and occasional+blinks, all deterministic and frozen under `prefers-reduced-motion: reduce`.## Consequences-Superseded (Superseded by ADR 0152). The full record is in git history.+Superseded by ADR 0152, which made eight-frame GIF artwork the empty-home mark.+The component kept no atlas, random selection, timer, or hover state.diff --git a/docs/adr/0151-internal-work-panel-dock.md b/docs/adr/0151-internal-work-panel-dock.mdindex 099dac115..38c5d607c 100644--- a/docs/adr/0151-internal-work-panel-dock.md+++ b/docs/adr/0151-internal-work-panel-dock.md@@ -1,62 +1,50 @@# ADR 0151: Keep the work panel inside the fixed application window-- Status: Accepted+- Status: Accepted; supersedes ADR 0122 and the work-panel boundary clauses of+ ADR 0146, restores the internal-dock direction from ADR 0033, and is amended by+ ADR 0238 (three-column width budget) and ADR 0226 (chat reservation)- Date: 2026-09-03-- Related: [01-ui-ia](../spec/04-ux/01-ui-ia.md) ·- [08-component-spec §5](../spec/04-ux/08-component-spec.md) ·- [09-interaction-patterns §8](../spec/04-ux/09-interaction-patterns.md) ·- [01-ipc-protocol](../spec/03-runtime/01-ipc-protocol.md) · E2E-056 · E2E-167-- Supersedes: ADR 0122 and the work-panel boundary clauses of ADR 0146-- Restores the internal-dock direction from ADR 0033+- Related: E2E-056, E2E-167## Context-The work panel is already rendered as an in-flow flex sibling, but ADR 0122 made-the renderer request a matching native reservation. Electron consequently grew-and later shrank the whole application window whenever the panel opened or-collapsed.+The work panel is already an in-flow flex sibling, but ADR 0122 made the renderer+request a matching native reservation, so Electron grew and later shrank the whole+window whenever the panel opened or collapsed. The panel should behave like the+left sidebar, taking its width from the existing client area while MainChat+reflows beside it, and the native Browser `WebContentsView` is positioned from the+renderer-measured panel rectangle instead of a larger window.## Decision-1. The work panel remains a fixed-width, right-side in-flow flex column.-2. The renderer keeps the `window/setWorkPanelReservation` seam at zero.-3. The panel's inner left-edge separator is renderer-owned.-4. Native window edges and corners continue to resize the application window,- but never resize or reserve the work panel.-5. The Browser view continues to use the renderer-measured panel rectangle and- is detached before the panel exit animation, because a native view cannot- follow renderer CSS animation.+1. The work panel stays a right-side in-flow flex column whose open and collapse+ animate its flex allocation without changing native BrowserWindow bounds, with+ its committed width bounded by the live three-column budget.+2. The renderer keeps the `window/setWorkPanelReservation` seam at zero; Main+ normalizes every valid request to `{ requested: 0, reserved: 0 }` and never+ applies panel width or x-offset geometry.+3. The panel's inner left-edge separator is renderer-owned: pointer preview is+ frame-coalesced, release commits the preferred width, and Escape, cancellation,+ or lost capture restores the press-time width.+4. Native window edges and corners resize the application window, never the panel;+ the preferred panel width stays renderer-local and persists independently of+ native bounds.+5. The Browser view follows the renderer-measured panel rectangle and is detached+ before the exit animation, because a native view cannot follow renderer CSS+ animation.## Consequences-- Opening and collapsing no longer move the window edge or change the user's- application bounds; the panel visibly occupies internal space like the left- sidebar.-- MainChat's minimum-width trade-off is amended by ADR 0226: the renderer- preserves a 515px chat reservation for the composer, even when the fixed- client area cannot show every side dock at its preferred width.-- Native reservation and chat-width IPC shapes remain as compatibility seams,- but the current renderer does not use them for panel presentation or resize.-- Native window bounds persistence no longer needs to remove temporary panel- geometry.+- Opening and collapsing no longer move the window edge or change application+ bounds; the panel occupies internal space like the left sidebar.+- The renderer keeps a 515px chat reservation for the composer even when the client+ area cannot show every dock at its preferred width.+- Native reservation and chat-width IPC shapes remain as unused compatibility+ seams, and bounds persistence no longer removes temporary panel geometry.-## Alternatives rejected+## Alternatives-### Keep the native reservation from ADR 0122--Rejected because expanding the whole application window is the outward behavior-this change removes.--### Overlay the panel without flex allocation--Rejected because it would cover chat content and break the measured Browser-surface, keyboard order, and continuous reflow.--## References--- `docs/adr/0033-internal-dock-work-panel.md`-- `docs/adr/0122-reserve-native-width-while-work-panel-visible.md`-- `docs/adr/0146-separate-work-panel-and-chat-resize-ownership.md`-- `apps/desktop/src/App.tsx`-- `apps/desktop/src/components/workpanel/WorkPanel.tsx`-- `apps/desktop/electron/main/index.ts`+- Keep the ADR 0122 native reservation: expanding the whole application window is+ exactly the outward behavior this change removes.+- Overlay the panel without flex allocation: it would cover chat content and break+ the measured Browser surface and focus order.diff --git a/docs/adr/0152-eight-frame-empty-home-mascot-gif.md b/docs/adr/0152-eight-frame-empty-home-mascot-gif.mdindex 2aa5579c2..20b507f9a 100644--- a/docs/adr/0152-eight-frame-empty-home-mascot-gif.md+++ b/docs/adr/0152-eight-frame-empty-home-mascot-gif.md@@ -2,48 +2,35 @@- Status: Accepted- Date: 2026-09-04-- Deciders: PI-Desktop core-- Related: D293, D294, E2E-046, E2E-099, US-UI-17+- Related: D293, D294- Supersedes: ADR 0150## Context-ADR 0150 replaced a randomized pixel-art sprite atlas with a 100px inline SVG-agent mark so the empty-home hero stayed quiet. A new eight-frame waving mascot-is now the intended empty-home mark, with separate light and dark artwork that-already uses a transparent background.+ADR 0150 made the empty-home hero a quiet inline SVG mark. The intended mark is+now an eight-frame waving mascot with separate light and dark artwork on a+transparent background, which does not match the SVG orbit cycle and would read+badly as one recolored raster under a theme change.## DecisionReplace the inline SVG with processed eight-frame GIFs in the existing 100px-empty-home slot. `HomeMascotLogo` is decorative (`aria-hidden="true"`) and-renders four images, of which CSS shows one at a time:+empty-home slot. `HomeMascotLogo` is decorative (`aria-hidden="true"`) and renders+four images, of which CSS shows one: the light and dark GIF loops, or their+matching first-frame stills under `prefers-reduced-motion: reduce`. The active+pair follows `document.documentElement[data-theme]`, with anything other than+`light` using the dark artwork like `BrandLogo`. Playback is native to the GIF,+with no random selection, JavaScript timer, or hover-dependent cadence.-- `src/assets/home-mascot-light.gif` / `home-mascot-dark.gif` — the looping- wave, with a short idle hold on the first frame-- `src/assets/home-mascot-still-light.png` / `home-mascot-still-dark.png` — the- matching first frame, shown only under `prefers-reduced-motion: reduce`+## Consequences-The active pair follows `document.documentElement[data-theme]`. Anything other-than `light` uses the dark artwork, matching `BrandLogo`.+- Branding uses the supplied mascot action set instead of code-native artwork.+- The layout slot, decorative role, and reduced-motion freeze remain.+- Each theme keeps dedicated artwork rather than recoloring one asset.-## Consequences+## Alternatives-- Empty-home branding uses the supplied mascot action set instead of a- code-native SVG.-- The 100px layout slot, decorative role, and reduced-motion freeze remain.-- Light and dark surfaces each keep a dedicated mascot treatment instead of- recoloring one asset through theme tokens.-- The historical `home-mascot-groups.png` atlas is not in the repository; the- GIFs and still frames are the source assets.--## Alternatives rejected--- Keep the SVG and ignore the new frames: this would discard the requested- empty-home action set.-- Restore the randomized sprite atlas: this would reintroduce timer, hover, and- pose-selection state that ADR 0150 removed.-- Drive the eight frames from JavaScript: this would add timer and- reduced-motion state the GIF plus CSS swap already cover.-- Use one GIF for both themes: the supplied light and dark artwork would clash+- Drive the frames from JavaScript: rejected because GIF plus CSS already covers+ playback and reduced motion without extra timer state.+- Use one GIF for both themes: rejected because the supplied artwork would clashwith the opposite surface.diff --git a/docs/adr/0153-inflight-reply-checkpoint.md b/docs/adr/0153-inflight-reply-checkpoint.mdindex 1cf400652..96a8d435d 100644--- a/docs/adr/0153-inflight-reply-checkpoint.md+++ b/docs/adr/0153-inflight-reply-checkpoint.md@@ -2,58 +2,58 @@- Status: Accepted (amended 2026-09-06 by D327)- Date: 2026-09-05-- Deciders: PI-Desktop core-- Related: D119, D287, D288, D299, D327, E2E-010, E2E-171, E2E-184, ADR 0030, ADR 0041+- Related: ADR 0030, ADR 0041, D119, D287, D288, D299, D327, E2E-010,+ E2E-171, E2E-184## Context-Spec 04 makes assistant and tool rows durable at their end events: the agent-runtime emits `message_end` once, and Electron main appends that row through the-persistence outbox. Everything the user watches stream before that point lives-only in the renderer and in the sidecar's memory.+Assistant and tool rows become durable only at their end events, so everything+streaming before that point lives in the renderer and sidecar memory. Agentic+replies stream for minutes and the app is quit or restarted often, so a quit, a+sidecar crash, or a restart mid-reply lost the entire reply under an `aborted`+turn. `before-quit` disposed host-core before the sidecar could persist a final+row, and the renderer Stop path rewrote the transcript from a stale snapshot,+hiding or deleting the reply.## Decision1. **Checkpoint file, not transcript lines.** Host-core owns- `sessions/<id>.inflight.json`: one atomically replaced object holding the- session's streaming assistant message and its turn id.-2. **Settlement rules.** The final `session.appendMessage` of the same id- removes the file.-3. **Quit settles turns first.** `before-quit` flushes checkpoints, aborts- active turns through the sidecar, and waits at most 2 s for the aborted rows- to drain while host-core is alive, then disposes host and sidecar.-4. **Renderer Stop never rewrites a started reply.** Settling is in-memory; the- durable copy is the runtime's aborted row or the promoted checkpoint.+ `sessions/<id>.inflight.json`, one atomically replaced object holding the+ streaming assistant message and its turn id, which Electron main writes from+ `message_update` through `session.saveInflightMessage` at a bounded interval+ with a trailing write.+2. **Settlement rules.** The final `session.appendMessage` of that id removes the+ file, `session.endTurn` removes it for `completed`/`error`, promotes it as an+ `aborted` row when asked to `recoverInflight`, and leaves it for a plain user+ Stop; host boot promotes leftovers whose final row never landed, and a+ checkpoint for an already indexed id is dropped.+3. **Quit settles turns first.** `before-quit` flushes checkpoints, aborts active+ turns through the sidecar, and waits a bounded time for the aborted rows to+ drain while host-core is alive before disposing host and sidecar.+4. **Renderer Stop never rewrites a started reply.** Settling stays in memory, the+ durable copy is the runtime's aborted row or the promoted checkpoint, and the+ undo and delete paths rewrite only from the full durable transcript merged+ with the live rows.++Amended 2026-09-06 (D327, issue #42, after D324): `message_end` checkpoints the+finished snapshot and then settles only a newer turn, `completed`/`error` endTurn+deletes the checkpoint only when the final row is already indexed, boot promotion+of an already-completed turn writes its leftover as `complete` instead of+`aborted`, and the host handshake awaits the persistence outbox drain before the+renderer can call `session.get`, then calls `session.recoverInflightMessages`+(amending ADR 0041).## Consequences-- Loss on quit or crash is bounded to the last 1.5 s of a reply plus tool rows- still running; the reopened session shows the prompt and the partial reply as- an `aborted` row under an `aborted` turn.-- One small file write per interval per streaming session; nothing new in- SQLite.+- Loss on quit or crash is bounded to the last interval of a reply plus tool rows+ still running; the reopened session shows the partial reply as an `aborted` row.+- One small file write per interval per streaming session and nothing new in+ SQLite; `session.endTurn` gains `recoverInflight` and `recovered`.- Session delete removes the checkpoint file with the other session files.-- Spec 01 §5.3, 04 §2.1 and §4.7, 06, 07 §5; E2E-171; D299.--## Amendment (2026-09-06) — Completed replies survive process restart (D327)--Issue #42 showed the same user-only transcript after a full quit that D324 fixed-for an in-process session switch. Two settlement rules dropped a finished reply-that was still only in the outbox:--1. `message_end` called `settle()` before enqueueing, so the host checkpoint was- up to 1.5 s stale and a trailing write of the finished snapshot was- cancelled.-2. `session.endTurn` for `completed`/`error` deleted the checkpoint even when- that id was not yet indexed.--Amendment:--- Electron main checkpoints the finished `message_end` snapshot, then `settleIf`- so a newer turn started during that write is not wiped.-- `completed`/`error` endTurn deletes the checkpoint only when the final row is- already indexed.-- Boot/recovery promotion of a leftover whose turn is `completed` writes the row- as `complete`, not `aborted`.-- Host handshake **awaits** the persistence outbox drain before the renderer can- `session.get`, then calls `session.recoverInflightMessages` (amends ADR 0041).++## Alternatives++- Append checkpoints as transcript lines: rejected; a multi-minute reply would+ leave dozens of near-copies that bloat the file and skew line paging.+- Skip quit-time settling: rejected; a reply that reached its final message would+ still be unpersistable.diff --git a/docs/adr/0154-reveal-new-task-empty-destination.md b/docs/adr/0154-reveal-new-task-empty-destination.mdindex 913211bd6..b16b8063a 100644--- a/docs/adr/0154-reveal-new-task-empty-destination.md+++ b/docs/adr/0154-reveal-new-task-empty-destination.md@@ -2,45 +2,32 @@- Status: Accepted- Date: 2026-09-05-- Deciders: PI-Desktop core- Related: D252, D305, ADR 0113, ADR 0137, E2E-011a, E2E-011d, E2E-011g## Context-ADR 0113 made New Task persist a durable empty session (or reuse the group's-latest empty row). The renderer implemented that by awaiting `session.list`,-then `session.create`, then another `session.list`, then `session.get` before-changing the visible transcript.+ADR 0113 made New Task persist a durable empty session or reuse the group's latest+empty row, and the renderer awaited `session.list`, `session.create`, another+`session.list`, and `session.get` before changing the transcript. The previous+conversation therefore stayed on screen: the cold-switch rule of ADR 0137 fits+opening an existing session but read as a dead click for a new empty destination.## Decision-1. **First-frame empty reveal.** Creating a session clears the previous- transcript and retained panes synchronously, before `session.create`.-2. **Reuse without a list refresh.** New Task decides from the in-memory session- list plus renderer signals (`runningSessions`, live/cached rows, submitted- drafts).-3. **Commit from `session.create`.** The created summary is inserted into the- sidebar list the way a fork child is.-4. **One in-flight create per group.** Send and paste wait for the same-scope- New Task promise instead of materializing a second session.--Protocol, storage, and host RPC are unchanged. `session.create` remains the-source of the durable id.+Creating a session clears the previous transcript and retained panes synchronously+before `session.create`, so the empty home composer is the destination on the first+frame, and reusing an empty slot commits an empty transcript without waiting for+`session.get`. New Task decides reuse from the in-memory session list plus renderer+signals (`runningSessions`, live or cached rows, submitted drafts), while host+`messageCount` stays the durable empty predicate. The summary returned by+`session.create` is inserted into the sidebar list and no follow-up list or get runs+for a new empty session. One in-flight create is shared per group, so Send and paste+await the same promise. Protocol, storage, and host RPC are unchanged.## Consequences-- New Task no longer leaves the previous conversation on screen.-- Rapid New Task clicks and first-message races stay serialized per group.-- An empty reuse still revalidates through `selectSession` after the empty pane- is already visible.-- Spec `04-ux/09-interaction-patterns.md` §1.6, `04-ux/08-component-spec.md`- §11, E2E-011a / E2E-011d / E2E-011g; D305 amends D252's refresh-then-select- timing, not the reuse rule.--## Alternatives considered--- Client-generated session ids on `session.create`: first-frame id without a- home-draft interval, but an additive protocol field and remapping if an older- host ignores it.-- Keep the previous pane with a progress track: that is the cold-switch rule for- existing transcripts and is the hitch this request removes.+- New Task no longer leaves the previous conversation on screen, and rapid clicks or+ a first-message race stay serialized per group.+- An empty reuse still revalidates through `selectSession` once the empty pane is+ visible; D305 amends D252's refresh-then-select timing, not the reuse rule.+- The change is renderer-side only: `session.create` still owns the durable id.diff --git a/docs/adr/0155-zhipu-endpoint-presets.md b/docs/adr/0155-zhipu-endpoint-presets.mdindex 118be5212..f8b74b5e1 100644--- a/docs/adr/0155-zhipu-endpoint-presets.md+++ b/docs/adr/0155-zhipu-endpoint-presets.md@@ -2,20 +2,20 @@- Status: Accepted- Date: 2026-09-05-- Deciders: PI-Desktop core-- Updates ADR 0012, ADR 0020, and ADR 0116+- Updates: ADR 0012, ADR 0020, ADR 0116; issue #35## Context-Zhipu AI (智谱) exposes two product modes and two regions:--- Standard API vs GLM Coding Plan-- China (`open.bigmodel.cn`) vs international (`api.z.ai`)+Zhipu AI offers a Standard API and a GLM Coding Plan in a China and an international+region, so four endpoints. pi-ai already carried transports for the Coding Plan URLs+and models.dev published all four, but the add-provider dialog was a generic+OpenAI-compatible form, so users had to know which URL to paste and a saved row ended+up with `vendorKey: "custom"`.## Decision-Expose four named endpoint presets in the add-provider **Service** select. They-stay on the existing OpenAI-compatible path:+Expose four named endpoint presets in the add-provider **Service** select, all on+the existing OpenAI-compatible path:```textvendorKey baseUrl@@ -25,15 +25,18 @@ zai https://api.z.ai/api/paas/v4zai-coding-plan https://api.z.ai/api/coding/paas/v4```-Selecting a preset fills the name, locks the Base URL, keeps `apiStyle:-"chat_completions"`, and persists the models.dev `vendorKey`. The display name-stays editable.+Selecting a preset fills the name, locks the Base URL, keeps+`apiStyle: "chat_completions"`, and persists the models.dev `vendorKey`; the display+name stays editable. Because pi-ai's `zai` transport is the international Coding+Plan while models.dev `zai` is the standard API, the row stores both key and exact+URL so catalog matching cannot confuse them, and `zai-coding-cn` remains an alias of+`zhipuai-coding-plan`. A matching URL or `vendorKey` makes the sidecar Completions+record carry `thinkingFormat: "zai"` and `zaiToolStream: true`, with no new wire+adapter, secret table, or host protocol.## Consequences-- China and international Zhipu users can pick API vs Coding Plan without- copying URLs from external docs.-- Catalog enrichment follows the selected endpoint, not a generic custom row.-- Generic OpenAI-compatible configuration remains the Custom endpoint option.-- OpenCode Go stays an API-style preset; Zhipu does not add four more apiStyle- values.+- Users pick API versus Coding Plan without copying URLs, and catalog enrichment+ follows the selected endpoint.+- Generic OpenAI-compatible configuration stays available as Custom, and Zhipu adds+ no new `apiStyle` values.diff --git a/docs/adr/0156-simplify-add-provider-common-path.md b/docs/adr/0156-simplify-add-provider-common-path.mdindex 32cce4ddf..1d8a66659 100644--- a/docs/adr/0156-simplify-add-provider-common-path.md+++ b/docs/adr/0156-simplify-add-provider-common-path.md@@ -2,28 +2,24 @@- Status: Accepted- Date: 2026-09-05-- Deciders: PI-Desktop core-- Updates ADR 0116 and ADR 0155+- Updates: ADR 0116, ADR 0155## ContextThe add-provider dialog stacked Service, Name, Base URL, API key, and API format-before the model panes. Named Zhipu / Z.AI endpoints already know their name,-URL, and wire format, so those extra fields made the first-run path look like a-generic gateway form.+before the model panes, so the first-run path looked like a generic gateway form+even for named endpoints that already know their name, URL, and wire format.## Decision-A new dialog starts with only **Service**. After a named endpoint is chosen-(Zhipu / Z.AI API or Coding Plan, OpenCode Go), the common path is Service + API-key, plus a one-line host summary.--No stepper, vendor-card grid, or extra `apiStyle` values. Persistence, catalog-matching, and Completions flags from ADR 0155 are unchanged.+A new dialog starts with **Service** only. Choosing a named endpoint (Zhipu / Z.AI+API or Coding Plan, OpenCode Go) reduces the common path to Service + API key plus+a one-line host summary, while Custom endpoint shows Name, Base URL, and API key.+Name for named rows and API format for custom rows stay behind Advanced, and+OpenCode Go is a Service option rather than an API-format option. Persistence,+catalog matching, and the Completions flags of ADR 0155 are unchanged.## Consequences-- Adding a known service is pick + paste + choose models.-- Custom OpenAI-compatible gateways keep the previous Name / URL / key contract,- with API format still available in Advanced.-- OpenCode Go is discoverable next to other named services.+- Adding a known service is pick, paste, choose models.+- Custom gateways keep the previous Name / URL / key contract.diff --git a/docs/adr/0157-main-owned-github-issue-feedback.md b/docs/adr/0157-main-owned-github-issue-feedback.mdindex e006b5de3..a52c31c7a 100644--- a/docs/adr/0157-main-owned-github-issue-feedback.md+++ b/docs/adr/0157-main-owned-github-issue-feedback.md@@ -7,28 +7,28 @@## Context-Bug reports without an app version, OS, or reproduction steps cannot be triaged.-Settings → Info already shows version and logs, but users had no in-app path to-GitHub issue creation, and the existing issue forms treated those triage fields-as optional.+Bug reports without an app version, OS, or reproduction steps cannot be triaged, and+although Settings → Info shows version and logs, users had no in-app path to GitHub+issue creation while the issue forms treated those fields as optional.## Decision-1. GitHub issue forms are the only intake path (`blank_issues_enabled: false`).-2. Settings → Info exposes one **Report a problem** row.-3. The constructed URL must stay on- `https://github.com/vastsa/PI-Desktop/issues/new` with- `template=bug_report.yml`.+1. GitHub issue forms are the only intake path (`blank_issues_enabled: false`). The+ bug form requires a description, reproduction steps, expected and actual behavior,+ app version, and OS.+2. Settings → Info exposes one **Report a problem** row invoking the allowlisted+ `pi-desktop/app/openFeedback` channel. Electron Main builds a fixed GitHub+ bug-form URL, prefills `app-version`, `os`, and `environment` from Main-owned+ version info, and opens it with `shell.openExternal`; the renderer supplies no URL.+3. The URL must stay on+ `https://github.com/vastsa/PI-Desktop/issues/new?template=bug_report.yml`; feature+ requests stay in GitHub's template picker.## Consequences-- Triage data is collected at intake instead of in follow-up comments.-- Opening GitHub follows the same Main-owned URL rule as the releases page.-- No host-protocol, storage, or update-feed change.+Triage data is collected at intake, opening GitHub follows the same Main-owned URL+rule as the releases page, and no host, storage, or feed contract changes.## Alternatives-- Renderer `window.open` of a constructed URL: rejected because it would let the- sandbox choose the destination, unlike `updates/openReleases`.-- Opening the template chooser without prefilling version: rejected because the- Settings row already has authoritative version info.+- Renderer `window.open`: the sandbox would choose the destination.diff --git a/docs/adr/0158-approval-card-focus-and-remembered-mode.md b/docs/adr/0158-approval-card-focus-and-remembered-mode.mdindex 8fcd5f997..bbd7dfa05 100644--- a/docs/adr/0158-approval-card-focus-and-remembered-mode.md+++ b/docs/adr/0158-approval-card-focus-and-remembered-mode.md@@ -2,47 +2,37 @@- Status: Accepted for implementation- Date: 2026-08-12-- Deciders: PI-Desktop core- Amends: D189 · ADR 0053- Related: D215 · E2E-106## Context-The Plan/Goal approval card duplicated the submitted question, status, and-deadline alongside the artifact opener. The approval mode also reset to Ask for-every proposal, even when the user had just chosen a different mode.+The Plan/Goal approval card repeated the question, status, and deadline beside+the artifact opener, reset the approval mode to Ask for every proposal, and+derived artifact filenames fell back to a generic `plan`/`goal` stem for+non-ASCII titles.## Decision-1. The pending approval card renders only the proposal title, the host-created- artifact path/open action, Reject, and the Approve split-button.-2. Selecting Ask, Accept edits, or Auto stores that choice in renderer-local- device preferences.-3. Host-generated artifact filenames preserve alphanumeric Unicode title- characters, normalize separators to hyphens, and retain the timestamp and- collision suffix.-4. The existing host approval deadline remains an internal compatibility and- fail-closed boundary; it is no longer exposed as an approval-card concept.+The pending card renders only the proposal title, the host-created artifact path+and open action, Reject, and the Approve split-button. Choosing Ask, Accept+edits, or Auto stores that choice in renderer-local device preferences as the+default for later approvals, with Ask as the fallback when storage is unavailable+or invalid, and generated filenames keep alphanumeric Unicode title characters,+normalize separators to hyphens, and retain the timestamp and collision suffix+under `.pi/<kind>/`. The host approval deadline stays an internal fail-closed+boundary rather than card content.## Consequences-- The card is compact and keeps attention on the decision and the reviewable- artifact.-- Users who routinely approve with Auto or Accept edits do not repeat that- selection for every proposal on the same device.-- Localized titles produce recognizable artifact names while preserving unique,- host-owned immutable files.-- The wire/storage contract remains compatible; legacy deadline data is not- presented by the renderer.+- The card stays compact and keeps attention on the decision and the artifact.+- Auto and Accept edits users do not reselect a mode per proposal on a device.+- Localized titles yield recognizable names while files stay host-owned; the+ wire and storage contract is unchanged.## Alternatives considered-### Persist the choice in the host settings table--Rejected for this change.--### Keep the question and deadline in a collapsed card section--Rejected. The requested approval surface is intentionally limited to title,-artifact review, and the two decisions; the full Markdown remains available by-opening the host-created file.+- Persist the mode in host settings: rejected; it is a renderer preference and+ would widen the protocol boundary.+- Keep a collapsed question and deadline section: rejected; the full Markdown is+ reachable through the host-created file.diff --git a/docs/adr/0159-plugin-generated-settings-and-local-shortcuts.md b/docs/adr/0159-plugin-generated-settings-and-local-shortcuts.mdindex ba206277f..2e2391baf 100644--- a/docs/adr/0159-plugin-generated-settings-and-local-shortcuts.md+++ b/docs/adr/0159-plugin-generated-settings-and-local-shortcuts.md@@ -2,32 +2,27 @@- Status: Accepted- Date: 2026-08-13-- Decision owners: PI-Desktop desktop/plugin maintainers## Context-Plugins already declared settings and could read/write their private settings,-but users had no standard way to edit those values. The next known setting is a-shortcut, and registering plugin shortcuts globally would expand the collision-and lifecycle surface before the plugin settings contract is stable.+Plugins could declare and read their own settings, but users had no standard+way to edit them. The next known setting is a shortcut, and registering plugin+shortcuts globally would widen the collision and lifecycle surface before the+settings contract is stable.## Decision-1. `contributes.settings` is the source of truth for the generated settings UI.-2. A shortcut setting declares a plugin command through `command` and has the- fixed `scope: "plugin"`.-3. Plugin shortcuts are handled by the renderer only while the PI-Desktop window- is focused.-4. The host validates values, persists them in the plugin-private settings file,- and sends `plugin:settingsChanged` to the plugin process.-5. Secret settings remain rejected until a dedicated secure storage contract is- designed.+`contributes.settings` is the single source for the generated settings UI,+supporting `string`, `number`, `boolean`, `select`, `json`, and `shortcut`. A+shortcut setting names a plugin command and is fixed to `scope: "plugin"`,+editable on the installed plugin page, and active only while the PI-Desktop+window is focused; the host re-checks plugin activation scope before running+the command. Values are validated and stored in the plugin-private settings+file, announced to the plugin as `plugin:settingsChanged`. Secret settings+stay rejected until a secure storage contract exists.## Consequences-- Plugin authors can ship a usable settings surface without bundling a custom- configuration page.-- The existing application shortcut map remains authoritative for app-global- behavior and plugin shortcuts cannot replace it.-- A future global plugin shortcut feature will require a separate decision for- collision handling, OS registration, and disabled/background plugin state.+- Plugin authors ship a settings surface without a custom page.+- The application shortcut map stays authoritative.+- Global plugin shortcuts need a separate decision.diff --git a/docs/adr/0160-shipped-locale-registry-and-language-picker.md b/docs/adr/0160-shipped-locale-registry-and-language-picker.mdindex a93794c07..ddff1d65b 100644--- a/docs/adr/0160-shipped-locale-registry-and-language-picker.md+++ b/docs/adr/0160-shipped-locale-registry-and-language-picker.md@@ -2,35 +2,35 @@- Status: Accepted (amended by ADR 0182)- Date: 2026-09-05-- Decision owners: PI-Desktop desktop/i18n maintainers- Related: D012, D073, ADR 0009## Context-The General appearance card presented language as three preview cards (Auto /-简体中文 / English). That control does not scale: every new locale needed a-hard-coded card, sample glyph, and catalog keys for its name.+Language was a row of preview cards (Auto / 简体中文 / English), so every new+locale needed a hard-coded card, sample glyph, and catalog keys for its name.+The product now ships more than two UI locales, starting with Turkish.## Decision-1. `@pi-desktop/i18n` owns a `supportedLocales` registry: id, native name- (endonym, never translated), and English name.-2. `AppSettings.language` is `"auto"` plus every registry id.-3. Settings → General → Appearance keeps Theme as three preview cards.-4. Plugin `PluginLocalizedString` still requires `en` and `zh-CN`.+`@pi-desktop/i18n` owns a `supportedLocales` registry of id, native name, and+English name, `resolveLocale` maps OS tags onto it, and `catalogs[locale]` is+the lookup for the renderer, application menu, tray, and native dialogs.+`AppSettings.language` is `"auto"` plus every registry id, where auto follows+`app.getLocale()` through the sandboxed preload bridge, and Settings → General →+Appearance keeps Theme as preview cards but shows Language as a searchable+picker that pins Auto with the detected native name. Plugin+`PluginLocalizedString` still requires `en` and `zh-CN` with English fallback,+and the changelog follows shipped shell locales when a translation exists.## Consequences- Adding a UI locale is a catalog file, a registry row, an- `AppSettings.language` union member, and an Electron locale pack.-- Native names stay findable even when the current UI language is unknown to the- user.-- Plugins and release notes do not have to ship every new shell locale on day- one.+ `AppSettings.language` member, and an Electron locale pack.+- Native names stay findable even when the current UI language is unknown.+- Plugins and release notes need not ship every new shell locale on day one.## Alternatives-- Keep language as wrapping preview cards: unreadable past three or four- options, and names would still be hard-coded.-- Require plugins to add every shipped locale: breaks existing manifests and is- out of proportion to a shell translation.+- Keep wrapping preview cards: rejected, they are unreadable past a few options.+- Require plugins to add every shipped locale: rejected, it breaks existing+ manifests for a shell translation.diff --git a/docs/adr/0161-searchable-theme-picker.md b/docs/adr/0161-searchable-theme-picker.mdindex d111e3652..5efb69ae1 100644--- a/docs/adr/0161-searchable-theme-picker.md+++ b/docs/adr/0161-searchable-theme-picker.md@@ -2,36 +2,29 @@- Status: Accepted- Date: 2026-09-05-- Decision owners: PI-Desktop desktop/settings maintainers- Related: D316, D314, ADR 0160, D175## Context-Settings → General → Appearance presented theme as three preview cards (System /-Light / Dark), with plugin themes wrapping into the same grid. Language and Font-are already searchable picker rows.+Appearance showed theme as three preview cards with plugin themes wrapped into the+same grid, which breaks past three columns, while Language and Font were already+searchable picker rows.## Decision-1. Theme is a searchable picker row, same anchored-menu pattern as Language: the- closed trigger sizes to the current label, capped by the settings control- column, the menu portals so the settings card cannot clip it, and search- filters the list.-2. Built-in System, Light, and Dark stay pinned at the top.+1. Theme becomes a searchable picker row on the Language pattern: the trigger sizes to+ the current label, the menu portals so the card cannot clip it, and search filters+ the list.+2. System, Light, and Dark stay pinned on top; plugin themes follow a divider under the+ host "Provided by" plugin hint, and search matches labels, descriptions, ids, and+ plugin ids.3. `AppSettings.theme` is unchanged (`system` | `light` | `dark` |- `plugin:<pluginId>:<themeId>`).-4. This amends ADR 0160's clause that Appearance keeps Theme as three preview- cards.+ `plugin:<pluginId>:<themeId>`), and an unavailable plugin theme falls back to+ `system`.+4. This amends ADR 0160's clause that Appearance keeps Theme as three cards.## Consequences-- Appearance's three rows — Theme, Language, Font — share one control pattern.-- Plugin themes no longer wrap a three-column card grid.-- Adding a plugin theme does not change the picker chrome.--## Alternatives--- Keep theme as wrapping preview cards: unreadable once plugins add more than- one or two palettes, and inconsistent with Language.-- Keep mini-window mockups inside the picker rows: extra chrome for a choice- that is already visible the moment it is selected.+- Appearance's three rows share one control pattern.+- Plugin themes no longer wrap a card grid.+- Adding a plugin theme leaves the picker chrome unchanged.diff --git a/docs/adr/0162-cross-session-a2a-addressing.md b/docs/adr/0162-cross-session-a2a-addressing.mdindex 801fc2dbd..ef725a1e4 100644--- a/docs/adr/0162-cross-session-a2a-addressing.md+++ b/docs/adr/0162-cross-session-a2a-addressing.md@@ -2,10 +2,7 @@- Status: Superseded by ADR 0165- Date: 2026-09-05-- Deciders: PI-Desktop core-- Related: D318, D277, ADR 0147, ADR 0062, ADR 0089,- `03-runtime/02-agent-runtime.md` §5f.2,- `03-runtime/06-host-rpc-protocol.md` §4, E2E-165, E2E-165b, E2E-165c+- Related: ADR 0062, ADR 0089, ADR 0147, ADR 0164, D318, D277- Amends: ADR 0147. The local A2A broker, capability-token auth, typed parts,durable task lifecycle, and parent-cannot-call-A2A boundary are unchanged.Same-context-only addressing is lifted.@@ -13,12 +10,21 @@## ContextADR 0147 bound every A2A agent to `contextId = sessionId` and refused-cross-context discovery, send, and task access with `A2A_CROSS_CONTEXT_DENIED`.+cross-context discovery, send, and task access with+`A2A_CROSS_CONTEXT_DENIED`, even though the broker is already process-global and+peer ids are only unique per session.## Decision-Allow A2A discovery and addressing across sessions on the same host.+Allow A2A discovery and addressing across sessions on the same host. Each Agent+Card carries `contextId` so a delegate can tell peers apart, task access becomes+membership in `requesterName` / `agentName`, `A2A_UNKNOWN_AGENT` covers strangers,+`A2A_CROSS_CONTEXT_DENIED` remains a documented but unproduced code, live peer ids+are uniquified at registration, and `a2a.task.event` / `a2a.push` carry+`recipientContextId` so a session runtime only delivers its own events.## Consequences-Superseded (Superseded by ADR 0165). The full record is in git history.+Superseded by ADR 0165. Cross-session discovery, the unique live peer ids, and the+`recipientContextId` event shape were kept; nested delegation and any network A2A+binding remained out of scope, with parent-to-parent A2A decided in ADR 0164.diff --git a/docs/adr/0163-transcript-file-reference-chips.md b/docs/adr/0163-transcript-file-reference-chips.mdindex 69ebb44d7..703f73972 100644--- a/docs/adr/0163-transcript-file-reference-chips.md+++ b/docs/adr/0163-transcript-file-reference-chips.md@@ -2,41 +2,34 @@- Status: Accepted- Date: 2026-09-05-- Deciders: PI-Desktop core- Related: D124, D209, D320, ADR 0024, ADR 0070, ADR 0019## Context-Composer file references are compact leaf-name chips in the draft (ADR 0070). On-send they serialize to canonical `@path` / `@"path with spaces"` text so the-agent can Read them.+Composer references are compact leaf-name chips (ADR 0070) but serialize to+canonical `@path` text on send, and the transcript painted those tokens as full+paths that crowded the bubble while clicking one opened a viewer that cannot+render HTML or open PDF and OS-handled types.## Decision-1. The transcript parses serialized `@path` tokens (quoted and unquoted,- relative and absolute) and renders each as a compact chip matching the- composer node: file-family icon, ellipsized leaf name, canonical path in the- tooltip and accessible name.-2. Clicking a workspace `.html` / `.htm` chip opens the work-panel browser- (existing local-file preview).-3. `fs/open` resolves relative paths inside the current workspace and absolute- paths only when they already live under the workspace, `<data_dir>/scratch/`,- or `<data_dir>/attachments/`.-4. Structured message attachments that are not already represented by an inline- `@path` chip use the same chip and click contract.--## Alternatives considered--- **Keep full-path text links:** rejected because it undoes ADR 0070's compact- display the moment the user sends.-- **Always open in the files tab:** rejected because HTML should preview as a- page and many suffixes need the OS handler.-- **Always `shell.openPath`:** rejected for workspace HTML, which already has a- live-reloading in-app browser.+The transcript parses serialized `@path` tokens, quoted or unquoted, relative or+absolute, and renders each as a chip with a file-family icon, ellipsized leaf+name, and the canonical path in tooltip and accessible name, while HTTP(S) URLs+stay inline links. A workspace `.html` / `.htm` chip opens the work-panel+browser, any other allowed file opens through the read-only+`pi-desktop/fs/open` channel, which accepts relative paths inside the workspace+and absolute paths only under the workspace, `<data_dir>/scratch/`, or+`<data_dir>/attachments/`.## Consequences-- Sent user turns show the same file nodes as the composer.-- Users can preview HTML in-app and open other files with the default app.-- Main gains one allowlisted open channel with the same containment roots as- scratch/workspace file tools.+- Sent turns show the same file nodes as the composer, with in-app HTML preview+ and OS handling for other suffixes.+- Main gains one allowlisted open channel confined to existing containment+ roots, with no host protocol or storage change.++## Alternatives++- Always open in the files tab: rejected, HTML needs a page preview and many+ suffixes need an OS handler.diff --git a/docs/adr/0164-parent-cross-conversation-a2a.md b/docs/adr/0164-parent-cross-conversation-a2a.mdindex 5d5cf1ec8..39258d52a 100644--- a/docs/adr/0164-parent-cross-conversation-a2a.md+++ b/docs/adr/0164-parent-cross-conversation-a2a.md@@ -2,25 +2,26 @@- Status: Superseded by ADR 0165- Date: 2026-09-05-- Deciders: PI-Desktop core-- Related: D321, D318, ADR 0147, ADR 0162, ADR 0062,- `03-runtime/02-agent-runtime.md` §5f.2,- `03-runtime/06-host-rpc-protocol.md` §4, E2E-165d- Amends: ADR 0147 (parent must not call `A2A`) and ADR 0162 (no messagingwith the parent). Subagent sibling coordination is unchanged.+- Related: D321, D318, ADR 0147, ADR 0162, ADR 0062## Context-ADR 0147 kept the `A2A` tool out of the parent catalog so the parent could not-open a second, weaker channel to its own delegates.+ADR 0147 kept `A2A` out of the parent catalog so a parent could not open a+second channel to its own delegates, and ADR 0162 then let subagents reach peers+in other sessions but not the parent. Users wanted two sidebar conversations to+coordinate, not two nested workers.## Decision-1. **Each Agent-mode session runtime registers a parent A2A agent** for its- lifetime (first prompt through dispose). The card uses `kind: "parent"`, name- `parent` (host-uniquified to `parent-2`, …), and a description that carries- the session title.+Each Agent-mode session runtime registered a parent A2A agent for its lifetime,+`A2A` became a core Agent-mode parent tool, kinds stayed separate so parents and+subagents could not address each other, inbound notes joined the next parent turn+as an inbox prefix, and reachability followed runtime lifetime.-## Consequences+## Superseded-Superseded (Superseded by ADR 0165). The full record is in git history.+ADR 0165 withdrew the whole A2A / Peer coordination stack, including the parent+agent card, the `A2A` tool, the broker, and the `a2a.*` RPC domain, and restored+`Task*` reports as the only delegate coordination channel.diff --git a/docs/adr/0165-withdraw-a2a-peer-stack.md b/docs/adr/0165-withdraw-a2a-peer-stack.mdindex 7d6175877..2a02e162a 100644--- a/docs/adr/0165-withdraw-a2a-peer-stack.md+++ b/docs/adr/0165-withdraw-a2a-peer-stack.md@@ -2,43 +2,49 @@- Status: Accepted- Date: 2026-09-05-- Deciders: PI-Desktop core-- Related: D326, D277, D318, D321, D325, ADR 0062, ADR 0089,- `03-runtime/02-agent-runtime.md` §5f.2,- `03-runtime/03-tools-and-permissions.md` §10.2,- `03-runtime/06-host-rpc-protocol.md` §3–§4, E2E-165+- Related: D326, D277, D318, D321, D325, ADR 0062, ADR 0089- Supersedes: ADR 0147, ADR 0162, and ADR 0164. ADR 0138 and ADR 0140 remainsuperseded by ADR 0147; this ADR withdraws the replacement those recordsdescribed. Historical ADR files are retained.## Context-ADR 0138 introduced in-process subagent peer messaging (`PeerSend` / `PeerInbox`-/ `PeerWait`). ADR 0140 folded those into one `Peer` tool.+ADR 0138 introduced in-process peer messaging, ADR 0140 folded it into one+`Peer` tool, ADR 0147 replaced it with a host-core A2A broker, an `a2a.*` RPC+domain, durable `a2a_*` tables, and a delegate `A2A` tool, and ADR 0162 / ADR+0164 extended it to cross-session parents. That stack sat beside the existing+`Task` contract, added a protocol capability the rest of the app did not use, and+was easy for the model to miss or misuse, while concurrent delegates already+report through the parent.## Decision-Remove the A2A / Peer coordination stack from the product:+Remove the A2A / Peer coordination stack from the product.1. **No A2A or Peer tool.** Neither name is a core Agent tool, an assignable- subagent tool, or a `ToolSearch` result.-2. **No broker.** Delete the host-core `a2a` module, the in-memory registry, the- leftover in-process `SubagentMailbox`, and every `a2a.*` RPC method and- `a2a.task.event` / `a2a.push` notification.+ subagent tool, or a `ToolSearch` result; a definition listing one is dropped+ with a parse warning like any unknown tool name.+2. **No broker.** The host-core `a2a` module, the in-memory registry, the+ in-process `SubagentMailbox`, every `a2a.*` RPC method, and the+ `a2a.task.event` / `a2a.push` notifications are deleted.3. **No parent or sibling channel.** Concurrent delegates coordinate only bywriting self-contained reports the parent collects through `Task*`.-4. **Protocol v11.** Handshake `PROTOCOL_VERSION` moves from 10 to 11.-5. **Schema v13.** `SCHEMA_VERSION` moves from 12 to 13.+4. **Protocol v11.** `PROTOCOL_VERSION` moves from 10 to 11, `capabilities` no+ longer advertises `"a2a"`, and a v10 host or client is rejected at handshake.+5. **Schema v13.** `SCHEMA_VERSION` moves from 12 to 13, `migrate_v12_to_v13`+ drops `a2a_tasks`, `a2a_messages`, `a2a_artifacts`, and `a2a_push_configs`,+ and fresh databases never create them.Delegation itself (ADR 0062 / ADR 0089) is unchanged: `Task` still fans out-bounded workers, reports still stay out of the parent model context until-`TaskWait`, and builtins stay read-only by default.+bounded workers, reports stay out of the parent context until `TaskWait`, and+builtins stay read-only by default.## Consequences-- Cross-conversation and sibling messaging are gone.-- The roundtable example plugin no longer tells delegates to call `Peer` or- `A2A`.-- Historical changelog entries for 0.11.3 (peer messaging) and 0.12.0 (A2A) stay- as shipped history.-- ADRs 0138, 0140, 0147, 0162, and 0164 remain on disk as records.+- Cross-conversation and sibling messaging are gone; sessions share facts+ through the prompt, not a tool.+- The roundtable example plugin runs independent concurrent `Task`s and lets the+ parent synthesize the reports instead of calling `Peer` or `A2A`.+- Historical changelog entries for 0.11.3 and 0.12.0 stay as shipped history,+ product READMEs drop current A2A claims, and ADRs 0138, 0140, 0147, 0162, and+ 0164 remain on disk as records.diff --git a/docs/adr/0166-parent-judged-subagent-lifetime.md b/docs/adr/0166-parent-judged-subagent-lifetime.mdindex 7fec17453..fc12b2a62 100644--- a/docs/adr/0166-parent-judged-subagent-lifetime.md+++ b/docs/adr/0166-parent-judged-subagent-lifetime.md@@ -2,38 +2,39 @@- Status: Accepted for implementation- Date: 2026-09-06-- Deciders: PI-Desktop core-- Related: D328, ADR 0089, ADR 0119, ADR 0129, issue discussion on- GitHub #44 follow-on (parent closing kills unfinished delegates)+- Related: D328, ADR 0089, ADR 0119, ADR 0129, GitHub #44 follow-on## Context-ADR 0089 made `Task` non-blocking and told the parent to `TaskWait` or-`TaskStop` before ending a turn. The safety net was to abort leftover delegates-on parent `agent_end`.+ADR 0089 made `Task` non-blocking and told the parent to converge before ending+a turn, with aborting leftover delegates as the safety net, and ADR 0119 /+ADR 0129 armed idle and duration watchdogs. In practice long compiles, tests,+and audits died because the parent closed, not because the work was done, and+prompting the model to wait longer cannot fix an event loop it cannot run.## Decision-1. **Do not time-kill a delegate.** Idle and duration watchdogs are not armed.-2. **Do not abort on parent idle.** `agent_end` / `turn_end` while delegates are- running are swallowed.-3. **Deliver reports when they finish.** After the parent loop idles with- running delegates, the runtime waits for them and prompts the parent with the- joined reports (not shown as a user bubble).-4. **Give the parent a heartbeat, not the transcript.** `TaskList` and a- timed-out `TaskWait` include agent, status, elapsed seconds, turns, tool- calls, and last tool name.+Do not time-kill a delegate: idle and duration watchdogs are not armed, though+`idle-timeout` / `max-duration` still parse as inert so old documents load,+explicit `maxTurns` remains a backstop, and concurrency stays capped at 10. Do+not abort on parent idle: `agent_end` / `turn_end` with running delegates are+swallowed and the durable turn stays open, while user Stop, `TaskStop`, runtime+dispose, and a parent fatal error (D352 / ADR 0189) still abort. Deliver the+joined reports when delegates finish and let the parent judge, and give the+parent a heartbeat through `TaskList` and a timed-out `TaskWait` rather than+transcript rows.## Consequences-- A long delegate can outlive the parent's last tool call.+- A delegate can outlive the parent's last tool call while the user still sees a+ live turn with Stop available.- The parent no longer has to poll correctly for the job to survive.-- A looping delegate without `maxTurns` can run until the user Stops it.-- ADR 0119 / ADR 0129 watchdog policy is withdrawn for killing.+- A looping delegate without `maxTurns` runs until the user stops it, and the+ watchdog killing policy of ADR 0119 / ADR 0129 is withdrawn.-## Alternatives rejected+## Alternatives-- **Progress file the parent Reads (Claude Code).** Puts live transcript into- the parent context and requires the model to remember to poll.-- **Keep abort-on-end and only raise TaskWait.** The model still closes.-- **Survive the turn with no auto-resume.** The user has to send 继续.+- A progress file the parent reads: rejected, it puts live transcript into the+ parent context and still depends on the model remembering to poll.+- Survive the turn without auto-resume: rejected, the user would have to send+ 继续 manually.diff --git a/docs/adr/0167-agent-chosen-bash-timeout.md b/docs/adr/0167-agent-chosen-bash-timeout.mdindex 89bcb90ac..88d86549e 100644--- a/docs/adr/0167-agent-chosen-bash-timeout.md+++ b/docs/adr/0167-agent-chosen-bash-timeout.md@@ -7,22 +7,23 @@## Context-ADR 0054 / D190 required a 60-second default Bash timeout and rejected any-override outside 1–300 seconds. That 5-minute ceiling killed legitimate builds,-tests, and audits, and `timeout: 600` / `1800` failed immediately with-`INVALID_ARGUMENT`.+ADR 0054 / D190 required a 60-second default Bash timeout and rejected overrides+outside 1–300 seconds, so legitimate builds, tests, and audits died at five minutes+and D273's millisecond tolerance still clamped them to that ceiling. A timeout stays+mandatory: every spawn needs a finite deadline.## Decision1. Missing `timeout` still means exactly 60 seconds.-2. An explicit override is 1 through 21,600 seconds (6 hours).-3. A value above 21,600 is read as milliseconds (D273), converted, and clamped- to 21,600 seconds.-4. Out-of-range values still fail validation and never spawn.-5. Timeout and user abort still terminate the complete process tree.+2. An explicit override is 1 through 21,600 seconds (6 hours) — a host safety bound+ keeping RPC and the process timer finite, not a product cap.+3. A value above 21,600 is read as milliseconds (D273), converted, and clamped to+ 21,600 seconds; in-range values, including 600 and 1800, are seconds.+4. Out-of-range values fail validation and never spawn, and timeout or abort still+ kills the process tree.## Consequences-- `timeout: 600` / `1800` / `1800000` honour 10 and 30 minutes.-- A command with no timeout still dies at 60 seconds.-- Host-core `MAX_BASH_TIMEOUT_MS` stays in lockstep with the runtime.+`timeout: 600`, `1800`, and `1800000` honour 10 and 30 minutes, no-timeout commands+still die at 60 seconds, and Host-core `MAX_BASH_TIMEOUT_MS` stays in lockstep with+the runtime.diff --git a/docs/adr/0168-main-owned-open-external-allowlist.md b/docs/adr/0168-main-owned-open-external-allowlist.mdindex 468feb0ba..821ffd123 100644--- a/docs/adr/0168-main-owned-open-external-allowlist.md+++ b/docs/adr/0168-main-owned-open-external-allowlist.md@@ -2,41 +2,30 @@- Status: Accepted- Date: 2026-09-06-- Deciders: PI-Desktop core-- Related: D330, ADR 0109, GitHub pull request #45+- Related: ADR 0109, D330, GitHub pull request #45## Context-Chat markdown, plugin panels, the plugin launcher, OAuth login, and the embedded-preview all eventually call Electron `shell.openExternal`. The main window and-launcher `setWindowOpenHandler` previously forwarded the raw URL.+Chat markdown, plugin panels, the launcher, OAuth login, and the embedded preview+all reach `shell.openExternal`, and the window-open handlers forwarded raw URLs,+so a prompt-injected `file:`, `javascript:`, `ms-msdt:`, or custom scheme could+reach an OS protocol handler after one click. Preview and plugin-view handlers+used a `/^https?:/i` prefix check, which is weaker than parsing.## Decision-1. Electron Main owns one parser (`parseAllowedExternalUrl`).-2. Disallowed URLs throw.-3. Workspace files stay on `shell.openPath` after the existing path gate.-4. Main-constructed URLs (GitHub feedback, releases) still pass the parser.+Electron Main owns one parser, `parseAllowedExternalUrl`: a URL reaches+`shell.openExternal` only when `new URL` yields `http:`, `https:` with a hostname+and a written `//`, or `mailto:` with an address, and control characters fail+closed. Disallowed URLs throw, so window-open handlers catch and ignore, OAuth+reports "browser did not open", and plugins keep `INVALID_ARGUMENT`.## Consequences-- Custom URI schemes from chat, plugins, or `window.open` cannot launch OS- handlers.-- `mailto:` remains a supported plugin and link target.-- `https:alert(1)`-style special-scheme filling is rejected.+- Custom URI schemes cannot launch OS handlers, while `mailto:` stays supported+ and `https:alert(1)`-style scheme filling is rejected.## Alternatives considered-### http/https only, blocking mailto--Rejected: it would break the documented plugin API and ADR 0109.--### Prefix regex `/^https?:/i`--Rejected: it matches `https:payload` without a host and diverges from the plugin-runtime's `://` check.--### Returning `false` instead of throwing--Rejected: OAuth already maps a rejected `openExternal` promise to `opened:-false`.+- Block `mailto:`: rejected; it breaks the documented plugin API and ADR 0109.+- Keep the prefix regex: rejected; it matches `https:payload` without a host.diff --git a/docs/adr/0169-classified-file-preview-and-live-workspace-events.md b/docs/adr/0169-classified-file-preview-and-live-workspace-events.mdindex 63a869b63..bb105b0a5 100644--- a/docs/adr/0169-classified-file-preview-and-live-workspace-events.md+++ b/docs/adr/0169-classified-file-preview-and-live-workspace-events.md@@ -2,55 +2,42 @@- Status: Accepted- Date: 2026-09-06-- Deciders: PI-Desktop core-- Related: [ADR 0104](0104-plugin-contributed-work-panel-views.md) ·- [ADR 0105](0105-files-as-a-bundled-plugin.md) ·- [ADR 0109](0109-open-files-with-the-os-associated-application.md) ·- [ADR 0111](0111-reveal-files-in-file-manager.md) · D332 · E2E-153+- Related: [ADR 0104](0104-plugin-contributed-work-panel-views.md) · [ADR 0105](0105-files-as-a-bundled-plugin.md) · [ADR 0109](0109-open-files-with-the-os-associated-application.md) · [ADR 0111](0111-reveal-files-in-file-manager.md) · D332 · E2E-153## ContextThe bundled `pi.files` view is a public plugin consumer (ADR 0105). After it-replaced the host Files tool, several first-party browsing behaviors were-missing or broken:--1. `fs.readText` cannot classify images, binary files, or oversized files, so- the plugin reported images as unavailable and could load large binaries as- UTF-8.-2. `fs.openDefault` existed (ADR 0109) but left the Files UI when reveal- replaced the header action (ADR 0111).-3. Panel events such as `appearance:changed` were broadcast only to detached- `ui.panel` windows.-4. `workspace:changed` was specified as planned.+replaced the host Files tool, `fs.readText` could not classify images, binaries, or+oversized files, **Open with default app** had left the UI with reveal (ADR 0111),+panel events reached only detached `ui.panel` windows, and the view polled+`workspace.get` because `workspace:changed` did not exist.## Decision1. Add `pi.fs.readPreview(pathFromRoot)` and the panel channel `fs.readPreview`,- gated by the existing `fs.read` permission and the complete declared-scope- checks.-2. Broadcast every plugin panel event to both detached panel windows and live- docked views over the same `pi-plugin-panel-event:<event>` preload channel.-3. Deliver `workspace:changed` to panels and plugin processes whenever the- cached workspace path changes.-4. Restore **Open with default app** in the bundled Files viewer, add search- through `fs.glob`, copy the root-relative path from a user gesture, and- preview images through `fs.readPreview`.+ gated by `fs.read` and the declared-scope checks, classifying one existing+ regular file as `text`, `image`, `binary`, or `tooLarge` under the host Files tab+ size caps; images return a data URL, binary and oversized files return no+ payload bytes, and directories are rejected.+2. Broadcast every plugin panel event to detached windows and live docked views+ over the same `pi-plugin-panel-event:<event>` preload channel.+3. Deliver `workspace:changed` to panels and plugin processes whenever the cached+ workspace path changes, with the `workspace.get()` payload `{ path, name } |+ null`.+4. Restore **Open with default app**, add search through `fs.glob`, copy the+ root-relative path from a user gesture, and preview images through+ `fs.readPreview`, all on public APIs.## Consequences-- Third-party plugins can preview images and oversized files without inventing a- second read API.+- Plugins can preview images and oversized files without a second read API.- A docked view follows theme, locale, and project switches live.-- The Files plugin remains a public-API consumer; transcript `file:<path>` tabs- stay host-owned.+- The Files plugin stays a public-API consumer; transcript `file:<path>` tabs stay+ host-owned.-## Alternatives considered+## Alternatives-### Reuse `fs.readText` and detect images in the plugin--Rejected: UTF-8 decoding of PNG/JPEG is lossy, has no size cap, and cannot-produce a data URL without a binary channel.--### A private Files IPC channel--Rejected: that would recreate the host/plugin exception ADR 0105 removed.+- Detect images in the plugin from `fs.readText`: rejected, UTF-8 decoding of PNG+ or JPEG is lossy and cannot produce a data URL.+- A private Files IPC channel: rejected, it recreates the host/plugin exception+ ADR 0105 removed.diff --git a/docs/adr/0170-work-panel-browser-as-bundled-plugin.md b/docs/adr/0170-work-panel-browser-as-bundled-plugin.mdindex 47f9097f3..2b8f44aa9 100644--- a/docs/adr/0170-work-panel-browser-as-bundled-plugin.md+++ b/docs/adr/0170-work-panel-browser-as-bundled-plugin.md@@ -11,45 +11,50 @@## ContextThe work-panel browser was a host-built launcher row (`HEADER_TOOLS`) plus a-Main-owned `WebContentsView` guest. Files already proved that a first-party-surface can ship as a bundled plugin on the public `contributes.views` channel.+Main-owned `WebContentsView` guest, while Files already proved a first-party surface+can ship as a bundled plugin on the public `contributes.views` channel — enabled or+disabled on the Plugins page, never uninstallable.++The plugin page cannot *be* the browser: plugin views are sandboxed, have+`webviewTag: false`, and are confined by `net.domains`, so arbitrary http(s),+workspace files, and Chrome DevTools Protocol must stay on a host-owned guest.## Decision1. **`pi.browser` is a bundled plugin** in `apps/desktop/resources/plugins/`,- enabled by default, disableable, not uninstallable.+ enabled by default, disableable, not uninstallable. It contributes view `browser`+ (icon token `browser`, order 10) and registers the agent tool `Browser`.2. **The guest `WebContentsView` (`persist:work-browser`) and debugger stay- host-owned.** Plugin chrome is a normal plugin view.-3. **`browser.cdp` is a public permission** (high).-4. **Raw CDP is allowlisted and deny-by-default.** Cookie, storage, target, and- network-interception methods are refused.-5. **Host `BrowserPreview` remains a thin facade** (Plan/subagent name- stability).-6. The original singleton guest decision is superseded by [Retain a host-owned- browser page per resource tab](retained-browser-pages-per-tab.md).--This supersedes ADR 0105 clause 4 (Browser remains a host-built launcher) and-the host-launcher clause of ADR 0019. Guest ownership and navigation policy are-unchanged.+ host-owned.** Plugin chrome is a normal plugin view, and the guest is stacked on a+ content-relative hole the chrome reports through `pi.browser.setBounds`.+3. **`browser.cdp` is a public high-risk permission** and `pi.browser.*` a public+ host API, with raw CDP allowlisted and deny-by-default (cookie, storage, target,+ and network-interception methods refused, no DevTools websocket), and bounds+ clamped to the calling plugin view.+4. **Host `BrowserPreview` remains a thin facade** for Plan/subagent name stability:+ it errors when `pi.browser` is disabled, otherwise loading the workspace file into+ a session-owned guest. [Background browser pages](browser-background-lifecycle.md)+ supersedes the visible-before-operation rule and+ [retained browser pages per tab](retained-browser-pages-per-tab.md) replaces the+ singleton guest with one page per session and tab.++This supersedes ADR 0105 clause 4, the host-launcher clause of ADR 0019, and+ADR 0108's "Browser as the host-built tool" clause; guest ownership and navigation+policy are unchanged.## Consequences-- Disabling `pi.browser` removes the launcher row, agent CDP, and guest.-- Tools with `browser.cdp` address their invoking session's connected page;- unscoped plugin UI calls still require the current visible Browser view.-- Plan still sees `BrowserPreview`.--## Alternatives considered--### Load the web page inside the plugin view--Rejected: would require `webviewTag`, a wildcard `net.domains`, and attaching-CDP to the wrong WebContents.--### Private host APIs only `pi.browser` may call--Rejected: the Files bar is that first-party features prove the public channel.+- Disabling `pi.browser` removes the launcher row, agent CDP, and guest, URL chips+ fall back to `openExternal`, and `BrowserPreview` fails closed.+- `browser.cdp` tools address their invoking session's connected page, and Plan keeps+ `BrowserPreview` with the four `planSafeActions` (`navigate`, `snapshot`,+ `screenshot`, `console`) Plan/Goal-safe while click/fill/evaluate/cdp stay+ Agent-only (ADR 0211).-### Keep React `BrowserTab` chrome and only plugin-ize the launcher+## Alternatives-Rejected: that is not “the whole default browser is a plugin.”+- Load the page inside the plugin view: needs `webviewTag`, a wildcard+ `net.domains`, and CDP on the wrong WebContents.+- Private host APIs only `pi.browser` may call: Files proved the public channel.+- Keep React `BrowserTab` chrome and only plugin-ize the launcher: that is not a+ browser shipped as a plugin.diff --git a/docs/adr/0171-host-owned-completed-turn-token-history.md b/docs/adr/0171-host-owned-completed-turn-token-history.mdindex e224e695f..eec148fa7 100644--- a/docs/adr/0171-host-owned-completed-turn-token-history.md+++ b/docs/adr/0171-host-owned-completed-turn-token-history.md@@ -2,41 +2,35 @@- Status: Accepted (amended by ADR 0173)- Date: 2026-09-07-- Deciders: PI-Desktop core-- Related: D103, D157, D331, D335, ADR 0014, ADR 0173,- `03-runtime/04-data-storage.md` §4.6,- `03-runtime/06-host-rpc-protocol.md`,- `04-ux/06-settings-ia.md`, E2E-186+- Related: D103, D157, D331, D335, ADR 0014, ADR 0173## Context-The `turns` table already stores `input_tokens`, `output_tokens`, and-`usage_json`, and `session.endTurn` already accepted `usage`. Electron never-sent it.+The `turns` table already stores `input_tokens`, `output_tokens`, and `usage_json`,+and `session.endTurn` already accepted `usage`, but Electron never sent it, while+per-message chips read provider usage from assistant `meta_json`, where subagent+spend would inflate the context inspector. A durable completed-turn total is still+needed without a new schema version.## Decision-1. **Parent `message.usage` stays provider-reported.** Subagent totals never- merge into an assistant row.-2. **Turn rollup is `session.endTurn.usage`.** Electron sums every parent- assistant `message_end` usage for the durable turn and adds- `turn_end.subagentUsage` deltas.-3. **`stats.getTokenUsageHistory` is an additive host RPC.** It reads completed- turns in a bounded local-calendar window, buckets by `day` / ISO `week` /- `month`, fills empty buckets, and does not bump `PROTOCOL_VERSION` or- `SCHEMA_VERSION`.-4. **The user-facing dashboard is not Settings.** ADR 0173 moves that surface to- marketplace plugin `pi.token-insights`.+1. **Parent `message.usage` stays provider-reported.** Subagent totals never merge+ into an assistant row.+2. **Turn rollup is `session.endTurn.usage`.** Electron sums every parent assistant+ `message_end` usage and adds `turn_end.subagentUsage` deltas.+3. **`stats.getTokenUsageHistory` is an additive host RPC** that reads completed+ turns in a bounded calendar window, buckets by `day` / ISO `week` / `month`, and+ bumps neither `PROTOCOL_VERSION` nor `SCHEMA_VERSION`.+4. **The dashboard is not Settings.** ADR 0173 moves that surface to plugin+ `pi.token-insights`, and rows written before Electron sent `usage` may be zero.## Consequences-- Context inspector and D103 chips keep exact provider values.+- Context inspector and chips keep exact provider values.- New completed turns populate host history; older turns may be zero.-- The heatmap lives in `pi.token-insights` (ADR 0173).-- A later backfill from transcript `meta.usage` would be a separate change.+- A backfill from transcript `meta.usage` would be a separate change.## Alternatives-- Rewrite parent `message.usage` with subagent spend: rejected (D103).-- Scan JSONL transcripts in the host Settings page: rejected (unbounded, wrong- owner).+- Rewrite parent `message.usage` with subagent spend — rejected: it corrupts the+ inspector and composed-turn total.diff --git a/docs/adr/0172-contained-in-chat-image-display.md b/docs/adr/0172-contained-in-chat-image-display.mdindex b64723eb8..b80b318f3 100644--- a/docs/adr/0172-contained-in-chat-image-display.md+++ b/docs/adr/0172-contained-in-chat-image-display.md@@ -2,43 +2,38 @@- Status: Accepted- Date: 2026-09-07-- Related: ADR 0019, ADR 0163, ADR 0169, decisions D320/D334, E2E-187+- Related: ADR 0019, ADR 0163, ADR 0169, decisions D320/D334- Amends: the `fs/read` workspace-only clause of the desktop IPC spec## Context-Pasted and uploaded images are stored as extension-less `attachments/<sha256>`-blobs under the data directory. Local Markdown images are workspace-relative.+Pasted and uploaded images are extension-less `attachments/<sha256>` blobs under the+data directory and local Markdown images are workspace-relative, so the renderer+origin could load neither and showed a chip instead of the picture. A generic+absolute-path read channel would let the renderer exfiltrate arbitrary disk+contents.## Decision-1. Keep `fs/list` workspace-only.-2. Add renderer-only `fs/readImageDataUrl({ref, mimeType?})`.-3. A known image extension always wins over a client-supplied `mimeType`.-4. Chat thumbnails and local Markdown images load through that channel.+1. `fs/list` stays workspace-only, while `fs/read`, `fs/reveal`, and `fs/open` share+ `resolveOpenablePath`: workspace-relative paths, absolute paths already inside the+ workspace, `<data_dir>/scratch/`, or `<data_dir>/attachments/`, and+ content-addressed `attachments/<sha256>` refs, with reads re-checking realpath+ containment.+2. A renderer-only `fs/readImageDataUrl({ref, mimeType?})` returns a bounded data URL+ or `missing` / `notImage` / `tooLarge` and never non-image bytes.+3. A known image extension always wins over a client-supplied `mimeType`, and+ extension-less blobs accept only the `IMAGE_MIME` allowlist.+4. Chat thumbnails and local Markdown images load through that channel, and clicking+ a resolved image opens the host files viewer.## Consequences-- History attachments and local Markdown images render inline when the file is- still present and under the cap.-- `/etc/passwd` and other outside-root paths stay unreadable even with a spoofed- `mimeType`.-- Plugin Files views remain workspace-scoped; transcript artifacts still use the- host `file:` tab.+- Attachments and local Markdown images render inline while the file exists and stays+ under the cap.+- Paths outside the allowed roots stay unreadable even with a spoofed `mimeType`.+- Plugin Files views remain workspace-scoped.-## Alternatives rejected+## Alternatives-### New unbounded absolute-path read--Rejected because the renderer IPC is not a user-click gate.--### Reuse `fs.readPreview` from the chat renderer--Rejected because that API is plugin-scoped to the workspace root and cannot see-`attachments/<sha256>` blobs.--## References--- `apps/desktop/electron/main/fs-panel.ts`-- `apps/desktop/src/lib/use-referenced-image-data-url.ts`-- `docs/spec/03-runtime/01-ipc-protocol.md`+- New unbounded absolute-path read — rejected: renderer IPC is not a user-click gate.diff --git a/docs/adr/0173-plugin-owned-token-usage-dashboard.md b/docs/adr/0173-plugin-owned-token-usage-dashboard.mdindex 97edf7424..9af28afce 100644--- a/docs/adr/0173-plugin-owned-token-usage-dashboard.md+++ b/docs/adr/0173-plugin-owned-token-usage-dashboard.md@@ -2,40 +2,36 @@- Status: Accepted- Date: 2026-09-07-- Deciders: PI-Desktop core-- Related: D103, D331, D335, ADR 0171, `04-ux/06-settings-ia.md`,- E2E-186, marketplace plugin `pi.token-insights`+- Related: D002, D103, D331, D335, ADR 0171## ContextADR 0171 added host-owned completed-turn token history and a Settings → Usage-destination. The marketplace plugin `pi.token-insights` already ships a private-local dashboard (heatmap, KPIs, filters, streaks, agent tool) across PI-Desktop,-Claude Code, Codex, and OpenCode.+destination, but the marketplace plugin `pi.token-insights` already ships a local+dashboard across PI-Desktop, Claude Code, Codex, and OpenCode, so keeping both+duplicated a weaker PI-Desktop-only matrix inside Preferences.## Decision-1. **Settings has no Usage destination.** Preferences is General, AI, and- Shortcuts.-2. **`pi.token-insights` is the user-facing dashboard.** Command palette- keywords (`usage`, `tokens`, `用量`) open that plugin.-3. **Host persistence stays.** Electron still sums parent `message_end` usages- plus `turn_end.subagentUsage` into `session.endTurn.usage`.-4. **The plugin may fold host completed-turn remainders** into its PI-Desktop- fact cube when those totals exceed transcript assistant `meta.usage`, so- subagent spend is visible without double-counting JSONL messages.+1. Settings has no Usage destination: Preferences is General, AI, and Shortcuts,+ and search does not index a usage tab.+2. `pi.token-insights` is the user-facing dashboard, and command palette keywords+ (`usage`, `tokens`, `用量`) open that plugin.+3. Host persistence stays: Electron still sums parent `message_end` usages plus+ `turn_end.subagentUsage` into `session.endTurn.usage`, and+ `stats.getTokenUsageHistory` remains an additive host RPC / IPC for local+ rollups, not a Settings page.+4. The plugin may fold host completed-turn remainders into its fact cube where they+ exceed transcript assistant `meta.usage`, so subagent spend is visible without+ double-counting; it never rewrites `message.usage`.## Consequences- Users who want a heatmap install or open Token Insights.-- Historical turns from before Electron sent `usage` may still be zero in the- host RPC; the plugin's JSONL scan remains the backfill for those days.-- A later first-party plugin API wrapping `stats.getTokenUsageHistory` is a- separate change.+- Historical turns may still be zero in the host RPC; the plugin's JSONL scan+ backfills those days.## Alternatives-- Keep Settings → Usage beside the plugin: rejected (duplicate IA).-- Delete host turn persistence: rejected (D331 accounting).-- Let the plugin replace JSONL with the turns table: rejected (loses per-message- model/provider rankings and pre-persistence history).+- Keep Settings → Usage beside the plugin: duplicates the IA.+- Delete host turn persistence: loses D331 accounting.diff --git a/docs/adr/0174-plugin-host-owned-completion-and-session-context.md b/docs/adr/0174-plugin-host-owned-completion-and-session-context.mdindex c4e5600b4..7e58f4f95 100644--- a/docs/adr/0174-plugin-host-owned-completion-and-session-context.md+++ b/docs/adr/0174-plugin-host-owned-completion-and-session-context.md@@ -8,73 +8,60 @@## Context-Pi CLI extensions can let an executor model call a zero-parameter reviewer tool.-The host serializes the resolved LLM context and runs a one-shot completion-against a stronger reviewer using the user's existing credentials.+Pi CLI extensions can let an executor model call a zero-parameter reviewer tool, with+the host serializing the resolved LLM context and running a one-shot completion on a+stronger reviewer under the user's existing credentials.-- list the models the user has authenticated-- read the current session's model-facing transcript-- spend the user's provider quota on a side completion+Desktop plugins can register tools, commands, settings, and skills, but cannot list+authenticated models, read the session's model-facing transcript, or spend quota on a+side completion. A plugin calling providers itself would need secrets (forbidden,+D018) or a pasted key, and D019 denied session-summary access by default, while+composer `prompt/enhance` already proves a host-owned one-shot path that never hands+a secret to the renderer.## Decision-1. **Three public plugin APIs**, gated by new permissions:- - `models.list` (medium) — `pi.models.list()` returns ready `(providerId,- modelId)` rows.- - `session.read` (high) — `pi.session.getLlmContext()` returns a bounded,- compaction-aware projection of the **in-flight tool session**.- - `agent.complete` (high) — `pi.agent.complete({ modelKey, thinkingLevel,- system, messages, includeSessionContext })` runs a host-owned one-shot- completion with `tools: []` through the same credential resolver as agent- turns and prompt enhancement.--2. **Host owns credentials and the wire call.** The plugin process never- receives an API key, OAuth refresh token, or short-lived `ModelAuth`.--3. **Session context is a projection, not a dump.** Subagent rows are omitted.--4. **Rate and size brakes.** Eight `agent.complete` calls per plugin per rolling- 60s.--5. **`session:modelChanged` is a host event** pushed after a successful- `session.configure` that changes provider, model, or thinking level.--6. **D019 is amended, not withdrawn.** Session content remains denied until- `session.read` is declared and granted.--7. **Bundled Advisor is temporarily not shipped.** The public APIs remain- available to explicitly installed plugins, but PI-Desktop does not bundle a- first-party reviewer command, panel, skill, or agent tool for now.--No host-protocol or storage schema bump. Completions are Electron-local, like-`prompt/enhance`.+1. **Three public plugin APIs**, gated by new permissions: `models.list` (medium)+ returns ready `(providerId, modelId)` rows without secrets; `session.read` (high)+ lets `pi.session.getLlmContext()` return a bounded, compaction-aware projection of+ the **in-flight tool session**, identified by `plugins.execute` rather than a+ plugin-supplied id (D333); `agent.complete` (high) runs+ `pi.agent.complete({ modelKey, thinkingLevel, system, messages,+ includeSessionContext })` as a host-owned one-shot with `tools: []`, where+ `includeSessionContext: true` also needs `session.read`.+2. **Host owns credentials and the wire call.** The plugin process never receives an+ API key, OAuth refresh token, or `ModelAuth`; completions reuse+ `resolveAgentRuntimeLaunch`.+3. **Session context is a projection, not a dump**: subagent rows are omitted, the+ plugin's own in-flight call is stripped from the tail, compaction summaries+ replace pre-checkpoint history, tool results are truncated, and the payload is+ capped. Audit logs record plugin id, model key, sizes, and usage, never transcript+ text.+4. **Rate and size brakes**: eight `agent.complete` calls per plugin per rolling 60s,+ system prompt ≤ 32 KiB, messages ≤ 200k characters, and a 90s completion budget+ under the 110s plugin-tool timeout.+5. **`session:modelChanged` is a host event** pushed after a `session.configure` that+ changes provider, model, or thinking level. D019 is amended, not withdrawn:+ session content stays denied without `session.read`, while tool-exec context may+ carry `modelKey` and `thinkingLevel` because those are configuration. No bundled+ Advisor ships.++No host-protocol or storage schema bump; completions are Electron-local.## Consequences-- Third-party plugins can build reviewer / second-opinion tools without holding- keys.-- `session.read` + `agent.complete` is a legitimate conversation-exfil channel- to another model the user already pays for.-- Plugin tools keep the D015 prefix.-- One-shot completion spend is audited on the plugin call and is not merged into- the parent assistant usage chip (ADR 0171).--## Alternatives rejected--### Load the npm Pi CLI extension in the sidecar--The sidecar is not the Pi TUI extension host.--### Let the plugin call providers through `net.fetch`--Would require secrets in plugin settings (D018) or a user-pasted key, and would-skip host retry, OAuth, and audit.--### First-party reviewer tool instead of a plugin--Deferred for now: the bundled reviewer experience is temporarily removed while-the public host APIs remain available for explicitly installed plugins.--### Give plugins an arbitrary `sessionId` argument--Rejected: a plugin could read every open conversation.+- Third-party plugins can build reviewer tools without keys, but `session.read` plus+ `agent.complete` is a legitimate conversation-exfiltration channel to another+ model the user pays for, so install UI must show both permissions and their help+ text.+- Plugin tools keep the D015 prefix, Plan/Goal still hard-deny them, and one-shot+ spend is audited on the plugin call rather than merged into the parent usage chip+ (ADR 0171).++## Alternatives++- Load the npm Pi CLI extension in the sidecar: it is not the Pi TUI extension host+ and the CLI command needs a TTY.+- Let plugins call providers through `net.fetch`: needs secrets in settings and skips+ host retry, OAuth, and audit.+- Give plugins an arbitrary `sessionId`: a plugin could read every conversation.diff --git a/docs/adr/0175-live-agent-activity-status.md b/docs/adr/0175-live-agent-activity-status.mdindex 09c5d657d..038cd2526 100644--- a/docs/adr/0175-live-agent-activity-status.md+++ b/docs/adr/0175-live-agent-activity-status.md@@ -5,62 +5,30 @@## Context-The transcript already shows a compact `Working…` row before the first model or-tool event and inline rows for concrete thinking and tool activity. A provider-request can still spend a long interval before its first event, and a bounded-retry backoff or parent-side delegated-task wait can contain no transcript row.+The transcript shows a compact `Working…` row before the first model or tool event,+but a provider request can spend a long interval before that event, and a retry+backoff or a parent-side delegated-task wait carries no row at all. The only signals+were the Stop button and a local timer, so users could not tell a normal wait from a+retry or a delegation wait (issue #56).## Decision-Extend the existing normalized `status` event with an optional runtime-owned-`AgentActivity` value:--1. `starting` covers the initial prompt handoff.-2. `waiting-model` starts when a provider request is issued and lasts until the- first assistant event.-3. `retrying` covers an abortable provider backoff and carries the attempt- number and calculated delay when available.-4. `waiting-subagents` covers parent-side convergence on delegated work and- carries the number of running targets.--The sidecar emits these phases from the same boundaries that own provider-requests, retry delays, and delegation waits. It clears the phase when assistant-output starts or the turn reaches a terminal event.+Extend the normalized `status` event with an optional runtime-owned `AgentActivity`+value. `starting` covers the prompt handoff, `waiting-model` runs from issuing a+provider request until the first assistant event, `retrying` covers an abortable+backoff and carries the attempt number and delay, and `waiting-subagents` covers+parent-side convergence with the number of running targets. The sidecar emits these+from the boundaries that already own provider requests, retry delays, and+delegation waits, and clears them when output starts or the turn terminates. The+renderer keeps the latest status per session and renders a compact localized inline+row with a monotonic phase timer; it claims no completion percentage and leaves Stop+and abort semantics alone.## Consequences-- A quiet active turn explains its current runtime-owned wait without adding- decorative or duplicate progress chrome.-- Retry lifecycle remains silent in the transcript, while the retry backoff- becomes observable and remains cancellable.-- Session switching remains isolated because status is keyed by session id and- is cleared with terminal events and session deletion.-- The status is intentionally coarse: provider internals and subagent child- events remain out of the renderer protocol unless they explain one of these- user-visible waits.--## Alternatives--### Keep the generic Working row for every wait--Rejected because it does not distinguish a normal provider wait from a retry or-delegation wait, which was the ambiguity reported in Issue #56.--### Add a permanent multi-step progress card--Rejected because agent turns do not have a reliable total-step or percentage-model, and the existing active-turn contract keeps the lower transcript surface-inline and compact.--### Emit raw provider or child-agent events--Rejected because it would expose unstable implementation details and create a-larger protocol surface than the user needs.--## References--- `docs/spec/03-runtime/01-ipc-protocol.md`-- `docs/spec/03-runtime/02-agent-runtime.md`-- `docs/spec/04-ux/09-interaction-patterns.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-008c, E2E-094)-- GitHub Issue #56+- A quiet turn explains its runtime-owned wait without duplicate progress chrome,+ and a retry backoff becomes observable while staying cancellable.+- Status is keyed by session id and cleared on terminal events and deletion, so+ session switching stays isolated.+- The protocol stays coarse: provider internals and child-agent events remain out of+ the renderer unless they explain one of these waits.diff --git a/docs/adr/0176-per-provider-user-agent.md b/docs/adr/0176-per-provider-user-agent.mdindex 6ecfb1d7d..b9e1d0347 100644--- a/docs/adr/0176-per-provider-user-agent.md+++ b/docs/adr/0176-per-provider-user-agent.md@@ -1,43 +1,30 @@# ADR 0176: Per-provider User-Agent override-- Status: Accepted+- Status: Accepted; the `config_json.userAgent` store is superseded by ADR 0178- Date: 2026-09-07-- Deciders: PI-Desktop core-- Amends ADR 0095 / ADR 0156+- Related: ADR 0095, ADR 0156, ADR 0178## Context-Some gateways and vendor subscriptions inspect `User-Agent`. pi-ai stamps `pi-(<platform> …)`, Anthropic OAuth inference sends `claude-cli/<version>`,-OpenCode Go sends `pi-desktop/<APP_VERSION>`, and Codex overwrites User-Agent-after extra headers. Settings had no way to set a per-row value.+Some gateways and vendor subscriptions inspect `User-Agent`, but each adapter+stamps its own, no per-row override existed, and the provider schema listed a+`headers` map that was never implemented.## DecisionEach provider row — API-key AI service and OAuth vendor account — may store an-optional `userAgent` in `config_json.userAgent`.--- Empty or omitted keeps today's adapter default.-- A non-empty trimmed value is sent as `User-Agent` on that row's outbound HTTP:- session turns, builtin subagents, prompt enhancement, plugin one-shots,- `/models` discovery (including an unsaved form value), connection tests, and- OAuth token refresh.-- A fetch wrapper is the last writer so Codex and the Anthropic SDK cannot- overwrite it.-- Update with `""` clears the override.-- Not a secret. No SQLite or host-protocol version bump.-- UI lives in Advanced on the AI-service dialog (named and custom) and the- vendor-account editor.-- `AgentRuntime.matches()` includes `userAgent` so editing it rebuilds the warm- runtime.-- The unused `headers` map stays unimplemented.--Overriding Anthropic OAuth's `claude-cli/…` User-Agent can make Claude Pro/Max-reject the request. That is the user's choice.+optional `userAgent` in `config_json.userAgent`, where empty or omitted keeps the+adapter default and a non-empty trimmed value is sent as `User-Agent` on that row's+outbound HTTP: session turns, subagents, prompt enhancement, plugin one-shots,+`/models` discovery, connection tests, and OAuth token refresh. A fetch wrapper is+the last writer so no SDK overwrites it, `""` clears the value, CR/LF are rejected,+and `AgentRuntime.matches()` includes the field so an edit rebuilds the warm+runtime. It is not a secret and needs no SQLite or protocol change; overriding+Anthropic OAuth's `claude-cli/…` value can make Claude Pro/Max reject the request,+which is the user's choice.## Consequences-- Users can impersonate another client per service or account without a global- User-Agent or a full custom-header editor.-- OAuth login HTTP uses the row value only after it is saved; first-login- traffic keeps pi-ai defaults.+- Users can present as another client per service or account without a global+ User-Agent or a custom-header editor.+- OAuth login traffic uses the row value only once saved.diff --git a/docs/adr/0177-user-configurable-outbound-proxy.md b/docs/adr/0177-user-configurable-outbound-proxy.mdindex c52286099..92c62a599 100644--- a/docs/adr/0177-user-configurable-outbound-proxy.md+++ b/docs/adr/0177-user-configurable-outbound-proxy.md@@ -2,62 +2,63 @@- Status: Accepted- Date: 2026-09-08-- Deciders: PI-Desktop core-- Related: D340, ADR 0083, ADR 0096,- `04-ux/06-settings-ia.md`, `03-runtime/07-process-model.md`+- Related: D340, ADR 0083, ADR 0096## Context-Outbound HTTP is split across processes:--- Electron main — model discovery, models.dev refresh, plugin `net.fetch`, OAuth- polling, GitHub-adjacent fetches-- Agent sidecar (Node `fetch` / pi-ai) — LLM provider calls-- host-core — marketplace catalog and package `curl`-- Chromium sessions — default session, `persist:work-browser`, plugin panels+Outbound HTTP is split across Electron main (model discovery, models.dev refresh,+plugin `net.fetch`, OAuth polling), the agent sidecar (Node `fetch` / pi-ai+provider calls), host-core (marketplace catalog and package `curl`), Chromium+sessions, and electron-updater, and system proxy mode did not reach Node provider+calls or host-core downloads because neither Node `fetch` nor `curl` resolves+Electron's system proxy or PAC configuration — so users behind Clash, V2Ray,+corporate proxies, or SOCKS5 could browse in-app while model and plugin downloads+failed.## Decision-1. **Settings → General → Network** exposes Proxy as System / Direct / Custom.--2. **System** (default): Chromium uses `session.setProxy({ mode: "system" })`.--3. **Direct**: Chromium `{ mode: "direct" }`.--4. **Custom**: Chromium `proxyRules` + `proxyBypassRules`; Electron main `fetch`- is `net.fetch` so SOCKS5 uses the Chromium stack; sidecar sets an undici- dispatcher (`ProxyAgent` for HTTP(S), SOCKS5 CONNECT + the same undici- `fetch`); host-core curl gets `--proxy` / `--noproxy` from the stored- settings.--For host-core curl in every proxy mode, Windows builds use Schannel's-best-effort revocation mode when the installed curl advertises it. This-tolerates unavailable or offline revocation distribution points while keeping-certificate verification on.--5. **Not rewritten**: workspace Bash (host-core spawn env strips proxy keys so- credentials cannot leak into `env`), and the system browser used for OAuth- (`shell.openExternal`).--6. **Apply without restart.** `settings.set` updates Chromium sessions- (including `session-created`), main env, and `sidecar.configure`.--7. **Secrets.** Custom proxy userinfo lives in the settings JSON next to other- non-API-key preferences.+1. Settings → General → Network exposes Proxy as System / Direct / Custom; Custom+ accepts `http`, `https`, `socks`, `socks5`, and `socks5h` URLs plus a bypass+ list, persisted as optional `AppSettings.networkProxy` with no protocol or+ schema bump.+2. System (default) uses `session.setProxy({ mode: "system" })`, and Electron main+ owns a loopback-only, authenticated SOCKS relay that resolves each destination+ through `session.defaultSession.resolveProxy`, including PAC decisions, which+ the sidecar's undici dispatcher and host-core `curl` use so provider and+ marketplace requests follow OS proxy policy.+3. Direct clears proxy env keys and gives host-core curl `--noproxy '*'`; Custom+ sets Chromium `proxyRules` plus `proxyBypassRules`, makes main `fetch` use+ `net.fetch` so SOCKS5 goes through Chromium, sets an undici dispatcher in the+ sidecar, and passes `--proxy` / `--noproxy` to host-core curl, with loopback in+ the default bypass list.+4. Workspace Bash, the OAuth system browser (`shell.openExternal`), and plugin+ utility processes are not rewritten: host-core strips proxy keys from the spawn+ env so credentials cannot leak into `env`, while `pi.net.fetch` still goes+ through main.+5. `settings.set` applies without restart to Chromium sessions (including+ `session-created`), the main env, and `sidecar.configure`, and a Test action+ (`pi-desktop/network/testProxy`) runs one bounded Chromium fetch through the+ supplied config without persisting it.+6. Custom proxy userinfo lives in the settings JSON beside other non-API-key+ preferences and logs redact passwords; System relay credentials are random,+ ephemeral, and accepted only on its loopback listener; and because Chromium+ `proxyRules` cannot carry userinfo or speak SOCKS5 username/password, main+ points Chromium at a `127.0.0.1` SOCKS5 relay that injects stored credentials+ (issue #490).## Consequences-- LLM, marketplace, updates, plugin `net.fetch`, and the in-app browser honor- the selected route.-- System proxies that require an interactive or OS-integrated authentication- challenge are not answered by the raw socket relay; those requests fail- closed.-- Adding `undici` to the sidecar bundle keeps the dispatcher and `fetch`- implementation on one package.+- LLM, marketplace, updates, plugin `net.fetch`, and the in-app browser honor the+ selected route, and System mode uses Electron's OS/PAC resolution for provider+ and marketplace requests too.+- System proxies requiring an interactive or OS-integrated authentication challenge+ are not answered by the raw socket relay; those requests fail closed, and users+ with explicit credentials can use Custom mode.+- Adding `undici` to the sidecar bundle keeps the dispatcher and `fetch` on one+ package.## Alternatives-- Env-only (`HTTP_PROXY`): Node `fetch` ignores it without a dispatcher; SOCKS5- is incomplete; host-core Bash would inherit credentials.+- Env-only (`HTTP_PROXY`): Node `fetch` ignores it without a dispatcher and+ host-core Bash would inherit credentials.- `app.commandLine.appendSwitch('proxy-server')`: cannot change at runtime.-- Per-provider proxy: does not cover marketplace, updates, or the browser.diff --git a/docs/adr/0178-per-provider-custom-headers.md b/docs/adr/0178-per-provider-custom-headers.mdindex 8998fdf4d..d71f0427e 100644--- a/docs/adr/0178-per-provider-custom-headers.md+++ b/docs/adr/0178-per-provider-custom-headers.md@@ -2,50 +2,48 @@- Status: Accepted- Date: 2026-09-08-- Deciders: PI-Desktop core-- Amends ADR 0176 / ADR 0095 / ADR 0156+- Related: ADR 0095, ADR 0156, ADR 0176, D621+- Amends: ADR 0176 / ADR 0095 / ADR 0156- Supersedes the User-Agent-only surface of ADR 0176## Context-ADR 0176 added a per-row User-Agent override because gateways inspect that-header and Codex overwrites it after extra headers. Users then needed the same-last-writer path for other non-secret request headers (routing, tenant, or-client identification), not a dedicated User-Agent field.+ADR 0176 added a per-row User-Agent override because gateways inspect that header+and Codex overwrites it after extra headers. Users needed the same last-writer path+for other non-secret request headers such as routing, tenant, or client+identification, and the provider schema already listed a `headers` map that ADR+0176 left unimplemented.## Decision-Each provider row — API-key AI service and OAuth vendor account — may store an-optional `headers` map in `config_json.headers`.--- Empty, omitted, or update `{}` keeps today's adapter defaults.-- A non-empty map is last-writer on that row's outbound HTTP: session turns,- builtin subagents, prompt enhancement, plugin one-shots, `/models` discovery- (including unsaved form values), connection tests, and OAuth token refresh.-- A fetch wrapper is the last writer so Codex and the Anthropic SDK cannot- overwrite the map.-- Stored `config_json.userAgent` migrates to `headers["User-Agent"]` on read.-- Host validation: trim keys and values; case-insensitive unique keys; at most- 32 headers; key ≤ 256 bytes; value ≤ 4096 bytes; no CR/LF; header names are- alphanumeric plus hyphen.-- Values are folded to half-width before that validation, and again on read: the- fullwidth block (U+FF01–U+FF5E) and the ideographic space (U+3000) become- their ASCII counterparts, because that is what an IME or a fullwidth-formatted- page produces for plain ASCII.-- Not a secret. No SQLite or host-protocol version bump.-- UI is an explicit Advanced settings button in the upper-right dialog actions- (named, custom, and vendor account) that opens a separate compact modal.-- `AgentRuntime.matches()` includes the header map so editing it rebuilds the- warm runtime.--Overriding Anthropic OAuth's `claude-cli/…` User-Agent can make Claude Pro/Max-reject the request. That is the user's choice.+Each provider row, API-key service or OAuth account, may store an optional+`headers` map in `config_json.headers`. An empty or omitted map keeps the adapter+defaults; a non-empty map is the last writer on that row's outbound HTTP, covering+session turns, subagents, prompt enhancement, plugin one-shots, `/models`+discovery, connection tests, and OAuth token refresh. A fetch wrapper applies it+so Codex and the Anthropic SDK cannot overwrite it, and the same values ride+pi-ai stream-option headers so OpenCode's caller-wins rule stays true. A stored+`config_json.userAgent` migrates to `headers["User-Agent"]` on read, and writing+`headers` drops the leftover field. Host validation trims keys and values, makes+keys case-insensitively unique, and rejects CR/LF, oversized keys or values, and+reserved names that would smash signing or hop-by-hop framing: `authorization`,+`host`, `content-type`, `content-length`, `cookie`, `connection`,+`transfer-encoding`, and the provider auth keys such as `x-api-key` and+`chatgpt-account-id`. Values are folded to half-width and must stay within the+ByteString range, because Han text or an emoji makes `Headers.set` throw mid-turn+(D621). The map is not a secret, so no storage or protocol version changes. The+UI is an Advance+d settings button that opens a compact modal with common presets including+`User-Agent`, JSON copy and import of the normalized record, and+case-insensitive merge. First OAuth login does not collect headers.+`AgentRuntime.matches()` includes the map, so editing it rebuilds the warm+runtime.## Consequences-- Users can impersonate another client and attach gateway-specific headers per- service or account without a global header dump or an auth-bearing editor.-- OAuth login HTTP uses the row map only after it is saved; first-login traffic- keeps pi-ai defaults.-- A previously saved User-Agent still applies until the row is next saved, at- which point it is stored only in `headers`.+- Users can attach gateway-specific headers per service or account without a+ global dump, and can override the Anthropic OAuth User-Agent even though Claude+ Pro/Max may then reject the request.+- OAuth login traffic keeps pi-ai defaults until the row is saved.+- A previously saved User-Agent applies until the next save, after which it lives+ only in `headers`.diff --git a/docs/adr/0179-import-model-configuration.md b/docs/adr/0179-import-model-configuration.mdindex 4a9f17da4..c88b6d08d 100644--- a/docs/adr/0179-import-model-configuration.md+++ b/docs/adr/0179-import-model-configuration.md@@ -4,65 +4,58 @@superseded by ADR 0319 / D645 (amended 2026-10-18: Pi auth.json and cachedcatalog)- Date: 2026-09-08-- Deciders: PI-Desktop core-- Related: D007, D342, ADR 0012,- ADR 0188,- `04-ux/06-settings-ia.md`, `04-ux/08-component-spec.md` §18.5,- `03-runtime/01-ipc-protocol.md`, `03-runtime/11-provider-model-system.md`+- Related: ADR 0012, ADR 0188, D007, D342## Context-At the time this decision was recorded, Settings → Import scanned Claude Code,-Codex, OpenCode, and Pi session stores. The same tools keep provider URLs, model-ids, and often API keys in well-known files.+Users switching to PI-Desktop otherwise retype provider URLs, model ids, and API+keys that other local agents already keep in well-known files. D007 forbids+auto-importing `~/.pi`, so a scan must stay an explicit action with nothing+written until the user imports, and secrets must never cross the renderer.## Decision-1. The original placement was a Model configuration card under **Settings →- Import**, with its own Scan / selection / Import selected.--2. **Sources** (same family as session import):- - Claude Code: `~/.claude/settings.json` plus `settings.local.json` overlay- (`env.ANTHROPIC_*`, `model`)- - Codex: `~/.codex/config.toml` `[model_providers.<id>]`- - OpenCode: `~/.config/opencode/opencode.json` `provider` map plus- `~/.local/share/opencode/auth.json` API keys- - Pi: `~/.pi/agent/models.json` (fallback `~/.pi/models.json`).- - CC Switch: `~/.cc-switch/cc-switch.db` `providers` table (legacy- `config.json`).--3. **IPC** (Electron only, no host protocol bump):- `pi-desktop/modelConfig/importScan` returns public drafts (`source`,- `externalId`, `name`, `baseUrl`, `apiStyle`, `modelIds`, `hasSecret`).--4. **Secrets.** A stored API key, `env:` / `env_key` resolution, or- `Authorization: Bearer` header is copied into the host secret store.--5. **Idempotence.** A candidate whose normalized base URL, API style, and- credential match an existing provider is skipped.--6. **Default model.** If `settings.defaultProviderId` is empty after the first- successful create in that run, that provider and its first model become the- global default.+1. The model configuration card originally lived under Settings → Import; ADR+ 0319 / D645 retires that Settings session-import UI while the model+ scan/import semantics below stay in force and plugin session-import contracts+ are unchanged.+2. Sources match the session-import family: Claude Code, Codex, OpenCode, Pi, and+ CC Switch, each read from its own settings, config, or database file. For Pi,+ provider entries and API keys from `auth.json` are paired with Pi's cached+ `models-store.json` so an auth-only provider still gets its endpoint, models,+ and limits, and `models.json` stays authoritative when both files describe one+ provider. CC Switch rows are converted by app type, official seeds and+ OAuth-only rows are omitted, and a live file matching the same endpoint and+ credential is not listed twice.+3. The Electron-only IPC `pi-desktop/modelConfig/importScan` returns public drafts+ (`source`, `externalId`, `name`, `baseUrl`, `apiStyle`, `modelIds`,+ `hasSecret`); `importRun` resolves the selection from the latest scan cache and+ calls host `providers.create`. No host protocol bump.+4. A stored API key, `env:` / `env_key` resolution, or `Authorization: Bearer`+ header is copied into the host secret store, while placeholder values count as+ missing, a `!<shell command>` key or header is never executed or stored, Pi+ `oauth` entries are skipped entirely, plain `api_key` entries are copied, and+ an unresolved environment reference in `models.json` is filled from the+ matching `auth.json` key.+5. Import is idempotent: a candidate whose normalized base URL, API style, and+ credential match an existing provider is skipped, different credentials stay+ independent rows, and credential comparison never reaches the renderer. ADR+ 0188 amends this rule.+6. If `settings.defaultProviderId` is empty after the first successful create in a+ run, that provider and its first model become the global default; an existing+ default is never overwritten.## Consequences-- Switching from another local agent can bring both transcripts and the models- those transcripts used, without pasting keys into Settings.-- PI-Desktop still does not silently ingest `~/.pi`.-- Users with only a ChatGPT/Claude subscription still sign in through Vendor- accounts; import cannot impersonate that grant.+- Switching tools can bring transcripts and the models they used, without pasting+ keys into Settings.+- PI-Desktop still never silently ingests `~/.pi`, and subscription grants stay+ with their own vendor sign-in.+- The 2026-10-18 amendment makes Settings → Models discover Pi auth-only providers+ through `auth.json` plus the cached catalog.## Alternatives- Auto-import on first launch: rejected by D007.-- Merge keys into an existing same-URL provider: would overwrite a working row.-- Renderer-side `providers.create` with the key in the IPC payload: the scan- cache already exists for sessions; keep secrets off the renderer.--## Amendment — 2026-10-18: discover Pi auth-only providers--Settings → Models only scanned `models.json`, so providers connected through `pi-/login` (for example DeepSeek or a Z.AI coding plan) never appeared in the Pi-group. The explicit scan now reads `auth.json` API keys and pairs them with the-catalog Pi already cached in `models-store.json`.+- Merge keys into an existing same-URL provider: rejected because it would+ overwrite a working row; skipping is safer.diff --git a/docs/adr/0180-custom-reading-font-size.md b/docs/adr/0180-custom-reading-font-size.mdindex ed4849673..b86960fe1 100644--- a/docs/adr/0180-custom-reading-font-size.md+++ b/docs/adr/0180-custom-reading-font-size.md@@ -2,44 +2,40 @@- Status: Accepted (amended)- Date: 2026-09-08-- Baseline: `0.4.16`-- Protocol: unchanged (renderer-owned `AppSettings` JSON field)-- Storage schema: unchanged (optional `AppSettings.fontScale`)-- Related: D343, ADR 0083, `04-ux/06-settings-ia.md`,- `04-ux/07-ui-design-system.md`+- Related: D343, ADR 0083, `04-ux/06-settings-ia.md`## Context-The `--text-*` ramp is a frozen set of product sizes (`--text-base` is 14px,-with denser chrome and larger headings). The application menu exposes Zoom In /-Zoom Out / Reset Zoom, but those scale the entire window, including layout and-controls.+The `--text-*` ramp is a frozen set of product sizes, and Zoom In / Zoom Out scale+the whole window including layout and controls, so a user who wants denser or+larger type had no remembered preference that keeps body, chrome, and headings in+proportion. An earlier draft remapped only the transcript and composer from a px+value, which left other surfaces at product size.## Decision-1. **Settings → General → Appearance** gains a **Font size** row under Font.--2. **Persistence** is optional `AppSettings.fontScale` (`1` = product ramp).--3. **Application** is global.--4. **Zoom stays independent.** Menu and shortcut Zoom In / Zoom Out / Reset Zoom- continue to scale the whole window.+1. **Settings → General → Appearance** gains a **Font size** row under Font, with+ four cup presets (Tall 85% / Grande 100% / Venti 115% / Trenta 125%) above a+ percentage slider; valid values are 80%–150% in 2.5% steps, and absent means+ 100%.+2. **Persistence** is the optional `AppSettings.fontScale`, rejected at the+ renderer edge on invalid writes and clamped through `normalizeFontScale` on+ read, with no protocol or schema version bump.+3. **Application** is global: the renderer sets `--font-scale` on+ `document.documentElement`, every `--text-*` token and `--leading-row` becomes+ `calc(<product px> * var(--font-scale))`, and shared Lucide wrappers scale+ glyphs the same way.+4. **Zoom stays independent** and composes with the type scale.## Consequences-- One control scales every `--text-*` consumer; places that are already smaller- or larger than body stay relatively smaller or larger.-- Users do not pick a px number that only matches `--text-base`.-- Large scales also enlarge compact chrome, including Lucide glyphs.+- One control scales every `--text-*` consumer while keeping relative steps.+- Users choose a scale, never a px number that only matches `--text-base`.+- Compact chrome grows too, so rows with a fixed px height may feel tighter; the+ 150% cap bounds that.## Alternatives-- **Reading-only remap of `.thread-wrap` / `.composer-dock`:** keeps chrome- compact, but users then have two type sizes in one window and still need a px- number for the body step.-- **Zoom In/Out only:** already exists; it scales chrome together with text and- is not a type preference.-- **Change `html { font-size }` and switch the ramp to rem:** larger refactor;- the product ramp is px tokens and the token guard forbids raw rem in component- CSS.+- Remap only `.thread-wrap` and `.composer-dock` — rejected: two type sizes in one+ window, and a px number is still required.+- Use Zoom In/Out as the type preference — rejected: it scales layout with text.diff --git a/docs/adr/0181-main-owned-picker-capabilities.md b/docs/adr/0181-main-owned-picker-capabilities.mdindex 919b94ac7..86b3cae0a 100644--- a/docs/adr/0181-main-owned-picker-capabilities.md+++ b/docs/adr/0181-main-owned-picker-capabilities.md@@ -2,42 +2,36 @@- Status: Accepted- Date: 2026-09-08-- Deciders: PI-Desktop core-- Related: ADR 0059, ADR 0172, D197, D334, D344,- `03-runtime/01-ipc-protocol.md` §13c, E2E-102h+- Related: ADR 0059, ADR 0172, D197, D334, D344## Context-Composer attachments can be selected through a native Electron file picker and-then copied into the owning session's scratch directory. The renderer needs to-request the copy after it materializes a home draft, but a renderer IPC payload-must not be treated as proof that a user selected the paths it contains.+Composer attachments are chosen in a native Electron file picker and copied into the+session scratch directory after the renderer materializes a home draft. An earlier+flow handed native absolute paths to the renderer and accepted them again through+`composer/importFiles`, which turned the channel into an arbitrary regular-file copy+primitive.## Decision-1. `composer/pickFiles` and `composer/pickPhotos` execute the native dialog in- Electron main.-2. The picker token expires after 60 seconds and is consumed before the import- starts.-3. `pickFiles` offers regular files only in the MVP.-4. Main still realpaths and stats every recorded source, enforces the existing- per-file and total-size limits, and copies only into the session scratch- directory.+`composer/pickFiles` and `composer/pickPhotos` run the native dialog in Electron main,+which stores the selected paths against a random token bound to the invoking+`WebContents`; the token expires after 60 seconds and is consumed before the import+starts. `composer/importFiles` therefore takes the token and a durable `sessionId` and+never renderer-supplied paths, and a token cannot be replayed or used by another+`WebContents`. The picker offers regular files only, and main still realpaths and+stats every source, applies the size limits, and copies only into the session scratch+directory.## Consequences-- A compromised or stale renderer cannot turn the picker import channel into an- arbitrary absolute-path copy primitive.-- Canceling a picker does not create a draft session or write scratch files.-- The renderer retains only the returned session-owned scratch references after- import, while the source paths remain in Electron main.-- Directory selection is no longer offered with a misleading unsupported label.--## Alternatives rejected--- Returning native paths from the picker and validating them again in the import- IPC: rejected because validation does not prove user selection.-- Importing directly before returning from the picker IPC: rejected because the- renderer must materialize a home draft only after a non-canceled selection.-- Supporting folders by recursive copy in this change: rejected because it needs- explicit traversal, size, symlink, and UI semantics beyond the current MVP.+- A compromised or stale renderer cannot turn the import channel into an arbitrary+ absolute-path copy primitive.+- Canceling the picker creates no draft session and writes no scratch files.+- The renderer keeps only session-owned scratch references, and no misleading+ directory option is offered.++## Alternatives++- Return native paths and re-validate them at import — rejected: validation does not+ prove user selection.diff --git a/docs/adr/0182-traditional-chinese-shell-locale.md b/docs/adr/0182-traditional-chinese-shell-locale.mdindex 1bab9b2cc..85d2c4141 100644--- a/docs/adr/0182-traditional-chinese-shell-locale.md+++ b/docs/adr/0182-traditional-chinese-shell-locale.md@@ -2,40 +2,32 @@- Status: Accepted- Date: 2026-09-08-- Decision owners: PI-Desktop desktop/i18n maintainers- Related: ADR 0160, D314, E2E-091## Context-The locale registry already made the language picker extensible, but every-Traditional Chinese OS tag still resolved to the Simplified Chinese catalog.-That made Auto selection incorrect for Traditional Chinese users and left the-shell and in-app release notes with Simplified Chinese terminology.+The locale registry made the language picker extensible, but every Traditional+Chinese OS tag still resolved to the Simplified catalog, so Auto selection was+wrong for those users.## Decision-1. Ship `zh-TW` as an independent full shell catalog with the native name- `繁體中文`, including the host-owned plugin-panel chrome.-2. Resolve `zh-TW`, `zh-Hant`, `zh-HK`, and `zh-MO` tags to `zh-TW`, including- underscore-separated forms.-3. Add `zh-TW` to `AppSettings.language` and package both `zh-TW` and `zh_TW`- Electron locale directories.-4. Add a matching `zh-TW` product changelog catalog and resolve Traditional- Chinese release-note requests to it.+Ship `zh-TW` as an independent full shell catalog named `繁體中文`, resolving+`zh-TW`, `zh-Hant`, `zh-HK`, and `zh-MO` (including underscore forms) to it while+generic `zh` and Simplified regions stay on `zh-CN`. Add `zh-TW` to+`AppSettings.language`, package the `zh-TW` and `zh_TW` Electron locale+directories, and add a matching changelog catalog, with no host protocol or+storage schema change; plugin manifests keep their `en` + `zh-CN` contract per+ADR 0160.## Consequences- Traditional Chinese users get an independent shell, correct Auto detection,- searchable language selection, locale-aware date formatting, and Traditional- Chinese release notes.-- The i18n and changelog catalog parity tests cover one additional shipped- locale.-- New shell locales still follow ADR 0160: add a catalog, registry row, settings- union member, Electron locale pack, and relevant validation.+ and Traditional Chinese release notes.+- Catalog parity tests cover one additional shipped locale, and new locales+ still follow ADR 0160's registry steps.## Alternatives-- Continue mapping Traditional Chinese tags to `zh-CN`: rejected because the- script and common UI terminology are different.-- Add only `zh-TW` while leaving release notes on `zh-CN`: rejected because the- update surface is part of the active product shell.+- Map Traditional Chinese tags to `zh-CN`: rejected, the script and terminology+ differ.diff --git a/docs/adr/0183-p0-international-shell-locales.md b/docs/adr/0183-p0-international-shell-locales.mdindex 0b28ed991..54a4e43ca 100644--- a/docs/adr/0183-p0-international-shell-locales.md+++ b/docs/adr/0183-p0-international-shell-locales.md@@ -2,39 +2,29 @@- Status: Accepted- Date: 2026-09-08-- Decision owners: PI-Desktop desktop/i18n maintainers- Related: ADR 0160, ADR 0182, D346, E2E-091## Context-The locale registry could add languages without renderer-specific picker work,-but the shipped shell stopped at English, Simplified Chinese, Traditional-Chinese, and Turkish. Spanish, French, and German are high-value international-locales for the desktop product and were missing from the UI catalog and in-app-release notes.+The locale registry accepts new languages without picker work, but the shipped+shell stopped at English, Simplified Chinese, Traditional Chinese, and Turkish,+leaving Spanish, French, and German out of the UI catalog and the release notes.## Decision-1. Ship complete shell catalogs for `de`, `es`, and `fr`, keeping English as the- source catalog and preserving key and interpolation parity.-2. Register native names `Deutsch`, `Español`, and `Français`; the searchable- picker continues to derive its options from the shared locale registry.-3. Resolve `de-*`, `es-*`, and `fr-*` OS locale tags to their shipped base- catalogs.-4. Ship matching product changelog catalogs so release notes follow the active- locale.+Ship complete shell catalogs for `de`, `es`, and `fr` with English as the source+and full key and interpolation parity, registered as `Deutsch`, `Español`, and+`Français` in the shared locale registry. `de-*`, `es-*`, and `fr-*` OS tags+resolve to those base catalogs, `AppSettings.language` accepts the three ids, and+matching changelog catalogs ship with them.## Consequences-- Users can select German, Spanish, or French without a renderer reload.-- Locale parity tests cover shell strings, both interpolation styles, and- release-note version/highlight parity.-- Regional variants intentionally share one base catalog; region-specific- spelling can be added later without changing the picker contract.+- Users select the languages without a reload and see localized release notes.+- Parity tests cover shell strings, both interpolation styles, and release-note+ parity, and regional variants share one base catalog.## Alternatives-- Add only registry rows and fall back to English: rejected because it would- advertise languages without localizing the shell.-- Add region-specific catalogs immediately: rejected because the P0 goal is- broad coverage with one maintainable catalog per language.+- Add registry rows only: rejected; it advertises untranslated languages.+- Add region-specific catalogs now: rejected; P0 wants one catalog per language.diff --git a/docs/adr/0184-composer-context-usage-inspector.md b/docs/adr/0184-composer-context-usage-inspector.mdindex aa54344de..94fb86e1b 100644--- a/docs/adr/0184-composer-context-usage-inspector.md+++ b/docs/adr/0184-composer-context-usage-inspector.md@@ -2,44 +2,36 @@- Status: Accepted (amended by D355 / ADR 0193)- Date: 2026-09-08-- Deciders: PI-Desktop renderer and UX maintainers-- Amends: D103, D184, D244, ADR 0047, ADR 0103-- Related: D347, D355, E2E-060d, US-UI-61+- Related: D103, D184, D244, D297, D347, D355, ADR 0047, ADR 0103, E2E-060d, US-UI-61## Context-The compact context inspector (ADR 0047, ADR 0103) hung under the newest-assistant turn. After the transcript scrolled, a routine remaining-capacity-check required hunting for that row.+The compact context inspector (ADR 0047, ADR 0103) hung under the newest assistant turn,+so checking remaining capacity meant finding that row again after the transcript+scrolled.## Decision-1. Render one context inspector in the composer right toolbar, immediately left- of the combined model × reasoning chip.-2. Keep the data contract, as amended by D355: remaining capacity, used/window- counts, turn total, and exact provider input/output/cache/reasoning/hit-rate- describe the newest usage-bearing assistant message (the last model request).-3. Keep the click/keyboard trigger, remaining-capacity ring, viewport-aware body- portal, outside-click dismissal, and Escape behavior.-4. Keep the compact summary contents.-5. Assistant meta under a completed turn keeps the optional model badge and the- usage-less throughput fallback.-6. Renderer only: no protocol, storage, runtime accounting, or model metadata- changes.+One inspector renders in the composer right toolbar, immediately left of the combined+model × reasoning chip, hidden until the session has usage, replacing the per-row copy. It+keeps the D355 data contract — remaining capacity, used/window counts, turn total, and+exact provider input/output/cache/reasoning/hit-rate describe the newest usage-bearing+assistant message, while completed-turn speed and the aggregate tool summary describe+that visual turn, delegate usage never drives the ring, and compaction marks split+overflow-retry turns — and keeps the click and keyboard trigger, capacity ring,+viewport-aware body portal, outside-click dismissal, Escape handling, and the compact+summary with a floating-layer edge and no inner section rules (D297). Assistant meta keeps+the optional model badge and the usage-less throughput fallback and no longer hosts the+inspector, and the change is renderer only: no protocol, storage, runtime accounting, or+model metadata change.## Consequences-- Remaining capacity stays reachable while composing, even after the transcript- has scrolled.-- Historical turns no longer expose a per-row inspector; the composer chip is- the single authority for the latest usage snapshot.-- The panel still opens above the dock when space allows, because placement- already prefers the side with room and clamps to the viewport.+- Remaining capacity stays reachable while composing, while historical turns lose their+ per-row inspector.+- Only one surface shows the numbers, so the authoritative copy is no longer ambiguous.-## Rejected alternatives+## Alternatives-- **Keep the message-row inspector and add a second composer entry:** two- surfaces would show the same numbers and leave users unsure which is- authoritative.-- **Inner hairlines between popover sections:** rejected by D297; floating- layers keep an outer edge, not internal rules.+- Keep the row inspector and add a composer entry: two surfaces with the same numbers.+- Inner hairlines between popover sections: D297 keeps an outer edge on floating layers.diff --git a/docs/adr/0185-korean-shell-locale.md b/docs/adr/0185-korean-shell-locale.mdindex ecf63b560..a8eedb7fa 100644--- a/docs/adr/0185-korean-shell-locale.md+++ b/docs/adr/0185-korean-shell-locale.md@@ -2,40 +2,32 @@- Status: Accepted- Date: 2026-09-09-- Decision owners: PI-Desktop desktop/i18n maintainers-- Related: ADR 0160, ADR 0182, ADR 0183, D349, E2E-091+- Related: ADR 0160, ADR 0182, ADR 0183, D349## Context-The searchable locale registry already supports complete shell catalogs, but-Korean users were still limited to English or another shipped locale. Korean is-a distinct language and should not be represented by an English fallback or by a-Chinese catalog with a Korean label.+The searchable locale registry already supported complete shell catalogs, but+Korean users were limited to English or another shipped locale. Korean is a+distinct language and must not be served by a fallback catalog.## Decision-1. Ship a complete Korean shell catalog at `packages/i18n/src/locales/ko`, with- native name `한국어` and English name `Korean`.-2. Resolve `ko` and regional `ko-*` OS locale tags to the Korean catalog.-3. Ship a Korean product changelog catalog with the same stable version and- highlight-count set as English so release notes follow the active shell- locale.-4. Preserve the existing English-first catalog contract: identical keys,- interpolation variables, searchable picker behavior, and English fallback for- plugin-contributed labels.+Ship a complete Korean shell catalog in the shared i18n package, named `한국어` /+`Korean`, and resolve `ko` and regional `ko-*` OS tags to it, including+`AppSettings.language` and the Electron Chromium locale allowlist. A Korean+product changelog catalog mirrors English versions and highlight counts. The+existing English-first contract holds: identical keys, interpolation variables,+searchable picker behavior, English fallback for plugin labels, and no host+protocol, storage schema, or IPC version change.## Consequences-- Korean users can select Korean or use Auto detection without reloading the- renderer.-- Catalog and changelog parity tests cover Korean alongside the existing shipped- locales.-- Regional Korean variants intentionally share one base catalog; spelling- differences can be added later without changing the picker contract.+- Korean is selectable and auto-detected without reloading the renderer.+- Catalog and changelog parity tests cover Korean like other shipped locales.+- Regional variants share one base catalog; spelling variants can be added later+ without changing the picker contract.## Alternatives-- Register `ko` while falling back to English: rejected because the picker would+- Register `ko` with an English fallback: rejected because the picker wouldadvertise an untranslated shell.-- Add region-specific Korean catalogs immediately: rejected because the current- locale contract uses one maintainable catalog per language.diff --git a/docs/adr/0186-session-auto-title-summary.md b/docs/adr/0186-session-auto-title-summary.mdindex 0f8e6f512..f5bf674d9 100644--- a/docs/adr/0186-session-auto-title-summary.md+++ b/docs/adr/0186-session-auto-title-summary.md@@ -5,16 +5,22 @@## Context-A first prompt currently needs an immediate sidebar label, but a raw truncated-prompt is noisy and can obscure the task's topic.+A first prompt needs an immediate sidebar label, but a raw truncated prompt is+noisy and can obscure the task topic. A summary had to use the session's own+provider and model without moving model execution into the renderer.## Decision (historical)-Keep the normalized first-prompt fallback synchronous from the renderer's point-of view. (D654 later restored that fallback as a host-owned write; only the-one-shot completion below stays removed.) After the initial turn emits-`agent_end`, the renderer calls the allowlisted `session/summarizeTitle` IPC.+After `agent_end`, the renderer called the allowlisted+`session/summarizeTitle` IPC; Electron validated the session and prompt,+resolved the effective provider/model, and ran `summarizeSessionTitle` with+thinking disabled, leaving the deterministic first-prompt fallback in place on an+empty or failed completion and persisting a valid result through `session.rename`.+Renderer-local metadata persisted `manualTitle`, so a manual or+fallback-owned title was never overwritten.-## Consequences+## Superseded-Superseded (Superseded by ADR 0323). The full record is in git history.+ADR 0323 replaced this main-owned one-shot title summary. D654 later restored the+first-prompt fallback as a host-owned write; only the one-shot completion stays+removed.diff --git a/docs/adr/0187-focus-aware-native-task-notifications.md b/docs/adr/0187-focus-aware-native-task-notifications.mdindex bbbe0483b..dca37ca03 100644--- a/docs/adr/0187-focus-aware-native-task-notifications.md+++ b/docs/adr/0187-focus-aware-native-task-notifications.md@@ -2,41 +2,30 @@- Status: Accepted- Date: 2026-09-08-- Related: ADR 0107, D117, D350, E2E-065, E2E-065a-- Note: The native IPC field is `kind` (`task` | `interactive`). A duplicate- 0187 that named the same field `source` was withdrawn.+- Related: D117, D350, ADR 0107, E2E-065, E2E-065a## Context-Durable task completion rows are created for a focused background session, but-the renderer and Electron main shared one native notification request with-interactive ask/permission/plan prompts. Suppressing native output based only on-the current session therefore showed a completion banner while the app was-focused on another session, violating D117 and E2E-065.+Durable task completion rows exist for a focused background session, but one+native notification request was shared with interactive ask, permission, and plan+prompts, so suppressing by current session showed a banner while another session+was focused.## Decision-Add an explicit `kind` to the Electron-only native notification request: `task`-or `interactive`. A task completion is never shown natively while the main-window is both visible and focused, regardless of which session is currently-selected.--The durable task insertion policy is unchanged: the exact visible focused-session suppresses the inbox row, while background, hidden, unknown, and-unfocused state creates it. Plugin-native notifications remain on their separate-permission-gated path.+The Electron-only native notification request carries an explicit `kind` of `task`+or `interactive`. A task completion never appears natively while the main window is+visible and focused, whichever session is selected, and stays eligible when hidden,+minimized, or unfocused; interactive prompts suppress only in the exact visible+focused session. Durable task insertion is unchanged, and plugin-native+notifications keep their permission-gated path.## Consequences-- Focused-background completions produce the durable inbox row without a- duplicate native banner.-- Interactive requests remain actionable when another session is selected.-- The behavior is unit-testable without launching Electron, and old callers- without a kind fail closed to the task behavior.+- Focused-background completions produce the inbox row without a duplicate banner.+- Callers without a `kind` fail closed to the task behavior.-## Alternatives considered+## Alternatives-- Relax the shared focus gate for all calls: rejected because it would hide- actionable interactive prompts.-- Add a second native IPC channel: rejected because an explicit kind keeps the- shared validation and click activation path without duplicating host code.+- Relax the shared focus gate for all calls: hides actionable prompts.+- Add a second native IPC channel: `kind` keeps shared validation and activation.diff --git a/docs/adr/0188-preserve-distinct-import-credentials.md b/docs/adr/0188-preserve-distinct-import-credentials.mdindex ec753a790..fd0dc6022 100644--- a/docs/adr/0188-preserve-distinct-import-credentials.md+++ b/docs/adr/0188-preserve-distinct-import-credentials.md@@ -2,40 +2,34 @@- Status: Accepted- Date: 2026-09-08-- Deciders: PI-Desktop core- Related: D342, D351, ADR 0179, E2E-209## Context-CC Switch can keep several named profiles for one gateway endpoint. Those-profiles may use different API keys, such as separate accounts or quotas.+CC Switch can keep several named profiles for one gateway endpoint with different+API keys, for separate accounts or quotas. The original import idempotence rule+treated normalized endpoint and API style as the whole identity, so importing a+selection created the first profile and silently skipped the rest. The renderer+still must not receive raw credentials, and re-importing the same profile must+stay idempotent.## Decision-1. An imported provider is equivalent only when its normalized endpoint, API- style, and credential match an existing provider.-2. Profiles using different credentials at the same endpoint are created as- independent provider rows and remain separately selectable in the Composer- model menu.-3. Electron main resolves existing API keys through the host secret boundary for- the comparison.-4. A no-credential candidate only matches another no-credential provider at the- same endpoint and API style.-5. The live-tool-versus-CC Switch scan applies the same credential-aware rule,- so an identical live profile is omitted while a different-key profile is- retained.+An imported provider matches an existing one only when its normalized endpoint,+API style, and credential all match. Profiles with different keys at one endpoint+become independent provider rows that stay separately selectable in the Composer+model menu, while Electron main resolves existing keys through the host secret+boundary so raw values stay in main-process memory and never enter scan results,+renderer state, logs, or provider metadata. A no-credential candidate matches only+another no-credential provider at the same endpoint and style, and OAuth-only+credentials never match an API-key candidate. The live-tool-versus-CC Switch scan+applies the same rule, and no host protocol or storage schema version changes.## Consequences-- Multiple CC Switch profiles for one gateway can be imported in one run.-- Re-importing an unchanged profile still reports it as skipped.-- If a source key changes, import creates a new independent row; the old row is- not overwritten.--## Alternatives--- Endpoint-only matching was rejected because it loses valid credentials.-- Matching by display name was rejected because names are editable and are not- stable credentials.-- Updating an existing row with the new key was rejected because it would- overwrite a working account and violate the explicit import review boundary.+- Several CC Switch profiles for one gateway import in a single run, while an+ unchanged profile still reports as skipped.+- A changed source key creates a new row instead of overwriting the working+ account.+- Matching by display name or updating an existing row would lose or overwrite+ credentials, so neither is used.diff --git a/docs/adr/0189-parent-fatal-error-aborts-leftover-delegates.md b/docs/adr/0189-parent-fatal-error-aborts-leftover-delegates.mdindex 62ffee967..5aa037dd3 100644--- a/docs/adr/0189-parent-fatal-error-aborts-leftover-delegates.md+++ b/docs/adr/0189-parent-fatal-error-aborts-leftover-delegates.md@@ -2,44 +2,45 @@- Status: Accepted for implementation- Date: 2026-09-08-- Deciders: PI-Desktop core-- Related: D352, D328, ADR 0166, ADR 0089, E2E-155+- Related: ADR 0166, ADR 0089, D352, D328## Context-D328 / ADR 0166 keep a durable turn open when the parent *idles* with running-delegates, then resume the parent with their reports. That path is correct for a-parent that stopped calling tools.+D328 / ADR 0166 keep a durable turn open when the parent idles with running+delegates, which is right for a parent that merely stopped calling tools. After a+terminal parent error the turn ends as `error`, yet leftover delegates kept+`isRunning` true, so Continue was rejected as `AGENT_BUSY` while the conversation+looked finished.## Decision-1. **Parent idle still does not abort delegates.** D328 is unchanged for a- parent that stops calling tools without a fatal error.-2. **A terminal parent error does abort leftover delegates.** Exhausted rate- limits, other terminal provider/stream errors, overflow-recovery failure,- mutation-budget termination, and rejected-prompt failures abort running- delegates, skip the resume prompt, and emit `agent_end`.-3. **The session becomes idle for Continue.** `getStatus().isRunning` does not- count leftover delegates after `turnHadError`.-4. **A later parent prompt does not inherit previous-turn delegates.** Each- `prompt()` / `executeApprovedPlan()` bumps a turn epoch, aborts leftover runs- from earlier epochs, and only auto-resumes delegates started in the current- turn.--No IPC, storage, or host-protocol change.+### 1. Parent idle still does not abort delegates++D328 is unchanged for a parent that stops calling tools without a fatal error.++### 2. A terminal parent error aborts leftover delegates++Exhausted rate limits, other terminal provider or stream errors, overflow-recovery+failure, mutation-budget termination, and rejected-prompt failures abort running+delegates, skip the resume prompt, and emit `agent_end`.++### 3. The session becomes idle for Continue++`getStatus().isRunning` ignores leftover delegates after `turnHadError`; the failed+TurnOutcomeCard stays visible and a later `agent_end` must not overwrite it.++### 4. A later prompt inherits no earlier delegates++Each `prompt()` / `executeApprovedPlan()` bumps a turn epoch, aborts runs from+earlier epochs, and auto-resumes only delegates started in the current turn.## Consequences-- Continue after a 429 (or other terminal parent error) is accepted even if a- Gemini (or other) subagent was still running.-- Work those leftover delegates had not yet reported is aborted rather than- written into a dead parent turn.-- Parent idle with live delegates still shows a live turn until reports are- delivered.+- Continue is accepted after a 429 even while an unrelated subagent was running.+- Unreported delegate work is aborted instead of landing in a dead turn.+- Idle parents with live delegates still show a live turn until reports arrive.-## Alternatives rejected+## Alternatives-- **Keep leftover delegates running after parent error.** The session stays busy- and Continue is `AGENT_BUSY`.-- **Detach leftover delegates from `isRunning` without aborting.** A later- Continue turn would race them on the workspace.+- Detach leftovers from `isRunning` without aborting: rejected because a later+ turn would race them on the workspace.diff --git a/docs/adr/0190-host-gated-large-file-and-drop-access.md b/docs/adr/0190-host-gated-large-file-and-drop-access.mdindex b875aef5a..306785385 100644--- a/docs/adr/0190-host-gated-large-file-and-drop-access.md+++ b/docs/adr/0190-host-gated-large-file-and-drop-access.md@@ -2,40 +2,37 @@- **Status:** Accepted- **Date:** 2026-09-09-- **Deciders:** PI-Desktop maintainers## Context-The log-viewer plugin needs byte-range reads and file metadata to page and-follow very large logs. Its previous implementation used `node:fs` in the plugin-process for those operations and used a renderer worker to read dropped `File`-snapshots.+The log-viewer plugin needs byte-range reads and file metadata to page and follow+very large logs, but its earlier implementation used `node:fs` in the plugin+process and a renderer worker for dropped `File` snapshots. That split the+engine and left the file-range path outside the host permission gateway.## Decision-Add host-owned `fs.stat` and bounded `fs.readRange` APIs under the existing-`fs.read` root, scope, symlink, protected-path, deny-list, consent, and audit-checks. A range call is capped at 8 MiB and returns `{ bytes, totalSize }`.+Add host-owned `fs.stat` and bounded `fs.readRange` under the existing `fs.read`+root, scope, symlink, protected-path, deny-list, consent, and audit checks, with+each range call capped at 8 MiB and returning `{ bytes, totalSize }`.+`webUtils.getPathForFile` is exposed through the panel preload as+`pluginBridge.getDroppedFilePath`, the panel host records paths from a real drop+gesture for a short time, and `fs.registerDropped` consumes one path once into a+memory-only read-only grant that is rechecked on every access, cannot address+another path, and dies with the plugin process.-Expose `webUtils.getPathForFile` through the panel preload as-`pluginBridge.getDroppedFilePath`. The panel host records paths from a real drop-gesture for a short time and lets `fs.registerDropped` consume one path once.+The log viewer uses the host APIs for picked and dropped files alike, with no raw+`node:fs` fallback and no export or write path.## Consequences-- Large-file indexing, pagination, search, follow, and rotation share one- permission-gated engine.-- Dropped files can follow appends during the current plugin session.-- Dropped-file grants do not become manifest scope and are not persisted.-- Older hosts without the new APIs cannot load this plugin version; it fails- closed instead of silently bypassing the gateway.-- The real drag-and-drop flow still requires desktop gesture testing; unit and- integration tests cover the grant, path, and byte-range boundaries.+- Indexing, pagination, search, follow, and rotation share one permission-gated+ engine, and dropped files can follow appends during the plugin session.+- Dropped-file grants never become manifest scope and are not persisted.+- Older hosts without these APIs fail closed instead of bypassing the gateway.## Alternatives considered-- Keep raw `node:fs` in the plugin: rejected because it bypasses host policy.-- Keep renderer `Blob.slice` worker reads: rejected because it duplicates the- engine and cannot observe file growth or preserve a host file identity.-- Add a broad user-selected root for dropped files: rejected because a single- dropped file should not authorize its containing directory.+- Keep raw `node:fs` in the plugin: it bypasses host policy.+- Add a user-selected root for dropped files: one dropped file should not+ authorize its containing directory.diff --git a/docs/adr/0191-label-both-macos-release-architectures.md b/docs/adr/0191-label-both-macos-release-architectures.mdindex f2bfb7118..376c825fd 100644--- a/docs/adr/0191-label-both-macos-release-architectures.md+++ b/docs/adr/0191-label-both-macos-release-architectures.md@@ -1,47 +1,36 @@# ADR 0191: Label Both macOS Release Architectures-- Status: Accepted (amended by D450 / ADR 0289)+- Status: Accepted (amended by D450 / ADR 0289: architecture-labelled ZIPs stay the+ in-app updater payloads and official tag artifacts are signed and notarized)- Date: 2026-09-09-- Deciders: PI-Desktop core-- Related: D126, D285, D353, D354, D450, ADR 0145, ADR 0289, E2E-092+- Related: D126, D285, D353, D354, D450, ADR 0145, ADR 0289## Context-D353 added an explicit `Intel` marker to the native macOS x64 artifacts but left-Apple Silicon artifacts with electron-builder's generic version-only name. A-file such as `PI-Desktop-0.14.4.dmg` therefore still does not reveal whether it-contains arm64 or x64 code, which is ambiguous when both downloads are listed in-the same GitHub Release.+D353 marked native macOS x64 artifacts `Intel` but left Apple Silicon artifacts with+electron-builder's generic version-only name, so a file such as+`PI-Desktop-0.14.4.dmg` never says whether it contains arm64 or x64 code when both+downloads sit in the same release.## Decision1. Both native macOS release lanes pass target-specific artifact patterns to-electron-builder.-2. The arm64 lane publishes `PI-Desktop-<version>-arm64.dmg` and- `PI-Desktop-<version>-arm64-mac.zip`.-3. The Intel x64 lane publishes `PI-Desktop-<version>-x64.dmg` and- `PI-Desktop-<version>-x64-mac.zip`.-4. The convention applies to unsigned and signed macOS workflow paths.-5. This changes release asset naming only.+ electron-builder.+2. The arm64 lane publishes `PI-Desktop-<version>-arm64.dmg` and `-arm64-mac.zip`,+ and the Intel x64 lane publishes the matching `-x64.dmg` and `-x64-mac.zip`+ names.+3. The convention covers unsigned and signed workflow paths, and the generated+ per-architecture updater feeds retain these asset URLs and checksums before the+ publish job merges them.## Consequences-- Users can identify the required macOS installer from its filename alone.-- DMG and ZIP names are consistent with the release matrix's `arm64` and `x64`- values instead of using a special `Intel` label for only one lane.-- Existing generic arm64 and `-Intel` x64 asset names are not reused by future- releases; the naming change is intentionally scoped to release artifacts.+- Users can identify the required installer from its filename alone, and DMG and+ ZIP names match the release matrix's `arm64` and `x64` values.+- Existing generic arm64 and `-Intel` x64 names are not reused by future releases.-## Alternatives considered+## Alternatives-- Keep the arm64 name generic: rejected because it leaves one of the two- architectures ambiguous.-- Use `Intel` for x64 and `Apple-Silicon` for arm64: rejected because the- release matrix and Electron target use standard architecture identifiers,- which are shorter and easier to match to the actual package contents.--## Amendment (D450 / ADR 0289)--Architecture-labelled ZIP names remain the in-app updater payloads. Official tag-artifacts are signed and notarized; the `-arm64` / `-x64` convention is-unchanged.+- Keep the arm64 name generic: leaves one of the two architectures ambiguous.+- Use `Intel` and `Apple-Silicon`: the release matrix and Electron target use the+ standard architecture identifiers.diff --git a/docs/adr/0192-model-alias.md b/docs/adr/0192-model-alias.mdindex 331420f09..7bada04e5 100644--- a/docs/adr/0192-model-alias.md+++ b/docs/adr/0192-model-alias.md@@ -2,49 +2,39 @@- Status: Accepted- Date: 2026-09-08-- Deciders: PI-Desktop renderer and UX maintainers- Amends: D266-- Related: E2E-201## Context-Settings → Model configuration lists models by their wire id, while the composer-shows the catalog's published `displayName`. Two gaps surfaced in daily use:--1. One provider row can carry several models with near-identical published- names, and a user cannot attach a short personal label ("fast", "pro") to one- of them.-2. Model ids in the configuration page could not be copied.+Settings lists models by wire id while the composer shows the catalog's published+`displayName`, so a user cannot attach a short personal label to one model, and+model ids could not be copied because the shell disables text selection+globally and the id sits inside a row `<label>`.## Decision-1. `ModelBinding` gains an optional `alias?: string`, persisted with the- provider's `models` array.-2. The alias is edited in the selected model's Advanced body and shown as a chip- beside the id in the selected-model row.-3. Where the composer names a model, a non-empty trimmed alias replaces the- published display name.-4. Model ids and names in the configuration page opt back into text selection- (`.selectable`).-5. Host-core persists and normalizes the alias inside the existing provider- `config_json` `models` array: a blank or absent alias is dropped, and an- alias longer than 60 characters is rejected with `MODEL_ALIAS_TOO_LONG`.+`ModelBinding` gains an optional `alias?: string` persisted with the provider's+`models` array as a display label only, while `id` remains the wire identity.+The alias is edited in the selected model's Advanced body, shown as a chip beside+the id, and used wherever the composer names a model when it is non-empty after+trimming; an absent or blank alias leaves the published name unchanged. Model+ids and names in the configuration page opt back into text selection so+drag-to-copy and click-to-toggle coexist. Host-core normalizes the alias inside+the existing provider `config_json` `models` array, dropping blanks and+rejecting an alias longer than 60 characters with `MODEL_ALIAS_TOO_LONG`, with+no protocol, RPC, or schema change.## Consequences- One provider can host several models under short personal labels withoutrenaming anything the catalog owns.- The composer, its search, and the model picker show the alias, while the- configuration page and the transcript badge keep the real id, so a mistyped- alias cannot hide which model will be called.-- Copying a model id no longer requires retyping it by hand.+ configuration page and transcript badge keep the real id.+- Storage schema stays v13 and copying a model id no longer requires retyping.## Rejected alternatives-- **Rename `displayName` on the binding:** duplicates catalog data and loses the+- Rename `displayName` on the binding: it duplicates catalog data and loses thepublished name once the alias is cleared.-- **A separate alias registry keyed by model id:** an alias belongs to one- provider row's configuration; a global map would collide across providers that- serve the same id.-- **Make the whole row selectable and drop click-to-toggle:** removes the fast- multi-select gesture the page is built around.+- A separate alias registry keyed by model id: aliases belong to one provider+ row and would collide across providers serving the same id.diff --git a/docs/adr/0193-last-request-context-occupancy.md b/docs/adr/0193-last-request-context-occupancy.mdindex 9c23c6794..ca74c71e7 100644--- a/docs/adr/0193-last-request-context-occupancy.md+++ b/docs/adr/0193-last-request-context-occupancy.md@@ -3,38 +3,34 @@- Status: Accepted (amended 2026-10-11: occupancy no longer adds`reasoningTokens`, which the reported output already contains)- Date: 2026-09-09-- Deciders: PI-Desktop renderer and UX maintainers- Amends: D103, D184, D244, D347, ADR 0047, ADR 0103, ADR 0184- Related: D355, E2E-060d, US-UI-61## Context-The composer inspector mixed two token scopes. Remaining capacity and the-used/window counts came from the newest assistant **message**.+The inspector mixed two token scopes: remaining capacity and used/window counts+came from the newest assistant message, while turn totals and cache figures came+from the summed visual turn, so a 55k window sat beside a 377k turn total and+looked like a leak.## Decision-1. Occupancy, remaining capacity, used/window counts, turn total, provider- input/output/cache/reasoning, and cache hit rate are the newest usage-bearing- assistant message (the last model request).-2. Completed-turn generation speed and the aggregate tool row still describe the- visual turn (every fragment and tool call between the surrounding user- messages).-3. Host completed-turn rollups, `addUsage`, and Token Insights stay additive- billing.-4. A later streaming turn without totals still does not steal the previous- usage-bearing turn.+Occupancy, remaining capacity, used/window counts, turn total, provider usage+counts, and cache hit rate all read from the newest usage-bearing assistant+message, with occupancy computed as `input + output + cacheRead + cacheWrite`,+where `output` already carries reasoning tokens so `reasoningTokens` is never+added again. Completed-turn speed and the aggregate tool row still describe the+visual turn, host rollups keep additive billing, and a streaming turn without+totals does not steal the previous usage-bearing turn.## Consequences-- Cache read stays on the same scale as the context window.-- A tool-heavy turn no longer looks like it overflowed the model window.-- Turn-summed cache and cost remain available to the usage plugin, not the- occupancy ring.+- Cache read stays on the same scale as the context window, so a tool-heavy turn+ no longer looks like an overflow.+- Turn-summed cache and cost remain available to the usage plugin rather than+ the occupancy ring.-## Rejected alternatives+## Alternatives-- **Keep the turn sum and only relabel it:** users still compare 367k cache read- to a 55k window in the same panel.-- **Show both last-request occupancy and turn-summed cache:** two totals in a- compact inspector recreate the original contradiction.+- Show both totals: rejected, two numbers in a compact inspector recreate the+ contradiction.diff --git a/docs/adr/0194-subagent-thinking-parameter-omission.md b/docs/adr/0194-subagent-thinking-parameter-omission.mdindex 93a7e79b7..5ca35edb8 100644--- a/docs/adr/0194-subagent-thinking-parameter-omission.md+++ b/docs/adr/0194-subagent-thinking-parameter-omission.md@@ -2,32 +2,25 @@- Status: Accepted for implementation- Date: 2026-09-09-- Deciders: PI-Desktop runtime and UX maintainers- Related: D356, E2E-203, ADR 0062, ADR 0063, ADR 0144## Context-The subagent editor previously offered inheritance and explicit thinking levels,-but no way to leave the provider's default untouched. The normal-provider-neutral stream path can translate the agent's `off` state into an-explicit provider setting.+The subagent editor offered inheritance and explicit thinking levels but no way+to leave the provider default untouched, because the provider-neutral stream+path translates the agent `off` state into an explicit provider setting.## Decision-1. Subagent frontmatter and input accept `thinkingLevel: omit` in addition to- the empty inherit value and the seven canonical levels.-2. The runtime represents `omit` as the agent's bookkeeping `off` state, but- uses pi-ai's low-level stream for the provider request so no provider-neutral- thinking override is synthesized.-3. Selected model-configuration thinking chips use the accent background and- inverted primary text in both themes.-4. This is an additive frontmatter/API value.+Subagent frontmatter and input accept `thinkingLevel: omit` alongside the empty+inherit value and the seven canonical levels, scoped to subagents only. The+runtime represents `omit` as the bookkeeping `off` state but sends the provider+request through pi-ai's low-level stream so no thinking override is+synthesized, while explicit `off` keeps the simple stream path. The value is+additive and needs no migration or protocol bump.## Consequences-- Users can distinguish inherit, explicit off, and no provider override.-- Existing definitions remain valid and retain their current behavior.-- Provider adapters remain responsible for deciding their default behavior when- the subagent selects `omit`.-- The selected chip state is more legible in dark mode while staying aligned- with the existing accent tokens.+- Users can tell inherit, explicit off, and no provider override apart.+- Existing definitions remain valid and behave unchanged.+- Provider adapters decide their own default when a subagent selects `omit`.diff --git a/docs/adr/0195-viewport-fixed-work-panel-toggle.md b/docs/adr/0195-viewport-fixed-work-panel-toggle.mdindex 310344370..a596a9b73 100644--- a/docs/adr/0195-viewport-fixed-work-panel-toggle.md+++ b/docs/adr/0195-viewport-fixed-work-panel-toggle.md@@ -2,50 +2,42 @@- Status: Accepted- Date: 2026-09-09-- Deciders: PI-Desktop core- Amends: ADR 0068, ADR 0085, D128, D207, D221- Related: [01-ui-ia](../spec/04-ux/01-ui-ia.md) ·- [08-component-spec](../spec/04-ux/08-component-spec.md) ·- [09-interaction-patterns](../spec/04-ux/09-interaction-patterns.md) ·- E2E-056, E2E-070, US-UI-57+ [09-interaction-patterns](../spec/04-ux/09-interaction-patterns.md)## ContextADR 0068 restored `Cmd/Ctrl + J` as a renderer-local way to reveal a session's-retained work-panel context without creating a tab. ADR 0085 made that chord a-toggle.+retained work-panel context and ADR 0085 made it a toggle, but pointer users had+no equivalent: the panel opened from an artifact or the chord and collapse lived+in the panel header, leaving the surface undiscoverable without the shortcut.## Decision-1. AppShell owns one viewport-fixed toggle in the top-right corner of every- non-Settings route.-2. The button prefers the visible presentation, including a subagent dock, over- a briefly stale store projection.-3. The toggle is the sole panel-level collapse control.-4. Windows/Linux window controls stay viewport-fixed at the window's right edge- so they do not slide with MainPane during the dock animation.+AppShell owns one viewport-fixed toggle in the top-right corner of every+non-Settings route as the pointer equivalent of `openWorkPanel`: it reveals the+active session's retained context without creating a tab, collapses a visible+panel without deleting tabs, and is disabled with no active session, while+Settings keeps neither panel nor toggle. The button prefers the visible+presentation over a briefly stale store projection, follows both store state and+the presented panel in `aria-pressed`, and is the sole panel-level collapse+control, leaving resource close in the panel header. Windows and Linux window+controls stay viewport-fixed at the window's right edge, the open panel header+reserves their band plus the toggle, and no host protocol, IPC channel, or native+menu command is added.## Consequences-- Pointer users can find and put away the work panel without a shortcut.+- Pointer users can find and dismiss the work panel without a shortcut.- Artifact-driven tab creation, session-scoped contexts, and startup-closed- behavior from D128 / D142 remain unchanged.-- The panel header is no longer a full-width action row on Windows/Linux while- the panel is open; close-tab sits left of the reserved overlay.+ behavior from D128 / D142 are unchanged.+- On Windows and Linux the panel header is no longer a full-width action row+ while the panel is open.## Alternatives considered-### Keep the header chevron and add a closed-state titlebar button--Rejected. Two collapse controls occupy the same corner once the toggle is-viewport-fixed over the open panel.--### Leave window controls in-flow in MainPane--Rejected for this chrome.--## References--- `docs/adr/0068-work-panel-keyboard-entry.md`-- `docs/adr/0085-work-panel-shortcut-toggle.md`-- `docs/spec/08-meta/decisions-log.md` (D128, D207, D221, D357)+- Add a closed-state titlebar button beside the header chevron: two collapse+ controls would occupy the same corner.+- Leave window controls in-flow in MainPane: they would split from the+ viewport-fixed toggle during the dock animation.diff --git a/docs/adr/0196-retry-cause-in-active-turn-status.md b/docs/adr/0196-retry-cause-in-active-turn-status.mdindex e502e6ab9..ef5990390 100644--- a/docs/adr/0196-retry-cause-in-active-turn-status.md+++ b/docs/adr/0196-retry-cause-in-active-turn-status.md@@ -3,49 +3,35 @@- Status: Accepted- Date: 2026-09-08- Related: ADR 0175, D358, US-UI-60d-- Note: First filed as ADR 0186, then 0195; 0186 is session titles and 0195 is the work-panel toggle.+- Note: first filed as ADR 0186, then ADR 0195.## Context-The live `retrying` status row tells users that a provider request is being-retried, but not why. The same classified provider failures already become-structured assistant errors when the retry budget is exhausted.+The live `retrying` status row says a provider request is being retried but not+why, even though the classified cause already becomes a structured assistant+error once the retry budget is exhausted. Users should be able to inspect the+cause during backoff without a duplicate transcript error.## Decision-Extend the shared `AgentActivity.retrying` payload with optional bounded error-details: the stable error code, the already-redacted and length-limited provider-message, and the HTTP status when known. The runtime supplies the details for-both request-setup and mid-stream retries.--The renderer keeps the existing compact retry row at rest. Hovering or focusing-its retry label reveals a small error-styled tooltip that reuses the assistant-error card's hierarchy: icon, localized summary, stable code/status, and the-provider message.+The shared `AgentActivity.retrying` payload gains optional bounded error details:+the stable error code, the already-redacted and length-limited provider message,+and the HTTP status when known, supplied for request-setup and mid-stream retries.+The renderer keeps the compact retry row at rest and reveals an error-styled+tooltip from a keyboard-focusable trigger that reuses the assistant error card's+hierarchy, closing when the activity phase clears.## Consequences- Users can identify rate limits, timeouts, network failures, and provider- errors during a retry wait.-- The transcript remains free of intermediate error rows and retry behavior is- unchanged.-- The protocol exposes only diagnostics already classified and redacted by the- runtime; arbitrary provider payloads do not cross the boundary.-- Older status payloads without `error` continue to render the ordinary retry- label.+ errors while waiting, with retry behavior unchanged.+- Only diagnostics the runtime already classified and redacted cross the+ protocol boundary.+- Older status payloads without `error` still render the ordinary retry label.## Alternatives-### Use only a native `title`--Rejected because it cannot match the existing error presentation, is difficult-to read for long provider messages, and provides inconsistent keyboard access.--### Add an assistant error row for every retry--Rejected because intermediate failures would duplicate the final assistant error-and make a successful same-turn retry look like a failed turn.--### Expose the full provider response--Rejected because provider responses can contain unstable or sensitive data.+- Use only a native `title`: rejected; it cannot match the error presentation or+ give consistent keyboard access.+- Add an assistant error row for every retry: rejected; a successful same-turn+ retry would look like a failed turn.diff --git a/docs/adr/0197-windows-portable-exe.md b/docs/adr/0197-windows-portable-exe.mdindex 0b2aff17f..e15a26f8d 100644--- a/docs/adr/0197-windows-portable-exe.md+++ b/docs/adr/0197-windows-portable-exe.md@@ -2,47 +2,39 @@- Status: Accepted (amended by D603)- Date: 2026-09-22-- Deciders: PI-Desktop core- Related: D120, D126, D364, D603, ADR 0022, E2E-211## Context-Windows tag releases publish an NSIS installer-(`PI-Desktop-Setup-<version>.exe`). Company environments that whitelist a single-executable, or that block installers, also need a no-install package.+Windows tag releases publish an NSIS installer, but company environments that+whitelist a single executable or block installers need a no-install package.+electron-builder's `portable` target produced a self-extracting wrapper that+could trigger an administrator prompt and gave no reliable normal executable+identity for the taskbar.## Decision-1. The Windows x64 release lane publishes both NSIS and ZIP targets.-2. The no-install artifact name is space-free:- `PI-Desktop-Portable-${version}.zip`.-3. The Windows release helper builds NSIS and ZIP in separate electron-builder- invocations.-4. The ZIP target does not write `latest.yml`.-5. The updater continues to recognize `PORTABLE_EXECUTABLE_FILE` for older- portable executables, but ordinary ZIP launches use the packaged metadata- marker instead.-6. User data, logs, and secrets stay in the existing application data directory.+The Windows x64 release lane publishes both NSIS and ZIP, with the no-install+artifact named `PI-Desktop-Portable-${version}.zip` and built in a separate+electron-builder invocation. Packaged metadata marks ZIP builds with+`piDistribution = "zip"` and installed builds with `"installed"`; ZIP builds+write no `latest.yml` and use notify-and-link delivery, while NSIS installs keep+in-app download and quit-and-install. The updater still recognizes+`PORTABLE_EXECUTABLE_FILE` for older portable executables, but ordinary ZIP+launches use the packaged marker. User data, logs, and secrets stay in the+existing application data directory.## Consequences-- Windows users who cannot run an installer can download, extract, and launch- `PI-Desktop.exe` from the ZIP without a self-extracting wrapper.-- The extracted executable keeps the normal PI-Desktop Windows identity for- taskbar grouping and icon display.-- ZIP users discover updates in-app and open the releases page; they replace the- extracted application themselves.-- NSIS in-app updates, hashes, and feed ownership are unchanged.-- The ZIP package is larger on disk after extraction than the old temporary- self-extracting wrapper, but it avoids runtime extraction and its related- execution-policy prompts.--## Alternatives considered--- Keep electron-builder's `portable` target: rejected because its- self-extracting wrapper is the source of the administrator-prompt and- taskbar-identity problems this amendment addresses.-- In-app update of ZIP via the NSIS installer: rejected because it would install- the application and require a whitelisted installer.-- Beside-the-exe data directory: rejected as an unrelated data-ownership change;- `PI_DESKTOP_DATA_DIR` already relocates the profile when needed.+- Users who cannot run an installer extract the ZIP and launch+ `PI-Desktop.exe` without a self-extracting wrapper.+- The extracted executable keeps the normal taskbar identity and icon.+- ZIP users replace the application themselves; NSIS in-app updates and feed+ ownership are unchanged.++## Alternatives++- Keep electron-builder's `portable` target: rejected, its wrapper causes the+ administrator prompt and taskbar-identity problems.+- Beside-the-exe data directory: rejected, it is an unrelated data-ownership+ change and `PI_DESKTOP_DATA_DIR` already relocates the profile.diff --git a/docs/adr/0198-quiet-interval-activity-phases.md b/docs/adr/0198-quiet-interval-activity-phases.mdindex cc6ff3418..72cb6a154 100644--- a/docs/adr/0198-quiet-interval-activity-phases.md+++ b/docs/adr/0198-quiet-interval-activity-phases.md@@ -2,66 +2,43 @@- Status: Accepted- Date: 2026-09-09-- Related: ADR 0175, ADR 0186, D338, D349, D365+- Related: D338, D349, D365, ADR 0175, ADR 0186## Context-ADR 0175 added a compact runtime status row for three quiet waits:-`waiting-model`, `retrying`, and `waiting-subagents`. Users still saw a-long-running turn with no explanation when the runtime was compacting context,-recovering a silent response, preparing the next provider request, or waiting on-subagents whose child work was invisible on that row.+ADR 0175 added a compact status row for three quiet waits (`waiting-model`,+`retrying`, `waiting-subagents`), but a turn still looked unexplained while the+runtime compacted context, recovered a silent response, prepared the next provider+request, or waited on subagents whose child work the row did not show.## Decision-Extend `AgentActivity` so every user-visible quiet interval has a named phase,-and enrich `waiting-subagents` with a live snapshot of running targets:--1. `starting` is rendered instead of generic `Working…`.-2. `preparing` covers the gap after a tool batch and before the next provider- request.-3. `compacting` covers an in-progress checkpoint and carries the reason- (`manual` / `threshold` / `overflow`).-4. `recovering` covers the silent-turn re-run until the retry request is issued.-5. `waiting-subagents` keeps `subagentCount` as the live running count and adds- optional `agents[]` with `name`, `lastPhase` (`waiting-model` | `thinking` |- `tool`), and `lastToolName`.--The renderer still draws one compact localized row with a monotonic phase timer.-A one-subagent wait names the agent and its latest action; a multi-agent wait-lists each running target.+Extend `AgentActivity` so every user-visible quiet interval has a named phase:+`starting` replaces the generic `Working…`, `preparing` covers the gap after a tool+batch and before the next provider request, `compacting` covers an in-progress+checkpoint and carries the reason (`manual` / `threshold` / `overflow`), and+`recovering` covers the silent-turn re-run until the retry request is issued.+`waiting-subagents` keeps `subagentCount` as the live running count and adds+optional `agents[]` with `name`, `lastPhase` (`waiting-model` | `thinking` | `tool`),+and `lastToolName`, updated when a child tool starts or ends or thinking begins but+never on token-level events. The renderer draws one compact localized row with a+monotonic phase timer that names the agent and its latest action or lists every+running target, and keeps it visible until completion or pending user interaction+(issue #669).## Consequences- Quiet compaction, recovery, and post-tool gaps are distinguishable from a hung- turn.-- A parent wait on delegates shows what those delegates are doing without- forwarding their event stream.-- Older `waiting-subagents` payloads without `agents` still render the- count-only label.-- ADR 0175's coarse-phase rule still holds: child internals stay out of the- protocol except as this bounded snapshot.+ turn, and a parent wait shows what delegates are doing without forwarding their+ event stream.+- Older `waiting-subagents` payloads without `agents` still render the count-only+ label.+- ADR 0175's coarse-phase rule holds: child internals stay out of the protocol+ except as this bounded snapshot.## Alternatives-### Restore a current-state capsule on the processing group--Rejected because it duplicated the dedicated runtime row and was already removed-as redundant chrome.--### Forward raw subagent events onto the parent status row--Rejected because it would expand the renderer protocol and flicker on every-thinking token.--### Keep generic `Working…` for starting, compaction, and recovery--Rejected because those intervals are the ones users already misread as a stuck-turn.--## References--- `docs/spec/03-runtime/01-ipc-protocol.md`-- `docs/spec/03-runtime/02-agent-runtime.md`-- `docs/spec/04-ux/09-interaction-patterns.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-008c, E2E-094)+- Forward raw subagent events: expands the renderer protocol and flickers on every+ thinking token.+- Keep generic `Working…` for starting, compaction, and recovery: those intervals+ are the ones users already misread as stuck.diff --git a/docs/adr/0200-plugin-owned-session-api.md b/docs/adr/0200-plugin-owned-session-api.mdindex 4acb41586..fef5a60b9 100644--- a/docs/adr/0200-plugin-owned-session-api.md+++ b/docs/adr/0200-plugin-owned-session-api.md@@ -1,62 +1,55 @@# ADR 0200: Host-Owned Plugin Session Import and Ownership API-- Status: Accepted+- Status: Accepted (D367; amended 2026-10-20 by ADR 0340, which adds the+ `session.*.all` grants and message-level writes while `.own` stays as below)- Date: 2026-09-09-- Decision: D367-- Amended: 2026-10-20 (ADR 0340 adds the `session.*.all` grants and the- message-level writes; the ownership boundary below still governs `.own`)+- Related: D367, ADR 0201, ADR 0340## Context-Plugins need to migrate and inspect conversation history from external tools.-The existing `session.getLlmContext` API is intentionally limited to the-in-flight tool call, while the core `session.import` boundary accepts a host-session summary and can bind a project.+Plugins need to migrate and inspect conversation history from external tools, but+`session.getLlmContext` is limited to the in-flight tool call and the core+`session.import` boundary accepts a host session summary and can bind a project, so+reusing either shape would let a plugin choose a core session identity or create+project records outside its ownership boundary.## Decision-Add a separate P0/P1 `pi.session` domain for plugin-owned imported sessions:--- `import`, `importBatch`, `list`, `get`, `listMessages`, `rename`, and `delete`- are exposed through new plugin permissions and additive host RPC methods.-- A manifest declares `contributes.sessionSources`.-- Host-core generates session, message, and internal tool-call ids.-- Imported sessions default to no active project/provider/model binding.-- `trash` soft-deletes and hides a row while preserving its transcript and- origin; `purge` cascades the row and removes transcript files.-- The host and Electron runtime enforce bounded content, tool values, payload- depth, message/batch sizes, strict timestamps, reserved-key scrubbing, and- per-plugin rolling import/delete limits.-- P2/P3 operations (session creation, message mutation, binding, batch delete,- and tags) remain deferred and are not represented as permissions.--Schema v14 adds `sessions.deleted_at` and the origin sidecar. The JSON-RPC-protocol remains v11 because these methods are additive and only Electron main-can provide the trusted plugin id.+A separate P0/P1 `pi.session` domain owns plugin-imported sessions: `import`,+`importBatch`, `list`, `get`, `listMessages`, `rename`, and `delete` are exposed+through new plugin permissions and additive host RPC methods, and a manifest+declares `contributes.sessionSources`, which the Electron permission gateway+validates before host dispatch. Host-core generates session, message, and internal+tool-call ids, keys idempotency by `(pluginId, source, externalId)` in+`session_import_origins`, and limits a plugin to its own rows. ADR 0201 adds an+explicit host-created project-id opt-in; imported sessions otherwise start with no+active project/provider/model binding, and original values stay history JSON for+inspection rather than live authorization. `trash` soft-deletes and hides a row+while preserving transcript and origin, and `purge` cascades the row and removes+transcript files, under bounded content, tool values, payload depth, message and+batch sizes, strict timestamps, reserved-key scrubbing, and per-plugin rolling+import/delete limits.++P2/P3 operations (session creation, message mutation, binding, batch delete, tags)+remain deferred and are not represented as permissions; schema v14 adds+`sessions.deleted_at` and the origin sidecar, while JSON-RPC stays at v11 because+these methods are additive and only Electron main can provide the trusted plugin+id. ADR 0340 later adds `session.read.all`, `session.update.all`, and+`session.delete.all` over every live session plus the message-level writes+(`appendMessage`, `replaceMessages`, `deleteMessage`, `truncateFrom`); `.all` is a+separate install-time grant that wins only when a manifest declares both, and the+`plugin_id` predicate now applies only to `.own`.## Consequences-The plugin API can safely support external-history migration without exposing-SQLite, transcripts, host ids, or another plugin's sessions.--## Amendment (ADR 0340)--The ownership premise above — "a plugin can only query or mutate its own rows" —-is no longer the only boundary the host can express. ADR 0340 adds-`session.read.all`, `session.update.all`, and `session.delete.all`, which carry-the same verbs over every live session, and it adds message-level writes-(`appendMessage`, `replaceMessages`, `deleteMessage`, `truncateFrom`) that this-ADR deferred as P2/P3.--What changes for this ADR:--- Everything here still describes `.own` exactly as written.-- "Host-core generates message ids" no longer holds for a plugin-supplied- `message.id` used as a retry key; the host still generates the id when the- caller omits one.-- The P2/P3 deferral in the Decision and Consequences no longer covers message- mutation.-- Ownership is still enforced in the queries, but no longer always: the P0/P1- SQL keeps its `plugin_id` predicate only for `.own`, and the `list`, `trash`,- and `purge` statements now follow the scope Electron sends instead of- hard-coding it.+- The plugin API supports external-history migration without exposing SQLite,+ transcripts, host ids, or another plugin's sessions.+- The storage layer gains one migration and a soft-delete state that core session+ lists must exclude, and future P2/P3 work must extend this ownership model rather+ than reuse the core import.++## Alternatives++- Reuse the core `session.import` boundary: lets a plugin choose a core identity and+ create project records outside its boundary.+- Widen `session.getLlmContext`: it is limited to the in-flight tool call.diff --git a/docs/adr/0201-plugin-project-ids-and-session-refresh.md b/docs/adr/0201-plugin-project-ids-and-session-refresh.mdindex 66198560b..6a4bd3f58 100644--- a/docs/adr/0201-plugin-project-ids-and-session-refresh.md+++ b/docs/adr/0201-plugin-project-ids-and-session-refresh.md@@ -2,29 +2,35 @@- Status: Accepted- Date: 2026-09-09-- Decision: D368+- Related: D368## Context-The P0/P1 plugin session API deliberately kept imported sessions unbound, but-external-history importers need an explicit way to place a session under a-durable project. The existing `workspace.set` method both creates a project and-changes the active workspace, so exposing it to plugins would couple import to-the user's current UI context.+The plugin session API deliberately kept imported sessions unbound, but+external-history importers need an explicit way to place a session under a durable+project. `workspace.set` both creates a project and changes the active workspace, so+exposing it to plugins would couple import to the user's current UI context, and+plugin session writes had no renderer notification path, leaving the sidebar stale.## Decision-- Add the permission-gated `pi.project.create({ path })` API.-- Allow `projectId` on plugin import items.-- Make plugin session list/get projections report the explicit project binding- and id while retaining ownership filtering and all existing import limits.-- Electron main emits one `pi-desktop/session/event/changed` event after each- successful plugin import, batch import, rename, or delete.--The host RPC remains additive to protocol v11; the new `projects.create`-operation is only reachable from the permission-checked plugin bridge.+Add the permission-gated `pi.project.create({ path })` API, which creates or reuses+a durable host project row without activating the workspace and returns the+host-generated `projectId`, canonical path, and display name. Plugin import items may+carry `projectId`, which must already exist and requires the `project.create`+permission, while omitted ids keep the safe unbound behavior and historical+`projectPath`, `modelId`, and `providerId` stay origin metadata. Plugin session list+and get projections report the explicit binding while keeping ownership filtering.+Electron main emits one `pi-desktop/session/event/changed` event after each+successful plugin import, batch import, rename, or delete, which the renderer handles+through `refreshSessions()`; skipped imports do not emit, and a refresh never reopens+a closed project tab. The host RPC stays additive to protocol v11.## Consequences-Importers can explicitly opt into a project-backed session without silently-activating a workspace or turning historical paths into tool roots.+- Importers opt into project-backed sessions without activating a workspace or+ turning historical paths into tool roots.+- The host owns sidebar synchronization, so import plugins need no private event+ bridge.+- The project permission is high risk, because an explicit project id is also a+ session tool-root authority, and users must approve it at install time.diff --git a/docs/adr/0202-effective-subagent-thinking-metadata.md b/docs/adr/0202-effective-subagent-thinking-metadata.mdindex a4ff870c6..8bdd34da4 100644--- a/docs/adr/0202-effective-subagent-thinking-metadata.md+++ b/docs/adr/0202-effective-subagent-thinking-metadata.md@@ -2,31 +2,31 @@- Status: Accepted- Date: 2026-09-09-- Decision: D369-- Related: ADR 0062, ADR 0089, ADR 0144, ADR 0194+- Related: ADR 0062, ADR 0089, ADR 0144, ADR 0194, D369## Context-Delegation cards already receive the provider/model selected for each `Task`-run, but they do not receive the thinking level that the runtime actually passed-to that delegate. The selected level can differ from the definition or parent-setting after inheritance and target-model capability clamping.+Delegation cards receive the provider/model chosen for each `Task` run but not the+thinking level the runtime actually passed to that delegate. That level can differ+from the parent or definition setting after inheritance and capability clamping,+and the renderer cannot infer it consistently for live, restored, and parallel+delegations.## Decision-- Resolve the delegate's effective thinking selection once, immediately before- constructing `SubagentRun`, using the same provider binding and clamping path- that controls the request.-- Include `modelId` and `thinkingLevel` in the immediate `Task` result, the- `SubagentRunResult`, and lifecycle snapshots (`TaskWait`, `TaskList`, and- `TaskStop`).-- Render the result's model and a localized thinking label together on each- delegation node and in the side-dock identity header.--This is additive to the existing delegation result details. It changes no host-protocol, storage schema, provider request, or delegation lifecycle behavior.+Resolve the delegate's effective thinking selection once, immediately before+building `SubagentRun`, through the same binding and clamping path that controls+the request. Report `modelId` and `thinkingLevel` in the immediate `Task` result,+in `SubagentRunResult`, and in lifecycle snapshots (`TaskWait`, `TaskList`,+`TaskStop`), keeping `omit` as an explicit no-override value. Delegation nodes and+the side-dock identity header render that model with a localized thinking label,+suppressing the label for `off`, `omit`, or unknown values instead of deriving one+from the parent session or the definition.## Consequences-Live and restored cards have one runtime-owned source of truth, and parallel-delegates can show different effective levels without cross-talk.+- One runtime-owned source of truth covers live and restored cards, and parallel+ delegates can differ without cross-talk.+- Narrow layouts stay bounded while the full label reaches the accessible name.+- `omit` shows no concrete level, because the adapter default is not a canonical+ thinking value.diff --git a/docs/adr/0203-local-mcp-control-plane.md b/docs/adr/0203-local-mcp-control-plane.mdindex 4b10575ff..b9a3cd3e4 100644--- a/docs/adr/0203-local-mcp-control-plane.md+++ b/docs/adr/0203-local-mcp-control-plane.md@@ -6,39 +6,36 @@## Context-PI-Desktop already has typed Electron-main IPC for projects, sessions, the pi-Agent, workspace views, plugins, settings, and other desktop operations. That-surface is available to the renderer only, so an external Agent cannot drive a-running desktop without a second application-specific integration.+PI-Desktop has typed Electron-main IPC for projects, sessions, the agent,+workspace views, plugins, and settings, but only the renderer can reach it, so an+external Agent cannot drive a running desktop without a second+application-specific integration. The remote Gateway stays out of scope under+baseline decision #20 and ADR 0004.## Decision-- Add an optional Streamable HTTP MCP server inside Electron Main.-- Validate any supplied `Origin` against loopback hostnames to prevent DNS- rebinding from remote web content.-- Persist a random 256-bit bearer token in the Electron user-data directory and- publish the current URL, token, PID, and active state in `mcp-control.json`.-- Delegate every exposed call to the existing registered main-process IPC- handler.-- Require `confirm: true` for dangerous generic operations and destructive named- tools, including `session/configure` (permission mode).-- Bind only loopback addresses; `initialize` negotiates `2025-06-18` or the- compatible `2025-03-26` value and never echoes an unsupported version.-- After successful **mutating** project/session/Agent calls, reuse the existing- `pi-desktop/session/event/changed` renderer event with additive project and- selection fields.+Add an optional Streamable HTTP MCP server inside Electron Main that starts only+with `PI_DESKTOP_MCP_CONTROL=1`, binds to `127.0.0.1` on `PI_DESKTOP_MCP_PORT`+(37123 by default), validates a supplied `Origin` against loopback hostnames, and+publishes its URL, bearer token, PID, and state in a mode-`0600`+`mcp-control.json` under the user-data directory. Every exposed call delegates to+the existing registered IPC handler, through named tools for the common+project/session/Agent/workspace flow plus a generic `pi_desktop_invoke` over a+risk-tagged catalog discovered by `pi_control_describe`. Dangerous generic+operations and named destructive tools, including `session/configure`, require+`confirm: true`, which is an agent acknowledgement rather than a user prompt.+Secret channels, provider/OAuth/MCP secret writes, settings writes, and+renderer-only picker channels are excluded, secret-shaped argument fields are+stripped, and a new IPC handler is never exposed automatically. Mutating+project, session, and Agent calls reuse `pi-desktop/session/event/changed` with+additive project and selection fields, while reads do not refresh the desktop.## Consequences-An external local Agent can open a project, create or inspect sessions, send a-prompt, observe status, and invoke reviewed desktop operations through a-standard MCP client.--The endpoint grants a local client the authority of the running desktop for the-operations it invokes.--## Amendment (D372)--Narrow the first-version catalog to the project/session/Agent/workspace flow-plus reviewed reads. `session/configure` is dangerous because it can set-`permissionMode: "auto"`.+- A local Agent can open a project, create or inspect sessions, send prompts,+ observe status, and invoke reviewed operations through a standard MCP client.+- Renderer and external Agent converge on the same IPC handlers and refresh+ path, so no authorization or persistence logic is duplicated.+- The endpoint grants the authority of the running desktop; loopback binding,+ opt-in startup, bearer authentication, and confirmation gates limit accidental+ exposure but not a process that can already read the token.diff --git a/docs/adr/0204-unsigned-macos-first-launch-helper.md b/docs/adr/0204-unsigned-macos-first-launch-helper.mdindex caa1f3da4..022e83ff2 100644--- a/docs/adr/0204-unsigned-macos-first-launch-helper.md+++ b/docs/adr/0204-unsigned-macos-first-launch-helper.md@@ -1,65 +1,45 @@# ADR 0204: Explicit Unsigned macOS First-Launch Helper-- Status: Superseded for macOS distribution by D634 / [ADR 0309](0309-remove-macos-first-launch-artifacts.md)+- Status: Superseded for macOS distribution by D634 /+ [ADR 0309](0309-remove-macos-first-launch-artifacts.md), as amended by D406 /+ ADR 0232, D450 / ADR 0289, and D457 / ADR 0296- Date: 2026-09-09-- Deciders: PI-Desktop core-- Related: D078, D371, D406, D450, D457, D634, E2E-196b, ADR 0289, ADR 0296, ADR 0309+- Related: D078, D371, D406, D450, D457, D634, ADR 0232, ADR 0289, ADR 0296,+ ADR 0309## Context-Local and debug macOS packaging remain unsigned so contributors and release-operators can build without Developer ID credentials. A trusted download of that-artifact can still carry Apple's quarantine attribute, which may make Gatekeeper-report that PI-Desktop is damaged.+Local and debug macOS packaging stays unsigned so contributors and release+operators can build without Developer ID credentials, but a trusted download can+still carry Apple's quarantine attribute, which may make Gatekeeper report that+PI-Desktop is damaged — and the existing `xattr -cr` guidance clears more than the+single attribute that causes the failure.## Decision-1. Every macOS distribution includes an executable- `PI-Desktop-macOS-open.command` alongside the opening-help note.+1. Every macOS distribution ships an executable `PI-Desktop-macOS-open.command`+ with an opening-help note in the ZIP.2. The helper searches only `/Applications/PI-Desktop.app` and- `~/Applications/PI-Desktop.app`.+ `~/Applications/PI-Desktop.app`, verifies the bundle identifier is+ `net.aiuo.pi-desktop`, and expects the user to move the app there first.3. When the verified app carries `com.apple.quarantine`, the helper recursively- removes only that attribute and then opens PI-Desktop.-4. The DMG labels the package as unsigned and the note continues to state that- signed and notarized builds do not need the helper.-5. Developer ID signing and notarization remain the release path for normal- Gatekeeper launches; this helper is an explicit user action for trusted- unsigned artifacts, not a replacement for signing.+ removes only that attribute and opens PI-Desktop; it never uses `sudo`, accepts+ no path argument, removes no other extended attribute, and does not claim the app+ passed Gatekeeper qualification.+4. Developer ID signing and notarization remain the release path and official tag+ releases are signed and notarized, so the helper serves trusted unsigned local or+ debug artifacts only.## Consequences-- A user can read the documented unsigned first-launch fallback from the DMG;- the ZIP retains the one-Finder-double-click helper after the normal- drag-to-Applications step.-- Other extended attributes remain intact, reducing the scope of the quarantine- workaround.-- The helper cannot repair an app installed outside the two standard- Applications directories; the opening note provides the supported Terminal- fallback for `/Applications`.-- The same helper is harmless in signed packages but is not needed there.+- Users can read the documented unsigned fallback, and other extended attributes+ stay intact.+- The helper cannot repair an app installed outside the two standard directories and+ is unnecessary in signed packages.-## Amendment (D406 / ADR 0232)+## Alternatives-The DMG-specific helper placement is replaced. DMGs now expose only the-opening-help note, displayed as `If app won't open, read this.txt`; the-executable helper remains in the macOS ZIP package.--## Alternatives considered--- Keep the Terminal-only `xattr -cr` instruction: rejected because it is not a- one-click flow and clears more metadata than necessary.-- Use `sudo` or target a user-selected arbitrary path: rejected because it would- expand the privilege and application scope of an installer workaround.-- Require signing for every local build: rejected because D078 intentionally- keeps local packaging available without Developer ID credentials.--## Amendment (D450 / ADR 0289)--Official GitHub tag releases are Developer ID-signed and notarized. The-first-launch helper and opening note remain for trusted unsigned local or debug-artifacts only.--## Amendment (D457 / ADR 0296)--The DMG no longer shows the opening-help note. ZIP retains the helper and note-for trusted unsigned local or debug artifacts.+- Keep the Terminal-only `xattr -cr` instruction: not a one-click flow and it clears+ more metadata than necessary.+- Use `sudo` or an arbitrary user-selected path: expands the privilege and+ application scope of an installer workaround.diff --git a/docs/adr/0205-remote-agent-control-boundary.md b/docs/adr/0205-remote-agent-control-boundary.mdindex 8374ee66c..eabc735ae 100644--- a/docs/adr/0205-remote-agent-control-boundary.md+++ b/docs/adr/0205-remote-agent-control-boundary.md@@ -2,203 +2,92 @@- Status: Accepted for implementation (post-MVP); amended by D374 and D375- Date: 2026-09-09-- Decision: D373 (amended by D374 and D375)-- Related: ADR 0004, ADR 0011, ADR 0203, ADR 0165,- `02-architecture/05-remote-agent-control.md`,- `03-runtime/19-remote-agent-control-protocol.md`,- `05-security/02-remote-control-security.md`+- Related: ADR 0004, ADR 0011, ADR 0165, ADR 0203, ADR 0310, D373, D374, D375,+ D385## Context-PI-Desktop currently embeds `pi-agent-core` in a Node sidecar. Electron Main-owns the sidecar and Rust host-core bridges, while the renderer communicates-through typed Electron IPC.+Local authority runs through Electron Main, the Node pi sidecar, and Rust+host-core over stdio NDJSON JSON-RPC, with typed IPC to the renderer. Remote+control is a different trust and lifecycle problem: a client may disconnect while+a turn continues, reconnect without missing events, answer host-owned approvals,+and share a session with other clients, which the existing IPC, `host.proxy`, or+host-core JSON-RPC cannot provide without turning the Electron process into a+public backend.## Decision-1. Keep Electron Main, the Node pi sidecar, and Rust host-core as the local- authority path.-2. Define a logical **Agent Host** boundary that owns sessions, turns, event- sequences, approvals, attachments, workspace policy, and crash recovery.-3. Define the **PI Remote Agent Control Protocol (RACP) v1** as a- transport-neutral semantic contract.-4. Use JSON-RPC over WSS as the primary interactive remote binding, HTTP/JSON- plus SSE as the browser binding, and gRPC over TLS as the native and- Gateway-to-Host binding.-5. Put authentication, user authorization, routing, rate limiting, revocation,- and audit at a separate Remote Gateway in production.-6. During migration, Electron Main may host a development-only facade above- existing handlers.-7. Keep remote control post-MVP.-8. Do not reuse the withdrawn subagent A2A/Peer coordination mechanism.+1. Electron Main, the Node sidecar, and Rust host-core stay the local authority+ path, and host-core still binds no network port.+2. A logical Agent Host boundary owns sessions, turns, event sequences,+ approvals, attachments, workspace policy, and crash recovery.+3. The PI Remote Agent Control Protocol (RACP) v1 is a transport-neutral semantic+ contract.+4. JSON-RPC over WSS is the primary interactive binding, HTTP/JSON with SSE the+ browser binding, and gRPC over TLS the native and Gateway-to-Host binding, all+ sharing one state machine, cursor, idempotency, authorization, and error+ semantics.+5. Authentication, authorization, routing, rate limiting, revocation, and audit+ belong to a separate Remote Gateway, with the Agent Host connecting outbound so+ a desktop needs no public inbound port.+6. During migration Main may host a development-only facade over existing+ handlers, while production targets a standalone Agent Host process group whose+ wire contract does not change.+7. Remote control stays post-MVP: ADR 0004 still governs the MVP, and this record+ is the follow-up it required.+8. The withdrawn subagent A2A/Peer mechanism is not reused; A2A is a reference for+ binding separation only.## Consequences-### Positive--- Local security boundaries remain intact.-- A running Agent is independent of any one UI connection.-- WebSocket, browser HTTP/SSE, and gRPC clients can share one semantic API.-- Event cursors, snapshots, idempotency, and approval lifecycles are explicit.-- A Gateway can route multiple Hosts without owning workspace secrets or durable+- Local security boundaries stay intact and a running agent is independent of any+ one UI connection, so WebSocket, HTTP/SSE, and gRPC clients share one API.+- A Gateway can route several Hosts without owning workspace secrets or durabletranscript truth.--### Costs and risks--- A Host/Gateway identity and revocation system is required.-- Event replay and snapshot retention add storage and testing complexity.-- Long-lived WebSocket/gRPC connections require load-balancer and backpressure- design.-- A canonical schema and generated binding conformance suite become release- surfaces.-- The standalone Agent Host extraction is a migration project, not a small- transport switch.--## Alternatives considered--### Expose the current JSON-RPC stdio endpoint--Rejected. Stdio is a local process boundary, has no remote identity model, and-would expose host internals rather than a reviewed control surface.--### Use gRPC for every link--Rejected. gRPC is appropriate for typed service-to-service communication, but an-interactive Agent also needs browser compatibility, server-initiated-approval/input requests, and easy transport debugging. gRPC remains a required-binding, not the only binding.--### Use JSON-RPC over HTTP only--Rejected as the complete design.--### Expose Electron Main directly on a public port--Rejected. It expands the desktop attack surface, couples public availability to-the UI process, and gives a network-facing process too much local lifecycle-authority.--### Extend local MCP into a public remote API--Rejected. MCP remains a local, reviewed desktop automation surface.--### Restore the historical A2A/Peer stack--Rejected. ADR 0165 removed it because subagent coordination was not a product-requirement.+- Host and Gateway identity, revocation, event replay retention, long-lived+ connection backpressure, and a binding conformance suite become required work,+ and extracting the standalone Agent Host is a migration project.## Amendment (D374)-Date: 2026-09-10. A pre-implementation review found that the D373 draft was-right about its layering but did not match the desktop it has to wrap, and-required more than v1 can carry. The following changes apply to decisions 3, 4,-and 6 above and to the four remote specifications.--1. **One normative v1 binding.** `RACP-WS` is the only normative binding in v1.- `RACP-HTTP` is the browser profile of the same contract and must ship before- any browser client.-2. **One IDL.** The RACP resources are authored as typebox schemas in- `packages/shared` (frozen decision 28).-3. **Headless Agent Host module first.** Decision 6's Electron facade is- replaced by `packages/agent-host`, a module with no Electron dependency that- owns session and turn admission, the per-session turn queue, the approval- broker, the in-memory event log, and the snapshot builder.-4. **Full local decision vocabulary.** Remote approvals offer `allow-once`,- `allow-session`, and `deny` for tools and `approve` with an explicit- permission mode, or `reject`, for Plan and Goal contracts; input requests- carry the asktool question and skip semantics.-5. **Cursors carry an epoch; deltas are ephemeral.** The cursor is `{ epoch,- sequence }`.-6. **Host-owned turn queue.** `turn/start` admits immediately or into a bounded- Host queue that every client, including the local desktop, sees.-7. **Pending requests are Host state.** Rust host-core exposes- `permissions.pending` so a late-attaching client receives open requests, and- a remote decision closes the local desktop card.-8. **Remote permission ceiling and approval lifetime.** A remote-initiated turn- runs under the lower of the session mode and a Host-configured ceiling that- defaults to `ask`.-9. **Host link relay profile.** The Gateway-to-Host connection multiplexes- logical client connections so server-initiated approval requests and- attachment bytes reach the right endpoint without an inbound port; the- Gateway buffers upload bytes only until the Host confirms them.-10. **Browser authentication profiles.** Browsers cannot set headers on the- WebSocket and EventSource APIs, so the cookie profile (HttpOnly cookie,- Origin allowlist, CSRF token) is the browser path and the header profile is- the non-browser path; URL tokens remain forbidden in both.-11. **Identity source and tenancy.** The Gateway may validate either an- OIDC/OAuth 2.0 provider or first-party product account tokens; the choice is- recorded when rollout R3 starts (superseded by D375 item 10, which fixes the- PI account service).-12. **Catalog additions.** `host/list`, `project/list`, `session/history`,- host-scope event subscriptions, and `turn/cancel` are added; deferred local- operations are listed by name so no binding invents a substitute.+`RACP-WS` is the only normative v1 binding, with `RACP-HTTP` as its browser+profile, `RACP-GRPC` reserved, and one typebox IDL in `packages/shared` generating+all fixtures and tables. A headless `packages/agent-host` module owns admission,+the per-session turn queue, the approval broker, the in-memory event log, and the+snapshot builder, and Desktop IPC, local MCP, and RACP all call into it. Remote+approvals offer `allow-once`, `allow-session`, and `deny`, plus explicit+`approve` / `reject` for Plan and Goal; cursors are `{ epoch, sequence }` with+ephemeral deltas; `turn/start` admits immediately or into one bounded Host queue+with separate `turn/stop` and `turn/interrupt`; pending requests are Host state+surfaced by `permissions.pending`; and a remote turn runs under the lower of the+session mode and a Host permission ceiling.## Amendment (D375)-Date: 2026-09-10. Recorded demand, not transport breadth, now orders the-milestones. Issues #176 and #140 ask to operate a project on a remote Linux or-WSL machine from the local desktop; issue #100 asks for task and approval-notifications on messaging channels with simple commands back; no recorded-request asks for a browser or phone client of the desktop.--1. **First remote topology: the desktop as Remote Client of a `pi-host` over an- SSH tunnel.** The `pi-host` bundle packages the headless module, the Node- sidecar, and the platform's host-core binary at the desktop's version.-2. **Desktop RACP client adapter.** Electron Main presents a remote Host to the- renderer through the existing `lib/api.ts` surface; the renderer stays- transport-agnostic and hides uncovered features by capability.-3. **Remote-host profile (RACP v1.1).** `session/configure`, `session/fork`,- `session/rename`, `session/delete`, `session/compact`, `workspace/list`,- `workspace/read`, `workspace/diff`, and the `terminal/open`,- `terminal/input`, `terminal/resize`, `terminal/close` operations join the- catalog, so mode, model, the work panel's files and diff, and a terminal on- the remote machine work against a remote session.-4. **Reverse tool relay in the same milestone.** The paired desktop advertises- its user-configured MCP servers and workspace-free plugin tools with- `tools/advertise`; the Host merges them into the remote session's catalog and- executes them through the `tool/execute` server request on the desktop, under- the desktop's own plugin permissions, after the Host's permission decision.-5. **Remote session ownership split.** Transcript, tools, workspace,- permissions, provider secrets, `~/.agents` definitions, MCP servers- configured on the Host, and scheduled tasks live on the remote Host.-6. **Ceiling exemption as Host policy.** A desktop device paired through the SSH- bootstrap holds `owner` and is exempt from the remote permission ceiling by- default, because SSH access already exceeds anything the ceiling withholds;- the Host policy `applyCeilingToPairedDevices` re-applies it.-7. **Persisted turn queue.** Queued turns and their idempotency keys are- persisted by Rust host-core, restored in order after a restart, and held- until a controller attaches.-8. **Remote approval lifetime.** While a remote subscriber is attached the- default remote approval lifetime is 30 minutes, operator-adjustable within a- bound; local desktop permission approvals have no automatic deadline.-9. **Second scheduled milestone: outbound messaging integration.** An adapter- beside the Host relays redacted event summaries to a webhook first, then- Telegram and Slack through outbound channels, and maps a fixed command- vocabulary to turn and approval operations under the linked principal's- roles.-10. **Gateway identity source.** When the Gateway is scheduled, it validates- first-party tokens of the PI account service specified in the pi-backend- repository; OIDC federation is not planned.-11. **Unscheduled.** The Gateway with its Host link, the browser profile with- its cookie authentication, and the reserved gRPC binding keep their- specifications and are scheduled only by a later product decision.-12. **Acceptance.** E2E-231 and E2E-232 are the acceptance targets of the- scheduled milestones; E2E-227 and E2E-228 apply when their milestones are- scheduled.+Recorded demand orders the milestones: a desktop acting as Remote Client of a+`pi-host` bundle over an SSH tunnel, paired through a bootstrap script that+verifies the published SHA-256, reached through an SSH port forward on the+`RACP-WS` header profile. The desktop adapter presents that Host through the+existing `lib/api.ts`, a remote-host profile adds session, workspace, and terminal+operations, and a reverse tool relay runs user-configured MCP servers and+workspace-free plugin tools on the paired desktop under its own permissions. Turn+queues persist in host-core, remote approvals default to a bounded lifetime while+a subscriber is attached, and outbound messaging becomes the second milestone.## Amendment (D385)-Date: 2026-09-10. The maintainer requires remote control to be user-local by-construction: no project-operated identity, account, or relay service may be in-the path, and a user's client must never authenticate through a service the-project runs.--1. **No first-party identity.** D375 item 10 is withdrawn.-2. **Gateway only as a self-hosted relay.** PI does not operate a Gateway.-3. **Outbound connections are the user's own.** The Host connects only to the- user's SSH hosts, the messaging channels the user configured with their own- bot tokens or webhooks, the model providers the user configured, and the- read-only, checksum-verified GitHub Releases download of `pi-host`.-4. **Unchanged.** The SSH-tunnel topology, device pairing, the messaging- integration, and every RACP shape already satisfy this rule; the- specifications change wording, not structure.+Remote control is user-local by construction: no project-operated identity,+account, or relay may sit in the path. D375's first-party identity item is+withdrawn, the only client credential is a device token issued by the user's Host+at pairing, PI operates no Gateway, and the Host connects only to the user's SSH+hosts, their configured messaging channels, their providers, and the+checksum-verified `pi-host` download.++## Alternatives++- Expose the current JSON-RPC stdio endpoint or bind Main on a public port:+ rejected because stdio has no remote identity model and a network-facing UI+ process expands the desktop attack surface.+- Use one binding for every link: rejected because gRPC lacks browser and+ server-initiated approval ergonomics while HTTP alone cannot carry efficient+ bidirectional control.diff --git a/docs/adr/0206-ten-provider-retries-and-progress-status.md b/docs/adr/0206-ten-provider-retries-and-progress-status.mdindex da621e97a..c2153d592 100644--- a/docs/adr/0206-ten-provider-retries-and-progress-status.md+++ b/docs/adr/0206-ten-provider-retries-and-progress-status.md@@ -1,76 +1,55 @@# ADR 0206: Extend provider retries and show bounded progress-- Status: Accepted+- Status: Accepted (amended 2026-09-20, issue #699; amended for opt-in infinite+ retry)- Date: 2026-09-10-- Deciders: PI-Desktop core-- Related: D378, E2E-096, E2E-149, ADR 0091, ADR 0128, ADR 0196+- Related: D378, ADR 0091, ADR 0128, ADR 0196## Context-### Amendment: successful response boundary (issue #699, 2026-09-20)--Desktop fault injection reproduced a long task stopping on its eleventh-independent network failure after ten successful recoveries and tool calls. The-budget previously survived successful model responses for the whole user turn.--### Amendment: opt-in infinite provider retry--The default ten-retry budgets remain unchanged. AppSettings may opt into-`infiniteProviderRetry`; the runtime then skips only the retry-count ceiling for-admitted network/transient provider failures in the main session and builtin-subagents.+PI-Desktop owns provider retries so setup and mid-stream failures share one+counter instead of multiplying attempts through pi-ai, but five rate-limit and+four transient retries surfaced short outages earlier than the product wants,+and the active-turn row showed only the retry number without the remaining wait+or the position in the budget. A fault-injection report also showed a long task+stopping on its eleventh independent network failure after ten recoveries, which+made a per-turn budget the wrong scope.## Decision-1. `PROVIDER_RATE_LIMITED` and the admitted non-429 transient provider errors- each receive a shared budget of ten retries after the initial provider- attempt.+1. `PROVIDER_RATE_LIMITED` and admitted non-429 transient provider errors each+ get ten retries after the initial attempt, with setup and stream failures+ drawing from the same budget within their class and the two classes kept+ separate. Both counters reset after a complete successful model response,+ including a tool-call response; partial output, headers, and phase changes do+ not reset them.2. `PROVIDER_RETRY_MAX_RETRIES` in `packages/shared` is the single budget- constant used by the runtime and renderer.-3. Delay behavior is unchanged except that the non-429 schedule remains at its- 8-second cap for retries after the first four waits.-4. The active-turn retry status uses the current `retryDelayMs` and `since` to- render a whole-second countdown and shows the shared budget, for example- `Retrying in 0s · attempt 9/10`.-5. Authentication, model-selection, malformed-request, context, mutation,- compaction, and other non-provider recovery policies are unchanged.+ constant for the main session, builtin subagents, and one-shot composer+ enhancement, with pi-ai's nested retry disabled. `AppSettings` may opt into+ `infiniteProviderRetry`, which skips only the retry-count ceiling for+ admitted network and transient failures; one-shots keep the bounded budget.+3. Delays are unchanged apart from the 8-second cap on the non-429 schedule+ after the first four waits, and provider headers, the 30-second 429 cap,+ abortability, failed-request-only replay, and terminal diagnostics stay as+ ADR 0091 and ADR 0128 define them.+4. The active-turn status renders a whole-second countdown from `retryDelayMs`+ and `since` plus the shared budget, for example+ `Retrying in 0s · attempt 9/10`, as a compact row that never creates+ intermediate transcript errors.## Consequences-- Short provider outages can recover through a longer, still bounded same-turn- window without duplicating assistant messages or lifecycle errors.-- Persistent provider failures take longer to surface, but remain abortable and- end with one structured terminal error after the retry budget is exhausted.-- Users can see the active wait and the retry budget in the same status row,- including during the final retry.-- No host protocol, storage schema, provider configuration, or nested SDK retry- behavior changes.+- Short outages recover inside a longer but still bounded same-turn window+ without duplicating assistant messages or lifecycle errors.+- Persistent failures surface later yet remain abortable and end in one+ structured terminal error; with infinite retry the turn stops only when the+ user cancels, so API usage may continue.+- The active wait and the retry budget appear in one status row, and no host+ protocol, storage schema, or nested SDK retry behavior changes.## Alternatives-### Increase pi-ai's `maxRetries`--Rejected because nested retries would multiply attempts, obscure phase sharing,-and reintroduce provider-controlled sleeping outside the runtime's abortable-policy.--### Use one budget for rate limits and other transient failures--Rejected because rate limits and upstream outages need different delay scales,-and one class should not consume the other's recovery budget.--### Show only a fixed `/10` label--Rejected because the status already carries the delay and start time needed for-an accurate countdown; deriving the remaining seconds keeps the UI useful while-waiting instead of showing stale information.--## References--- `docs/spec/03-runtime/02-agent-runtime.md` §5d-- `docs/spec/03-runtime/08-error-codes.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` E2E-096, E2E-149-- `docs/spec/08-meta/decisions-log.md` D378-- `packages/shared/src/provider-retry.ts`-- `packages/agent-runtime/src/provider-retry.ts`-- `apps/desktop/src/components/ChatTranscript.tsx`+- Raise pi-ai's `maxRetries`: nested retries multiply attempts and reintroduce+ provider-controlled sleeping outside the abortable policy.+- Use one budget for rate limits and other transient failures: the two need+ different delay scales and should not consume each other's budget.diff --git a/docs/adr/0207-three-mutation-recovery-failures.md b/docs/adr/0207-three-mutation-recovery-failures.mdindex 34b7d939c..7c54f997a 100644--- a/docs/adr/0207-three-mutation-recovery-failures.md+++ b/docs/adr/0207-three-mutation-recovery-failures.md@@ -6,39 +6,38 @@## Context-The line-anchored mutation guard previously terminated a prompt after two-counted failures for the same path. The first failure often exposes a syntax,-range, or provenance correction, while the second failure can still be the agent-applying that correction.+The line-anchored mutation guard terminated a prompt after two counted failures+for the same path, although the first failure usually exposes a syntax, range,+or provenance correction and the second can be the agent applying it.## DecisionAmend D186 and ADR 0087: a prompt may make three counted failed `Edit` calls on-one path before the repeat guard terminates the turn. A recognized shell patch-command uses the same three-failure limit under its patch-command key.--The existing rules remain unchanged: recoverable error codes each receive one-per-code grace, counters are scoped to the prompt and path, and a successful-mutation clears that path's failure history. Provider retry budgets and other-tool concurrency limits are unaffected.+one path, and a recognized shell patch command shares that limit under its+patch-command key. The first two failures return their error-specific recovery+hints and leave the turn running; the third carries `terminate: true` and+finalizes the assistant row with `MUTATION_RETRY_BUDGET_EXHAUSTED`. Recoverable+codes keep one per-code grace, counters stay scoped to the prompt and path, a+successful mutation clears that path's history, and provider retry and+concurrency budgets are untouched.### Delegate ownership correction (2026-10-07)-The prompt scope means the individual executing agent, not the whole session.-Sharing path keys caused concurrent delegates to spend one another's attempts-and report exhaustion on the parent.+The prompt scope is the executing agent, not the whole session, so recovery keys+include the parent or delegation owner instead of letting concurrent delegates+spend one another's attempts. Settlement releases a delegate's counters and+graces, a terminal tool error is carried into the delegate result, and the+failed chain stays resumable through the existing Task flow.## Consequences-- The model gets one additional bounded opportunity to correct an Edit or- recognized shell patch failure.-- Persistent or guessing mutation loops still terminate deterministically.-- The runtime error message and every shipped locale must say three failures.+- The model gets one more bounded correction attempt per path.+- Persistent or guessing loops still terminate deterministically, and every+ shipped locale must say three failures.- No IPC, storage, host protocol, or tool result shape changes.-## Alternatives considered+## Alternatives-- Keep the two-failure limit: rejected because the second correction attempt can- still be an honest recovery after a distinct first error.-- Remove the limit: rejected because malformed or blind mutation loops must not- consume an unbounded turn.+- Keep the two-failure limit: rejected, an honest second correction can follow a+ distinct first error.+- Remove the limit: rejected, blind mutation loops must stay bounded.diff --git a/docs/adr/0208-plugin-desktop-control-native-consent.md b/docs/adr/0208-plugin-desktop-control-native-consent.mdindex 561efac52..81563a242 100644--- a/docs/adr/0208-plugin-desktop-control-native-consent.md+++ b/docs/adr/0208-plugin-desktop-control-native-consent.md@@ -2,41 +2,34 @@- Status: Accepted- Date: 2026-09-10-- Decision: D377-- Related: ADR 0203 (local MCP control plane), D370, D372,- [07-plugins/03-plugin-api.md](../spec/07-plugins/03-plugin-api.md),- [07-plugins/04-plugin-security.md](../spec/07-plugins/04-plugin-security.md) §8.2,- [07-plugins/13-plugin-permissions-matrix.md](../spec/07-plugins/13-plugin-permissions-matrix.md)+- Related: D370, D372, D377, ADR 0203## Context-`desktop.control` gives a plugin the reviewed operation catalog that the local-MCP control plane exposes: project, session, Agent, and workspace operations,-each tagged `read`, `write`, or `dangerous`. The catalog and the invocation path-are shared with MCP so there is one permission and persistence implementation.+`desktop.control` gives a plugin the reviewed operation catalog of the local MCP+control plane, sharing one permission and persistence implementation with MCP, where+the controller's `confirm: true` is the agent's own acknowledgement (D372). From+plugin code the plugin sets that flag itself, so a holder could delete sessions,+switch a session to `auto` tool approval, or resolve a pending tool permission with+no human in the loop.## Decision-1. A `dangerous` desktop operation from a plugin needs two answers.-2. After that, Electron main asks the user in a native, blocking dialog- (`plugin-desktop-consent.ts`) attached to the main window.-3. Escape, dismissal, and Deny are refusals (`PERMISSION_DENIED`).-4. A host that supplies no dialog service (headless or test runtime) refuses- every dangerous operation from plugins.-5. Every invocation is audited with plugin id, operation, and risk; a refusal is- audited as `PERMISSION_DENIED`.-6. `ui.microphone` stays a separate, narrower grant: audio capture only, inside- the plugin's isolated panel session; camera and other device permissions- remain denied.+A `dangerous` desktop operation from a plugin needs two answers: the plugin's+`confirm: true` stays required first (`CONFIRMATION_REQUIRED` otherwise), and+Electron main then asks the user in a native blocking dialog attached to the main+window showing the catalog operation id, its description, and a bounded argument+preview, never plugin- or model-authored text, so an injected transcript cannot+relabel `session/delete`. Escape, dismissal, and Deny are refusals+(`PERMISSION_DENIED`), the answer is per call with no "allow until quit", a host+without a dialog service refuses every dangerous plugin operation, and every+invocation and refusal is audited with plugin id, operation, and risk. `read` and+`write` operations are unchanged, and `ui.microphone` stays a separate narrower+grant for audio capture inside the plugin's isolated panel session.## Consequences-- Plugin-originated destructive desktop operations gain the same- human-in-the-loop guarantee that plugin file access outside the manifest scope- already has (`confirmFsAccess`).-- The MCP contract is unchanged: an external agent still acknowledges with- `confirm: true` and the desktop user is the one who enabled the loopback- control plane.-- Plugin authors must expect a native prompt and should not promise unattended- dangerous operations.-- Covered by `apps/desktop/test/plugin-desktop-control.test.mjs` and E2E-236.+- Plugin-originated destructive operations gain the human-in-the-loop guarantee that+ out-of-scope plugin file access already has (`confirmFsAccess`).+- The MCP contract is unchanged, so external agents still acknowledge with `confirm:+ true` once the user enables the loopback control plane.diff --git a/docs/adr/0209-powershell-7-selectable-windows-shell.md b/docs/adr/0209-powershell-7-selectable-windows-shell.mdindex 245c7c60e..3234097e3 100644--- a/docs/adr/0209-powershell-7-selectable-windows-shell.md+++ b/docs/adr/0209-powershell-7-selectable-windows-shell.md@@ -2,95 +2,64 @@- Status: Accepted (issue #151, merged in #191)- Date: 2026-09-10-- Baseline: `0.14.6`-- Protocol: v11 (unchanged; additive catalog ID)-- Storage schema: v14 (unchanged; no migration)- Decision: D381- Amends: ADR 0054 §1 (Windows catalog table and Windows catalog list)-- Related: [03-runtime/03-tools-and-permissions.md](../spec/03-runtime/03-tools-and-permissions.md),- [03-runtime/01-ipc-protocol.md](../spec/03-runtime/01-ipc-protocol.md),- [03-runtime/06-host-rpc-protocol.md](../spec/03-runtime/06-host-rpc-protocol.md),- [04-ux/06-settings-ia.md](../spec/04-ux/06-settings-ia.md),- [05-security/01-security.md](../spec/05-security/01-security.md),- [06-delivery/04-e2e-test-plan.md](../spec/06-delivery/04-e2e-test-plan.md) (E2E-112)+- Related: [03-runtime/03-tools-and-permissions.md](../spec/03-runtime/03-tools-and-permissions.md)## Context-ADR 0054 froze a Windows catalog of `windows-powershell`, `cmd`, and `git-bash`.-The `windows-powershell` entry resolves the in-box Windows PowerShell 5.1-(`%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe`).+ADR 0054 froze a Windows catalog of `windows-powershell`, `cmd`, and `git-bash`,+where `windows-powershell` resolves the in-box Windows PowerShell 5.1. PowerShell+7 is a separate side-by-side product that never replaces 5.1, so a user who+installed `pwsh.exe` had no way to select it and `Bash` kept launching 5.1, as+Issue #151 reports.## Decision### 1. A fifth stable ID: `windows-pwsh`The Windows catalog gains `windows-pwsh` (`PowerShell 7`), selectable from-Settings and persisted in `defaultCommandShell` like every other entry. The ID-is stable and platform-scoped, and joins the `CommandShellId` protocol union.+Settings and persisted in `defaultCommandShell` like every other entry, and it+joins the `CommandShellId` protocol union.### 2. Resolution order and failure guidance-`windows-pwsh` resolves, in order:--1. `%ProgramFiles%\PowerShell\7\pwsh.exe`, which is where a machine-scope MSI or- `winget --scope machine` install lands.-2. `pwsh.exe` on PATH, which covers Store, user-scope, and portable installs.--Neither location is discoverable by guessing, so a miss returns-`SHELL_NOT_FOUND` with guidance that names both searched locations and points at-installing PowerShell 7. The wording lives in `PWSH_MISSING_GUIDANCE` next to-the resolver.+`windows-pwsh` resolves `%ProgramFiles%\PowerShell\7\pwsh.exe` first — probing+`%ProgramW6432%` as well so a 32-bit host on 64-bit Windows finds the real+64-bit install — and then `pwsh.exe` on PATH, which covers Store, user-scope, and+portable installs. A miss returns `SHELL_NOT_FOUND` with `PWSH_MISSING_GUIDANCE`+naming both searched locations.### 3. One shared invocation contract-PowerShell 7 accepts the same non-interactive flags as 5.1 (`-NoLogo -NoProfile--NonInteractive -InputFormat Text -OutputFormat Text -Command`), so both IDs-keep the `powershell` dialect and share the existing pinned script, including-the UTF-8 output setup and `$LASTEXITCODE` propagation. The catalog ID stays-distinct so the pinned turn identity, the folded settings write path, and-`COMMAND_SHELL_CHANGED` still compare exactly.+PowerShell 7 accepts the same non-interactive flags as 5.1, so both IDs keep the+`powershell` dialect and share the pinned script with its UTF-8 output setup and+`$LASTEXITCODE` propagation, while the distinct catalog ID keeps the pinned turn+identity and `COMMAND_SHELL_CHANGED` comparing exactly.### 4. The platform default does not change-`windows-powershell` remains the default for a fresh Windows install, keeps-`is_default`, and stays the value `defaultCommandShell` falls back to when-unset. PowerShell 7 is never chosen for a user who did not ask for it: selecting-it is an explicit Settings action.--Catalog order still decides the first-available fallback (ADR 0054 §1), and-`windows-pwsh` sits directly after the in-box entry, so a persisted-`windows-powershell` that later becomes unavailable now resolves to-`windows-pwsh` before `cmd`. This follows the existing fallback rule instead of-adding a new one, and it cannot change the command language — both entries share-the `powershell` dialect.+`windows-powershell` remains the default for a fresh Windows install and the+value unset `defaultCommandShell` falls back to, so PowerShell 7 is only ever an+explicit Settings choice. `windows-pwsh` sits directly after the in-box entry, so+a persisted `windows-powershell` that becomes unavailable resolves to+`windows-pwsh` before `cmd` under ADR 0054 §1's existing first-available rule,+which cannot change the command language.## Consequences-- Windows users can run agent commands under PowerShell 7 while keeping 5.1- available as a separate, still-default choice.-- The protocol gains one ID, so the folded settings validation, the catalog E2E- lane (E2E-112), `scripts/e2e-plan.mjs`, and the protocol type unions move with- it.-- One existing behavior moves: a persisted `windows-powershell` that becomes- unavailable now falls back to `windows-pwsh` instead of `cmd`, because the new- entry sits earlier in catalog order.-- A machine without PowerShell 7 keeps the entry visible and unavailable, the- same presentation `git-bash` already uses.--## Alternatives rejected--### Make `windows-powershell` prefer `pwsh.exe` when present--Rejected: it silently changes the shell an existing user already runs, and it-makes the pinned turn identity ambiguous between two different executables that-share a dialect.--### Let the user configure an arbitrary `pwsh.exe` path--Rejected: ADR 0054 already rejected renderer- or sidecar-supplied executable-paths, because catalog policy and identity validation depend on a closed ID set.--### Add a `PowerShell7` tool name--Rejected: ADR 0054 §3 keeps `Bash` as the tool and protocol name and treats-shell choice as request data.+- Windows users can run agent commands under PowerShell 7 while 5.1 stays+ available and remains the default.+- One protocol ID is added, so settings validation and the type unions move with+ it; no RPC method, tool name, or storage migration is needed, and an unknown ID+ is still rejected as before.+- A missing PowerShell 7 keeps the entry visible and unavailable, the same+ presentation `git-bash` already uses, and the reordered fallback is+ unreachable on a normal install.++## Alternatives++- Make `windows-powershell` prefer `pwsh.exe` when present — rejected: it+ silently changes an existing user's shell and makes turn identity ambiguous.+- Let the user configure an arbitrary `pwsh.exe` path — rejected: catalog policy+ and identity validation depend on a closed ID set.diff --git a/docs/adr/0210-subagent-output-token-cap.md b/docs/adr/0210-subagent-output-token-cap.mdindex fd8430980..fd7eae81e 100644--- a/docs/adr/0210-subagent-output-token-cap.md+++ b/docs/adr/0210-subagent-output-token-cap.md@@ -2,57 +2,43 @@- Status: Accepted (issue #171, merged in #193)- Date: 2026-09-10-- Deciders: PI-Desktop runtime and UX maintainers-- Related: D383, E2E-155, E2E-119, ADR 0062, ADR 0063, ADR 0194+- Related: ADR 0062, ADR 0063, ADR 0194, D383, E2E-119, E2E-155## Context-A subagent definition could bound a delegate's turns and its reasoning level,-but not its response length. The only output limit in play was the one the model-binding carries: `ModelBinding.maxTokens` is edited under **Max output** in a-model's Advanced settings, and `modelConfigWithBinding` folds it into the model-the session builds.+A subagent definition could bound a delegate's turns and reasoning level but not+its response length. The only limit available was `ModelBinding.maxTokens`, the+per-model **Max output** value that `modelConfigWithBinding` folds into the model a+session builds, so it applies to every request that model serves. Delegation needs+a finer granularity: `explorer` sweeps many files and reports a conclusion while+`fixer` edits one path, and capping the model to size the cheap one would also cap+the session and every other delegate.## Decision-1. **D383 — a definition declares its own output cap.** Subagent frontmatter and- the settings API accept `maxTokens`, an optional non-negative integer.-2. **The ceiling is 200000 and the accepted range starts at 1.** The clamp is- defensive, not policy: no published model accepts an output limit above 128k,- so a larger number is a typo, and a limit of `0` would mean "no output" — a- state the empty field already expresses.-3. **The cap overrides the model built for that delegate, and only that- delegate.** `SubagentRun` already builds its own model and its own- single-model provider registry, so the cap is applied as `{ ...builtModel,- maxTokens }` on that object.-4. **The editor places it beside the turn limit, in the Advanced area that- already exists.** Both are caps that belong to the definition rather than to- the model; the pre-existing Advanced disclosure already carries model,- thinking, turn limit and scope, so no new surface is created.-5. **Additive only.** No SQLite migration, protocol version bump, IPC method, or+1. D383: a definition declares its own cap. Subagent frontmatter and the settings+ API accept `maxTokens`, an optional non-negative integer where omitted, `none`,+ or `0` means "follow the model's published limit", which is what every existing+ document already does. The value travels the same path as `maxTurns`.+2. The accepted range starts at 1 and has a defensive ceiling set above every+ published model limit, so an out-of-range value is clamped or ignored as a+ warning instead of silently changing what the document asked for.+3. The cap overrides the model built for that delegate and only that delegate.+ `SubagentRun` already builds its own model and single-model provider registry,+ so the cap is applied as `{ ...builtModel, maxTokens }` and the adapters derive+ `max_tokens` / `max_completion_tokens` / `max_output_tokens` from it without an+ adapter branch. The session's binding stays untouched.+4. The editor places the field next to the turn limit inside the existing Advanced+ disclosure, and an empty field reads as "follow the model" rather than "no+ limit".+5. The change is additive only: no migration, protocol bump, IPC method, ortool-result shape changes.## Consequences-- A delegate's output can be bounded without changing the model binding, so- sizing one worker no longer resizes the session or its siblings.-- A cap may be stricter than the model's own limit but never looser in effect:- the provider still enforces its own maximum, and the ceiling keeps a typo from- reaching it.-- Definitions gain a field that only matters when a delegate writes long- answers; an existing document keeps following the model.-- The built-in definitions do not declare a cap, so their behavior is unchanged.--## Alternatives rejected--- **Reuse `ModelBinding.maxTokens`.** It is a per-model value, so it would cap- the session and every delegate pinned to that model.-- **Make the cap a turn-level or session-level setting.** Both are coarser than- the problem: the issue is one delegate's report length, and a session-wide cap- would silently truncate the parent's answers.-- **Reject a value above the ceiling instead of clamping it.** A definition- document is hand-editable, and refusing to load it over one typo would take- the delegate out of the catalog.-- **Default the field to a concrete number.** A default would change existing- delegates' requests on upgrade, which is exactly what an opt-in cap must not- do.+- Sizing one worker no longer resizes the session or its siblings, and the+ provider still enforces its own maximum.+- A definition that omits the field parses, stores, and runs exactly as before,+ so built-in definitions are unchanged.+- Presets could carry a per-role cap later; that is a follow-up because it would+ change what a preset overwrites in the editor.diff --git a/docs/adr/0211-plan-safe-plugin-actions.md b/docs/adr/0211-plan-safe-plugin-actions.mdindex 2cfc332a5..442f578fa 100644--- a/docs/adr/0211-plan-safe-plugin-actions.md+++ b/docs/adr/0211-plan-safe-plugin-actions.md@@ -2,137 +2,89 @@- Status: Accepted- Date: 2026-09-10-- Deciders: PI-Desktop core- - Amended by: D438 (the window-summon shortcut in §7 becomes one+- Amended by: D438 (the window-summon shortcut in §7 becomes onewindow-visibility toggle) and D439 (that toggle ships on `Alt+Shift+W`because macOS owns `Cmd+W`; the plan-safe plugin-action opt-in is unchanged)- - Related: ADR 0052, ADR 0053, ADR 0170, E2E-PLAN-005+- Related: ADR 0052, ADR 0053, ADR 0170, D384, E2E-PLAN-005## Context-PI-Desktop splits sessions into Agent and Plan (and Goal) operating states. ADR-0052 and ADR 0053 lock the contract: Plan exposes `Read`, `Glob`, `Grep`,-`BrowserPreview` (workspace HTML preview), `Bash`, `EnterPlanMode`, and-`SubmitPlan`, and denies every plugin tool, `Write`, `Edit`, and unknown tools.+ADR 0052 and ADR 0053 make Plan and Goal expose `Read`, `Glob`, `Grep`,+`BrowserPreview`, `Bash`, `EnterPlanMode`, and `SubmitPlan` and deny every plugin+tool, `Write`, `Edit`, and unknown tool. That line blocks legitimate inspection:+a planner asked to look at a bug tracker or an MCP calendar source cannot open+any inspection-capable plugin. The contract is right — Plan must not click,+fill, evaluate, or send raw CDP — so the fix is a validated per-plugin+declaration, not a looser gate.## Decision### 1. Plugin tools declare plan-safe actions-A plugin tool may set a `planSafeActions` array on its registration descriptor-(in `packages/plugin-sdk`). The array lists the exact action strings the plugin-author considers safe in Plan and Goal modes.--The runtime validates the declaration at registration time. Every entry must be-a non-empty string.+A plugin tool may set a `planSafeActions` array of action strings on its+registration descriptor in `packages/plugin-sdk`; omitting it or sending an empty+array keeps plugins Plan-denied. Registration rejects empty entries and entries+outside the schema's `properties.action` enum instead of accepting a+mis-declaration.### 2. Runtime filters plugin tools by mode-`packages/agent-runtime/src/runtime.ts` exposes a plugin tool to the model in-Agent mode the same way it does today. In Plan and Goal modes it exposes only-plugins whose `planSafeActions` is a non-empty array.+`packages/agent-runtime/src/runtime.ts` exposes only plugins with a non-empty+`planSafeActions` list in Plan and Goal, annotating the tool description with the+allowed actions; the renderer keeps the full catalog.### 3. Runtime forwards the declaration to host-core-When the runtime calls `tools.execute` for a `plugin_*` tool it includes the-tool's `planSafeActions` list in the RPC params. Host-core treats the list as-part of the call's contract and forwards it to the desktop runner in the-`plugins.execute` notification alongside the session mode.+A `plugin_*` call carries `planSafeActions` in the `tools.execute` params, and+host-core forwards it to the desktop runner in the `plugins.execute`+notification together with the session mode.### 4. Host-core admits plan-safe plugin tools in contract modes-`crates/host-core/src/permissions.rs` retains the existing contract-mode hard-deny (`plan_mode_allows`) for `Write`, `Edit`, unknown tools, and plugin tools-that arrive without `planSafeActions`. A plugin tool that arrives with a-non-empty `planSafeActions` list now passes the contract gate.+`plan_mode_allows` in `crates/host-core/src/permissions.rs` still hard-denies+`Write`, `Edit`, unknown tools, and plugin tools without `planSafeActions`, while+a non-empty list passes the contract gate. No other rule changes: low-risk+auto-allow, the external-path prompt, session grants, and the `auto` posture apply+as for any Agent-mode plugin call.### 5. Plugin-runtime enforces the action restriction-`apps/desktop/electron/main/plugin-runtime.ts` validates each plugin tool's-`planSafeActions` against its schema at registration and stores the normalized-list on `RegisteredPluginTool`. When the desktop runner receives a-`plugins.execute` notification it now carries the session mode in the `ctx`-argument to the tool's `execute`.+`apps/desktop/electron/main/plugin-runtime.ts` validates each declaration+against its schema, stores the normalized list on `RegisteredPluginTool`, and+passes the session mode in the `ctx` given to `execute`, rejecting the call with+`PERMISSION_DENIED` when the action is not declared in `plan` or `goal` mode.+This third layer means a runtime or host-core bug cannot reach the plugin.### 6. Bundled Browser plugin declares its four read-only actions-The bundled `pi.browser` plugin (ADR 0170) declares `planSafeActions:-["navigate", "snapshot", "screenshot", "console"]`. The mutating actions-(`click`, `fill`, `evaluate`, `cdp`) stay Agent-only, which matches the public-risk model and the user's expectation that "read the URL" is Plan-acceptable-while "fill in the form" is not.+`pi.browser` (ADR 0170) declares `planSafeActions: ["navigate", "snapshot",+"screenshot", "console"]`, keeping `click`, `fill`, `evaluate`, and `cdp`+Agent-only.### 7. Window-summon shortcut-The existing keyboard shortcut catalog gains a `summonWindow` id bound to-`Mod+Shift+W` by default, in the `window` group, alongside `closeWindow`-(`Mod+W`). The desktop main process registers it through `globalShortcut` the-same way it does `openPluginLauncher`, and the native menu gains a "bring the-window back" item that calls `restoreMainWindow`.--*(Amended by D438: the catalog now ships one `toggleWindow` id instead of the-`summonWindow` / `closeWindow` pair, the retired `Mod+Shift+W` chord is-registered by nothing, and stored overrides for the two retired ids are folded-into the toggle on read. Hiding is `Window.hide()` and never the close path.-Amended again by D439: the toggle ships on `Alt+Shift+W`, not on the `Mod+W`-this ADR's D438 amendment first named, because the key is registered-process-wide and macOS spends `Cmd+W` on its own close-window command.)*+The shortcut catalog gains a `summonWindow` id bound to `Mod+Shift+W` in the+`window` group, registered through `globalShortcut` with a native menu item+calling `restoreMainWindow`, as the counterpart to `closeWindow` (`Mod+W`).+Amended by D438 and D439: the catalog now ships one `toggleWindow` id instead of+the pair, the retired chord is registered by nothing, stored overrides fold into+the toggle on read, hiding uses `Window.hide()` and never the close path, and the+toggle ships on `Alt+Shift+W` because the key is process-wide and macOS spends+`Cmd+W` on its own close-window command.## Consequences-- Plan and Goal modes can inspect external resources through any plugin whose- author opts in.-- Plugin authors remain responsible for declaring exactly which actions are- read-only.-- The contract modes' hard deny for `Write`, `Edit`, and unknown tools is- unchanged.-- The defense-in-depth check in the plugin-runtime means a bug in the runtime or- host-core cannot escalate a Plan call into a mutation: the plugin rejects it- itself.-- The `Mod+Shift+W` summon shortcut pairs with `Mod+W` close, so users on- Windows/Linux with a tray-residing window have one shortcut to hide and one to- bring back.+- Plan and Goal can inspect external resources through any plugin that opts in;+ MCP tools take the same path with the same declaration.+- A wrong declaration fails at registration rather than at the user's prompt, and+ the hard deny for `Write`, `Edit`, and unknown tools is unchanged.+- The plugin runtime's own check means a runtime or host-core bug cannot escalate+ a Plan call into a mutation.## Alternatives-### Add a separate read-only URL fetcher tool--Rejected because it duplicates the Browser plugin's CDP-backed snapshot and-bypasses the public contribution channel; plugin authors would have to maintain-two copies of the same plumbing to expose the same capability in both modes.--### Allow all plugins in Plan mode and trust the manifest--Rejected because it weakens the contract and gives plugin authors an implicit-"everything is safe" default.--### Use a per-tool risk-only flag--Rejected because plugin tools are not uniformly read-only across actions.--### Auto-detect safe actions from the schema--Rejected because "no `Write` argument" is not the same as "no side-effect".--### Default `summonWindow` to a tray-only affordance--Rejected because the tray icon already summons on click; the request was a-keyboard shortcut to do the same thing without leaving the current focus.--## References--- `docs/spec/03-runtime/03-tools-and-permissions.md`-- `docs/spec/06-delivery/04-e2e-test-plan.md` E2E-PLAN-005- - `docs/spec/08-meta/decisions-log.md` D384, D438-- `packages/plugin-sdk/src/index.ts`-- `packages/agent-runtime/src/runtime.ts`-- `packages/agent-runtime/src/mode-prompts.ts`-- `crates/host-core/src/tools/mod.rs`-- `crates/host-core/src/permissions.rs`-- `crates/host-core/src/rpc/mod.rs`-- `apps/desktop/electron/main/plugin-runtime.ts`-- `apps/desktop/electron/main/index.ts`-- `apps/desktop/resources/plugins/pi.browser/main.js`-- `packages/shared/src/keyboard-shortcuts.ts`-- `packages/shared/src/protocol.ts`-- `apps/desktop/electron/main/application-menu.ts`+- Add a separate read-only URL fetcher: rejected; it duplicates the Browser+ plugin's snapshot path and bypasses the public contribution channel.+- Use a per-tool risk flag or auto-detect safe actions from the schema: rejected;+ plugin actions are not uniformly read-only and a schema cannot know that a+ navigation triggers a login or that `evaluate` posts a comment.diff --git a/docs/adr/0212-remove-diagnostic-timing-log-streams.md b/docs/adr/0212-remove-diagnostic-timing-log-streams.mdindex 160cd2f00..4c01740cc 100644--- a/docs/adr/0212-remove-diagnostic-timing-log-streams.md+++ b/docs/adr/0212-remove-diagnostic-timing-log-streams.md@@ -8,25 +8,23 @@## ContextD137/D183 added per-tool, per-model, boot-phase, and updater timing output to-help diagnose a slow run. The investigation is complete, and those records now-create noise in local log directories during normal use.+diagnose a slow run. That investigation is complete and those records now only+add noise to local log directories during normal use.## Decision-1. Stop emitting sidecar `[timing]` lines, host `tool timing` lines, boot-phase- timing records, updater timing records, and renderer bootstrap timing output.-2. Remove the dedicated `timing` log category and the `PI_DESKTOP_TIMING`- suppression environment variable.-3. Keep key lifecycle, state-change, permission, tool, plugin, provider,- persistence, updater, and error records.-4. Do not delete or migrate timing files already present in a user's local data- directory.+Stop emitting sidecar `[timing]` lines, host `tool timing` lines, boot-phase and+updater timing records, and renderer bootstrap timing, and remove the dedicated+`timing` log category with the `PI_DESKTOP_TIMING` suppression variable; the+updater's functional timeout stays. Lifecycle, state-change, permission, tool,+plugin, provider, persistence, updater, and error records remain, as do audit+fields and duration metadata consumed by product features or security forensics,+and timing files already in a user's data directory are left untouched.## Consequences-- Normal launches, turns, retries, and tool calls produce fewer log records and- no longer create dedicated timing files.-- Failures remain diagnosable through stable lifecycle records, error codes,- tool/permission audit rows, and the visible transcript.-- Timing-specific troubleshooting scenarios and documentation are retired.-- Existing local timing files may remain until the user removes them.+- Normal launches, turns, retries, and tool calls produce fewer records and no+ dedicated timing files.+- Failures stay diagnosable through lifecycle records, error codes, audit rows,+ and the visible transcript.+- Timing-specific troubleshooting documentation is retired.diff --git a/docs/adr/0213-persist-host-owned-turn-queue.md b/docs/adr/0213-persist-host-owned-turn-queue.mdindex d52a2eff2..12a83aef4 100644--- a/docs/adr/0213-persist-host-owned-turn-queue.md+++ b/docs/adr/0213-persist-host-owned-turn-queue.md@@ -3,50 +3,46 @@- Status: Accepted- Date: 2026-09-10- Decision: D386-- Related: ADR 0205 (D375), `03-runtime/04-data-storage.md` §4.6b,- `03-runtime/06-host-rpc-protocol.md`,- `02-architecture/05-remote-agent-control.md` §6+- Related: ADR 0205 (D375), `03-runtime/04-data-storage.md` §4.6b, `03-runtime/06-host-rpc-protocol.md`, `02-architecture/05-remote-agent-control.md` §6## ContextD375 moved the per-session prompt queue out of renderer memory into the Host and-chose to persist it. The headless Agent Host module (`packages/agent-host`) owns-admission and draining, but it needs a store that survives a restart and never-starts work on its own.+chose to persist it. The headless Agent Host module owns admission and draining+but needs a store that survives a restart and never starts work on its own, and+host-core owns SQLite exclusively (frozen decision 12).## Decision-1. **Schema v15 adds `turn_queue`.** Columns: `id`, `session_id` (FK, cascade),- `principal`, `idempotency_key`, `input_hash`, `content`, `attachments_json`,- `permission_mode`, `position`, `created_at`; a per-session `position` index- and a unique `(session_id, principal, idempotency_key)` index.-2. **Four additive RPC methods.** `session.queuePush` is idempotent on- `(session, principal, idempotencyKey)`, returns the existing entry when the- input hash matches, fails with `IDEMPOTENCY_CONFLICT` when a key is reused- with other input, and fails with `AGENT_BUSY` when the session already holds- eight entries.-3. **The store never decides execution.** The Agent Host module restores entries- when host-core answers, holds every restored session until a controller- attaches, and drains one entry only after the active turn's terminal event.-4. **The renderer's in-memory queue is retired.** The composer pushes through- `agent/queue/push`, mirrors `agent/event/queueChanged`, and its "send now"- uses `agent/queue/prioritize` to deliver promoted input into the current turn- through steering (ADR 0265, issue #1607).-5. **Schema v20 extends queued input provenance.** `user_message_id` preserves- the stable user row across queue recovery, and `voice_origin_json` records- the originating Live Voice call and operation.+1. An additive schema migration adds `turn_queue` with a per-session `position`+ index and a unique `(session_id, principal, idempotency_key)` index, so+ existing chains gain only the new step.+2. Four additive RPC methods: `session.queuePush`, idempotent on+ `(session, principal, idempotencyKey)`, returning the existing entry for a+ matching input hash and failing with `IDEMPOTENCY_CONFLICT` on key reuse with+ other input or `AGENT_BUSY` at the per-session limit; `session.queueList`;+ `session.queueRemove`; and `session.queuePrioritize`, which moves an entry to+ the head of its session as RACP `turn/prioritize`. The protocol version does+ not change.+3. The store never decides execution: the Agent Host restores entries, holds a+ restored session until a controller attaches, drains one entry only after the+ active turn's terminal event, and never replays or auto-starts work.+4. The renderer's in-memory queue is retired in favor of `agent/queue/push`,+ `agent/event/queueChanged`, and `agent/queue/prioritize` for "send now"+ (ADR 0265, issue #1607).+5. Queued input keeps provenance through the nullable `user_message_id` and+ `voice_origin_json` columns, added by an additive migration.## Consequences-- A reboot no longer loses queued prompts; they reappear, held, in the- snapshot's `queuedTurns`.-- Every client of a Host sees the same queue once the renderer switch lands.-- Deleting a session cascades to its queue entries.-- Fresh installs and every migration path produce the current schema; schema v15- remains the original queue introduction, and schema v20 adds optional- identity/provenance metadata without changing prior rows.+- Queued prompts survive a reboot and reappear, held, as `queuedTurns`.+- Every client of a Host sees the same queue; deleting a session cascades to+ its entries.+- Fresh installs and every migration path reach the current schema.-## Alternatives considered+## Alternatives-- Keep the queue in Agent Host memory, as the D373 draft did.-- Persist in the renderer's `localStorage`.+- Keep the queue in Agent Host memory, as the D373 draft did: rejected by D375,+ because a restart loses prompts.+- Persist in renderer `localStorage`: rejected, it is invisible to other clients+ and to a headless Host.diff --git a/docs/adr/0214-trusted-extensions.md b/docs/adr/0214-trusted-extensions.mdindex 252566c3a..4b90ae80d 100644--- a/docs/adr/0214-trusted-extensions.md+++ b/docs/adr/0214-trusted-extensions.md@@ -2,58 +2,52 @@- Status: Accepted (v1 implemented 2026-09-10)- Date: 2026-09-10-- Decision: D387-- Related: ADR 0002, ADR 0008, D007, `07-plugins/16-trusted-extensions.md`,- `07-plugins/01-plugin-system.md` §14+- Related: ADR 0002, ADR 0008, D007, D387## Context-PI-Desktop's plugin system (ADR 0008) runs plugins in their own process behind a-permission gateway. That is the right shape for distributed, untrusted code, but-it leaves no surface for code that must sit on the agent loop itself: tools that-execute in-process with the session's working directory, hooks on every turn,-tool call, and provider request, and slash commands that carry session context.+The plugin system (ADR 0008) runs plugins in their own process behind a permission+gateway, which leaves no surface for code that must sit on the agent loop itself:+in-process tools, hooks on turns, tool calls, and provider requests, and slash+commands carrying session context. The kernel's sibling `pi-coding-agent` package+already defines an `ExtensionAPI` contract and loader with existing extensions+written against it.## Decision1. **Trusted extensions are the second extension surface.** The sidecar pins- `pi-coding-agent` at the same version as the other two kernel packages as a- types-only dependency, mirrors its discovery rules, loads modules with- `jiti/static` and virtual modules, and implements `ExtensionAPI` on top of- the desktop runtime's hook points in a desktop-owned Runner.+ `pi-coding-agent` as a types-only dependency, mirrors its discovery rules,+ loads modules with `jiti/static` and virtual modules, and implements+ `ExtensionAPI` over the desktop runtime's hook points in a desktop-owned+ Runner, one per session.2. **Trusted, opt-in, no auto-import.** Extensions are labelled "Trusted- extension", run with sidecar trust, and are disabled until the user enables- each one.+ extension", run with sidecar trust, and stay disabled until the user enables+ each one. D007 still holds: `~/.pi` is scanned for candidates, never imported,+ and project-scoped extensions are enabled per project.3. **Explicit support classes.** Every `ExtensionAPI` member is Supported,- Deferred, or Unsupported.-4. **Plugins are untouched.** No plugin manifest, permission, or process- boundary changes.-5. **No host-core change in v1.** Enablement is app settings; new traffic is- sidecar-to-main proxy methods and Electron IPC only.+ Deferred, or Unsupported; unsupported members stay inert and produce+ diagnostics instead of throwing, and terminal-UI surfaces stay Unsupported.+4. **Plugins are untouched.** No manifest, permission, or process boundary+ changes; extension tools and commands join the same catalogs after plugins and+ lose name collisions.+5. **No host-core change in v1.** Enablement is app settings, and the new traffic+ is sidecar-to-main proxy methods plus Electron IPC.## Consequences-### Prompt chaining amendment (2026-09-29, issue #1023)--The desktop initially folded `before_agent_start` results while giving every-handler the original prompt.--This matches the sequential prompt replacement behavior of the pinned Pi-extension runner without sharing mutable handler inputs.--### General consequences--- Users can attach in-process tools, hooks, and commands to the agent loop- without a new app release.-- Two extension surfaces coexist and are explained in user documentation as- "plugins" (sandboxed) and "trusted extensions" (in-sidecar).-- The three kernel packages move in lockstep; a contract test with sample- extensions guards every upgrade.-- The sidecar bundle must keep jiti loadable; this is verified first.+- Users attach in-process tools, hooks, and commands without an app release, and+ documentation separates sandboxed plugins from in-sidecar trusted extensions.+- The three kernel packages move in lockstep, guarded by a contract test with+ sample extensions.- Module-level extension state is shared across sessions in one sidecar.+- The prompt-chaining amendment of 2026-09-29 (issue #1023) chains+ `before_agent_start` string replacements through a turn-local payload in the+ existing order, starting fresh each turn, so two extensions appending to the+ same input no longer overwrite each other.-## Alternatives considered+## Alternatives-- A new plugin contribution type for in-process hooks.-- Replace the desktop runtime with `AgentSession`.-- Run extensions inside the plugin host process.+- A new plugin contribution type for in-process hooks: rejected because it would+ breach the plugin sandbox or duplicate `ExtensionAPI` with no extensions to run.+- Run extensions in the plugin host process: rejected because the permission+ gateway denies most of what extensions do.diff --git a/docs/adr/0215-agent-extensions-as-plugin-contribution.md b/docs/adr/0215-agent-extensions-as-plugin-contribution.mdindex 95a5febd0..8ccbebb3e 100644--- a/docs/adr/0215-agent-extensions-as-plugin-contribution.md+++ b/docs/adr/0215-agent-extensions-as-plugin-contribution.md@@ -4,43 +4,39 @@- Date: 2026-09-11- Decision: D388 (amends D387 / ADR 0214)- Related: ADR 0008, ADR 0214, `07-plugins/16-trusted-extensions.md`,- `07-plugins/02-plugin-manifest-schema.md` §4, `07-plugins/13-plugin-permissions-matrix.md`+ `07-plugins/13-plugin-permissions-matrix.md`## Context-ADR 0214 delivered ExtensionAPI modules as a separate surface next to plugins:-its own discovery over `~/.pi/agent/extensions`, its own enablement store, its-own Settings destination. That gave users two lists that mean "extend the agent"-and left pi CLI extensions outside the plugin lifecycle (install, scope, update,-remove, marketplace).+ADR 0214 delivered ExtensionAPI modules beside plugins, with their own discovery,+enablement store, and Settings destination, so users had two lists meaning+"extend the agent" and pi CLI extensions stayed outside install, scope, update,+and removal.## Decision-1. **`contributes.agentExtensions` + `agent.extension`.** A plugin lists- ExtensionAPI modules in its manifest and must hold the `agent.extension`- permission (high risk, explicit confirmation).-2. **Plugin lifecycle owns enablement and scope.** Enabling, disabling,- per-project activation, reload, and removal are the plugin's.-3. **Import generates a plugin.** "Import pi extension" copies the chosen file- or directory into `<dataDir>/plugins/imported/<slug>/src`, writes a manifest- with the contribution and the permission, and registers it as a development- plugin.-4. **The standalone surface is removed.** No registry file, no Settings- destination, no list / enable / rescan / add-path / remove IPC.-5. **Marketplace distribution waits for signing.** `agent.extension` is accepted- from local imports and development plugins in v1.1.+A plugin lists ExtensionAPI modules in `contributes.agentExtensions` and must hold+the `agent.extension` permission (high risk, explicit confirmation), because those+modules still run in the Agent sidecar outside the plugin sandbox; validation+rejects the contribution without it, and a grant list that omits it skips the+modules with an audit entry. Plugin lifecycle owns enablement, per-project scope,+reload, and removal. "Import pi extension" copies the chosen file into+`<dataDir>/plugins/imported/<slug>/src`, writes a manifest with the contribution+and permission, and registers it as a development plugin, with the confirm before+the picker as the trust decision. The standalone surface is removed — no registry+file, no Settings destination, no registry IPC — leaving the plugin row with its+capability, permission, load state, names, and diagnostics, and marketplace+distribution waits for signing.## Consequences-- One mental model for users: extensions are plugins.-- The sidecar engine (loader, Runner, hooks, command and prompt bridges) is- untouched; only the ownership layer moved.-- Sandbox level is unchanged and now explicit as a permission.-- The v1 harness covers plugin-form fixtures and the importer/runtime contracts;- the native picker, npm install, and provider-turn journey remain separate- environment-dependent validation.+- Users get one model: extensions are plugins, so the ecosystem gap closes with+ "import as a plugin".+- The sidecar engine is untouched and the sandbox level is unchanged, now+ explicit as a permission.## Alternatives considered-- Keep two surfaces and cross-link them.-- Source-convert pi extensions into plugin main modules.+- Keep two surfaces and cross-link them: rejected by the maintainer.+- Source-convert extensions into plugin main modules: rejected; in-process+ ExtensionAPI semantics do not map onto the sandboxed plugin API.diff --git a/docs/adr/0216-truncate-regenerates-under-the-rpc-lock.md b/docs/adr/0216-truncate-regenerates-under-the-rpc-lock.mdindex 01a0114e4..250627575 100644--- a/docs/adr/0216-truncate-regenerates-under-the-rpc-lock.md+++ b/docs/adr/0216-truncate-regenerates-under-the-rpc-lock.md@@ -2,46 +2,39 @@- Status: Accepted- Date: 2026-09-10-- Deciders: PI-Desktop core-- Related: D199 / ADR 0060, D258 / ADR 0127, D307, issue #211+- Related: ADR 0060, ADR 0127, ADR 0217, D199, D258, D307, issue #211## ContextRetry, regenerate, and edit-resend truncated the live transcript from Electron-main: `session.get` of the whole history, `session.saveRevision` of the-discarded tail, then `session.replaceMessages` with the kept prefix.+main through `session.get`, `session.saveRevision`, and+`session.replaceMessages`, shipping the kept transcript as one NDJSON line. A+few-thousand-message session exceeds the 64 MiB stdin line cap or the RPC+deadline, the client timeout does not cancel the host rewrite, and a retry+queues another full one while the previous turn can stay `running`.## Decision-1. `session.truncateFrom` is a host-owned cut: `{ sessionId, fromMessageId? ,- truncateBefore? }`.-2. `agent/prompt` calls that method when a truncate is requested, loads only a- bounded `session.get` for launch configuration, and disposes the sidecar- session after the cut.-3. An NDJSON request line over 64 MiB is drained through to the next newline and- answered with `LIMIT_EXCEEDED`.-4. Protocol version stays at 11.--`session.replaceMessages` remains for callers that truly replace the whole array-(message delete, unanswered smart Stop). It is still unsafe as a-read-modify-write from a snapshot taken outside the lock.--## Alternatives considered--- **Raise the 130 s deadline for `session.replaceMessages`:** the 64 MiB stdin- cap still kills or rejects the line.-- **Chunk the kept array across many RPCs:** keeps the snapshot outside the lock- and still races `session.appendMessage`.-- **Bump the protocol version:** handshake requires exact equality between- components that ship together, and nothing a v11 client relies on changes.+`session.truncateFrom` (`{ sessionId, fromMessageId?, truncateBefore? }`) is a+host-owned cut that resolves the boundary against the durable transcript, aborts+a leftover running turn, archives the discarded regenerate tail, and rewrites+the kept prefix under the state lock, returning counts and optional pager+metadata. `agent/prompt` calls it instead of `session.replaceMessages` and+`session.saveRevision` on this path, an oversized NDJSON request line is drained+to the next newline and answered with `LIMIT_EXCEEDED` instead of ending the+stdin reader, and the protocol stays at version 11. `session.replaceMessages`+remains only for callers that truly replace the whole array.## Consequences-- Retry and regenerate on a multi-thousand-message session no longer depend on- shipping the kept prefix through JSON-RPC.+- Retry and regenerate on long sessions no longer ship the kept prefix through+ JSON-RPC.- A leftover `running` turn is settled as `aborted` inside the same lock, so the- following `beginTurn` is not `AGENT_BUSY` and UI failure cannot leave sqlite- `running`.+ following `beginTurn` is not `AGENT_BUSY`.- Oversized control-pipe lines no longer take down host-core.-- On Windows, a leftover strong stdout sender in the Alt+Space hook could still- keep host-core alive after stdin ended (the 130 s timeout in issue #211).++## Alternatives considered++- Raise the RPC deadline: rejected; the 64 MiB stdin cap still rejects the line.+- Chunk the kept array across RPCs: rejected; the snapshot stays outside the+ lock and still races `session.appendMessage`.diff --git a/docs/adr/0217-host-stdout-sender-must-not-outlive-serve.md b/docs/adr/0217-host-stdout-sender-must-not-outlive-serve.mdindex 4b9d705e1..47d5e9f80 100644--- a/docs/adr/0217-host-stdout-sender-must-not-outlive-serve.md+++ b/docs/adr/0217-host-stdout-sender-must-not-outlive-serve.md@@ -2,41 +2,43 @@- Status: Accepted- Date: 2026-09-11-- Deciders: PI-Desktop core-- Related: D390 / ADR 0216, issue #211+- Related: ADR 0216, D390, issue #211## Context-ADR 0216 stopped regenerate from shipping the kept transcript as one NDJSON-line, and stopped an oversize line from ending the stdin reader. That is-necessary but not sufficient for the Windows failure in issue #211.+ADR 0216 stopped regenerate from shipping the kept transcript as one NDJSON line,+but on Windows an oversize line still hung shutdown: the Alt+Space keyboard hook+holds a strong sender clone, so the stdout writer thread never unblocks,+`serve()` never returns, and Electron reports a host RPC timeout instead of a+dead host. A `LIMIT_EXCEEDED` reply with a null JSON-RPC id had the same client+symptom, because Electron treats `id: null` as a notification.## Decision-1. The Windows keyboard hook retains only a `WeakUnboundedSender`.-2. After stdin ends, `serve()` waits at most 5 s for the stdout writer, then- returns even if some other clone leaked.-3. Electron measures the UTF-8 byte length of each host RPC payload and rejects- a line over 64 MiB with `LIMIT_EXCEEDED` before writing stdin.+1. The Windows keyboard hook keeps only a weak sender and upgrades it when a+ shortcut is sent, so dropping serve's last strong sender still closes the+ writer channel.+2. After stdin ends, `serve()` waits at most 5 s for the writer and then returns+ even if some clone leaked; protocol version stays at 11.+3. Electron measures each host RPC payload and rejects a line over 64 MiB with+ `LIMIT_EXCEEDED` before writing stdin, using one shared constant that matches+ host-core.4. If the host still sees an oversize line, it peeks the JSON-RPC id from the- truncated prefix so the `LIMIT_EXCEEDED` reply can be matched.+ truncated prefix so the reply can be matched.-`session.truncateFrom` remains the regenerate path (ADR 0216). Whole-transcript-`session.replaceMessages` (message delete, unanswered smart Stop) still exists;-the client precheck is the guard if those payloads grow past 64 MiB.--## Alternatives considered--- **O(tail) jsonl truncation:** makes regenerate cheaper on huge sessions, but- does not explain the 130 s Windows timeout.-- **Daemonize the stdout writer thread:** process exit would still wait for- non-daemon OS threads on some platforms.-- **Bump protocol version:** host and Electron ship together; nothing a v11- client relies on is removed.+`session.truncateFrom` remains the regenerate path (ADR 0216), and+`session.replaceMessages` stays available behind the client precheck.## Consequences-- Windows host-core exits after stdin EOF the same way macOS/Linux already did.+- Windows host-core exits after stdin EOF like macOS and Linux.- An oversized control-pipe write fails immediately with `LIMIT_EXCEEDED`- instead of `host RPC timeout`.-- A leftover strong sender cannot keep `serve()` blocked for more than 5 s.+ instead of a deadline.+- A leaked strong sender cannot block `serve()` beyond the bounded wait.++## Alternatives++- O(tail) jsonl truncation: rejected as the fix because it does not explain the+ hung shutdown; deferred.+- Bump the protocol version: rejected because host and Electron ship together and+ no v11 client capability is removed.diff --git a/docs/adr/0218-effective-image-input-overrides.md b/docs/adr/0218-effective-image-input-overrides.mdindex 5b63c0bd7..7b22a58ec 100644--- a/docs/adr/0218-effective-image-input-overrides.md+++ b/docs/adr/0218-effective-image-input-overrides.md@@ -2,42 +2,37 @@- Status: Accepted- Date: 2026-09-11-- Deciders: PI-Desktop runtime and desktop UI maintainers- Amends: ADR 0101, D243## Context-Advanced model settings allow a provider binding to override whether an endpoint-accepts image input. The override is intentionally three-state: `null` means-follow the published model record, while `true` and `false` explicitly enable or-disable image input.+A provider binding can override whether an endpoint accepts image input with a+three-state `supportsImages`: `null` follows the published model record while+`true` and `false` enable or disable it. Composer model rows read the vision+badge from the published catalog alone, so the badge and the transport decision+could disagree.## Decision-1. Resolve the effective image-input capability for the exact provider/model- binding.-2. Use that same effective result for the Composer model-row badge, attachment- status, and main-process image transport.-3. Keep unknown or custom model ids conservative when no explicit binding- override exists.-4. Preserve the existing attachment boundary: eligible images within the decimal- 10 MB app limit use transient image blocks; disabled, unknown, or oversized- images use the safe `@path` fallback.+Resolve one effective image-input capability per provider/model binding, where an+explicit `supportsImages` wins and `null` or absence follows the published model+capability, and use that result for the Composer badge, attachment status, and+main-process image transport without mutating the shared `ModelInfo` record.+Unknown or custom model ids stay conservative when no binding override exists,+because discovery or cache metadata alone cannot promote them to image+transport. The attachment boundary is unchanged: eligible images within the app+limit become transient image blocks, and disabled, unknown, or oversized images+fall back to `@path`.## Consequences-- A provider binding can accurately describe a custom or proxied endpoint in- both the model picker and the request path.-- Resetting an override to `null` restores the published catalog behavior.-- Published catalog metadata remains immutable and authoritative when no local- endpoint-specific override is configured.-- The Composer's vision badge and transport decision cannot drift apart.--## Alternatives considered--- **Keep the badge catalog-only:** rejected because it misrepresents configured- endpoints and diverges from the transport decision.-- **Mutate the published model record:** rejected because it would leak- endpoint-local settings into shared catalog state and other bindings.-- **Trust discovery for unknown models:** rejected because discovery is not a- sufficient serialization or safety guarantee for image transport.+- A binding describes a custom or proxied endpoint the same way in the picker+ and in the request path.+- Resetting an override to `null` restores published catalog behavior.+- Published catalog metadata stays immutable and authoritative.++## Alternatives++- Keep the badge catalog-only: rejected, it misreports configured endpoints.+- Mutate the published model record: rejected, it leaks endpoint-local settings+ into shared catalog state.diff --git a/docs/adr/0219-user-invoked-skills-in-composer.md b/docs/adr/0219-user-invoked-skills-in-composer.mdindex 43ffeab54..75cd7e6f2 100644--- a/docs/adr/0219-user-invoked-skills-in-composer.md+++ b/docs/adr/0219-user-invoked-skills-in-composer.md@@ -2,42 +2,38 @@- Status: Accepted- Date: 2026-09-11-- Deciders: PI-Desktop runtime and desktop UI maintainers-- Amends: D123, D174, ADR 0024, ADR 0039+- Related: D123, D174, ADR 0024, ADR 0039## Context-D174 established the Skill catalog and local `Skill` tool as a model-invoked-capability, and explicitly rejected user-facing slash commands. That keeps skill-bodies out of the system prompt and preserves the existing permission,-activation, and runtime-reload boundaries, but it also makes active skills-undiscoverable when a user knows that a specific workflow should be applied.+D174 made the Skill catalog and the local `Skill` tool model-invoked and rejected+user-facing slash commands, which keeps bodies out of the system prompt and preserves+permission and activation boundaries, but leaves an active skill undiscoverable to a+user who knows a workflow should apply.## Decision-1. Active built-in, plugin, and user Skills contribute entries to the composer- slash menu.-2. Selecting a Skill inserts `/skill:<skill-id> `.-3. Main persists a model-facing instruction asking the model to call the local- `Skill` tool with each validated id, followed by the remaining user text.-4. No host protocol version or SQL migration is required.+Active built-in, plugin, and user Skills contribute entries to the composer slash menu+in a trailing `Skills` group, named with the explicit `skill:<id>` prefix while+`skillId` keeps the original id. Selecting one inserts `/skill:<skill-id> `, and+sending uses the ordinary prompt path: Electron main resolves the command against the+session project, revalidates active scope and permissions at send time, and keeps the+typed slash form for the transcript chip. Main then persists a model-facing+instruction to call the local `Skill` tool with each validated id before the remaining+user text, so the body loads on demand and never reaches the renderer or the prompt.+No host protocol version or SQL migration is needed: optional `command` and+`skillMentions` transcript metadata keep the typed text across reloads, the additive+command contract permits `kind: "skill"` and `skillId`, and catalog, body-size, and+runtime-reuse boundaries stay those of D174 and ADR 0039.## Consequences-- Users can explicitly discover and invoke an active Skill while the model can- still choose Skills implicitly from the same catalog.-- A Skill disabled or removed between autocomplete and send falls back to the- existing literal slash-prompt behavior rather than bypassing activation.-- The final autocomplete group may grow with the active Skill catalog, but its- stable placement keeps existing command ordering predictable.--## Alternatives considered--- **Inject the Skill body directly into the prompt:** rejected because it- bypasses the local `Skill` tool's scope checks, on-demand loading, and runtime- reload semantics.-- **Auto-trigger a Skill from the renderer:** rejected because invocation and- active-scope validation belong in Electron main, not in a renderer hint.-- **Add a new host protocol or durable message schema:** rejected because the- existing Electron command channel and optional transcript command metadata are- sufficient.+- Users can invoke an active Skill explicitly while the model still chooses Skills+ implicitly from the same catalog.+- A Skill disabled between autocomplete and send falls back to the literal slash+ prompt instead of bypassing activation.++## Alternatives++- Inject the Skill body into the prompt: bypasses scope checks and reload semantics.+- Auto-trigger from the renderer: scope validation belongs in Electron main.diff --git a/docs/adr/0220-windows-work-panel-toolbar.md b/docs/adr/0220-windows-work-panel-toolbar.mdindex f129fa587..c4d605a31 100644--- a/docs/adr/0220-windows-work-panel-toolbar.md+++ b/docs/adr/0220-windows-work-panel-toolbar.md@@ -12,33 +12,28 @@## Context-On Windows, the open work-panel header placed the active resource close button-beside the viewport-fixed panel toggle and the native minimize/maximize/close-cluster. At narrow widths, the two close icons read as a duplicate top-right-action and the header became difficult to scan.+On Windows the open work-panel header put the active resource close button beside the+viewport-fixed toggle and the native window cluster, so at narrow widths two close+icons read as one duplicated top-right action.## Decision-1. The open work-panel header exposes one compact resource switcher.-2. The viewport-fixed work-panel toggle remains the sole panel-level collapse- control.-3. Subagent detail uses a back chevron to return to the resource list, so its- navigation action is visually distinct from both resource close and native- window close.-4. The change is renderer presentation and interaction only.+The header exposes one compact resource switcher, and closing a resource is owned by+its existing unified context-menu row. The viewport-fixed toggle stays the sole+panel-level collapse control, Windows/Linux window controls stay in their fixed right+edge band, and subagent detail uses a back chevron. This is renderer presentation+only: panel state ownership, resource lifecycle, window geometry, IPC, protocol, and+storage are unchanged.## Consequences-- The Windows top-right row has one clear window-close action and a separated- panel toggle.-- Resource close remains available from the keyboard-operable unified menu and- can no longer be mistaken for closing the application.-- The header gives up one direct-click close affordance in exchange for a- stable, less crowded action cluster.+The Windows top-right row has one window-close action and a separated toggle, so+resource close can no longer be mistaken for closing the application, at the cost of+one direct-click close affordance.-## Alternatives considered+## Alternatives-- **Keep the header resource `X` and shrink the native controls:** rejected;- native window affordances must keep their platform-sized hit targets.-- **Add another panel-specific close or collapse icon:** rejected; D357 and ADR- 0195 make the viewport-fixed toggle the sole panel-level collapse control.+- Keep the header `X` and shrink native controls: platform hit targets must keep+ their size.+- Add another close icon: D357 and ADR 0195 make the viewport-fixed toggle the only+ panel-level collapse control.diff --git a/docs/adr/0221-canonical-thinking-level-values.md b/docs/adr/0221-canonical-thinking-level-values.mdindex 5fc5402a8..13fa266b7 100644--- a/docs/adr/0221-canonical-thinking-level-values.md+++ b/docs/adr/0221-canonical-thinking-level-values.md@@ -1,28 +1,27 @@# ADR 0221: Render Canonical Thinking-Level Values Without Translation-- Status: Accepted+- Status: Accepted; amends D369 and ADR 0202- Date: 2026-09-11-- Deciders: PI-Desktop desktop UI maintainers-- Amends: D369, ADR 0202-- Related: [02-i18n-english-first](../spec/04-ux/02-i18n-english-first.md) ·- [08-component-spec](../spec/04-ux/08-component-spec.md) · E2E-219+- Related: D369, ADR 0202## ContextThinking levels are protocol values shared by provider bindings, session-configuration, runtime results, and model metadata. The renderer translated the-same values in the Composer, model configuration, and delegation cards, which-made a stable technical value vary with the selected application locale.+configuration, runtime results, and model metadata, yet the renderer translated them+in the Composer, model configuration, and delegation cards, so a stable technical+value varied with the applied locale.## Decision-1. Composer, model-configuration, and delegation surfaces render the canonical- values `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max` as-is.-2. The thinking-level values are not locale catalog entries.-3. `off` and `omit` remain omitted from delegation captions as specified by ADR- 0202.+Composer, model-configuration, and delegation surfaces render the canonical values+`off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max` as-is: they are not+locale catalog entries, their localized labels are removed from every shipped+catalog, and `off` and `omit` remain omitted from delegation captions per ADR 0202.+This changes presentation only; effective metadata, clamping, provider requests,+protocol, and storage are unchanged.## Consequences-Users see the same unambiguous value in every locale, and provider/runtime-terminology remains easy to compare with configuration and diagnostics.+Users see the same unambiguous value in every locale, comparable with configuration+and diagnostics, and the lower-case values keep their canonical wire and storage+representation.diff --git a/docs/adr/0222-composer-native-file-folder-drops.md b/docs/adr/0222-composer-native-file-folder-drops.mdindex 9fade316b..8385400b9 100644--- a/docs/adr/0222-composer-native-file-folder-drops.md+++ b/docs/adr/0222-composer-native-file-folder-drops.md@@ -2,53 +2,40 @@- Status: Accepted- Date: 2026-09-11-- Deciders: PI-Desktop core- Amends: ADR 0101 (drag/drop scope)- Related: D397, ADR 0059, ADR 0070## Context-The Composer already handles clipboard files and picker-selected files through-the session-scoped scratch flow. Native file-system drag-and-drop was still left-to the browser default, which could open or navigate away from the app.+The Composer handled clipboard and picker-selected files through the session-scoped+scratch flow, but native file-system drops still fell to the browser default, which+could open or navigate away from the app. Folders need different treatment: their+path is useful for `@` completion, while traversing or copying one would be+unbounded and would violate scratch ownership.## Decision-1. The Composer shell accepts native file-system drops and prevents the browser- default for transfers containing file items.-2. The Electron preload exposes only `webUtils.getPathForFile` for the- user-originated dropped `File` object.-3. Regular dropped files are transferred as bounded bytes through the existing- `composer/pasteFiles` bridge.-4. Dropped folders are never read, traversed, or copied.-5. This is a renderer/preload interaction change only.--## Security and boundary notes--- The renderer receives a source path only for a native user drop and uses it as- visible prompt text; it does not gain arbitrary filesystem read or write- access.-- Folder drops do not enumerate entries or transfer bytes, so a large folder- cannot turn into an unbounded scratch operation.-- Regular files retain the existing main-process size, name, session, and- scratch-root validation from ADR 0059.--## Alternatives considered--- **Traverse and copy dropped folders:** rejected because it is unbounded and- would make a path-display gesture mutate session scratch contents.-- **Insert only the folder leaf name:** rejected because it loses the path- needed to disambiguate and continue `@` completion.-- **Add a new main-process folder IPC:** rejected because the preload path- bridge supplies the source path for this user-originated gesture without- widening filesystem capabilities or adding a protocol surface.-- **Keep the browser default:** rejected because dropping a file or folder could- navigate or open the dropped resource instead of editing the prompt.+The Composer shell accepts native drops and prevents the browser default for+transfers containing file items, drawing a non-layout-affecting accent outline+during drag-over. The preload exposes only `webUtils.getPathForFile` for the+user-originated dropped `File`, and the renderer classifies folders from+`webkitGetAsEntry()` while keeping OS item order. Regular files travel as bounded+bytes through `composer/pasteFiles` into the session's scratch directory and appear+as removable leaf-name chips, while dropped folders are never read, traversed, or+copied: their complete native path is inserted at the caret as the literal+`@<path>/` form. This is a renderer/preload change only.## Consequences-- Users can drag files and folders directly into the chat input.-- Files have the same bounded scratch lifecycle and attachment metadata as- pasted files; folders remain visible references without being copied.-- The Composer's existing draft and chip persistence logic remains the single- source of truth for mixed asynchronous drops.+- Users can drag files and folders straight into the chat input, with folders kept+ as visible references instead of copies.+- Files keep the same bounded scratch lifecycle and validation as pasted files.+- The renderer gains a path only for a native user drop and uses it as prompt text,+ so no filesystem capability widens.++## Alternatives++- Traverse and copy dropped folders — rejected: unbounded, and a path-display+ gesture would mutate scratch contents.+- Insert only the folder leaf name — rejected: it loses the path needed for `@`+ completion.diff --git a/docs/adr/0223-context-usage-display-preference.md b/docs/adr/0223-context-usage-display-preference.mdindex b546e4c2d..3e98ded44 100644--- a/docs/adr/0223-context-usage-display-preference.md+++ b/docs/adr/0223-context-usage-display-preference.md@@ -2,57 +2,41 @@- Status: Accepted- Date: 2026-09-11-- Deciders: PI-Desktop desktop UI maintainers-- Amends: 0184-- Related: [04-ux/06-settings-ia](../spec/04-ux/06-settings-ia.md) ·- [04-ux/08-component-spec](../spec/04-ux/08-component-spec.md) ·- [08-meta/decisions-log](../spec/08-meta/decisions-log.md) (D398) ·- E2E-250+- Amends: ADR 0184+- Related: [04-ux/06-settings-ia](../spec/04-ux/06-settings-ia.md) · [04-ux/08-component-spec](../spec/04-ux/08-component-spec.md) · [08-meta/decisions-log](../spec/08-meta/decisions-log.md) (D398) · E2E-250## Context-The composer toolbar's context usage inspector (ADR 0184 / D347) always leads-with the remaining-capacity figure: the trigger ring, popover heading, tooltip,-and `aria-label` all show the remaining token count and percentage. Some users-find the used-capacity figure more intuitive — especially when context is-lightly loaded and the remaining number is close to the total window, which-provides little signal at a glance.+The composer toolbar's context usage inspector introduced by ADR 0184 (D347)+always led with remaining capacity, in the trigger ring, popover heading, tooltip,+and `aria-label`. Some users find used capacity more intuitive, especially when the+remaining figure sits close to the total window and gives little signal at a+glance.## Decision-1. A new setting `AppSettings.contextUsageDisplay` (`ContextUsageDisplay =- "remaining" | "used"`) lets the user choose which figure the context- inspector leads with.-2. When `contextUsageDisplay` is `"used"`, the composer toolbar ring's arc- length (`strokeDashoffset`), the trigger percentage and token label, the- popover heading, the tooltip, and the `aria-label` all switch to the- used-capacity pair instead of the remaining pair.-3. Warning and critical color thresholds remain based on **remaining** capacity- (remaining ≤ 25 % → warning, ≤ 10 % → critical) regardless of the display- mode.-4. Settings → AI → Defaults gains a `ContextUsageDisplayRow` (segmented control:- Remaining / Used) placed after the Link open destination row and before the- Enter-to-send row.-5. The change is renderer-only: no protocol, storage schema, host-side- migration, or IPC change.+1. `AppSettings.contextUsageDisplay` of type+ `ContextUsageDisplay = "remaining" | "used"` chooses which figure the inspector+ leads with, and `"remaining"` stays the default and the fallback for absent or+ unrecognized values.+2. With `"used"`, the ring arc, trigger label, popover heading, tooltip, and+ `aria-label` all report used capacity, and the ring fills proportionally to the+ used ratio.+3. Warning and critical colors stay keyed to remaining capacity in both modes, so a+ ring reading used capacity still warns when little space remains.+4. Settings → AI → Defaults gains a segmented Remaining / Used row.+5. The change is renderer-only: no protocol, storage schema, or IPC change, and+ host-core preserves the unknown settings key across upgrades.## Consequences-- Users who prefer a "how much have I spent" mental model get a consistent- display; users who prefer the original "how much is left" model see no change- by default.-- The ring arc direction flips visually when switching to `"used"`, which is the- correct correspondence: a fuller ring means more context consumed.-- Color semantics stay stable across modes, so the warning/critical signal is- never ambiguous regardless of the chosen display direction.-- No host or storage change means no migration risk and no protocol version- bump.--## Rejected alternatives--- **Boolean toggle (show-used: true/false):** a two-value segmented control- reads clearer than a checkbox for mutually exclusive display modes, and the- `ContextUsageDisplay` union type leaves room for future modes without a type- rename.-- **Color thresholds also follow display mode:** rejected; it would make a "used- 90 %" ring green despite only 10 % remaining, which is dangerously misleading.+- Both mental models are available, and the default behavior is unchanged.+- A fuller ring means more context consumed, which is the correct reading.+- Color semantics stay stable, so the warning signal is never ambiguous.++## Alternatives++- Boolean toggle: rejected, a segmented control reads clearer for mutually+ exclusive modes and the union type can grow.+- Color thresholds following the display mode: rejected, it would show a safe ring+ while almost no context remains.diff --git a/docs/adr/0224-right-panel-tab-strip.md b/docs/adr/0224-right-panel-tab-strip.mdindex 215cf698c..ec6ef9474 100644--- a/docs/adr/0224-right-panel-tab-strip.md+++ b/docs/adr/0224-right-panel-tab-strip.md@@ -2,33 +2,39 @@- Status: Accepted- Date: 2026-09-11-- Related issue: #229+- Related: Issue #229## ContextThe right work panel used one header menu for both tool launchers and-conversation-opened resources. That made open resources harder to scan, put-close actions far from their tabs, and allowed the menu to become a second-scrolling surface.+conversation-opened resources, so open resources were hard to scan, close actions+sat far from their tabs, and the menu could become a second scrolling surface.## Decision-The work-panel header is a horizontally scrollable tab strip followed by a-fixed, tight `+` trigger. The strip is the only horizontally scrolling region;-the `+` remains visible.+The work-panel header becomes a horizontally scrollable tab strip followed by a+fixed `+` trigger, with every open Review, file, or plugin view as one ARIA tab that+activates on click, closes from its own button or middle-click, reorders by pointer+drag or `Alt+ArrowLeft`/`Alt+ArrowRight`, keeps keyboard navigation and+Delete/Backspace closing, and auto-scrolls near the edges while dragging. Closing+the final tab keeps the panel open and shows a New launcher in the body.-The `+` menu has one **Tools & panels** group. Review is the only host-owned-entry; all other entries come from the current plugin-view metadata returned by-`contributes.views`.+The `+` menu has one **Tools & panels** group whose only host-owned entry is Review,+every other entry coming from the plugin-view metadata in `contributes.views`, so the+renderer hardcodes neither Files nor Browser. Plugin views stay singleton tabs, and+the viewport-fixed toggle remains the sole collapse control with a tooltip naming the+resolved `Mod+J` binding. No protocol, persisted tab schema, or native-window+reservation is introduced.## Consequences-- The tab strip makes the active resource and its close affordance visible while- preserving panel width and the existing native-surface occlusion boundary.-- The New launcher gives an intentional next action after the last tab closes- without changing the panel's session-scoped state model.-- Plugin authors automatically receive a panel launcher whenever their scoped- view contribution is available; the host's built-in list does not drift from- plugin metadata.-- The larger default gives the header enough room for the 166px Windows/Linux- titlebar reservation while preserving existing user-selected widths.+- The active resource and its close affordance are visible without losing panel width+ or the native-surface occlusion boundary.+- The New launcher offers an intentional next action after the last tab closes.+- Plugin authors get a launcher from their view contribution, so the host list cannot+ drift from plugin metadata.++## Alternatives++- Keep one header menu for launchers and resources — rejected: it hides open resources+ and grows into a second scrolling surface.diff --git a/docs/adr/0225-restore-deferred-tools-from-effective-session-context.md b/docs/adr/0225-restore-deferred-tools-from-effective-session-context.mdindex 5b031547c..d7d3d44ef 100644--- a/docs/adr/0225-restore-deferred-tools-from-effective-session-context.md+++ b/docs/adr/0225-restore-deferred-tools-from-effective-session-context.md@@ -7,49 +7,33 @@## Context-Lazy tool activation keeps optional schemas out of the first provider request,-but a new prompt previously cleared the active deferred set while retaining the-successful `ToolSearch` rows and tool results in the model context. The model-could therefore see evidence that a capability was available while the next-request omitted its schema.+Lazy tool activation keeps optional schemas out of the first provider request, but a+new prompt cleared the active deferred set while keeping the successful `ToolSearch`+rows and tool results in the model context, so the model saw evidence of a capability+whose schema the request omitted. The same mismatch followed a mode switch.## Decision-Before each new prompt and after a mode switch, the sidecar clears its in-memory+Before each new prompt and after a mode switch the sidecar clears its in-memorydeferred activation set and restores it from the effective `buildSessionContext`-projection. When system declarations exist, their replayed active set is the-baseline; only successful results after the last declaration can add a newly-activated tool.--The existing tool registry, host permission checks, workspace and scratch-containment, timeouts, and audit behavior remain unchanged. Compaction and mode-catalog rebuilding continue to define which historical markers are effective.+projection. Where system declarations exist, their replayed active set is the+baseline and only successful results after the last declaration may add a tool, so an+earlier success cannot resurrect a later removal and the set survives a compaction+checkpoint. For older histories a successful `ToolSearch` result contributes its+`addedToolNames` and a successful deferred-tool result contributes that tool's name,+restored only while it remains in the current mode's deferred catalog. Failed,+interrupted, and placeholder rows are ignored, and prose is never activation+evidence. Registry, permission, containment, and audit behavior are unchanged.## Consequences-- Provider requests remain coherent with the successful tool evidence retained- in the effective transcript.-- A runtime restart can reuse a deferred capability when its successful marker- remains in effective context, without moving optional schemas into the core- set or granting a new permission.-- Failed, interrupted, stale, and mode-disallowed activations do not revive a- deferred tool.+Provider requests stay coherent with the retained success evidence, a restart can+reuse a deferred capability without moving optional schemas into the core set or+granting a new permission, and failed, interrupted, stale, or mode-disallowed+activations never revive a tool.## Alternatives-### Keep clearing the set and require a new search--Rejected because the model still receives the successful activation marker and-may call a tool whose schema is absent from the request.--### Parse assistant or user prose for tool names--Rejected because prose is not authoritative activation evidence and could-activate a capability that never succeeded or is no longer allowed.--## References--- `docs/adr/0048-lazy-per-turn-tool-activation.md`-- `docs/spec/03-runtime/02-agent-runtime.md` §7.1-- `docs/spec/03-runtime/03-tools-and-permissions.md` §2.1-- `docs/spec/06-delivery/04-e2e-test-plan.md` E2E-008a+- Keep clearing the set and require a new search: the model still sees the success+ marker and may call a tool whose schema is absent.+- Parse prose for tool names: prose could activate a capability that never succeeded.diff --git a/docs/adr/0226-reserve-chat-width-for-composer-controls.md b/docs/adr/0226-reserve-chat-width-for-composer-controls.mdindex 601be35ff..8968a868d 100644--- a/docs/adr/0226-reserve-chat-width-for-composer-controls.md+++ b/docs/adr/0226-reserve-chat-width-for-composer-controls.md@@ -1,49 +1,27 @@# ADR 0226: Reserve Chat Width for Composer Controls-- Status: Accepted+- Status: Accepted (amends ADR 0151)- Date: 2026-09-11-- Amends: [ADR 0151](0151-internal-work-panel-dock.md)-- Related: [07-ui-design-system §10](../spec/04-ux/07-ui-design-system.md) ·- [08-component-spec §1 and §11](../spec/04-ux/08-component-spec.md) · E2E-168+- Related: E2E-168, ADR 0151## Context-The sidebar and in-flow work panel can both take flex space from MainChat. When-the remaining chat column becomes too narrow, the floating composer toolbar-squeezes its localized chips or wraps its control groups.+The sidebar and the in-flow work panel both take flex space from MainChat, so a+narrow chat column squeezes the floating composer toolbar's localized chips or wraps+its control groups, and a side dock overlapping an input surface is not an+acceptable fallback.## Decision-MainPane and its chat surface reserve a 515px minimum width. This reservation-belongs to the chat flex item, so sidebar and work-panel resize gestures cannot-consume or paint over the space needed by the composer.--The composer toolbar stays single-row with `flex-wrap: nowrap`, and its left and-right control groups are non-shrinking flex items. Mode and permission labels-remain single-line and use chip-local ellipsis when their localized text is-longer than the available label slot.+MainPane and its chat surface reserve a fixed minimum width on the chat flex item, so+sidebar and work-panel resize gestures cannot consume or paint over the space the+composer needs. The toolbar stays single-row with `flex-wrap: nowrap` and+non-shrinking control groups, mode and permission labels stay single-line with+chip-local ellipsis, and the work panel remains an in-flow renderer-owned column+requesting no positive native window reservation.## Consequences-- Sidebar and work-panel resizing preserve a readable composer control row.-- At a constrained client width, the shell may need more horizontal space than- the native minimum to show every fixed-width column simultaneously; the- composer reservation takes priority over flex compression and overlap.-- The 515px minimum is the shared renderer/test contract for MainPane layout.--## Alternatives rejected--### Wrap the toolbar below a narrow threshold--Rejected because the toolbar becomes taller during a side-dock gesture and the-bottom controls stop presenting as one stable action row.--### Allow side docks to overlap the composer--Rejected because it hides input actions and creates pointer/focus ambiguity.--## References--- `apps/desktop/src/styles/chat-shell.css`-- `apps/desktop/src/styles/composer.css`-- `apps/desktop/src/lib/work-panel-resize.ts`+- Sidebar and work-panel resizing preserve a readable control row.+- At a constrained client width the shell may need more horizontal space than the+ native minimum, because the reservation outranks flex compression and overlap.diff --git a/docs/adr/0227-project-group-manual-ordering.md b/docs/adr/0227-project-group-manual-ordering.mdindex 68b56b38a..d49e50740 100644--- a/docs/adr/0227-project-group-manual-ordering.md+++ b/docs/adr/0227-project-group-manual-ordering.md@@ -3,37 +3,27 @@- Status: Accepted (amended by 0228)- Date: 2026-09-11- Amends: [ADR 0016](0016-sidebar-organization-and-multi-project-tabs.md)-- Related: [D399](../spec/08-meta/decisions-log.md) · [D402](../spec/08-meta/decisions-log.md) · [Component spec](../spec/04-ux/08-component-spec.md) · E2E-253+- Related: [D399](../spec/08-meta/decisions-log.md) · [D402](../spec/08-meta/decisions-log.md) · E2E-253## Context-Retained project groups need a stable working order that is independent of-recent activity and alphabetical names. The existing sidebar organization is-renderer-owned presentation state, while project paths, selected workspace-identity, session ownership, and tool roots remain host-owned.+Retained project groups need a stable working order independent of recent activity+and alphabetical names, while project paths, workspace identity, session ownership,+and tool roots stay host-owned.## Decision-Project groups expose a hover/focus-visible reorder grip. Native drag/drop and-ArrowUp/ArrowDown on the grip write contiguous non-negative integer `order`-values keyed by normalized project path and select the renderer-local `manual`-project sort.--The interaction is presentation-only. It does not move directories, change the-selected host workspace, change session ordering, or change durable session-project membership.+Groups expose a hover/focus-visible reorder grip; native drag and ArrowUp/ArrowDown+on the grip write contiguous non-negative integer `order` values keyed by+normalized project path and select the renderer-local `manual` sort. Reordering+stays inside one archived/pinned priority bucket, which ranks ahead of manual order;+Escape cancels without reading stale transfer data and invalid legacy ranks fall+back to stable path order. Nothing moves directories, the selected host workspace,+session ordering, or durable project membership.## Consequences-- Users can keep repositories in a stable personal order across renderer- restarts.-- Renderer localStorage remains the only persistence surface; no IPC, host RPC,- schema, or migration is required.-- Priority boundaries make cross-bucket drops and keyboard moves no-ops instead- of producing an order that the comparator immediately overrides.--## References--- `apps/desktop/src/components/Sidebar.tsx`-- `apps/desktop/src/lib/sidebar-preferences.ts`-- `apps/desktop/test/sidebar-preferences.test.mjs`+- Users keep repositories in a stable personal order across renderer restarts.+- Renderer localStorage stays the only persistence surface; no IPC, host RPC,+ schema, or migration is involved.+- Cross-bucket drops are no-ops instead of an order the comparator overrides.diff --git a/docs/adr/0228-long-press-project-title-reorder.md b/docs/adr/0228-long-press-project-title-reorder.mdindex a14296f7f..e227e5a3e 100644--- a/docs/adr/0228-long-press-project-title-reorder.md+++ b/docs/adr/0228-long-press-project-title-reorder.md@@ -1,40 +1,27 @@# ADR 0228: Long-press the project title to reorder-- Status: Accepted (amended by 0229)+- Status: Accepted (amended by ADR 0229)- Date: 2026-09-11-- Amends: [ADR 0227](0227-project-group-manual-ordering.md)-- Related: [D402](../spec/08-meta/decisions-log.md) · [Component spec](../spec/04-ux/08-component-spec.md) · E2E-253+- Related: D402, ADR 0227, E2E-253## Context-ADR 0227 added renderer-local manual project order behind a hover/focus grip.-The grip consumed a leading column, stayed hidden until hover, and made reorder-a second control beside the title that already selects and collapses the group.+ADR 0227 put renderer-local manual project order behind a hover/focus grip that took+a leading column, stayed hidden until hover, and made reordering a second control+beside the title.## Decision-Retained project groups no longer render a reorder grip. The project title is-the reorder control:--- A still press of 400ms on the title arms a pointer reorder.-- After the title is armed, moving the pointer highlights another group in the- same pinned/archived bucket; release inserts before or after that group from- the pointer's vertical midpoint.-- ArrowUp/ArrowDown on the focused title remains the keyboard path.-- Persistence is unchanged: contiguous normalized-path `order` values and- `projectSort: "manual"` in renderer-local sidebar preferences.--The title's path tooltip dismisses on press so it does not cover the drag.-Session-to-project HTML5 drops and native folder drops are unchanged.+Retained groups render no reorder grip, and the title is the reorder control: a still+press arms a pointer reorder, movement before the delay cancels it so a click still+activates the project, an armed move highlights another group in the same pinned or+archived bucket, release inserts before or after by vertical midpoint, and Escape+cancels without writing order. ArrowUp/ArrowDown on the focused title stays the+keyboard path, and persistence keeps contiguous normalized-path `order` values with+`projectSort: "manual"` in renderer-local sidebar preferences.## Consequences-- Reorder no longer needs a dedicated visible handle.-- Long-press is the pointer disambiguation for a title that also clicks.+- Reorder needs no dedicated handle, and long-press disambiguates a title that also+ clicks.- Keyboard users keep ArrowUp/ArrowDown on the same title button.--## References--- `apps/desktop/src/components/Sidebar.tsx`-- `apps/desktop/src/lib/sidebar-project-reorder.ts`-- `apps/desktop/test/sidebar-project-reorder.test.mjs`diff --git a/docs/adr/0229-press-and-move-project-title-reorder.md b/docs/adr/0229-press-and-move-project-title-reorder.mdindex 81bde1282..cdec08281 100644--- a/docs/adr/0229-press-and-move-project-title-reorder.md+++ b/docs/adr/0229-press-and-move-project-title-reorder.md@@ -3,31 +3,26 @@- Status: Accepted- Date: 2026-09-11- Amends: [ADR 0228](0228-long-press-project-title-reorder.md)-- Related: [D403](../spec/08-meta/decisions-log.md) · [Component spec](../spec/04-ux/08-component-spec.md) · E2E-253+- Related: [D403](../spec/08-meta/decisions-log.md) · E2E-253## Context-ADR 0228 removed the reorder grip and armed a drag after a 400ms still press.-That delay is a mobile long-press pattern.+ADR 0228 armed the reorder drag after a still press, a mobile long-press+pattern that makes desktop sidebar reordering feel slower than product lists+that drag on immediate movement.## Decision-The project title remains the reorder control, with no grip. Pointer-disambiguation is movement, not time:--- Mouse and pen: an 8px move while pressed arms the drag.-- Touch presses do not start a reorder, so a one-finger pan can scroll the list.-- While dragging, an accent insertion line on the target group shows- before/after placement from the pointer's vertical midpoint.+The project title stays the reorder control with no grip, and pointer+disambiguation is movement instead of time. A pressed mouse or pen that moves+arms the drag; a click without qualifying movement still selects the project+and toggles collapse; touch presses never reorder, so one-finger panning+scrolls. An insertion line shows before/after placement from the pointer's+vertical midpoint, Escape cancels, and persistence and pin/archive buckets are+unchanged.## Consequences-- Desktop reorder matches common sidebar lists: press, move, drop.-- Touch scrolling is not stolen by an accidental 8px pan on a title.-- The 400ms still-press contract in ADR 0228 is replaced.--## References--- `apps/desktop/src/components/Sidebar.tsx`-- `apps/desktop/src/lib/sidebar-project-reorder.ts`-- `apps/desktop/test/sidebar-project-reorder.test.mjs`+- Reorder reads as press, move, drop, like common sidebar lists.+- Touch scrolling survives an accidental pan on a title.+- The still-press contract in ADR 0228 is replaced.diff --git a/docs/adr/0230-skill-ships-with-the-agent-core-tool-set.md b/docs/adr/0230-skill-ships-with-the-agent-core-tool-set.mdindex 544c6e61c..429ea29eb 100644--- a/docs/adr/0230-skill-ships-with-the-agent-core-tool-set.md+++ b/docs/adr/0230-skill-ships-with-the-agent-core-tool-set.md@@ -2,53 +2,43 @@- Status: Accepted- Date: 2026-09-11-- Deciders: PI-Desktop runtime maintainers- Amends: D174, ADR 0048, ADR 0219## Context-As originally accepted, ADR 0048 kept the first Agent request on a small core-set and deferred optional capabilities behind the local `ToolSearch` tool, so a-large plugin surface could not recreate the original prompt bloat. `Skill` was-registered into that deferred set: it only appeared in the provider schema after-the model searched for it.--- D174 makes the skill catalog the model-invoked way to load a document, and- advertises it in the `# Skills` system-prompt section with an instruction to- load a matching skill first.-- ADR 0219 answers a user-typed `/skill:<skill-id>` by persisting an instruction- to call the local `Skill` tool with the validated id on that turn.+ADR 0048 kept the first Agent request on a small core set and deferred optional+capabilities behind `ToolSearch`, and `Skill` sat in that deferred set. Two later+decisions assume a `Skill` tool the model can call immediately: D174 advertises the+skill catalog in the `# Skills` system-prompt section, and ADR 0219 answers a+typed `/skill:<skill-id>` by persisting an instruction to call the local `Skill`+tool. Neither works when the tool is absent from the first request, so the model+re-searches, calls a tool it cannot see, or answers from the catalog line alone.## Decision1. `Skill` joins `AGENT_CORE_TOOL_NAMES`, so an Agent-mode request carries its- schema from the first turn.-2. The tool stays out of the deferred catalog and therefore never appears under- `# On-demand tools`.-3. No protocol, storage, permission, or skill-body change follows from this.+ schema from the first turn. Its registration gate is unchanged: the tool exists+ only when the skill catalog is non-empty, and Plan and Goal still omit it.+2. The tool leaves the deferred catalog and never appears under+ `# On-demand tools`. Other on-demand capabilities (`BrowserPreview`, plugin+ tools, plugin-development helpers, MCP tools) keep their lazy behavior, and+ `ToolSearch` stays registered whenever any of them exist.+3. No protocol, storage, permission, or skill-body change follows. Bodies still+ load on demand through the same tool, host path, and permission checks.## Consequences-- A matching task loads its skill on the first turn instead of discovering the- tool first, and a `/skill:<skill-id>` invocation works as ADR 0219 describes.-- Every Agent-mode request carries one more tool schema.-- Removing the `Skill` row from the deferred catalog also removes the only path- that could route a skill through `ToolSearch`, so the catalog description for- it is deleted rather than left unreachable.--## Alternatives considered--- **Keep `Skill` deferred and rely on prompting:** rejected because a tool- absent from the schema cannot be called no matter what the system prompt says,- which is the behavior that produced this issue.-- **Inject skill bodies into the system prompt:** rejected for the cost and- reload semantics D174 and ADR 0039 already settled.-- **Make every on-demand tool core:** rejected because it recreates the prompt- bloat ADR 0048 exists to prevent.+- A matching task loads its skill on the first turn and `/skill:<skill-id>` works+ as ADR 0219 describes.+- Every Agent-mode request carries one more tool schema; the catalog is already+ bounded per session, and a capability the model must go looking for is one it+ will not use.+- The `ToolSearch` catalog row for `Skill` is deleted rather than left+ unreachable.## Amendment — 2026-09-27: Agent search tools start active-The amendment to ADR 0048 also places `Glob` and `Grep` in the first Agent-request to remove the discovery round trip for routine workspace exploration.-This does not change ADR 0230: `Skill` remains core when its catalog exists, and-plugin, preview, and development tools remain deferred.+The amendment to ADR 0048 also places `Glob` and `Grep` in the first Agent request+to remove the discovery round trip for routine exploration. This does not change+this record: `Skill` remains core while its catalog exists, and plugin, preview,+and development tools remain deferred.diff --git a/docs/adr/0231-ideographic-comma-opens-the-slash-menu.md b/docs/adr/0231-ideographic-comma-opens-the-slash-menu.mdindex e4cf4c6ea..27c27c912 100644--- a/docs/adr/0231-ideographic-comma-opens-the-slash-menu.md+++ b/docs/adr/0231-ideographic-comma-opens-the-slash-menu.md@@ -2,38 +2,35 @@- Status: Accepted- Date: 2026-09-11-- Deciders: PI-Desktop desktop UI maintainers- Amends: D123, D139, ADR 0024## Context-The composer `/` menu mirrors the pi CLI grammar: the trigger is the ASCII `/`-as the very first character of the draft. A Chinese IME produces `、` (U+3001,-ideographic comma) for that keystroke, so a user writing in Chinese has to-switch to ASCII input before they can reach the command menu, then switch back.+The composer `/` menu mirrors the pi CLI grammar, where the trigger is an ASCII+`/` as the very first character of the draft. A Chinese IME produces `、`+(U+3001, ideographic comma) for that keystroke, so the user must switch input+methods to reach the command menu. In-flight IME composition is already ignored+(D139), leaving only the alias missing.## Decision-1. A `、` committed as the first character of an empty composer draft is- rewritten to `/` before trigger detection runs.-2. Only that position is rewritten.-3. The rewrite is a pure string function in the shared composer-trigger module,- unit tested next to the trigger grammar it feeds.+A `、` committed as the first character of an empty draft is rewritten to `/`+before trigger detection, after which the draft is an ordinary slash invocation+with the same menu, filtering, and send path. Only that position is rewritten:+the draft must have been empty before the keystroke, so a later `、` inside+existing text stays ordinary punctuation. The rewrite is a pure string function+in the shared composer-trigger module, and the `@` file menu is unaffected.## Consequences-- A Chinese IME user reaches `/new`, `/compact`, the mode aliases, template- commands, plugin commands, and Skills without leaving the input method.-- A message that genuinely starts with `、` in an empty composer is rewritten.+- Chinese IME users reach `/new`, `/compact`, mode aliases, template and plugin+ commands, and Skills without leaving the input method.+- A message genuinely starting with `、` in an empty composer is rewritten,+ which keeps the substitution visible instead of altering text mid-sentence.- No IPC, storage, or autocomplete-source change is required.-## Alternatives considered+## Alternatives-- **Accept `、` as an additional trigger character in `detectTrigger`:** rejected- because the draft would keep a character the send path and transcript chip- would then have to understand, and the menu would open on a mark the pi CLI- grammar does not define.-- **Rewrite on every `、`, not just the first character:** rejected because it- would corrupt ordinary prose, where `、` is the standard list separator.-- **A toolbar button for commands:** rejected as a duplicate entry point to a- menu that already exists (see D123).+- Accept `、` as another trigger in `detectTrigger`: rejected, the draft would+ keep a character the send path must understand.+- Rewrite every `、`: rejected, it corrupts ordinary prose.diff --git a/docs/adr/0232-macos-dmg-text-only-opening-guidance.md b/docs/adr/0232-macos-dmg-text-only-opening-guidance.mdindex 6bb1a2fa4..75f0abd8c 100644--- a/docs/adr/0232-macos-dmg-text-only-opening-guidance.md+++ b/docs/adr/0232-macos-dmg-text-only-opening-guidance.md@@ -2,43 +2,29 @@- Status: Superseded for macOS distribution by D634 / [ADR 0309](0309-remove-macos-first-launch-artifacts.md)- Date: 2026-09-12-- Deciders: PI-Desktop release maintainers- Amends: D371 / [ADR 0204](0204-unsigned-macos-first-launch-helper.md)-- Related: [E2E-196b](../spec/06-delivery/04-e2e-test-plan.md)+- Related: [ADR 0296](0296-macos-signed-dmg-two-icon-install.md)## Context-D371 made the unsigned macOS helper visible in every distribution, including the-DMG. The DMG's primary action is the normal app-to-Applications install, while-the fallback is needed only when a trusted unsigned app does not open.+D371 made the unsigned macOS helper visible in every distribution, but the DMG's+primary action is the normal install to Applications, and the fallback matters+only when a trusted unsigned app does not open. The DMG needed that fallback+discoverable without an executable command item beside the normal action.## Decision-1. The macOS DMG contains the app, the Applications link, and the opening-help- note only.-2. The macOS ZIP package retains both `PI-Desktop-macOS-opening-help.txt` and- the executable `PI-Desktop-macOS-open.command` at its root.-3. The shared opening note leads with the narrow Terminal fallback `xattr -r -d- com.apple.quarantine /Applications/PI-Desktop.app`, limits it to trusted- unsigned builds, and states that signed and notarized builds do not need the- fallback.+The macOS DMG contained the app, the Applications link, and an opening-help note+shown in Finder as `If app won't open, read this.txt`, but not the executable+`PI-Desktop-macOS-open.command`. The ZIP kept both+`PI-Desktop-macOS-opening-help.txt` and `PI-Desktop-macOS-open.command` at its+root under D371's fixed-path, bundle-id, quarantine-only, and no-`sudo`+boundaries, and the shared note led with+`xattr -r -d com.apple.quarantine /Applications/PI-Desktop.app`, limited to+trusted unsigned builds.-## Consequences+## Superseded-- The DMG presents a focused two-icon installation row and one clearly named- fallback note.-- Users of the ZIP retain the one-click helper after moving the app to a- supported Applications directory.-- DMG users with an unsigned launch failure must use the documented Terminal- fallback; this does not widen the quarantine-clearing scope.--## Amendment (D457 / ADR 0296)--Official signed DMGs no longer include the opening-help note. The two-icon-install row is the whole DMG.--## Amendment (D634 / ADR 0309)--Neither macOS DMG nor ZIP now ships the opening note or executable helper. The-ZIP-helper provisions above are historical; see ADR 0309 for the current-distribution rule.+D457 / ADR 0296 dropped the note from official signed DMGs, leaving the two-icon+install row alone, and D634 / ADR 0309 stopped shipping the note or the helper in+either the DMG or the ZIP. The ZIP helper provisions above are historical.diff --git a/docs/adr/0233-renderer-owned-multi-folder-project-creation.md b/docs/adr/0233-renderer-owned-multi-folder-project-creation.mdindex 7cb0ee12d..674e5aa23 100644--- a/docs/adr/0233-renderer-owned-multi-folder-project-creation.md+++ b/docs/adr/0233-renderer-owned-multi-folder-project-creation.md@@ -1,47 +1,40 @@# ADR 0233: Renderer-Owned Multi-Folder Project Creation-- Status: Accepted; behavior superseded in part by ADR 0249+- Status: Accepted; behavior superseded in part by ADR 0249, and amends ADR 0011+ and ADR 0016- Date: 2026-09-12-- Deciders: PI-Desktop desktop UI maintainers-- Amends: ADR 0011, ADR 0016+- Related: ADR 0011, ADR 0016, ADR 0249## Context-The existing project entry point opens a native directory picker and activates-the single directory returned by it. The redesigned Create project flow needs to-collect a project name and support selecting multiple local folders in one-operation, while preserving the host-core boundary that exposes one current-visible workspace.+The existing project entry point opens a native directory picker and activates the+single directory it returns, while the redesigned Create project flow must collect a+project name and several local folders in one operation without expanding the+host-core boundary that exposes one current visible workspace.## Decision-1. The renderer owns the Create project dialog, including the project name,- selected-folder list, remove actions, primary marker, validation, focus- handling, and creation state.-2. The main process exposes `project/pickFolders` as a narrow native capability.-3. The first selected folder is the primary root of one logical project group.-4. The sidebar and Settings project entry points use the same dialog and- creation action.+1. The renderer owns the Create project dialog: project name, selected-folder list,+ remove actions, primary marker, validation, focus handling, and creation state.+2. The main process exposes `project/pickFolders` as a narrow native capability that+ may open a multi-selection directory picker and returns absolute paths, without+ changing the active host workspace.+3. The first selected folder is the primary root of one logical project group:+ creation activates it and applies the display name to the group, every other+ folder is retained as a group root rather than an independent project tab, and the+ host still exposes only the primary root as the active workspace.+4. The sidebar and Settings entry points use the same dialog and action.## Consequences-- Users can name a project and add multiple folders without repeating the- project-entry flow.-- Additional folders remain available as durable roots of the same named project- group.-- The host RPC and security boundary remain unchanged apart from the additive- directory-picker capability; switching tabs still changes the one active host- workspace through the existing project activation path.-- The first folder's position is meaningful.--## Alternatives considered--- **Add multi-root execution to the host workspace:** rejected because it- changes the frozen one-visible-workspace model and requires a separate- containment and permission design.-- **Keep the native picker as the entire UI:** rejected because it cannot- collect a project name, expose selected-folder removal, or provide a- consistent ChatGPT-like creation surface.-- **Open each folder in a separate user action:** rejected because it makes a- multi-folder setup slow and hides the relationship between the selected- folders during creation.+- Users can name a project and add several folders without repeating the entry flow,+ and the extra folders stay durable roots of the same group.+- Host RPC and the security boundary are unchanged apart from the additive directory+ picker, and the first folder's position is meaningful: choosing a different+ primary folder is out of scope.++## Alternatives++- Add multi-root execution to the host workspace: changes the frozen+ one-visible-workspace model and needs a separate containment design.+- Keep the native picker as the entire UI: cannot collect a name or expose removal.diff --git a/docs/adr/0234-project-owned-memory-context.md b/docs/adr/0234-project-owned-memory-context.mdindex 1bd28bfc7..caba2b490 100644--- a/docs/adr/0234-project-owned-memory-context.md+++ b/docs/adr/0234-project-owned-memory-context.md@@ -2,34 +2,32 @@- Status: Accepted- Date: 2026-09-12-- Deciders: PI-Desktop maintainers## Context-Projects need a durable memory surface similar to ChatGPT Projects. Renderer-preferences are not a safe owner for model context: they are presentation state,-can be reset independently, and do not provide a host-enforced boundary when a-session switches projects.+Projects need a durable memory surface similar to ChatGPT Projects, and renderer+preferences cannot own model context: they are presentation state and give no+host-enforced boundary when a session switches projects.## Decision-Store one user-authored memory collection per canonical project path in the-existing host `kv` table under the `projectMemory` namespace. The visual editor-stores normalized entries with an id, optional title, and content using the-`entries-v1` format.--The memory editor is exposed from the Project archive row menu. Creating a-project keeps the creation surface compact and shows that project memory is-available later; it does not add a memory mode selector whose semantics the-application does not implement.+Store one user-authored memory collection per canonical project path in the host `kv`+table under the `projectMemory` namespace, with normalized `entries-v1` entries and a+host-derived plain-text `content` projection. Electron main loads the value for the+session-bound project path, and the runtime renders it after project instructions as+explicitly user-provided context and compares it when deciding whether an idle+runtime can be reused.## Consequences-- Memory survives renderer restarts and is isolated by canonical project path.-- The visual editor can add, edit, and remove memory entries while the runtime- consumes the host-derived plain-text projection.-- Changing memory retires the next reusable runtime so a follow-up prompt sees- the new value.-- Project memory cannot override runtime safety, tool, or collaboration rules.-- No schema migration is needed because `kv` is the existing extensibility- boundary for new configuration domains.+- Memory survives renderer restarts and is isolated by canonical project path, with+ legacy `content`-only records readable as one untitled entry.+- Changing memory retires the next reusable runtime so a follow-up prompt sees the+ new value.+- No migration is needed, and ADR 0249's project-group identity leaves path-scoped+ records as the compatibility behavior.++## Alternatives++- Keep memory in renderer preferences — rejected: presentation state cannot be the+ host-enforced boundary.diff --git a/docs/adr/0235-domain-facades-and-architecture-budgets.md b/docs/adr/0235-domain-facades-and-architecture-budgets.mdindex f1873700a..70b023ca4 100644--- a/docs/adr/0235-domain-facades-and-architecture-budgets.md+++ b/docs/adr/0235-domain-facades-and-architecture-budgets.md@@ -2,45 +2,43 @@- Status: Accepted- Date: 2026-09-12-- Deciders: PI-Desktop maintainers## Context-The desktop application had several large modules that combined wiring with-multiple domain responsibilities. Splitting those modules reduces change-coupling, but replacing established entry points would break imports, source-contracts, plugin integrations, or protocol assumptions.+Several large desktop modules combined wiring with multiple domain+responsibilities. Splitting them reduces change coupling, but replacing+established entry points would break imports, source contracts, plugin+integrations, or protocol assumptions, and nothing stopped the same hotspots from+growing again.## Decision-1. Keep stable facade modules at established public paths.-2. Put implementation responsibility in domain modules: Electron IPC and runtime- modules, renderer `features/*` modules, host-core domain submodules, and- `packages/shared/src/types/*` files.-3. Keep source-contract tests at the owning module boundary and retain public- re-export coverage for compatibility paths.-4. Enforce source-size budgets with `node scripts/check-architecture.mjs`.+1. Keep stable facades at the established paths: Electron main `index.ts`,+ renderer page entries, shared `types.ts`, and the Rust `plugins`, `db`,+ `providers`, and `plans` modules.+2. Put implementation responsibility in domain modules — Electron IPC and runtime+ modules, renderer `features/*`, host-core domain submodules, and+ `packages/shared/src/types/*` — where a facade may wire or re-export but never+ become a second implementation.+3. Keep source-contract tests at the owning module boundary and shared E2E boot,+ session, plan, plugin, host, fixture, wait, and assertion helpers as the common+ test surface.+4. Enforce source-size budgets with `node scripts/check-architecture.mjs`, which+ protects the facade limits, rejects newly oversized TypeScript files, and+ requires a documented reason for oversized Rust files.5. Run the focused Biome lint, architecture checker, Rust formatting, and- workspace Clippy checks in CI alongside the existing build, typecheck, and- test gates.+ workspace Clippy checks in CI alongside build, typecheck, and test.## Consequences-- Existing import paths, IPC channels, plugin SDK contracts, host RPC data, and- persistence formats remain stable while implementation ownership is easier to- locate.-- New domain work has a clear home and is measured against source-size limits.-- A small set of legacy modules remains explicitly documented as technical debt- instead of being expanded silently.-- The architecture checker adds a repository-level maintenance gate and its- metrics make future refactor progress reviewable.+- Import paths, IPC channels, plugin SDK contracts, host RPC data, and persisted+ formats stay stable while implementation ownership becomes easier to locate.+- New domain work has a clear home and is measured against size limits, with the+ remaining legacy modules documented as technical debt.## Alternatives considered-- **Replace the public modules with new paths:** rejected because it would make- compatibility the responsibility of every caller and plugin.-- **Apply a broad formatter or stylistic lint migration:** rejected because it- would mix historical cleanup with the architecture change and obscure- behavioral review.-- **Use an undocumented size exception:** rejected because a ratchet without an- explicit reason would allow new hotspots to accumulate.+- Replace the public modules with new paths: rejected; it makes compatibility+ every caller's and plugin's problem.+- Use an undocumented size exception: rejected; a ratchet without a reason lets+ new hotspots accumulate.diff --git a/docs/adr/0236-restore-archived-project-on-session-import.md b/docs/adr/0236-restore-archived-project-on-session-import.mdindex dc871204b..4b202afb1 100644--- a/docs/adr/0236-restore-archived-project-on-session-import.md+++ b/docs/adr/0236-restore-archived-project-on-session-import.md@@ -2,40 +2,32 @@- Status: Accepted- Date: 2026-09-12-- Deciders: PI-Desktop maintainers## Context-Project archive state belongs to renderer-local sidebar presentation metadata,-while session import is completed by the host. A successful import can create or-reuse a durable project and bind the new session to it without changing the-renderer metadata.+Project archive state lives in renderer-local sidebar metadata, while session+import completes in the host. An import can create or reuse a durable project and+bind a new session to it without touching that metadata, so the session exists but+its project stays hidden and the import looks failed (issue #250).## Decision-- Core and plugin imports use an explicit import-refresh option when the- renderer refreshes its session list.-- The renderer compares session ids before and after that refresh, collects- normalized project paths for newly added project-bound sessions, and restores- only matching project metadata that is currently archived.-- Pathless sessions, skipped imports, historical plugin project paths without an- active project binding, and ordinary session refreshes do not change archive- state.-- The host project model, IPC channel names, plugin SDK methods, storage schema,- and persisted session/project data formats remain unchanged.+Core and plugin imports refresh the session list with an explicit import flag. The+renderer compares session ids across that refresh, collects normalized paths of+newly added project-bound sessions, and un-archives only matching project+metadata. Pathless sessions, skipped imports, historical plugin paths without an+active binding, and ordinary refreshes never change archive state. The host+project model, IPC channels, plugin SDK, storage schema, and persisted formats are+unchanged.## Consequences-An imported session is immediately discoverable in the default project view,-including when a plugin uses an explicit host project id.+- Imported sessions are immediately visible in the default project view.+- Unrelated archived projects stay hidden, including after restart.-## Alternatives considered+## Alternatives-- **Add an archived column to host projects:** rejected because archive is a- renderer presentation preference and the storage change would widen the- persistence and migration surface.-- **Show archived projects whenever sessions refresh:** rejected because a- normal refresh would silently undo deliberate archive choices.-- **Return an import error for archived projects:** rejected because importing- into an existing project is valid and the user has already expressed intent to- use that project.+- Persist an archived column on host projects: rejected because archive is a+ renderer preference and the schema change would widen the migration surface.+- Un-archive on every session refresh: rejected because it silently undoes+ deliberate archive choices.diff --git a/docs/adr/0237-session-orchestrator-as-a-plugin.md b/docs/adr/0237-session-orchestrator-as-a-plugin.mdindex e06fc92a0..d01b78db3 100644--- a/docs/adr/0237-session-orchestrator-as-a-plugin.md+++ b/docs/adr/0237-session-orchestrator-as-a-plugin.md@@ -8,39 +8,43 @@## Context-Some tasks benefit from several independent Agents working at the same time, but-the existing `Task` family is intentionally a bounded in-process subagent-system. A new orchestration feature must not create a second session store,-bypass plugin permissions, or make the renderer an Agent runtime.+Some tasks benefit from several independent Agents working at once, but the+`Task` family is intentionally a bounded in-process subagent system. A new+orchestration feature must not create a second session store, bypass plugin+permissions, or make the renderer an Agent runtime, and the public plugin SDK+exposes Agent tools and the reviewed `desktop.control` gateway but no live+session creation or Agent lifecycle events.## Decision-Ship `pi.session-orchestrator` as an ordinary marketplace plugin. It registers-the `SessionTask` Agent Tool with `spawn`, `send`, `supervise`, `status`,-`wait`, `result`, `accept`, `cancel`, and `list` actions.--- `spawn` uses `session/create` followed by `agent/prompt`, creating a new- durable session with no copied transcript.-- `send` reuses the recorded worker session.-- The plugin persists only the parent/worker relationship, task, status,- timestamp, and bounded report in its private data directory.-- A parent may control only Worker Session IDs recorded under its own session- id.-- Until a lifecycle subscription exists, `wait` performs one-second lightweight- status polling with a 25-second default and 45-second maximum timeout.-- A simple `Agents` work-panel view lists workers and offers status refresh,- Open Session, and Stop.--Two additive host primitives support these boundaries:--1. `session/create` accepts optional `inheritPermissionFromSessionId`.-2. The reviewed desktop catalog gains `session/open`, which validates and- selects an existing durable session.+Ship `pi.session-orchestrator` as an ordinary marketplace plugin registering the+`SessionTask` Agent Tool with `spawn`, `send`, `supervise`, `status`, `wait`,+`result`, `accept`, `cancel`, and `list`. `spawn` calls `session/create` then+`agent/prompt` to create a new durable session with no copied transcript,+inheriting the parent project, provider/model, thinking level, and permission+mode; `send` reuses the recorded worker session and `cancel` uses `agent/abort`+without deleting it. The plugin persists only the parent/worker relationship,+task, status, timestamps, and a bounded report in its private data directory,+while the canonical worker identity is the durable `sessionId` returned by+`session/create`. A parent may control only worker sessions recorded under its+own session id, workers cannot create or control further workers, and the+concurrency ceiling is the plugin's own `maxConcurrentSessions` setting. Until+lifecycle subscription exists, `wait` polls status with bounded timeouts and+returns `timedOut`, and an `Agents` work-panel view lists workers with refresh,+Open Session, and Stop. Two additive host primitives support this:+`session/create` accepts `inheritPermissionFromSessionId`, bound to the current+Agent tool session for plugin callers and copying the parent's persisted+permission mode, and the reviewed desktop catalog gains `session/open`, the only+action that navigates the renderer. No schema migration, MCP self-call, message+bus, DAG, or change to the `Task` tools is added.## Consequences-The parent can fan out real durable workers while every worker stays visible and-inspectable in the normal session UI.--The first version does not receive lifecycle events and therefore has bounded-polling latency.+- The parent fans out real durable workers that stay visible and inspectable in+ the normal session UI, and plugin data restores the relationship list after a+ restart.+- The first version has bounded polling latency, no worker-to-worker messaging,+ and no unscoped arbitrary-session control.+- A delivery interrupted by restart cannot settle, so `recover` emits one+ receipt with `status: "interrupted"` and the fence's error text instead of+ leaving the sender polling forever.diff --git a/docs/adr/0238-three-column-width-priority.md b/docs/adr/0238-three-column-width-priority.mdindex 1fa4f9f7e..3ea6cb308 100644--- a/docs/adr/0238-three-column-width-priority.md+++ b/docs/adr/0238-three-column-width-priority.md@@ -1,73 +1,67 @@# ADR 0238: Prioritize MainChat in the three-column shell-- Status: Accepted (sidebar width clamp amended by [ADR 0290](0290-resizable-sidebar-collapse-threshold.md))+- Status: Accepted (sidebar width clamp amended by+ [ADR 0290](0290-resizable-sidebar-collapse-threshold.md); amends ADR 0226,+ ADR 0151, and ADR 0033, whose fixed `244..720px` panel clamp is replaced by the+ live budget below)- Date: 2026-09-13-- Amends: [ADR 0226](0226-reserve-chat-width-for-composer-controls.md) ·- [ADR 0151](0151-internal-work-panel-dock.md) ·- [ADR 0033](0033-internal-dock-work-panel.md) — the fixed `244..720px` clamp- from D167/ADR 0033/ADR 0151 is replaced by the live budget below-- Related: [ADR 0033](0033-internal-dock-work-panel.md) ·- [ADR 0151](0151-internal-work-panel-dock.md) ·- [01-ui-ia](../spec/04-ux/01-ui-ia.md) ·- [07-ui-design-system §10](../spec/04-ux/07-ui-design-system.md) ·- [08-component-spec §1 and §5](../spec/04-ux/08-component-spec.md) ·- [09-interaction-patterns §8](../spec/04-ux/09-interaction-patterns.md) ·- E2E-LAYOUT-three-column-width-priority+- Related: D167, D433, ADR 0033, ADR 0151, ADR 0226, ADR 0290## Context-The renderer shell has three in-flow columns inside a fixed client area: the-expanded sidebar, MainChat and the work panel. ADR 0033 and ADR 0151 keep native-window bounds out of the panel's reach, but the shell still has no explicit-width priority.+The renderer shell has three in-flow columns inside a fixed client area — expanded+sidebar, MainChat, and work panel — but no explicit width priority: the ADR 0226+chat reservation and the fixed panel range left pointer resizing, keyboard resizing,+sidebar toggles, and window resizing under different rules, so a narrow window could+pin MainChat to its floor while the expanded sidebar kept full width.## Decision-1. MainChat has a hard `450px` minimum, derived from the composer toolbar's- unfolded row (plus button, mode and permission chips, model/thinking chip,- enhance and send buttons) plus its margins.-2. When the expanded sidebar would make MainChat reach the 450px floor, the- renderer immediately collapses the sidebar through the existing mounted- `sidebar-out` animation.-3. A manual sidebar reopen spends work-panel width first.-4. Automatic sidebar collapse is remembered only until the work panel closes.-5. The window itself stays fixed.-6. The panel header exposes a preview (maximize) toggle.+1. MainChat has a hard minimum derived from the composer toolbar's unfolded row plus+ margins; the work-panel maximum is the remaining client width after that floor and+ the expanded sidebar, with no fixed cap, and one shared renderer budget function+ serves pointer preview, keyboard resize, panel presentation, sidebar changes, and+ shell resize observation.+2. When the expanded sidebar would push MainChat to the floor, the renderer+ immediately collapses the sidebar through the existing mounted `sidebar-out`+ animation; while that animation still occupies flex space the budget keeps+ counting the sidebar, and the preferred panel width stays the persisted user+ target.+3. A manual sidebar reopen spends work-panel width first, preserving current MainChat+ width and lending the panel a compact width below its ordinary presentation+ minimum; the loan holds while the sidebar stays expanded, extra client width+ returns to the panel first, and collapsing the sidebar or resizing the panel ends+ it, with the preferred width still stored as the resize target.+4. Automatic sidebar collapse is remembered only until the work panel closes, which+ restores the sidebar; manual collapse, manual reopen, and a subsequent manual+ collapse clear that record.+5. The window itself stays fixed: the renderer keeps+ `window/setWorkPanelReservation` at zero and Main normalizes every valid request to+ `{ requested: 0, reserved: 0 }` without applying width or x-offset geometry+ (ADR 0033 / ADR 0151).+6. The panel header exposes a preview (maximize) toggle: while on, MainChat is not+ rendered and the panel takes the whole client area beside the sidebar, so the chat+ floor is suspended by design; leaving preview restores the previous panel width and+ the last sidebar state, and the mode is transient, never persisted, and never+ changes native bounds. AppShell then supplies a window-level chrome row with New+ Task, sidebar, and native window controls, whose spacer passes pointer events+ through outside controls, and the panel header is the sole drag owner in the+ preview pane.## Consequences-- MainChat cannot be compressed below 450px by any supported shell width change;- the sidebar is the column that yields.-- A constrained window shows a narrower work panel during the current layout,- while the persisted preferred width remains available when space returns.-- The composer toolbar now handles widths between 450px and its comfortable- layout instead of relying on a 515px reservation, so its control groups- ellipsize or reflow below that width.-- No host protocol, SQLite schema, plugin contract, security boundary or native+- MainChat cannot be compressed below its floor by any supported shell width change;+ the sidebar is the column that yields, and a constrained window shows a narrower+ panel while the persisted preferred width returns with space.+- The composer toolbar handles widths between the floor and its comfortable layout+ instead of relying on a fixed reservation, so its control groups ellipsize or+ reflow.+- No host protocol, SQLite schema, plugin contract, security boundary, or nativewindow geometry changes.-## Alternatives rejected+## Alternatives-### Keep the 515px chat reservation of ADR 0226--Rejected because it leaves side-dock priority implicit and cannot satisfy the-450px hard floor with automatic sidebar-yield behaviour, which is what keeps-MainChat usable in the fixed window.--### Let the sidebar resize continuously to preserve every column--Rejected because the sidebar remains a discrete expanded/collapsed column for-this interaction.--### Mirror the committed panel width into native window bounds--Rejected because expanding the application window is the outward behaviour ADR-0033 and ADR 0151 removed.--## References--- `apps/desktop/src/lib/work-panel-resize.ts`-- `apps/desktop/src/components/workpanel/WorkPanel.tsx`-- `apps/desktop/src/features/app/useAppShellRuntime.tsx`-- `apps/desktop/src/features/app/AppShell.tsx`-- `apps/desktop/src/styles/chat-shell.css`+- Keep the ADR 0226 reservation: it leaves side-dock priority implicit and cannot+ satisfy the floor with automatic sidebar yield.+- Mirror the committed panel width into native bounds: expanding the window is the+ outward behavior ADR 0033 and ADR 0151 removed.diff --git a/docs/adr/0239-session-collaboration-messages.md b/docs/adr/0239-session-collaboration-messages.mdindex 47f3587df..af98c97fa 100644--- a/docs/adr/0239-session-collaboration-messages.md+++ b/docs/adr/0239-session-collaboration-messages.md@@ -8,48 +8,56 @@## ContextSession Orchestrator must address existing durable sessions in both directions,-reuse their context, deliver completion callbacks, and expose reliable state.-Polling assistant text cannot establish a turn's outcome.+deliver completion callbacks, and expose reliable state, but polling assistant+text cannot establish a turn's outcome, and plugin settings must not become an+authority for session identity, authorization, or execution state.## Decision-Rust host-core owns a durable session communication ledger keyed by message ID,-referencing the existing source and target Session IDs. Session IDs remain the-only session identity.--The official plugin composes reviewed desktop operations for spawn, send,-status, result, and cancellation. The host authenticates the sending Session ID-from a correlated plugin tool invocation; plugins cannot supply a forged sender.--## Compatibility and validation--The storage migration is additive. Existing conversations, plugin settings, and-the core Task family remain intact.--Validation covers concurrent senders, durable identity, reuse, queue admission,-source preservation across reload, exactly-once callback creation, failure and-cancellation results, permission ceilings, model resolution, hover lifecycle,-and the relevant host/Electron E2E journeys.+Rust host-core owns a durable session communication ledger keyed by message ID+and referencing the source and target Session IDs, where Session IDs remain the+only session identity and message IDs identify deliveries and idempotency+rather than a second work identity. Each delivery binds to its actual durable+turn before execution and derives results from that turn's persisted terminal+state, while the official plugin only composes reviewed desktop operations for+spawn, send, status, result, and cancellation. The host authenticates the+sending Session ID from a correlated plugin tool invocation, so a plugin cannot+forge a sender; existing targets keep their project, model, context, and+permissions, new sessions inherit the initiating project and permission mode,+and messaging can never raise a target above the initiating operation's+authorized ceiling. Messages carry explicit task, message, or completion+provenance, persist with the transcript, and render separately from human+input; they are not new user authorization and take no part in user-message+editing or regeneration, and a client-supplied `session_message` is stripped+(D597). A completion callback produces at most one durable completion message+referencing the original delivery and the real turn outcome, never requesting+another callback. The plugin resolves models through the host's public catalog+and returns candidates or a clear error rather than substituting an unrelated+model, and the session-list hover card gains a bounded on-demand host+projection of creation source, current task, recent exchanges, status, and+turn-bound result.++## Consequences++- The storage migration is additive: existing conversations, plugin settings,+ and the core Task family stay intact.+- This is a plugin-mediated exception to ADR 0165's withdrawn cross-session+ coordination; the old A2A broker, tools, and protocol are not restored, and+ ADR 0237's parent-only messaging and polling-based result inference are+ superseded.+- The host bounds autonomous communication chains, retains delivery failures for+ passive inspection, and preserves a cancelled session and its history.## Amendment (2026-09-18, D446): a completion notice's own reply may stay silent-Issue #504: the completion prompt states that a notice needs no acknowledgement,-yet the runtime's silent-turn recovery (spec 02-agent-runtime §5e) retried the-resulting silence and reported `EMPTY_MODEL_RESPONSE` after a task that had-succeeded. This amendment bounds one exception; every other decision above is-unchanged.--- The first settled assistant reply to a completion notice may end with no- visible text and no tool call without silent-turn recovery or- `EMPTY_MODEL_RESPONSE`.-- The exception covers exactly that reply.-- Only provenance that Main resolved from the queued Host ledger record can- enable it: `kind: completion`, the current target session, and nonempty- message and reply-to IDs.-- An accepted silent reply is still not worth resending.--Validation: runtime unit coverage for the accepted shapes, the trust boundary,-tool batches, provider retry, steering before and after the reply, and context-exclusion; `pnpm test:e2e:session-completion` against the real host ledger,-sidecar, and a local SSE provider. See-E2E-SESSION-completion-notice-allows-silence.+Issue #504 reported that a successful task ended in `EMPTY_MODEL_RESPONSE`+because silent-turn recovery retried the silence the completion prompt asked+for. The first settled assistant reply to a completion notice may now end with+no visible text and no tool call without silent-turn recovery, emitted as a+completed message, spent by that first settled response and revoked once an+accepted steering message enters the model context; only provenance Main+resolved from the queued Host ledger record (`kind: completion`, the current+target session, nonempty message and reply-to IDs) can enable it, so no+protocol field or caller authority is added. Main persists an accepted silent+reply as an empty completed row that the runtime keeps out of its entries and+pi's transcript state, so the next request carries no empty assistant message.diff --git a/docs/adr/0240-independent-session-discovery-and-navigable-projections.md b/docs/adr/0240-independent-session-discovery-and-navigable-projections.mdindex 0fc8dcf76..ca7442efb 100644--- a/docs/adr/0240-independent-session-discovery-and-navigable-projections.md+++ b/docs/adr/0240-independent-session-discovery-and-navigable-projections.md@@ -7,38 +7,42 @@## Context-The host-owned collaboration ledger already permits a delivery between any two-existing Agent Session IDs, but Session Orchestrator's private recent-reference-store is not an authority for discovering those IDs. A session created through-the normal New Task flow can therefore be a valid communication target while-remaining invisible to `SessionTask.list`.+The host collaboration ledger permits delivery between any two existing Agent Session+IDs, but Session Orchestrator's private recent-reference store is not an authority for+discovering them, so a session created through New Task can be a valid target while+staying invisible to `SessionTask.list`.## DecisionThe reviewed `desktop.control` catalog gains the additive read operation-`session/collaboration/list`. It returns at most 100 non-deleted Agent sessions-with their real Session IDs, titles, status, updated time, readable provider and-model labels, and bounded creation links.+`session/collaboration/list`, returning up to 100 non-deleted Agent sessions with+their real Session IDs, titles, status, updated time, readable provider and model+labels, and bounded creation links, but no project paths, credentials, transcripts, or+previews; `send` stays the authenticated mutation path. The sidebar projection adds+`providerName`, `modelName`, and at most eight `createdSessions` references, and since+`createdBySession` describes only durable creation links, an independently created+session gets no fabricated creator.++The renderer renders references as keyboard-focusable buttons that open the durable+session and focus the Composer, the hover card stays on-demand and bounded, and+Session Orchestrator keeps the legacy `workers` field beside the new host-backed+`sessions` directory.-The host sidebar projection adds readable `providerName` and `modelName` fields-plus at most eight `createdSessions` references. `createdBySession` and-`createdSessions` describe only durable Session Orchestrator creation links;-ordinary independently created sessions do not receive a fabricated creator.+## Amendment (2026-09-13): reference availability-## Compatibility and validation+`SessionReference` gained an optional `available` field that the host reports as+`false` for a `createdBySession`, `createdSessions`, `currentTask.senderSession`, or+`recentExchanges[].peer` reference whose session row is deleted or absent.-The new operation and projection fields are additive. Existing `status`, `send`,-`spawn`, result, cancellation, private references, and session data are-unchanged.+## Consequences-The list is restricted to Agent sessions because the host already rejects-delivery to Plan and Goal sessions. Host-core projection tests cover readable-provider/model names, creator/created-session links, and independent session-discovery.+- Any existing Agent session is a discoverable collaboration target.+- Unavailable references render as plain text, and activating a vanished session+ reports a visible error instead of an empty selection.+- The optional field is additive, so existing callers and persisted data are+ unaffected.-## Amendment (2026-09-13): reference availability+## Alternatives-`SessionReference` gained an optional `available` field. The host reports-`available: false` for a `createdBySession`, `createdSessions`,-`currentTask.senderSession`, or `recentExchanges[].peer` reference whose session-row is deleted or absent, and falls back to the Session ID as the title.+- Keep the private recent-reference store as the discovery authority — rejected: it+ hides valid targets.diff --git a/docs/adr/0241-vendored-updatable-file-view-plugin.md b/docs/adr/0241-vendored-updatable-file-view-plugin.mdindex 2699e4350..3be3e2e00 100644--- a/docs/adr/0241-vendored-updatable-file-view-plugin.md+++ b/docs/adr/0241-vendored-updatable-file-view-plugin.md@@ -2,9 +2,7 @@- Status: Accepted (supersedes ADR 0105; issue #304)- Date: 2026-09-13-- Deciders: PI-Desktop core- Related: [ADR 0104](0104-plugin-contributed-work-panel-views.md) ·- [ADR 0105](0105-files-as-a-bundled-plugin.md) ·[ADR 0109](0109-open-files-with-the-os-associated-application.md) ·[ADR 0111](0111-reveal-files-in-file-manager.md) ·[ADR 0169](0169-classified-file-preview-and-live-workspace-events.md) ·@@ -12,61 +10,53 @@## Context-The bundled `pi.files` view (ADR 0105) browsed and previewed the workspace and-nothing else: no editing, no image, CSV, JSON, or SQLite surface, and a line cap-on text preview. Anything more than looking at a file meant leaving the app.+The bundled `pi.files` view (ADR 0105) could only browse and preview the+workspace, so anything beyond looking at a file meant leaving the app.+`pi.file-manager` already covers editing and the image, CSV, JSON, and SQLite+surfaces as a third-party plugin on the same public channel — `contributes.views`,+a sandboxed page over `pluginBridge`, `ui.view` plus `fs.read` on root+`workspace` with scope `**` — and is published in the official marketplace.+Vendoring it raises two questions: how its writes are mediated, and how the+in-app copy stays consistent with the published one.## Decision1. The bundled file view is `pi.file-manager`, vendored into- `apps/desktop/resources/plugins/`.-2. It declares only `ui.view` and `fs.read` (`root: workspace`, `scope: ["**"]`)- — the same permissions the view it replaces declared.**+ `apps/desktop/resources/plugins/` as the upstream release's own artifacts byte+ for byte plus a `license` manifest field, with `UPSTREAM.md` recording+ repository, tag, commit, and checksums; `pi.files` is removed and a build that+ stops shipping a plugin leaves no orphan registry row (ADR 0104).+2. It declares only `ui.view` and `fs.read` on root `workspace` with scope `**`,+ the same permissions the replaced view declared, and reaches the host only+ through the public bridge.3. Editing writes are the plugin's own: its host process keeps the path jail,- atomic writes, `mtime`/size conflict detection, and the write audit.-4. **Bundled means default and non-removable, not frozen.** A bundled plugin- cannot be uninstalled, but it can be updated from the marketplace, and that- update survives the next launch:- - `sync_builtin` keeps an installed row whose source is not `builtin` for as- long as this build does not ship a *strictly newer* version.- - `uninstall` refuses by id against the set of plugins this build ships,- rebuilt from disk on every launch.-5. A catalog version is offered as an update only when it is strictly newer than- what is installed.-6. The panel title is the manifest's localized title, as for any plugin.+ atomic writes, `mtime` and size conflict detection, and the write audit, none+ of which the host gateway mediates. A manifest cannot express a whole-tree+ write and this host does not sandbox a plugin process's `fs` access anyway, so+ bundling grants no capability a third-party plugin lacks; the boundary is+ stated in the manifest's `safetyNotes`.+4. Bundled means default and non-removable, not frozen: `sync_builtin` keeps an+ installed row whose source is not `builtin` while this build ships no strictly+ newer version, and `uninstall` refuses by id against the set of plugins this+ build ships, rebuilt from disk on every launch.+5. A catalog version is offered as an update only when it is strictly newer; a+ panel title comes from the manifest's localized title like any plugin, with no+ renderer label and no hardcoded view id.## Consequences-- The work panel's file surface is a vendor copy, so the application's own- release cycle no longer decides when the view improves; upstream releases do,- and users can take them without waiting for an app update.-- Maintaining the copy is a deliberate act: `UPSTREAM.md` and- `apps/desktop/test/bundled-plugins.test.mjs` pin the vendored release, so a- silent edit or a half-done re-sync fails the build.-- "Cannot be uninstalled" is now separate from "came from `resources/plugins`".-- The marketplace keeps listing a bundled plugin and offers its updates.-- A plugin the user updated keeps a marketplace/`local` source while remaining- bundled.+- Upstream releases, not the application release cycle, decide when the file+ surface improves, and users can take them without an app update.+- `UPSTREAM.md` and the bundled-plugin test pin the vendored release, so a+ silent edit or half-done re-sync fails the build.+- "Cannot be uninstalled" is separate from "came from `resources/plugins`":+ `PluginSummary.bundled` carries that distinction, so `source == "builtin"` no+ longer answers whether a plugin is protected, and the bundled view's+ filesystem reach is the plugin's own.## Alternatives considered-### Reimplement the missing viewers and editing in `pi.files`--Rejected: it duplicates a maintained third-party plugin, and the line cap, media-viewers, structured viewers, and SQLite browsing are a large surface to keep in-the host.--### Bundle it read-only and leave editing to the marketplace copy--Rejected: the same plugin cannot offer two capability levels without forking it,-and a read-only default would leave the most common request — change this line —-unanswered.--### Let the bundled copy always win, with no updates--Rejected: a user could then only get a newer upstream release by updating the-application, which defeats the point of vendoring a published plugin.--### Hide the marketplace entry for a bundled id--Rejected: the entry is where a newer upstream release is published.+- Reimplement the viewers and editing in `pi.files`: it duplicates a maintained+ third-party plugin and keeps a large surface in the host.+- Bundle it read-only and leave editing to the marketplace copy: one plugin+ cannot offer two capability levels without forking it.diff --git a/docs/adr/0242-delta-only-streaming-updates.md b/docs/adr/0242-delta-only-streaming-updates.mdindex d9ffece90..3d1ae71b0 100644--- a/docs/adr/0242-delta-only-streaming-updates.md+++ b/docs/adr/0242-delta-only-streaming-updates.md@@ -2,53 +2,46 @@- Status: Accepted- Date: 2026-09-14-- Decision: D412-- Amends: ADR 0127, ADR 0130, ADR 0149, ADR 0153-- Issue: #299+- Related: D412, ADR 0127, ADR 0130, ADR 0149, ADR 0153, issue #299## Context-Long Agent turns streamed at 200+ tokens/s from the provider, but PI-Desktop-displayed them at a much lower rate that got worse the longer the turn ran. Stop-plus a new prompt restored speed; the same turn's later short thinking blocks-stayed slow.+Long agent turns streamed at high token rates but displayed more slowly the longer+the turn ran, and subagents showed the same lag: each `message_update` flattened the+full assistant snapshot, compared it against the accumulated string, serialized the+whole `UiMessage` onto sidecar stdout, and AgentHost `boundPayload()` stringified it+again for frame-size checks before renderer batching ran, so a length-n stream cost+about O(n²) bytes and CPU. RACP already documents `item.delta` as non-durable delta+text with the full row in `item.completed`.## Decision-Keep `currentAssistant` as the in-memory authority in the runtime. On the-append-only streaming path, emit `message_update` with:--- `stream: "delta"`-- `deltaText` / `deltaThinking`-- `resetText` / `resetThinking` when the provider replaced rather than appended-- a slim `message` identity (id, role, status, createdAt, model/provider,- parentToolCallId, agentName) without growing `content` / `thinking`--A 16ms coalescer in `DesktopAgentRuntime` concatenates pending deltas and-flushes immediately before `tool_start`, `tool_end`, `message_end`, `error`,-`abort`, retry snapshots, and other semantic events so order is preserved.--- AgentHost patches `activeItems` and skips `JSON.stringify` for small delta- frames-- Electron main reconstructs the inflight checkpoint snapshot from deltas-- the renderer concatenates same-frame deltas, then patches the live `UiMessage`+`currentAssistant` stays the in-memory authority: on the append-only streaming path+`message_update` carries `stream: "delta"`, `deltaText` / `deltaThinking`,+`resetText` / `resetThinking` when the provider replaced rather than appended, and a+slim `message` identity (id, role, status, createdAt, model/provider,+parentToolCallId, agentName) without growing `content` / `thinking`. A 16ms+coalescer in `DesktopAgentRuntime` concatenates pending deltas and flushes+immediately before `tool_start`, `tool_end`, `message_end`, `error`, `abort`, and+retry snapshots, so order is preserved; `message_start` and `message_end` still carry+a full `UiMessage`, and snapshot replacements omit `stream` while replacing the live+row. AgentHost patches `activeItems` and skips serialization for small delta frames,+Electron main reconstructs the inflight checkpoint from deltas, and the transcript+projection reuses unchanged activity parts with stable delegation status and timing+`Map`s, passing `runtimeActivity` only to the live tail ActivityGroup. Protocol+version stays 11 and the fields are additive, so consumers that ignore `stream` still+get `message_end` as the authoritative row.## Consequences-- Cross-process streaming bytes grow with the new chunk, not with the cumulative- snapshot.-- A long turn no longer forms a serialization backlog that later short chunks- wait behind.-- Historical activity groups in the active turn do not re-render for each tail- token.-- Crash-recovery checkpoints still see a reconstructed full snapshot.+- Cross-process streaming bytes grow with the new chunk rather than the cumulative+ snapshot, so a long turn no longer forms a serialization backlog.+- Historical activity groups stop re-rendering per tail token, while crash-recovery+ checkpoints still see a reconstructed full snapshot.- Remote RACP `item.delta` payloads match the documented delta contract.## Alternatives-- Coalesce only in the renderer: rejected; the O(n²) stringify already happened- in the sidecar and main.-- Drop tokens or raise the debounce to 50ms: rejected; that hides backlog rather- than removing it.-- New `message_delta` event type: unnecessary; additive fields on the existing- `message_update` keep old consumers compiling.+- Coalesce only in the renderer: the O(n²) stringify already happened in the sidecar+ and main.+- Add a `message_delta` event type: additive fields keep old consumers compiling.diff --git a/docs/adr/0243-skill-market-public-https-catalog.md b/docs/adr/0243-skill-market-public-https-catalog.mdindex 6c6e250e0..852eb5d63 100644--- a/docs/adr/0243-skill-market-public-https-catalog.md+++ b/docs/adr/0243-skill-market-public-https-catalog.md@@ -2,42 +2,38 @@- Status: Accepted- Date: 2026-09-13-- Decision: D413+- Related: D413, issue #287, PR #290- Amends: ADR 0009-- Issue: #287-- PR: #290## Context-Settings → Skills gained a Market view that installs community `SKILL.md`-documents through the existing `skills.create` write path. The renderer CSP only-allows localhost, so catalog discovery and document fetch run in Electron main.+The Settings → Skills Market view installs community `SKILL.md` documents through+the existing `skills.create` write path. The renderer CSP allows only localhost, so+catalog discovery and document fetch run in Electron main, where a naive+`net.fetch` would follow redirects onto loopback or RFC1918 space. The plugin+marketplace's fixed host allowlist cannot cover user-supplied GitHub repositories,+and MCP market (#285) needs the same classifier.## Decision-1. Keep a single I/O-free classifier in `packages/shared`- (`isSafePublicHttpsUrl`, `isPublicHostname`, `isPublicIpLiteral`).-2. Main-process fetches go through `createPublicHttpsClient`: HTTPS only,- route-aware DNS classification, direct-route address pinning when a mixed DNS- answer contains rejected addresses (ADR 0321), `redirect: "manual"` with- per-hop re-validation, and retries only for non-policy failures.-3. The renderer never fetches catalog or document URLs.-4. Scanned and catalog ids are sanitized to host `valid_capability_id` before- they reach the UI.-5. Preview shows the assembled body (skill text plus inlined sibling markdown).-6. Builtin catalog titles are English (ADR 0009).+A single I/O-free classifier lives in `packages/shared` (`isSafePublicHttpsUrl`,+`isPublicHostname`, `isPublicIpLiteral`), which the skill market wraps as+`isSafeSkillSourceUrl` and the future MCP market imports. Main-process fetches go+through `createPublicHttpsClient`: HTTPS only, route-aware DNS classification,+direct-route address pinning when a mixed answer contains rejected addresses+(ADR 0321), `redirect: "manual"` with per-hop re-validation, and retries only for+non-policy failures. The renderer never fetches catalog or document URLs, install+stays `skills.create`, and host-core stays unaware of the market. Scanned and+catalog ids are sanitized to host `valid_capability_id` before reaching the UI,+preview shows the assembled body including inlined sibling markdown, a document+that would exceed `MAX_SKILL_BYTES` cannot be installed, and builtin catalog titles+are English per ADR 0009.## Consequences-- User-added `https://github.com/org/repo` sources make main walk the git tree- and pull jsDelivr copies.-- Installing a skill still writes model instructions.+- User-added `https://github.com/org/repo` sources make main walk the git tree and+ pull jsDelivr copies; the boundary is public HTTPS plus public resolved IPs, and+ DNS rebinding between lookup and `net.fetch` stays a residual risk.+- Installing a skill still writes model instructions: preview is the disclosure,+ and `verified` on builtin rows is not a signature.- MCP market must import `public-network.ts` instead of copying the classifier.--## Alternatives--- Plugin-marketplace host allowlist: too narrow for user GitHub sources.-- Directory install (`~/.agents/skills/<slug>/`): incompatible with the current- single-file user-skill model.-- Pin fetched IPs into undici: stronger against rebinding, but would skip- Chromium's proxy stack that `net.fetch` honors.diff --git a/docs/adr/0244-imported-extension-dependency-boundary.md b/docs/adr/0244-imported-extension-dependency-boundary.mdindex d4543b254..43aebd73f 100644--- a/docs/adr/0244-imported-extension-dependency-boundary.md+++ b/docs/adr/0244-imported-extension-dependency-boundary.md@@ -2,48 +2,47 @@- Status: Accepted- Date: 2026-09-14-- Decision: Imported pi extension dependencies use a registry-only, non-lifecycle npm boundary+- Decision: Imported pi extension dependencies use a registry-only, non-lifecycle+ npm boundary- Related: ADR 0214, ADR 0215, `07-plugins/16-trusted-extensions.md` §3.2## Context-The explicit `Plugins → Import pi extension` flow copies a local pi package and-may install its declared dependencies before the first sidecar load. A normal+The `Plugins → Import pi extension` flow copies a local pi package and may+install its declared dependencies before the first sidecar load. A normal`npm install` inherits user configuration and can resolve local paths, git-repositories, private registries, proxies, or HTTP tarballs.+repositories, private registries, proxies, or HTTP tarballs, `--ignore-scripts`+alone is not a boundary, and a packaged build ships no standalone npm.## Decision-1. The importer validates registry-only specs in `dependencies`,- `optionalDependencies`, `devDependencies`, and `peerDependencies`, plus- recursive `overrides`.-2. npm lockfiles are accepted only when package locations, nested dependency- specs, and every `resolved` URL are registry-safe.-3. Real npm runs with a minimal environment: user/global config files are- isolated, the registry is fixed to `https://registry.npmjs.org/`, git- resolution is disabled, lifecycle scripts/audit/fund/update notifications are- disabled, and npm uses a per-import cache removed after completion.-4. Real npm traffic goes through a loopback proxy that permits only- `registry.npmjs.org` on ports 80/443.-5. Dependency resolution and installation are separate bounded commands: `npm- install --package-lock-only` validates the complete resolved lockfile, then- `npm ci` installs it.-6. Imported copies omit credential files and repository metadata, create the- destination directory atomically, and derive the plugin id from the final- unique directory name.-7. A validated user-selected npm path is saved atomically in Main-owned- `<dataDir>/npm-path.json` and revalidated on future imports.+The importer accepts only registry-safe specs in `dependencies`,+`optionalDependencies`, `devDependencies`, `peerDependencies`, and recursive+`overrides`, failing before npm starts. A lockfile is usable only when package+locations, nested dependency specs, and every `resolved` URL are registry-safe;+unsupported lockfile formats are removed and unsafe lockfiles are never reused.++Real npm runs with an isolated minimal environment — user and global config+ignored, registry fixed to `https://registry.npmjs.org/`, git resolution+disabled, lifecycle scripts, audit, fund, and update notifications off, and a+per-import cache deleted afterwards — and its traffic passes through a loopback+proxy that permits only `registry.npmjs.org` on ports 80 and 443. Resolution and+installation stay separate bounded commands, `npm install --package-lock-only`+then `npm ci`, and a failure removes partial `node_modules`, the cache, and+generated lockfiles while keeping a safe source lockfile when possible.++Imported copies omit credential files and repository metadata, create the+destination atomically, and derive the plugin id from the final unique directory+name. A missing npm or Node.js yields a structured unavailable error and a+Main-owned native picker; the chosen executable is saved atomically in+`<dataDir>/npm-path.json`, revalidated on later imports, and passed to the+install child alone through `PATH`, while cancellation or dependency failure+stays non-blocking for registration.## Consequences- Private registries, private dependency URLs, git dependencies, local paths,- npm aliases, and lifecycle-build dependencies are intentionally unsupported by- this import path.-- The explicit import flow still requires a user-trusted local extension and a- usable Node.js/npm installation, either on `PATH` or explicitly selected from- a trusted installation.-- The main process owns the proxy and child-process lifecycle; dependency- installation remains outside the renderer and sidecar.-- The dependency install and full picker/provider journey remain separate E2E- validation surfaces; deterministic boundary and cleanup tests cover the- security contract.+ npm aliases, and lifecycle-build dependencies are unsupported on this path.+- Import still requires a user-trusted local extension and a usable Node.js/npm,+ and the main process owns the proxy and child-process lifecycle.+- Registry and network errors do not prompt for a different executable.diff --git a/docs/adr/0245-mcp-market-public-network-boundary.md b/docs/adr/0245-mcp-market-public-network-boundary.mdindex ce326f078..111a7200e 100644--- a/docs/adr/0245-mcp-market-public-network-boundary.md+++ b/docs/adr/0245-mcp-market-public-network-boundary.md@@ -6,46 +6,44 @@## Context-The MCP market fetches user-configurable Registry and catalog sources from-Electron Main. A syntactic HTTPS check and a separate DNS lookup are not enough-to enforce a public-network boundary: a DNS-rebinding source can resolve to a-public address during validation and to a private address when the HTTP client-connects.+The MCP market fetches user-configurable Registry and catalog sources from Electron+Main. A syntactic HTTPS check plus a separate DNS lookup cannot enforce a+public-network boundary, because a DNS-rebinding source can resolve publicly during+validation and privately when the client connects, and unbounded responses can+exhaust the main process. Dropping the Registry's published versions and launcher+arguments would also make an install resolve mutable latest content.## Decision-1. Shared renderer and Main URL validation accepts credentials-free HTTPS only.-2. Main asks the Electron session carrying each request for its proxy route- immediately before connecting.-3. Redirects are manual, HTTPS-only, and revalidated at every hop, with a- maximum of five redirects.-4. Market source responses are bounded to 4 MiB, DNS and HTTP requests share an- eight-second deadline, at most 16 sources are processed per call, and the- in-memory catalog/search caches are bounded.-5. Registry npm packages are mapped as `identifier@version` and PyPI packages as- `identifier==version` when a version is present.-6. Market HTTP catalog entries are restricted to public HTTPS endpoints.+1. URL validation accepts credentials-free HTTPS only and rejects loopback,+ unspecified, private, CGNAT, link-local, multicast, reserved, documentation,+ benchmark, ULA, site-local, IPv4-mapped, and IPv4-compatible ranges, including+ URL-normalization and trailing-dot forms.+2. Main asks the Electron session for its proxy route immediately before connecting.+ On a `direct` or `unknown` route it pins the selected public address to the HTTPS+ socket while keeping the original host as TLS SNI and HTTP `Host`; on a `proxied`+ route it uses that session's `net.fetch`, tolerating the resolver's `benchmark`+ class under ADR 0272 while still rejecting real private targets.+3. Redirects are manual, HTTPS-only, revalidated at every hop, and capped at five.+4. Responses are bounded to 4 MiB, DNS and HTTP share an eight-second deadline, at+ most 16 sources are processed per call, and caches are bounded.+5. npm packages map to `identifier@version` and PyPI to `identifier==version`, with+ runtime and package arguments preserved in order; only `streamable-http` remotes+ with public HTTPS endpoints are installable.+6. Catalog entries must be public HTTPS, while manual MCP configuration keeps the+ existing local/LAN policy; MCP HTTP redirects never forward authorization, cookie,+ proxy-authorization, or API-key headers to another origin.## Consequences- Public market data cannot use DNS rebinding to turn the Main fetcher into a- private-network request, subject to the operating system and proxy's own- network behavior.-- Slow, oversized, malformed, or excessively configured sources fail as one- source and do not grow the Main process without bound.-- Installs are reproducible with respect to the Registry package version and- preserve the launch semantics that the publisher supplied.-- A Registry/catalog entry cannot be used as a market shortcut for a private MCP- endpoint; users can still add such endpoints through the explicit MCP editor- permitted by ADR 0142.-- Direct and unknown routes keep pinned Node HTTPS sockets and the strict- public-address rule.--## Alternatives considered--- **Preflight DNS followed by ordinary fetch:** rejected because the two- resolutions leave a DNS-rebinding race.-- **Allowlist only the official Registry hostname:** rejected because the- product supports user-hosted catalog and Registry sources.-- **Install the Registry's latest package:** rejected because it ignores the- version selected and published by the Registry.+ private-network request, and slow, oversized, or malformed sources fail as one+ source without unbounded growth.+- A Registry or catalog entry is not a shortcut to a private MCP endpoint, which+ users can still add through the explicit MCP editor (ADR 0142).++## Alternatives++- Preflight DNS then ordinary fetch: the two resolutions leave a rebinding race.+- Allowlist only the official Registry hostname: user-hosted sources are supported.+- Install the Registry's latest package: ignores the published version.diff --git a/docs/adr/0246-subagent-opt-in-parent-tool-inherit.md b/docs/adr/0246-subagent-opt-in-parent-tool-inherit.mdindex 756eff10e..5a5186065 100644--- a/docs/adr/0246-subagent-opt-in-parent-tool-inherit.md+++ b/docs/adr/0246-subagent-opt-in-parent-tool-inherit.md@@ -2,72 +2,55 @@- Status: Accepted- Date: 2026-09-14-- Deciders: PI-Desktop core- Related: ADR 0062, ADR 0089, ADR 0100, D201, D415, issue #215, PR #319## Context-ADR 0062 made a subagent a bounded worker: it could only receive tools from-`SUBAGENT_ASSIGNABLE_TOOLS` (Read, Glob, Grep, BrowserPreview, Bash, Edit,-Write). Plugin tools, `Skill`, `ToolSearch`, mode tools, and `Task` were out of-reach on purpose so a definition remained the place a reader could see what a-delegate may do.+ADR 0062 made a subagent a bounded worker limited to+`SUBAGENT_ASSIGNABLE_TOOLS`, deliberately excluding plugin tools, `Skill`,+`ToolSearch`, mode tools, and `Task`. Permission mode and the model pin already+follow the parent, but tool capability did not, so a parent holding `Skill`, MCP,+or plugin tools could not share them with a worker it spawned, and always+inheriting would make every delegation as dangerous as the session.## Decision-1. Frontmatter may opt a definition into parent-tool inheritance:-- ```yaml- tools: inherit- # or- tools: [inherit, Bash]- ```--`inherit` sets `SubagentDefinition.inheritTools`. Extra names still have to be-on `SUBAGENT_ASSIGNABLE_TOOLS`.--2. At `Task` spawn, `resolveSubagentToolNames` unions the session runtime's- **live `toolCatalog` keys** (including deferred plugin/MCP tools the parent- is allowed to call) with any declared extras, then drops- `SUBAGENT_INHERIT_DENY_TOOLS`:-- | Never inherited | Why |- |---|---|- | `Task` / `TaskWait` / `TaskList` / `TaskStop` | no nested fan-out |- | `EnterPlanMode` / `EnterGoalMode` | mode stays the parent's |- | `asktool` | a delegate has no user |- | `new_context` | compaction is a parent-runtime flag |- | `ToolSearch` | activates deferred tools on the parent catalog |--The child receives the full allowed catalog without `ToolSearch`. Inherit is-stronger than the parent's first-request active set; that is the point of-handing Skill/MCP/plugin tools to a worker.--3. Spawn-time resolved names drive the delegate tool list, mutation framing,- search/edit/Bash guidance, and — when `Skill` is present — the same `#- Skills` catalog the parent already received.--4. host-core's user-subagent scanner keeps the `inherit` token in `tools` so- `tools: inherit` alone still appears in `agents.active` and round-trips- through Settings.--5. Default documents that omit `tools` stay read-only (`Read, Glob, Grep`).+1. Frontmatter may opt a definition in with `tools: inherit` or+ `tools: [inherit, Bash]`. `inherit` sets `SubagentDefinition.inheritTools`, any+ extra name must still be assignable, and builtins do not opt in.+2. At `Task` spawn, `resolveSubagentToolNames` unions the session runtime's live+ `toolCatalog` keys, including deferred plugin and MCP tools, with declared+ extras and drops `SUBAGENT_INHERIT_DENY_TOOLS`: `Task`, `TaskWait`, `TaskList`,+ and `TaskStop` (no nested fan-out), `EnterPlanMode` and `EnterGoalMode` (mode+ stays the parent's), `asktool` (a delegate has no user), `new_context`+ (compaction is a parent flag), and `ToolSearch` (it activates tools on the+ parent catalog). The child receives the allowed catalog without `ToolSearch`,+ and inherit is deliberately stronger than the parent's first-request set.+3. Spawn-time names drive the delegate tool list, mutation framing,+ search/edit/Bash guidance, and, when `Skill` is present, the same `# Skills`+ catalog the parent received; the Task catalog prints `inherit` plus extras+ instead of listing every MCP name.+4. host-core's user-subagent scanner keeps the `inherit` token in `tools` so a+ `tools: inherit`-only definition still appears in `agents.active` and+ round-trips through Settings without the editor stripping it.+5. Documents that omit `tools` stay read-only (`Read, Glob, Grep`), and `tools:+ "*"` still means the assignable tools rather than the session catalog.++This amends ADR 0062 §2 and its rejected "let delegates inherit the parent's+tools" alternative: inherit is now an explicit document opt-in with a deny list.## Consequences-- A user-owned worker can call Skill/MCP/plugin tools the parent already had,- without turning explorer into a nested Agent.-- Inherit of Bash/Edit/Write is inheriting mutation.-- Definitions remain the readable grant: `tools: inherit` is visible in the- Markdown and in Settings.-- Child `ToolSearch` / `new_context` cannot mutate parent runtime state.+- A user-owned worker can call Skill, MCP, and plugin tools the parent already+ had, without turning builtins into nested agents.+- Inheriting Bash, Edit, or Write inherits mutation; permission mode and the+ external-path gate are unchanged.+- The grant stays readable in Markdown and Settings, and a child cannot mutate+ parent runtime state through `ToolSearch` or `new_context`.-## Alternatives considered+## Alternatives-- **Always inherit for user agents, never for builtins.** Rejected as a hidden- default.-- **Inherit only currently active tools.** Rejected because MCP/plugin tools are- deferred behind `ToolSearch`; a worker would still lack the catalog the issue- asked for, and inheriting `ToolSearch` would activate tools on the parent.-- **Add `Skill` to `SUBAGENT_ASSIGNABLE_TOOLS` only.** Rejected: no MCP/plugin- tools, still a second catalog.+- Always inherit for user agents: rejected as a hidden default where Markdown+ opt-in matches `permission: inherit`.+- Add `Skill` to the assignable list only: rejected because it leaves MCP and+ plugin tools as a second catalog.diff --git a/docs/adr/0247-git-clone-public-hostname.md b/docs/adr/0247-git-clone-public-hostname.mdindex 10286cd97..87073eaa7 100644--- a/docs/adr/0247-git-clone-public-hostname.md+++ b/docs/adr/0247-git-clone-public-hostname.md@@ -2,37 +2,29 @@- Status: Accepted- Date: 2026-09-14-- Deciders: PI-Desktop core-- Related: ADR 0243, ADR 0245, D416+- Related: D416, ADR 0243, ADR 0245## Context-Home "Clone git project" runs `git clone` with a user-supplied remote-(`apps/desktop/src/lib/git-clone-url.ts`). The parser already rejected `file:`-URLs and embedded passwords so a clone could not read arbitrary local paths or-smuggle credentials in the URL.+Home "Clone git project" runs `git clone` with a user-supplied remote, and the parser+rejected `file:` URLs and embedded passwords but still accepted loopback, RFC1918,+link-local, and IPv6 loopback literals. Unlike the market fetchers (ADR 0243 /+ADR 0245), git uses its own HTTP and SSH stacks, so a Main-process DNS pin cannot+apply.## Decision-1. `parseGitCloneUrl` reuses `isPublicHostname` from- `packages/shared/src/public-network.ts` for URL hosts and `git@host:path`- hosts.-2. Protocols stay `https`, `http`, `ssh`, and `git`.-3. Git still resolves DNS and opens sockets itself.+`parseGitCloneUrl` reuses `isPublicHostname` from the shared network guards for URL+hosts and `git@host:path` hosts, rejecting loopback, unspecified, private, CGNAT,+link-local, multicast, reserved, documentation, ULA, site-local, `.localhost`,+`.local`, and `.internal` names. Protocols stay `https`, `http`, `ssh`, and `git`, so+SSH and HTTPS GitHub remotes keep working while `file:` URLs and URL passwords stay+rejected. Git still resolves DNS itself, so clone traffic is not pinned and a public+hostname resolving to a private address remains accepted residual risk.## Consequences-- Accidental or malicious clones to loopback/LAN IP literals fail in the- renderer before `git` runs.-- Cloning a public git host by DNS name still works, including HTTP remotes.-- Operators who clone from a private git host by literal IP must use an- out-of-app git remote; that is an intentional reduction in convenience.-- Residual risk: a public hostname can still resolve to a private address inside- git.--## Alternatives considered--- **Apply market DNS pin to git clone:** rejected; git speaks SSH and its own- HTTP, and replacing it is out of scope.-- **HTTPS-only remotes:** rejected; SSH `git@host:path` is the common GitHub- path and is not an HTTP SSRF vector in Electron Main.+- Loopback and LAN literal clones fail before `git` runs; public hosts still clone by+ name, and a private host by literal IP needs an out-of-app remote.+- That convenience loss is intentional, and the residual rebinding risk is documented+ rather than pinned as the market fetchers do.diff --git a/docs/adr/0248-plugin-theme-assets-and-window-background.md b/docs/adr/0248-plugin-theme-assets-and-window-background.mdindex c2a6dc80d..02ac02c08 100644--- a/docs/adr/0248-plugin-theme-assets-and-window-background.md+++ b/docs/adr/0248-plugin-theme-assets-and-window-background.md@@ -1,87 +1,54 @@# ADR 0248 — Package theme assets and contributed window backgrounds-- **Status**: Accepted for implementation-- **Date**: 2026-09-14-- **Related**: issue #334, issue #335, `07-plugins/04-plugin-security.md` §3.1, `07-plugins/02-plugin-manifest-schema.md` §4, `07-plugins/13-plugin-permissions-matrix.md`+- Status: Accepted for implementation+- Date: 2026-09-14+- Related: issue #334, issue #335, ADR 0332## Context-A contributed theme (`ui.theme`) could only affect the renderer's CSS, and only-within two walls that made real theming impossible:--1. **References were `data:`-only.** `sanitizeThemeCss` refuses every `url()`- target that is not a `data:` URI, and the sheet itself is capped at 256 KB.-2. **The native window background ignored plugin themes.** The window is created- with the host palette for the resolved light/dark base, so a plugin theme- with a dark #0d1424 plate flashed — and kept — the host's `#181818`, while- the renderer painted the theme's own colours inside it.+A contributed theme (`ui.theme`) could only touch renderer CSS inside two walls:+`sanitizeThemeCss` refused every non-`data:` `url()` under a small sheet cap, so a+photographic background was inexpressible, and the native window background used the+host palette, so a plugin theme with a dark plate flashed and kept the host colour.## Decision-Two opt-in additions, both inert when absent.+Two opt-in additions, inert when absent.### 1. `contributes.themes[].assets` and the `plugin-asset:` scheme-A theme may declare `assets: string[]` — package-relative paths whose extension-is on a whitelist (`png`, `jpg`, `jpeg`, `webp`, `avif`, `svg`, `woff2`) and-whose summed size is at most 4 MB. The declaration **does not** widen the sheet:-validation still refuses the raw text of any reference, and instead rewrites-each `url()` that matches a declared asset to-`plugin-asset://<pluginId>/<normalizedPath>`.--The scheme is host-owned:--- Reserved as privileged (`standard`, `secure`, `supportFetchAPI`,- `corsEnabled`, `stream`) before the app is ready.-- Handled by a main-process resolver that answers only from the runtime's- per-plugin asset map — populated at theme registration from files that exist- inside the plugin package, are not under `node_modules`, and fit the budget.-- Served with an explicit MIME type, `nosniff`, and `no-store`.-- Admitted by the renderer CSP for `img-src` and `font-src`, and by the plugin- panel egress policy as a local scheme (it is read-only and package-scoped, so- it does not widen panel egress).+A theme may declare `assets: string[]` of package-relative paths with a whitelisted+extension and a bounded summed size, which does not widen the sheet: validation still+rewrites each `url()` matching a declared asset to+`plugin-asset://<pluginId>/<normalizedPath>`, keeps the `data:`-only rule for everything+else, and the scheme is reserved as privileged before app readiness, served by a+main-process resolver from the runtime's per-plugin asset map only, and admitted by the+renderer CSP for `img-src`/`font-src` and by the plugin panel egress policy, while+`ui.theme` already grants reading files the plugin ships.### 2. `contributes.windowAppearance.backgroundColor.{light,dark}`-A theme may name the native window background as `#rrggbb` or `#rrggbbaa`, one-slot per resolved palette. It is applied only while one of that plugin's themes-is the selected theme, and only for the palette the renderer has resolved —-`system` resolves to light or dark first, exactly as `data-theme` does.--Restoration is **derived, not remembered**. The renderer recomputes the colour-from the persisted preference and the live theme catalog on every theme, plugin,-and OS-appearance change and sends the result (or nothing).--> **Amended by ADR 0332.** macOS keeps its translucent vibrancy surface by-> default, so `windowAppearance.backgroundColor` is skipped there exactly as-> described above; turning off `settings.macosWindowTranslucency` paints the-> opaque native surface and applies the colour like every other platform. The-> permission, the derived-not-remembered restoration, and the palette resolution-> above are unchanged.+A theme may name the native window background as `#rrggbb` or `#rrggbbaa`, one slot per+resolved palette, applied only while one of that plugin's themes is selected, with+restoration derived rather than remembered so switching, disabling, or uninstalling+converges on the host palette and no exit path leaves a half-applied colour; the new+`ui.window.appearance` permission gates it, a declaration without the grant is audited+and ignored, macOS keeps its `vibrancy` plate unless `settings.macosWindowTranslucency`+is off (ADR 0332), and built-in themes reach the same table through `BUILTIN_THEMES` and+`isThemeColorScheme` in `packages/shared/src/theme.ts`.## Consequences-- A theme can ship a photographic background or a webfont and can own the native- plate behind its own palette, without loosening the sheet's own rules.-- The renderer only ever sees a host scheme or a `data:` URI; a relative path- still cannot reach the sheet.-- `contributes.windowAppearance` without `ui.window.appearance` is a manifest- error in the SDK validator and in host-core, so the mismatch surfaces at- install rather than at load.-- The window is created before any theme is known, so the very first frame of a- cold start still uses the host palette.-- The asset handler reads each file synchronously.+- A theme can ship a photographic background or webfont and own the native plate behind+ its own palette, while the renderer only ever sees a host scheme or a `data:` URI.+- `contributes.windowAppearance` without `ui.window.appearance` is a manifest error in+ the SDK validator and host-core, surfacing at install.+- The window exists before any theme is known, so the first cold-start frame uses the+ host palette.## Alternatives-- **Raise the `data:` size cap.** Keeps one channel, but a 4 MB sheet in a- `<style>` element costs base64 inflation, a parse on every plugin change, and- memory in the renderer, and it still cannot express a large image well.-- **Allow relative `url()` and let the renderer resolve it.** Hands path- resolution back to plugin-authored content; that is precisely what the- `data:`-only rule exists to prevent.-- **Serve assets over `file://`.** No allowlist, no MIME control, and every- plugin would reach the whole filesystem the app can read.-- **Remember and restore the native background on the main side.** Requires- persisting a derived value and re-deriving it on every exit path; deriving it- from live state on each change has no state to restore.+- Raise the `data:` size cap: base64 inflation, a parse per plugin change, and renderer+ memory.+- Serve assets over `file://`: no allowlist, no MIME control, and every plugin reaches+ the whole filesystem.diff --git a/docs/adr/0249-chatgpt-style-logical-project-groups.md b/docs/adr/0249-chatgpt-style-logical-project-groups.mdindex 756ef8009..2f3a9605f 100644--- a/docs/adr/0249-chatgpt-style-logical-project-groups.md+++ b/docs/adr/0249-chatgpt-style-logical-project-groups.md@@ -2,49 +2,51 @@- Status: Accepted- Date: 2026-09-13-- Deciders: PI-Desktop maintainers- Amends: ADR 0233, ADR 0234, ADR 0016## Context-The first multi-folder project flow selected several directories but treated-every directory after the first as an independent sidebar project. That does not-match the user-facing meaning of a ChatGPT Project: one named container should-own its chats, instructions, memory, and attached sources.+The first multi-folder flow selected several directories but treated every+directory after the first as an independent sidebar project, which is not the+ChatGPT Project meaning of one named container owning its chats, instructions,+memory, and sources. Host-core still exposes one visible workspace at a time, so+a logical group cannot be built by giving the renderer a multi-root security+policy.## Decision1. A project group is a host-owned logical identity with a display name, an- ordered list of local folder roots, and a primary root.-2. Group records and group-level instructions/memory are stored through the- host-owned `kv` extension boundary.-3. Sessions created for a group continue to carry their primary project path for- compatibility.-4. The sidebar and Project archive render one row per logical group.-5. The host keeps the primary root as the default visible workspace for builtin- file tools.-6. The project overflow action is named **Edit project**.+ ordered list of local folder roots, and a primary root, which is always the+ first selected folder.+2. Group records and group-level instructions and memory live in the host-owned+ `kv` extension boundary, and existing path projects stay readable as legacy+ single-root groups, so no database reset or migration is required.+3. Sessions keep their primary project path, and the runtime resolves group+ instructions and memory from it before launching the agent.+4. The sidebar and Project archive render one row per group; expanding it shows+ all roots and the group's sessions instead of opening extra project tabs.+5. The host keeps the primary root as the default visible workspace, and a tool+ request under another registered root is canonicalized against that root;+ group membership never grants arbitrary filesystem access.+6. **Edit project** changes the group name and root list through the additive+ `project.group.update` capability, which can promote a registered root to+ primary; the primary root stays first and cannot be removed, and detaching a+ root that has chats leaves those chats as a standalone project.7. Group creation, editing, shared instruction editing, and shared memory- editing are additive IPC capabilities.+ editing are additive IPC capabilities, and path-scoped legacy APIs remain.## Consequences-- A named group behaves like one ChatGPT-style project in the UI: its chats,- instructions, and memory are shared across the selected roots.-- Existing projects retain their paths, sessions, transcripts, and renderer- presentation metadata.-- The first folder remains meaningful as the default execution root and cannot- be reordered in this iteration.-- Selecting another group still changes the one visible host workspace; a- background session remains bound to its own primary path.-- The native picker remains local-only.--## Alternatives considered--- **Keep additional folders as independent tabs:** rejected because it loses the- logical project relationship and duplicates the ChatGPT Project identity.-- **Move multi-root execution into the renderer or sidecar:** rejected because- it bypasses the host-owned filesystem and permission boundary.-- **Add a new relational schema immediately:** rejected because the existing- host `kv` extension boundary can durably store this configuration without- changing the schema version.+- A group behaves like one ChatGPT-style project, sharing chats, instructions,+ and memory across its roots.+- Existing projects keep their paths, sessions, transcripts, and presentation+ metadata.+- Selecting a group still switches the one visible host workspace, and the+ native picker stays local-only.++## Alternatives++- Keep additional folders as independent tabs: rejected, it loses the logical+ project relationship.+- Move multi-root execution into the renderer or sidecar: rejected, it bypasses+ the host-owned filesystem boundary.diff --git a/docs/adr/0250-structured-bounded-redacted-process-logs.md b/docs/adr/0250-structured-bounded-redacted-process-logs.mdindex 836501b4b..266fd5be6 100644--- a/docs/adr/0250-structured-bounded-redacted-process-logs.md+++ b/docs/adr/0250-structured-bounded-redacted-process-logs.md@@ -1,48 +1,43 @@# ADR 0250 — Structured, bounded, and redacted process logs-- **Status**: Accepted for implementation-- **Date**: 2026-09-14-- **Amends**: [ADR 0046](0046-categorized-process-logs.md) · [ADR 0212](0212-remove-diagnostic-timing-log-streams.md)-- **Related**: [Logging and observability](../spec/03-runtime/09-logging-and-observability.md)+- Status: Accepted for implementation (amends ADR 0046, ADR 0212)+- Date: 2026-09-14## Context-The categorized logger removed the old aggregate and timing streams, but its-remaining records were still too dependent on free-form messages. In particular,-a normal tool call produced separate `tool start` and `tool end` rows while-console mirroring discarded most correlation fields.+The categorized logger removed the aggregate and timing streams, but its records+leaned on free-form messages: a normal tool call produced separate start and end rows+and child stderr and error details could carry credentials, absolute local paths, or+unbounded diagnostic text.## Decision-1. Every process log record has a stable dot-separated `event` in addition to- its short human-readable `message`.-2. A normal tool execution emits one `tool.execution.completed` or- `tool.execution.failed` record after `tool_end`.-3. The Electron logger redacts sensitive object keys, authorization schemes, URL- credentials, and common provider token formats.-4. Tool results are represented by safe summaries: outcome, stable error/code- fields, duration, field names, content-block count, and stdout/stderr sizes.-5. Child stderr is emitted as a bounded, ANSI-free `data.output` value with the- stable `child.process.stderr` event.+Every record carries a stable dot-separated `event` beside its short `message`, with+correlation fields (`traceId`, `requestId`, `sessionId`, `turnId`, `toolCallId`,+parent tool call, agent, plugin, and execution IDs) kept top-level, and a normal tool+execution emits one `tool.execution.completed`, `tool.execution.failed`, or+`tool.execution.interrupted` record while `tool_start`/`tool_end` protocol events and+transcript persistence stay unchanged. The Electron logger redacts sensitive object+keys, authorization schemes, URL credentials, and provider token formats, replaces+home, application-data, and log-directory prefixes with placeholders, and bounds+string length, depth, field counts, array items, and serialized `data`, with host-core+audit payloads receiving the same treatment. Tool results appear as safe summaries —+outcome, stable error and code fields, duration, field names, content-block count, and+stdout/stderr sizes — never raw arguments, file contents, command output, or plugin+responses, and child stderr is a bounded, ANSI-free `data.output` under+`child.process.stderr`. Console mirrors carry the same sanitized record, and+production mirrors only errors.## Consequences-- Normal tool-loop storage and console noise are reduced without losing the- final outcome, identifiers, error code, or duration needed for diagnosis.-- Logs are searchable by event and correlation ID and can be joined across app,- host, and agent channels without parsing message text.-- Sensitive or unusually large diagnostic values are removed, summarized, or- truncated before writing.-- Existing protocol, transcript, audit timing fields, retention, category files,- and historical log files remain compatible.+- Tool-loop storage and console noise drop without losing outcome, identifiers, error+ code, or duration, and records join across app, host, and agent channels.+- Sensitive or oversized values are removed, summarized, or truncated before writing,+ and logging stays best-effort.+- Existing protocol, transcript, timing fields, retention, category files, and+ historical logs remain compatible.## Alternatives-- **Keep start/end records and improve their wording.** Rejected because it- preserves duplicate storage and still leaves the outcome split across rows.-- **Log complete tool arguments and results behind a debug switch.** Rejected- because local debug logs are still user data and can contain credentials or- private workspace content.-- **Add a separate timing stream for duration.** Rejected by ADR 0212; duration- is retained only as functional metadata on the relevant outcome or audit- record.+- Keep start/end rows with better wording: keeps duplicate storage.+- Log full arguments behind a debug switch: debug logs are still user data.diff --git a/docs/adr/0251-project-delete-with-owned-sessions.md b/docs/adr/0251-project-delete-with-owned-sessions.mdindex dbaca71c8..1e9143b02 100644--- a/docs/adr/0251-project-delete-with-owned-sessions.md+++ b/docs/adr/0251-project-delete-with-owned-sessions.md@@ -2,63 +2,54 @@- Status: Accepted- Date: 2026-09-15-- Deciders: PI-Desktop maintainers+- Related: ADR 0016, ADR 0026## Context-The Projects index has listed durable project records since ADR 0026 moved it-into Settings, and ADR 0016 made the sidebar a retained-tab surface. Archive,-pin, close, and ordering are deliberately renderer-local metadata: the component-contract states that "Project close removes retained tab only; durable-project/sessions remain", and `US-UI-47` states that renderer metadata never-hides or deletes a durable Project-archive row.--- `PRAGMA foreign_keys = ON` is enforced.-- A stored (non-legacy) project group owns an ordered root list and a primary- root.+Archive, pin, close, and ordering are renderer-local metadata, and the Projects+index unions durable `projects` rows with recent-project storage, projects derived+from live sessions, and the active workspace, so there was no user-facing way to+remove a durable project row. Deleting only the row would also orphan sessions+through `ON DELETE SET NULL`, and removing a stored group's primary root would+leave the group without a valid primary.## Decision-1. Host-core gains the additive RPC `projects.remove({ path })`, returning `{- removed, sessionsRemoved }`.+1. Host-core gains the additive RPC `projects.remove({ path })`, returning+ `{ removed, sessionsRemoved }`, as the only supported way to remove a durable+ project record.2. The RPC deletes the project row together with every session whose- `project_id` points at it, reusing the existing `sessions::delete_session`- path so transcript, scratch, and review files are removed exactly as they are- for a single conversation delete, and it clears the project's durable memory.-3. The RPC never touches the project's folder on disk.-4. A path that is a root of a stored multi-folder project group is refused with- a structured error.-5. Deleting is a renderer action behind a second confirmation that names the- project and the number of sessions it owns.-6. The action stays renderer-only.-7. The bulk delete is refused while any attached session has a running turn- (1008 / `CONFLICT`).+ `project_id` points at it, reusing the existing single-session delete path so+ transcript, scratch, and review files go with it, clears the project's durable+ memory, is idempotent for an unknown path, and never touches the folder on disk.+3. A path that is a root of a stored multi-folder project group is refused with a+ structured error, because the user must remove the folder from the group first+ to keep the group's primary root valid; legacy single-root projections delete+ normally.+4. The renderer deletes behind a second confirmation naming the project and its+ session count, and in the same operation drops the archived and pinned+ metadata, the recent-project entry, the retained tab, and the active workspace+ selection, falling back to another open project or Temporary.+5. The action stays renderer-only and is absent from `CONTROL_OPERATION_SPECS`, so+ local MCP control cannot delete projects.+6. A bulk delete is refused while any attached session has a running turn (1008 /+ `CONFLICT`), because that turn still owns its tools and is still appending to+ the transcript the delete would remove; the check and the deletes run in one+ host RPC under the single state lock.## Consequences-- A durable project row can finally be removed from the UI, and the row no- longer reappears after a reload, because the durable row and the- renderer-local records are removed by one action.-- Sessions and transcripts of a deleted project are gone permanently.-- Group structure is never silently rewritten.-- Composer/sidebar code that lists projects must treat the four index sources- consistently; a future index source has to be cleaned by the same action, or- the row will reappear.-- A project with a running task must be stopped before it can be deleted, which- is one extra step in that case; the alternative was deleting under a live- writer, which can resurrect a session row for the transcript the user just- removed.+- A durable project row can be removed from the UI without reappearing after+ reload, but its sessions and transcripts are gone permanently and cannot be+ recovered inside the application.+- Group structure is never silently rewritten, so multi-folder users see an+ explicit refusal instead of a corrupted group.+- Listing code must keep all four index sources consistent, and a project with a+ running task must be stopped before deletion.## Alternatives-- **Add a renderer-only "hide" flag.** Rejected: it keeps the durable row, the- sessions, and the disk usage, which is the complaint that motivated the- change, and it contradicts `US-UI-47`'s promise about renderer metadata.-- **Delete the project row and let `ON DELETE SET NULL` orphan the sessions.**- Rejected: it produces unreachable conversations that still occupy the- transcript directory and still look like a project in the index.-- **Delete the project's folder on disk too.** Rejected: an application action- must not remove user files.-- **Detach the root from a multi-folder group inside the same call.** Rejected:- root membership changes remain an explicit Edit project action, separate from- the destructive project-delete confirmation.+- Add a renderer-only hide flag: rejected because it keeps the durable row,+ sessions, and disk usage, which is the reported complaint.+- Abort running turns inside the same call: rejected because the runtime can still+ append afterwards and re-create the session as a stub (D318).diff --git a/docs/adr/0252-plugin-host-turn-end-event.md b/docs/adr/0252-plugin-host-turn-end-event.mdindex b17828cb5..8359f4a28 100644--- a/docs/adr/0252-plugin-host-turn-end-event.md+++ b/docs/adr/0252-plugin-host-turn-end-event.md@@ -2,82 +2,58 @@- Status: Accepted- Date: 2026-09-13-- Deciders: PI-Desktop core-- Related: [D422](../spec/08-meta/decisions-log.md) · [ADR 0005](0005-user-installable-plugin-system.md) · [ADR 0040](0040-plugin-resident-services-and-message-bus.md) · [ADR 0213](0213-persist-host-owned-turn-queue.md) · [ADR 0235](0235-domain-facades-and-architecture-budgets.md) · `07-plugins/03-plugin-api.md` · `07-plugins/13-plugin-permissions-matrix.md`+- Related: [D422](../spec/08-meta/decisions-log.md) ·+ [ADR 0005](0005-user-installable-plugin-system.md) ·+ [ADR 0040](0040-plugin-resident-services-and-message-bus.md) ·+ [ADR 0213](0213-persist-host-owned-turn-queue.md) ·+ [ADR 0235](0235-domain-facades-and-architecture-budgets.md) ·+ `07-plugins/03-plugin-api.md`## Context-A plugin that drives a GUI — a notification surface, a launcher, a work-panel-view — can already observe `workspace:changed`, `plugin:settingsChanged`, and-`session:modelChanged`, but nothing told it when the host turn it was reacting-to had actually finished. Plugins fell back to idle timers, which are wrong in-both directions: they fire during a long tool call, and they fire again for a-turn that ended moments earlier.+A plugin driving a notification surface, launcher, or work-panel view could+observe `workspace:changed`, `plugin:settingsChanged`, and+`session:modelChanged`, but nothing told it when the turn it reacted to had+finished, so plugins fell back to idle timers that fire during a long tool call+and again for a turn that already ended. The host already resolves the durable+`session.endTurn` row for the turn created by `session.beginTurn`; what was+missing was a published identity and boundary, since the plugin tool context+declared `turnId` but the host never populated it.## Decision-1. **`session:turnEnded` is a host event.** Payload is `{ sessionId: string;- turnId: string; reason: "completed" | "aborted" | "error" }`, delivered to- plugin processes exactly like `workspace:changed` and `session:modelChanged`,- and (like `workspace:changed`) to plugin panel pages and docked views.--2. **Once per turn actually started.** The event is emitted at the end of turn- teardown, after the durable `session.endTurn` attempt, and only for a turn- created by `session.beginTurn`: a user submission, an approved plan- execution, or a scheduled run.--3. **Turn identity is authoritative.** The finalizer is called with an explicit- `turnId` and never infers one from whichever turn happens to be active, so a- late terminal event from an earlier turn cannot settle a newer one, and a- terminal event carrying no identity settles nothing at all.-+1. **`session:turnEnded` is a host event.** Payload is+ `{ sessionId: string; turnId: string; reason: "completed" | "aborted" | "error" }`,+ delivered to plugin processes like `workspace:changed` and+ `session:modelChanged`, and also to plugin panel pages and docked views.+2. **Once per turn actually started.** It is emitted at turn teardown after the+ durable `session.endTurn` attempt and only for a turn created by+ `session.beginTurn`, so a queued item that never started produces no event+ and a second terminal event joins the first claim.+3. **Turn identity is authoritative.** The finalizer receives an explicit+ `turnId` and never infers one from the active turn, so a late terminal event+ from an earlier turn cannot settle a newer one; plugin tool contexts carry+ the same `turnId` unchanged.4. **No new permission.** The event travels on the existing plugin event channelto every loaded plugin, and subscribing to an unknown event name does noterror.-Explicit non-promises: there is no ack and no replay. The host broadcasts once-per started turn; a plugin that is alive and subscribed receives it once.+There is no ack and no replay: the host broadcasts once per started turn, so+delivery racing a plugin crash, reload, or host quit is not guaranteed, and+receiving the event does not mean every in-flight tool of that turn has exited.## Consequences- Plugins settle turn-scoped UI, notifications, and bookkeeping from the host'sown terminal state instead of guessing with idle timers.-- The event bounds the turn, not the individual tool calls, so a plugin must- still treat late tool results as valid.-- The announcement is one call made from one finalizer that validates turn- identity, requires no `await` before it claims the turn, and runs after the- local teardown.-- Turn-scoped cleanup that ignores `turnId` can settle the wrong turn; the tool- context's `turnId` now makes correct scoping possible.-- No published release emits this event yet: the first release that contains it- has not shipped, and 0.14.8 does not include it.+- The event bounds the turn, not individual tool calls, so late results stay+ valid and cleanup must be scoped by `turnId`.+- A plugin that depends on the event must require the first release that ships+ it, not 0.14.7 or 0.14.8.## Alternatives rejected-### Poll a session API for the active turn--Reading session state on a timer would need `session.read`, would hand a plugin-the conversation it does not otherwise see, and would still leave the end-boundary to guesswork — the event carries no more than the identity and reason-the host already owns.--### Release the plugin per invocation--Unloading a plugin when its turn ends ties turn end to a lifecycle event that-also has to survive reload, crash, and quit, and would drop the resident-services and panel state a plugin holds across turns.--### Raise the idle timeout--A longer silence threshold detects turn end later and still cannot distinguish-"a tool is thinking" from "the turn is over"; it also delays exactly the-completion signal a GUI plugin exists to deliver.--## References--- `apps/desktop/electron/main/runtime/plans.ts` — `finishTurn`, the single- teardown entry every terminal path funnels through-- `apps/desktop/electron/main/runtime/session-coordination.ts` — turn identity,- the abort lock, and the shared busy check-- `apps/desktop/electron/main/services/plugin-services.ts` — `announceTurnEnded`-- `apps/desktop/electron/main/plugin-runtime.ts` — `broadcastEvent`+- Poll a session API for the active turn: it needs `session.read`, exposes the+ conversation, and still leaves the end boundary to guesswork.+- Raise the idle timeout: it detects turn end later and still cannot tell a+ thinking tool from a finished turn.diff --git a/docs/adr/0253-remove-subagent-turn-limit.md b/docs/adr/0253-remove-subagent-turn-limit.mdindex 5777bf584..a5966c6b7 100644--- a/docs/adr/0253-remove-subagent-turn-limit.md+++ b/docs/adr/0253-remove-subagent-turn-limit.md@@ -2,66 +2,59 @@- Status: Accepted- Date: 2026-09-15-- Deciders: PI-Desktop core-- Related: D423, ADR 0062, ADR 0063, ADR 0089, ADR 0119, ADR 0126, ADR 0166,- ADR 0189, ADR 0210, `03-runtime/02-agent-runtime.md` §5f,- `04-ux/06-settings-ia.md` §7, E2E-155,- E2E-SUBAGENT-legacy-turn-limit-frontmatter-is-ignored+- Related: ADR 0062, ADR 0063, ADR 0089, ADR 0119, ADR 0126, ADR 0166,+ ADR 0189, ADR 0210, D328, D423- Supersedes: the `maxTurns` clauses of ADR 0062, ADR 0063, ADR 0119, ADR 0126,ADR 0166, and ADR 0210. Historical ADR files are retained. This record removesthe field those records described; it does not change their other clauses.## Context-ADR 0062 introduced subagents as bounded workers and gave a definition a-`maxTurns` frontmatter cap. ADR 0119 made the key optional — omission, `none`-and `0` meant unlimited, and an explicit value was clamped to 80.+ADR 0062 gave a definition a `maxTurns` cap, later made optional and clamped, and+ADR 0166 kept it as the last definition-level kill switch. The parent cannot see a+delegate's live work, so it cannot distinguish a delegate one turn from converging+from one that never will, which leaves no honest cap but "large enough". Reaching+the cap killed a delegate mid-task as `truncated` with a partial report that+neither the user nor the parent model could resume.## Decision-1. **Delete the mechanism.** A delegate has no turn limit.-+1. **Delete the mechanism.** A delegate has no turn limit; it ends when it+ finishes, when the parent calls `TaskStop`, when the user Stops, or when a+ terminal parent error aborts it, and there is no `truncated` outcome or+ turn-related termination path.2. **Remove `maxTurns` from the contract.** The field leaves- `SubagentDefinition`, the frontmatter parser and its invalid/clamped- warnings, `MAX_SUBAGENT_MAX_TURNS`, `UserSubagentRecord` /- `UserSubagentInput`, the host-core registry (record, input, frontmatter- parse, document render, `MAX_TURNS_CEILING`), the five built-in documents,- `SUBAGENT_PRESETS`, and the Subagent editor's Advanced disclosure.--3. **Legacy documents keep loading.** `maxTurns`, `max-turns` and `max_turns`- become unrecognized frontmatter keys and are ignored exactly like every other- unknown key: no error, no warning, the definition still resolves, and nothing- rewrites the user's file.--4. **Remove the `truncated` status.** `SubagentRunStatus` drops it, and the- renderer's `SubagentOutcome` union, the `chat.subagentStatus` catalog entry- in every locale, and the delegation topology's "finished with warnings" count- drop it with it.-+ `SubagentDefinition`, the frontmatter parser and its warnings, the shared+ subagent types, the host-core registry, the built-in documents, the presets,+ and the Subagent editor's Advanced disclosure, while the host-core input+ struct keeps ignoring unknown fields.+3. **Legacy documents keep loading.** `maxTurns`, `max-turns`, and `max_turns`+ become unrecognized frontmatter keys that are ignored like any other, so a+ definition that declared a cap loses it silently and nothing rewrites the+ user's file.+4. **Remove the `truncated` status.** It leaves `SubagentRunStatus`, the+ renderer outcome union, the localized status catalog, and the topology's+ warning count, while `timed_out` stays in the type because no other record+ withdraws it.5. **No protocol and no schema change.** `PROTOCOL_VERSION` stays 11 and- `SCHEMA_VERSION` stays 16.+ `SCHEMA_VERSION` stays 16, older renderers sending the field are tolerated,+ and no column ever stored the cap.## Consequences-- A looping delegate now runs until the user Stops it, or the parent calls- `TaskStop`.-- Existing user documents that relied on the cap lose it without a prompt.-- Settings no longer offers a "no limit" spelling for turns because there is no- limit left to express.-- The built-in definitions lose one frontmatter line each and no longer carry a- number that had no derivation.-- E2E-155 steps and the topology's warning count change with the status and the- built-in backstops.--## Alternatives rejected--- **Raise the ceiling, or make every builtin unlimited.** Keeps a knob that- cannot be set correctly, keeps the `truncated` state and its user-visible- copy, and still kills a delegate mid-task at an arbitrary point.-- **Keep parsing the key and warn on it.** Unknown frontmatter keys are already- ignored silently, so a warning would make `maxTurns` the only key with a- special diagnostic while the definition still ignored it.-- **Keep the field and never enforce it.** A contract field that does nothing is- worse than no field: the editor would keep offering it, the settings API would- keep round-tripping it, and `truncated` would stay in the status union as dead- surface the UI must still render.+- A looping delegate runs until the user Stops it or the parent calls+ `TaskStop`, which is the exposure every definition omitting `maxTurns` already+ had.+- Existing documents lose their cap without a prompt; the stopping condition+ belongs in the prompt body, where a delegate already reads when its work is+ done.+- Settings and the built-in documents drop the field, and callers must treat the+ legacy frontmatter keys as silently ignored.++## Alternatives++- Raise the ceiling or keep the field unenforced: rejected because it preserves a+ knob that cannot be set correctly, plus a dead contract surface.+- Warn on the legacy key: rejected because unknown frontmatter keys are already+ ignored silently, and `idle-timeout` / `max-duration` differ, since those keys+ still exist and are merely unarmed.diff --git a/docs/adr/0254-native-pi-session-continuation.md b/docs/adr/0254-native-pi-session-continuation.mdindex c231c1477..8fb9329e5 100644--- a/docs/adr/0254-native-pi-session-continuation.md+++ b/docs/adr/0254-native-pi-session-continuation.md@@ -7,62 +7,95 @@## Context-PI-Desktop historically imports Pi sessions by flattening them into-Desktop-owned transcripts. That copy cannot preserve the native tree,-compaction, custom entries, or receive turns subsequently sent from either-application.+PI-Desktop historically imported Pi sessions by flattening them into+Desktop-owned transcripts, which preserves neither the native tree, compaction,+and custom entries nor the ability to accept turns sent later from either+application. The coding-agent SDK already owns the v3 session format and the+native model, auth, and resource lifecycle.## Decision-1. The Node agent sidecar exposes a source-discriminated `pi-native` adapter.-2. Native identity is an opaque composite derived from canonical file path plus- native header id.-3. Native continuation uses `createAgentSession` with Pi `ModelRuntime`,- `SettingsManager`, `DefaultResourceLoader`, saved provider/model/thinking,- and the original `SessionManager`.-4. The first slice supports list, detail, refresh, text-only Agent prompt with- no tools (`noTools: "all"`), stop, and renderer-local pin/archive.-5. A cooperative sidecar lease serializes PI-Desktop writers.-6. Version other than exactly v3, a missing trailing newline, missing cwd,- unavailable saved provider/auth, untrusted project resources, corrupt+1. The Node agent sidecar exposes a source-discriminated `pi-native` adapter that+ discovers files below Pi's agent session directory and below each+ `sessionDir` Pi resolves, projects immutable byte snapshots through+ `SessionManager.inMemory`, and opens a persistent `SessionManager` only when a+ prompt is accepted.+2. Native identity is an opaque composite of canonical file path and native+ header id, and paths never cross the preload boundary; Electron merges native+ summaries with Rust-owned Desktop summaries, while Rust stays the exclusive+ SQLite and Desktop-transcript owner.+3. Continuation uses `createAgentSession` with Pi `ModelRuntime`,+ `SettingsManager`, `DefaultResourceLoader`, the saved provider, model, and+ thinking level, and the original `SessionManager`, with no Desktop provider+ fallback and no `UiMessage` reconstruction.+4. The slice covers list, detail, refresh, a text-only Agent prompt without tools+ (`noTools: "all"`), stop, and renderer-local pin/archive, with fork and side+ chat added by the amendments; rename, delete, move, revision, Plan/Goal,+ queue, collaboration, attachment, and transcript rewrite stay rejected.+5. A cooperative sidecar lease serializes Desktop writers: the adapter verifies+ canonical file identity and full-byte fingerprint before each SDK append and+ that exactly one expected line with the right entry and parent was added+ after it, failing closed on divergence. A stale lease is reclaimed only for a+ dead local PID whose target is unchanged or a complete append-only+ extension, and live, remote, malformed, or uncertain ownership is never+ stolen.+6. Any version other than exactly v3, a missing trailing newline, missing cwd,+ unavailable saved provider or auth, untrusted project resources, corruptidentity, or another live lease keeps the session browseable and read-only- with an explicit reason.+ with an explicit reason, and projection never repairs or migrates the source.## Consequences-- Desktop sessions and their host-owned persistence are unchanged.-- Native branches, compaction data (including unknown fields such as- `retainedTail`), custom/context messages, and future unknown entries remain- untouched because reads are in-memory and writes are SDK append-only.-- With the 0.87.1 coding-agent pin, `context_edit` entries are append-only and- affect only the SDK's future model-context projection.-- An uncooperative writer can still race within the OS append operation.-- `@earendil-works/pi-coding-agent` is a runtime dependency of the bundled- sidecar and its session format behavior is version-pinned.+- Native branches, compaction data, custom and context messages, and unknown+ entries survive untouched because reads are in memory and writes are SDK+ append-only, with `context_edit` entries covered by the same lease and+ parent-chain guard.+- Native compact and session-addressed queue push/list fail with+ `NATIVE_PI_UNSUPPORTED` before host access, so a native path never creates a+ host queue entry.+- An uncooperative Pi writer can still race inside the OS append; the adapter+ detects the divergence, preserves bytes, and requires a reload, so full mutual+ exclusion needs every Pi client to adopt the lease protocol.## Amendment: native side-chat forks (2026-09-14)-The `sidechat:` panel and tab described in this amendment were removed by ADR-0268; the `session.fork` capability they routed to remains in place and is used-by the Fork action.+The `sidechat:` panel and tab described here were removed by ADR 0268; the+`session.fork` capability they routed to remains and is used by the Fork action.-`session/fork` is now source-discriminated. Desktop sources keep the existing-Rust `session.fork` contract; `native-pi:` sources route to a sidecar-`native.session.fork`, which returns the child as an ordinary `SessionDetail`.+`session/fork` is source-discriminated: Desktop sources keep the Rust+`session.fork` contract, while `native-pi:` sources route to a sidecar+`native.session.fork` that returns the child as an ordinary `SessionDetail`, and+the renderer never supplies or receives a file path. A native fork branches the+parent snapshot through the SDK (`createBranchedSession`), so ancestry, label+re-chaining, compaction re-parenting, and unknown entries follow SDK rules. The+child is a new v3 JSONL in the parent's session directory whose header+`parentSession` points at the canonical source path, published by writing a+complete temporary file and hardlinking it after verifying the staged inode and+content hash. A failed fork exposes no partial child, clobbers nothing, and+removes only files this operation wrote; an altered staging or published file+fails closed with `NATIVE_PI_SESSION_CHANGED` and its bytes are preserved.++A child with no saved model records the parent session's saved provider and+model, and with no saved thinking change the parent's level, while an explicit+branch value including "off" always wins. Forking is a data-only copy that+executes no model and loads no project resources, so it stays allowed while the+parent is provider-unavailable or project-untrusted without granting prompt+readiness.## Amendment: configured sessionDir discovery (2026-10-18)-Pi writes a session into `sessionDir` when that setting is present in global-`~/.pi/agent/settings.json` or in `<cwd>/.pi/settings.json`. Desktop history-must discover and open those files with the same resolution the CLI uses, in-addition to the default agent session root (`<agentDir>/sessions`).+Pi writes a session into `sessionDir` when that setting appears in global+`~/.pi/agent/settings.json` or `<cwd>/.pi/settings.json`, and Desktop history must+discover those files with the same resolution the CLI uses, in addition to the+recursive default root `<agentDir>/sessions`.-- The default root stays a recursive scan, so sessions written before a custom- directory remain visible.-- An absolute or `~` global `sessionDir` is scanned even when no project is- known.-- Custom directories are scanned non-recursively, matching Pi's flat `*.jsonl`- layout.-- Detail, prompt, and fork authorize the file against the default root, the- session directories for the current project list, and any session directory- that already admitted a file.+- An absolute or `~` global `sessionDir` is scanned without a known project,+ while a relative value resolves from each known local project working+ directory rather than the Desktop process cwd; remote project ids are ignored.+- Custom directories are scanned non-recursively as Pi's flat `*.jsonl` layout,+ and a file is admitted only when its real path stays inside the default root or+ a resolved `sessionDir`, so symlink escapes are dropped.+- Detail, prompt, and fork authorize a file against the default root, the session+ directories of the current project list, and any directory that already+ admitted it; a fork publishes the child beside its parent, and trust and+ provider gates still follow the session header cwd.diff --git a/docs/adr/0255-theme-assets-by-absolute-path.md b/docs/adr/0255-theme-assets-by-absolute-path.mdindex fdc32b3bb..0ea55f388 100644--- a/docs/adr/0255-theme-assets-by-absolute-path.md+++ b/docs/adr/0255-theme-assets-by-absolute-path.md@@ -1,63 +1,47 @@# ADR 0255: Theme assets are absolute paths-- Status: Accepted+- Status: Accepted (supersedes ADR 0248 §1 for asset path resolution)- Date: 2026-09-15-- Decision: D422-- Supersedes: ADR 0248 §1 for asset path resolution; the scheme, the `url()`- rewrite, the extension whitelist, the size budget, and the unload revocation- carry over unchanged.+- Related: D422, ADR 0248## Context-ADR 0248 let a theme reference plugin package bytes:-`contributes.themes[].assets` listed package-relative paths, the host resolved-them inside the plugin package, and each matching `url()` was rewritten to-`plugin-asset://`.--- A plugin that wants a user-chosen image has to copy it into its own package.-- The plugin's own data directory — `pi.plugin.getDataPath()`, the one writable- area a plugin owns outside its package — cannot be referenced at all.+ADR 0248 let a theme reference plugin package bytes: `contributes.themes[].assets`+listed package-relative paths and each matching `url()` was rewritten to+`plugin-asset://`. A plugin wanting a user-chosen image therefore had to copy it into+its own package, where the recursive development watcher reloaded the plugin and closed+its panel window, and the plugin's own data directory — `pi.plugin.getDataPath()` — could+not be referenced at all. Plugins already run as ordinary Node processes with full+filesystem access, so package scope constrained what theme CSS text reached, not what a+plugin could read.## Decision-1. A theme asset is an **absolute path**: `C:/art/bg.png`, `/art/bg.png`, or- either spelled as a `file:` URL.-2. Both authorization routes accept absolute paths:- - `contributes.themes[].assets` — load-time, auditable in the manifest;- - `pi.themes.upsert({ id, label, base, css })` — the runtime route now- resolves asset references in the sheet and registers them in that plugin's- asset map for as long as the plugin stays loaded.-3. Everything else about the mechanism is unchanged: the extension whitelist- (`png`, `jpg`, `jpeg`, `webp`, `avif`, `svg`, `woff2`), the summed 4 MB- budget for declared assets, `.`/`..` rejection, the `url()` →- `plugin-asset://` rewrite, `nosniff`, `no-store`, and revocation when the- plugin unloads.-4. Absolute keys are percent-encoded in the `plugin-asset://` URL- (`themeAssetUrl`) and decoded by the handler, so spaces, `?`, `#`, and the- drive colon cannot be re-read as anything but a path.-5. The handler serves what the plugin registered: a path from its manifest, or a- path its own sanitized sheet referenced through an upsert.+A theme asset is an absolute path (`C:/art/bg.png`, `/art/bg.png`, or either as a+`file:` URL), and `normalizeThemeAssetPath` in the SDK and `normalize_theme_asset_path`+in host-core reject package-relative references. Both authorization routes accept them:+`contributes.themes[].assets` at load time, auditable in the manifest, and+`pi.themes.upsert({ id, label, base, css })`, where the runtime resolves asset+references in the sheet and registers them in that plugin's asset map while it stays+loaded, so a theme picks up a new image without a reload. The rest of the mechanism is+unchanged: the `png`, `jpg`, `jpeg`, `webp`, `avif`, `svg`, `woff2` whitelist, the summed+4 MB budget, `.`/`..` rejection, the `url()` rewrite, `nosniff`, `no-store`, and+revocation on unload. Absolute keys are percent-encoded by `themeAssetUrl` and decoded by+the handler, which serves only what the plugin registered — a manifest path or one its+own sanitized sheet referenced through an upsert.## Consequences-- A plugin can hand the renderer **any local file it can read**, as an image or- a font.-- The extension whitelist still bounds what may be served, the size budget still- bounds declared assets, and an unregistered reference is still refused.-- Because a theme may point at the plugin's data directory, a development plugin- no longer reloads when the user picks or replaces an image: the upload writes- into `getDataPath()/images/`, and the theme reaches it through an upsert.-- Themes that declared package-relative assets stop resolving.-- The plugin devkit (`pi-plugin check`) rejects package-relative theme assets at- author time with the `theme.asset-package-relative` diagnostic, preventing a- package from passing validation only to fail installation on every user's- machine.--## Alternatives considered--- **Allow both spellings.** Rejected: the owner chose an absolute-only rule, and- keeping two resolutions for one concept invites exactly the confusion this- change removes.-- **Add only the plugin data directory as a second root.** Narrower, but it does- not cover a file the user picked outside the data directory without a copy- step, and the runtime route would still have no way to authorize it.+- A plugin can hand the renderer any local file it can read as image or font, so a theme+ can name a file the user never chose; manifest assets keep a static audit trail,+ runtime-registered ones have none and vanish with the plugin.+- The whitelist, budget, and unregistered-reference refusal still bound what is served.+- Themes with package-relative assets stop resolving, a deliberate breaking change that+ `pi-plugin check` reports as `theme.asset-package-relative`; `resolveInsidePlugin`+ remains for `contributes.themes[].path`.++## Alternatives++- Allow both spellings: two resolutions for one concept invite the same confusion.+- Add only the plugin data directory as a second root: does not cover a file picked+ outside it without a copy step.diff --git a/docs/adr/0256-deepseek-reasoning-across-compaction.md b/docs/adr/0256-deepseek-reasoning-across-compaction.mdindex 8ea020c40..671954129 100644--- a/docs/adr/0256-deepseek-reasoning-across-compaction.md+++ b/docs/adr/0256-deepseek-reasoning-across-compaction.md@@ -2,7 +2,6 @@- Status: Accepted- Date: 2026-09-15-- Deciders: PI-Desktop core- Amends: D389 / ADR 0136 / ADR 0064- Fixes: #296- Amended by: D677 (#1945) — decision 3 now normalizes every row to the@@ -11,37 +10,41 @@## ContextDeepSeek thinking mode requires every replayed Completions assistant message to-carry a reasoning field (`reasoning_content`, or `reasoning_text` / `reasoning`-on some relays). Official `deepseek.com` endpoints accept `""` for turns that-produced no thinking (D389 / #223).+carry a reasoning field (`reasoning_content`, or `reasoning_text` / `reasoning` on+some relays). Official endpoints accept `""` for a turn that produced no thinking+(D389 / #223), while OpenCode and third-party relays reject empty echoes with HTTP+400, and Codex-shaped compaction (ADR 0064 / ADR 0136) drops the assistant turns+that carried thinking.## Decision1. History rebuild stamps `thinkingSignature: "reasoning_content"` only for- DeepSeek-compatible OpenAI Completions rows.-2. Checkpoints for models with `requiresReasoningContentOnAssistantMessages`- store the last few thinking turns in opaque `details.retainedReasoning` (text- + thinking only, no tool calls).-3. The pi-ai patch backfills the reasoning field already present on the history- (`reasoning_content` | `reasoning_text` | `reasoning`).-4. ADR 0136 retained-tail rules are unchanged: user-only tails, no tool-call- replay.-5. Amendment (D677, #1945): the field is taken from the newest assistant row- that has real reasoning, not from fixed list order.+ DeepSeek-compatible OpenAI Completions rows; other APIs keep unsigned thinking so+ pi-ai preserves their plain-text fallback.+2. Checkpoints for models with `requiresReasoningContentOnAssistantMessages` store+ the last few thinking turns in opaque `details.retainedReasoning`, and session+ context injects them between the compaction summary and the user tail only for+ the live DeepSeek-compatible binding.+3. The pi-ai patch backfills the reasoning field already present on the history,+ keeping empty-string fill for official DeepSeek URLs while non-official rows set+ `requiresNonEmptyReasoningReplay` and receive the placeholder+ `[reasoning not retained for this turn]`.+4. ADR 0136 retained-tail rules are unchanged: user-only tails, no tool-call replay.+5. Amendment (D677, #1945): the field is taken from the newest assistant row with+ real reasoning and every row is normalized to it, so real reasoning under another+ name moves there and the placeholder fills only rows with none.## Consequences-- Post-compaction DeepSeek requests on OpenCode / aggregators keep real or- placeholder reasoning and no longer 400 on empty echoes.-- Official DeepSeek and #223 empty-backfill behaviour remain available.-- Checkpoint `details` grow by a bounded reasoning excerpt; the visible- transcript and host schema do not change.-- Unit tests cover convertMessages + compaction retained-reasoning wire shape.+- Post-compaction DeepSeek requests through OpenCode and aggregators keep real or+ placeholder reasoning instead of failing on an empty echo.+- Official DeepSeek empty backfill keeps working, and checkpoint `details` grow only+ by a bounded reasoning excerpt.+- The visible transcript and host schema do not change.## Alternatives-- Degrade to non-thinking mode after the 400: avoids the echo requirement but- loses reasoning for that turn and hides the compaction gap.-- Put full assistant/tool messages back in `retainedTail`: preserves reasoning- but reintroduces stranded tool calls and weakens the task boundary (rejected- by ADR 0136).+- Degrade to non-thinking mode after the 400 — rejected: it loses reasoning and+ hides the compaction gap.+- Put full assistant and tool messages back in `retainedTail` — rejected: it+ reintroduces stranded tool calls.diff --git a/docs/adr/0257-plugin-real-time-capabilities.md b/docs/adr/0257-plugin-real-time-capabilities.mdindex eba948c3a..5b05168f2 100644--- a/docs/adr/0257-plugin-real-time-capabilities.md+++ b/docs/adr/0257-plugin-real-time-capabilities.md@@ -1,68 +1,53 @@# ADR 0257: Host-mediated real-time capabilities for plugins-## Status--Accepted for implementation.+- Status: Accepted for implementation## Context-A plugin that wants to behave like an always-on voice assistant needs four-capabilities the plugin runtime does not offer today. Each one would otherwise-force a plugin out of the host's control:--- `ui.microphone` grants a *visible* plugin surface an audio-only `media`- permission inside its own Chromium session.-- `globalShortcut` is used in exactly two places, both owned by the app- (`bootstrap/launcher.ts`), with a Windows low-level hook as the fallback for- `Alt+Space` in host-core.-- `pi.net.fetch` is confined to `manifest.net.domains` but carries one request- and one response; it cannot hold a long-lived frame stream.-- The plugin host process is a Node `utilityProcess`; the plugin itself runs- inside that process.+An always-on voice-assistant plugin needs audio capture and playback, global+shortcuts, and sockets, and each would otherwise force it out of host control:+`ui.microphone` needs a visible panel, `globalShortcut` is app-owned, `pi.net.fetch`+carries one request and one response, and the plugin host's Node `utilityProcess`+broker contract is not a sandbox.## Decision-1. Four permissions are added additively: `audio.capture.background` (high),- `audio.playback.background` (medium), `keyboard.globalShortcut` (medium),- `net.websocket` (high).--2. Devices and transports are host-owned.--3. System-wide shortcuts stay inside the host's registration model.--4. `net.websocket` connects are confined by the same `manifest.net.domains`- allowlist and the same `assertEgress` chokepoint as `pi.net.fetch`.--5. Fail closed, and release on every exit path.--6. The host bounds every stream: one input stream per plugin, a bounded frame- queue with backpressure and dropped-frame accounting, bounded send and- receive buffers, a maximum frame size, and a maximum socket count.--7. Audit records the operations that change authority — open and close of an- input, open, stop and close of an output, shortcut register and unregister,- socket connect and close — with plugin id, operation, result, and timestamp.--8. Existing Control semantics are unchanged.--9. Delivery is staged under this single decision.+Four additive permissions arrive — `audio.capture.background` (high),+`audio.playback.background` (medium), `keyboard.globalShortcut` (medium), and+`net.websocket` (high) — with `ui.microphone` keeping its panel-scoped meaning.+Devices and transports stay host-owned: plugins exchange typed frames (PCM16 in and+out, text and binary) through host APIs, and no `MediaStream`, device handle, Node+stream, socket object, or native handle crosses the boundary. Shortcuts stay inside the+host registration model, where a plugin declares `contributes.globalShortcuts` (at most+8, one accelerator to one of its own commands) and adjusts the set through+`pi.keyboard.*`, and registration is refused rather than taken over with+`SHORTCUT_CONFLICT`, `SHORTCUT_UNAVAILABLE`, `INVALID_ACCELERATOR`, or+`LIMIT_EXCEEDED`, never by monitoring keys or installing a hook. `net.websocket`+connects obey the same `manifest.net.domains` allowlist and `assertEgress` chokepoint as+`pi.net.fetch`, and every exit path — deny, disable, unload, crash, revocation, app+exit — releases capture, queued playback, sockets, and accelerators with no orphan+device, listener, or timer. The host bounds every stream (one input stream per plugin, a+bounded frame queue with dropped-frame accounting, bounded buffers, a maximum frame size+and socket count) and audits authority-changing operations with plugin id, operation,+result, and timestamp, never audio bytes, message bodies, headers, tokens, or keys.+Delivery is staged: permission plumbing plus the full `keyboard.globalShortcut` and+`net.websocket` runtime ship first, while `pi.audio` gates, audits, and answers+`UNSUPPORTED` until a device service exists.## Consequences-- The plugin surface grows by four permissions and three host API namespaces- (`pi.audio`, `pi.keyboard`, `pi.net.websocket`).-- Background audio adds a second audio path to the app that is not the- renderer's own playback.-- A signed macOS build cannot capture audio until the microphone usage string- and the audio-input entitlement are added to packaging; background playback- works without them.-- Because the plugin process is a Node process, these permissions govern what- the host *provides* and audits, not what the process could technically reach.+- The surface grows by four permissions and three namespaces, so the permission+ matrix, install copy in every locale, devkit checks, and both validators must stay in+ sync.+- Background audio is a second non-renderer audio path that must stay off the main+ thread, and a signed macOS build cannot capture audio without the microphone usage+ string and audio-input entitlement.+- These permissions govern what the host provides and audits, not what the Node process+ can reach: the sandbox remains a contract, not a kernel boundary.## Alternatives-- Hand plugins a `MediaStream` or a Node stream.-- Keep an invisible panel alive to own the audio.-- Move voice into a dedicated sidecar process.-- Reach system-wide shortcuts through a low-level keyboard hook on every- platform.+- Hand plugins a `MediaStream` or Node stream: authority the host cannot bound, audit,+ or release.+- Use a low-level keyboard hook: that is the keylogger-shaped surface the security model+ forbids.diff --git a/docs/adr/0258-trusted-extension-custom-agents.md b/docs/adr/0258-trusted-extension-custom-agents.mdindex 3dc7a85ac..84770e5da 100644--- a/docs/adr/0258-trusted-extension-custom-agents.md+++ b/docs/adr/0258-trusted-extension-custom-agents.md@@ -7,46 +7,40 @@## Context-Trusted extensions run beside the Agent runtime and are the appropriate surface-for providers that cannot be represented by a built-in pi-ai adapter. Issue #401-asks for model selection and custom agent/provider registration so a plugin can-integrate services such as Command Code with its own endpoint and authentication-flow.+Trusted extensions run beside the Agent runtime and are the right surface for+providers no built-in pi-ai adapter can represent (issue #401, e.g. Command Code with+its own endpoint and auth). The pinned pi-coding-agent API has `registerProvider` but+no `registerAgent`, and its registry assumes coding-agent-owned credentials and model+persistence, which would bypass the product's session binding and secret ownership.## Decision-1. Add a PI-Desktop `registerAgent` ExtensionAPI member.-2. Keep the registration in the Agent sidecar.-3. Use namespaced `extension-agent:<encoded-agent-key>` provider ids.-4. Expose a read-only model registry projection to the extension context.-5. `registerProvider` accepts the same plugin-owned streaming shape as a- compatibility alias.-6. Registration is session-scoped and is removed with the runtime.+1. Add a `registerAgent` ExtensionAPI member: an id, bounded model metadata, and+ either a `stream` or `complete` implementation, with the plugin owning endpoint,+ authentication, request serialization, and response conversion.+2. Register inside the Agent sidecar. The host receives only the opaque provider+ id/model id and persists the binding through `session.configure`, so registration+ is session-scoped, removed with the runtime, and limited to trusted extensions+ holding the high-risk `agent.extension` grant.+3. Use namespaced `extension-agent:<encoded-agent-key>` provider ids: later turns pass+ the binding as a placeholder provider, and the sidecar reloads the extension and+ reactivates that implementation.+4. Expose a read-only model registry projection — models and auth availability, never+ host API keys, secret refs, OAuth tokens, provider headers, or internals.+5. `registerProvider` accepts the same plugin-owned streaming shape as a compatibility+ alias, and the host writes no provider registration into the Host database or+ global defaults.## Consequences-- Command Code and similar integrations can implement their own auth and wire- protocol without an app release or a new Rust transport.-- Session model selection remains host-owned and observable through the existing- `session:modelChanged` event.-- Custom agent definitions are not visible in the ordinary provider Settings- picker; a plugin may expose its own command or UI to select them.-- Trusted extension code has sidecar-level authority by design.-- The public ExtensionAPI contract is PI-Desktop-specific for `registerAgent`;- upstream pi API upgrades must preserve the adapter contract or add a- compatibility translation.+- Similar integrations ship their own auth and wire protocol without an app release or+ new Rust transport, while model selection stays host-owned and observable through+ `session:modelChanged`.+- Custom agents stay out of the ordinary provider Settings picker, and `registerAgent`+ being PI-Desktop-specific means upstream pi upgrades must preserve or translate it.-## Alternatives considered+## Alternatives-### Expose pi-coding-agent ModelRegistry directly--Rejected: it exposes credential resolution and assumes pi's persistence model.--### Add every custom provider to Rust/SQLite--Rejected: the plugin owns the implementation and credentials, while Host storage-must not persist opaque plugin transport code or secrets.--### Register an executable subagent instead--Deferred to a separate API.+- Expose `ModelRegistry` directly: it leaks credential resolution.+- Write custom providers into Rust/SQLite: the plugin owns them.+- Register an executable subagent: deferred; this covers LLM transport only.diff --git a/docs/adr/0259-plugin-declared-providers.md b/docs/adr/0259-plugin-declared-providers.mdindex 2c1459526..45dacd641 100644--- a/docs/adr/0259-plugin-declared-providers.md+++ b/docs/adr/0259-plugin-declared-providers.md@@ -3,70 +3,67 @@- Status: Accepted for implementation- Date: 2026-09-15- Decision: D427-- Related: ADR 0011, `07-plugins/02-plugin-manifest-schema.md`, `07-plugins/13-plugin-permissions-matrix.md`, `03-runtime/04-data-storage.md`, `03-runtime/12-provider-config-schema.md`+- Related: ADR 0011, ADR 0320, `07-plugins/02-plugin-manifest-schema.md`,+ `07-plugins/13-plugin-permissions-matrix.md`, `03-runtime/12-provider-config-schema.md`## Context-A plugin that integrates an LLM service has two surfaces today: an agent tool,-or a session-scoped agent implementation registered through the-trusted-extension API (ADR 0258). Neither puts the service in the native-provider list, so the user cannot select it for a session and the plugin ends up-keeping a private provider registry beside the Host's one.+A plugin integrating an LLM service can offer an agent tool or a session-scoped+agent implementation (ADR 0258); neither puts the service in the native provider+list, so the plugin keeps a private provider registry beside the Host's. The Host+owns provider rows, credentials, the model catalog cache, and the Settings list,+and duplicating that state would give one service two identities and hide it from+the surface that manages every other endpoint.## Decision-1. Add `contributes.providers[]` to the plugin manifest.-2. The Host materializes each declaration as a real row in `providers`, not in a- plugin-side registry.+1. Add `contributes.providers[]` to the plugin manifest, shaped per the manifest+ schema §5.4: `id`, required `name`, optional `vendorKey`, `baseUrl`,+ `apiStyle`, `authKind`, and 1..64 `models`.+2. The Host materializes each declaration as a real `providers` row with id+ `plugin:<pluginId>:<declaredId>`, owned by that plugin and listed in native+ Settings → Provider like a user row.3. Schema v17 adds the nullable `providers.owner_plugin_id` column and its- partial index.-4. The declaration is re-read from the manifest on every plugin load and is- authoritative for the fields it declares (name, vendorKey, baseUrl, authKind,- apiStyle, models).-5. Credentials stay in the Host secret store under the same refs as any- provider: `secret:provider:<id>:api_key` and `secret:provider:<id>:oauth`.-6. The user path refuses a plugin-owned row.-7. Disabling a plugin keeps its rows and sets `enabled = 0`, so re-enabling- restores the credential the user already stored.-8. A non-empty declaration requires the new high-risk `provider.register`- permission.+ partial index; pre-v17 rows stay user rows with a NULL owner, and the public+ payload carries `ownerPluginId`.+4. The declaration is re-read on every plugin load and is authoritative for the+ fields it declares, while values it does not own — stored headers and the+ OAuth account label — survive a refresh.+5. Credentials stay in the Host secret store as `secret:provider:<id>:api_key`+ and `secret:provider:<id>:oauth`; API keys never reach the plugin, and OAuth+ is reachable only through `onProviderOAuth` with the `provider.oauth` grant+ (ADR 0320).+6. `providers.update` and `providers.delete` fail with+ `PROVIDER_OWNED_BY_PLUGIN` for a plugin row, because the declaration would+ overwrite a user edit and only the plugin lifecycle can remove the row.+7. Disabling a plugin keeps its rows with `enabled = 0`, so re-enabling restores+ the stored credential, while uninstalling it or dropping an entry deletes the+ row with both credential references.+8. A non-empty declaration requires the high-risk `provider.register`+ permission, and a manifest that declares providers without it fails+ validation.9. Reconciliation runs on `plugins.enable`, `plugins.disable`,- `plugins.loadDev`, `plugins.uninstall`, and once at host startup for every- registered plugin.-10. OAuth contributions use the host-owned account UI and callback protocol in- ADR 0320.-11. The plugin SDK mirrors the same authoring-time rules, requires- `provider.oauth` for OAuth declarations, and derives the `providers`- capability token for the plugin row.+ `plugins.loadDev`, `plugins.uninstall`, and once at host startup, and a sync+ failure is logged as a warning without changing enablement.+10. OAuth contributions use the host-owned account UI and callback protocol of+ ADR 0320, with one encrypted credential per declaration and no multi-account+ rows.+11. The plugin SDK mirrors these authoring rules, requires `provider.oauth` for+ OAuth declarations, and derives the `providers` capability token.## Consequences-- A plugin-provided service is a first-class provider: it lists, discovers- models, and resolves through the same Host path as a user row, with no new- wire adapter.-- Provider rows now have an owner, so every Host path that mutates a row must- respect `owner_plugin_id`; the user path can no longer assume it owns the row- it is editing or deleting.-- An unreviewed manifest can add rows to the user's provider list.-- A credential is only as durable as the declaration: dropping an entry from the- manifest, or uninstalling the plugin, deletes the stored key or token.-- The plugin-side surface is deliberately narrow: OAuth code runs only in the- isolated plugin process for its own provider, while host-owned UI and secret- storage retain account and renderer ownership.+- A plugin-provided service is a first-class provider that lists, discovers+ models, and resolves through the same Host path with no new wire adapter.+- Every Host path that mutates a row must respect `owner_plugin_id`, and a+ credential lasts only as long as the declaration that introduced it.+- An unreviewed manifest can add rows to the provider list; the permission, the+ install confirmation, and the local-only limit for v1.1 bound that exposure.## Alternatives considered-### A sidecar-only provider registry--Rejected: the same service would exist twice, with a private identity the UI,-the model catalog cache, the session binding, and the Host secret store cannot-address.--### Let the plugin write provider rows through `providers.create`--Rejected: the plugin host is not a second provider author.--### Store plugin providers outside the database--Rejected: a JSON file in the plugin data directory cannot participate in the-relational state a provider row anchors.+- A sidecar-only provider registry: rejected; the service would exist twice with+ a private identity the catalog, session binding, and secret store cannot+ address.+- Let the plugin write rows through `providers.create`: rejected; user edits and+ the declaration would fight over the row, and uninstall would leave an orphan.diff --git a/docs/adr/0260-plugin-runtime-theme-apis.md b/docs/adr/0260-plugin-runtime-theme-apis.mdindex 856cb7bfa..895397783 100644--- a/docs/adr/0260-plugin-runtime-theme-apis.md+++ b/docs/adr/0260-plugin-runtime-theme-apis.md@@ -2,67 +2,47 @@- **Status**: Accepted for implementation- **Date**: 2026-09-15-- **Related**: issue #352, ADR 0248, `07-plugins/03-plugin-api.md`, `07-plugins/13-plugin-permissions-matrix.md`+- **Related**: issue #352, ADR 0248, `07-plugins/03-plugin-api.md`## Context-A visual theme editor plugin (Theme Studio) cannot ship the product flow users-expect against the shipped host contract:--1. **No apply API.** Theme selection only lives in Settings (`settingsSet` from- the renderer).-2. **Static load-time registry.** `registerThemes()` reads `contributes.themes`- once.-3. **Hard cap of 8 themes per plugin** (`MAX_THEMES_PER_PLUGIN`), which blocks- an unlimited user-authored library.-4. **Sidebar paint is color-only.** `--ds-bg-sidebar` feeds `color-mix` glass- tint and borders.+A theme editor plugin cannot ship the expected flow against the shipped host+contract: theme selection lives only in Settings, `registerThemes()` reads+`contributes.themes` once at load, a hard cap of 8 themes blocks a user-authored+library, and `--ds-bg-sidebar` feeds `color-mix` glass tint and borders, so a+gradient there breaks its consumers.## Decision### 1. `app.setTheme` (permission `ui.theme`)-```ts-pi.app.setTheme(themeId: "system" | "light" | "dark" | `plugin:${string}`): Promise<void>-```--Validates the id (built-in preference, or a currently registered plugin theme),-persists `AppSettings.theme` through host-core `settings.set`, then applies the-theme-only appearance reaction (`applyAppThemePreference`) that the full-settings path also reuses. That entry point touches nothing but theme state, so-`setTheme` can never disturb the locale, keybindings, or developer-mode menu-state.+`pi.app.setTheme(themeId)` accepts `"system"`, `"light"`, `"dark"`, or+`` `plugin:${string}` ``; it validates the id, persists `AppSettings.theme`+through host-core `settings.set`, and then runs the theme-only appearance+reaction that the full settings path reuses, so locale, keybindings, and+developer-mode menu state are untouched.### 2. Runtime theme lifecycle (permission `ui.theme`, own themes only)-```ts-pi.themes.upsert({ id, label, base, css })-pi.themes.remove(themeId)-pi.themes.list()-```--- Production plugins, no unload/reload.-- CSS goes through the same `sanitizeThemeCss` + size cap as load-time.-- Ids are namespaced `plugin:<pluginId>:<themeId>`; upsert replaces- label/base/css.-- Host emits `pluginChanged` (`reason: "themes"`) and refreshes panel appearance- so an updated **active** theme restyles immediately.-- The 8-theme hard cap is removed.+`pi.themes.upsert({ id, label, base, css })`, `pi.themes.remove(themeId)`, and+`pi.themes.list()` work in production plugins without a reload. CSS passes the+same sanitizer and size cap as load-time, ids are namespaced+`plugin:<pluginId>:<themeId>`, the host emits `pluginChanged` with reason+`"themes"` and refreshes panel appearance so an active theme restyles+immediately, and the 8-theme cap is removed with the size cap, sanitizer, and+permission gate as the remaining controls.### 3. Sidebar image token-- `--ds-bg-sidebar` stays a **color**.-- New optional `--ds-bg-sidebar-image` holds a CSS `<image>` (`none` by- default).-- `.sidebar` / `.sidebar-rail` use `background-color` + `background-image`.-- macOS stacks the image layer **under** the glass sheen gradients over the- opaque window surface (ADR 0332 superseded the vibrancy plate).+`--ds-bg-sidebar` stays a color and a new optional `--ds-bg-sidebar-image` holds+a CSS `<image>`, `none` by default; the sidebar and rail use `background-color`+plus `background-image`, and macOS stacks the image under the glass sheen over+the opaque window surface (ADR 0332 superseded the vibrancy plate).## Consequences-- Theme Studio (and any `ui.theme` plugin) can apply, create, edit, and delete- themes without a reload path.-- `ui.theme` is no longer "additive style only": it can change the active app- theme.-- Specs, permissions matrix, E2E docs, and this ADR stay the contract for plugin- authors.+- Any `ui.theme` plugin can apply, create, edit, and delete themes without a+ reload path.+- `ui.theme` can now change the active theme, which stays low-risk because ids+ are host-validated and CSS sanitized.+- Specs and the permissions matrix remain the contract for plugin authors.diff --git a/docs/adr/0261-plugin-appearance-extensions.md b/docs/adr/0261-plugin-appearance-extensions.mdindex 7b3b6583b..0e08d260f 100644--- a/docs/adr/0261-plugin-appearance-extensions.md+++ b/docs/adr/0261-plugin-appearance-extensions.md@@ -6,23 +6,28 @@ Accepted for implementation.## Context-Plugins can contribute static sanitized themes, but cannot safely vary a-declared theme at runtime or offer a dedicated configuration surface. Letting-plugin code inject CSS, renderer DOM, or arbitrary Settings routes would widen-its authority and break host ownership of navigation and native window chrome.+Plugins can contribute static sanitized themes but cannot safely vary a declared+theme at runtime or offer their own configuration surface, and letting plugin code+inject CSS, renderer DOM, or arbitrary Settings routes would break host ownership of+navigation and native window chrome.## Decision-1. `ui.settings` is an independent permission.-2. The host renders contributed items only in the **Extensions** group after all- core Settings groups.-3. The host renders every scenic Settings DOM node in its normal React tree.-4. `pi.themes.setVariables(themeId, values)` requires `ui.theme`.-5. The host persists accepted values in plugin-private settings and serializes a- separate host-generated variable rule after static sanitized theme CSS.-6. Disable, uninstall, crash and reload remove every owned destination.+`ui.settings` is an independent permission: a loaded plugin holding it and+`ui.theme` may contribute one validated, data-only scenic destination, which the+host renders in the **Extensions** group after the core Settings groups while+keeping ordering, the search shell, titlebar, and fallback navigation. Every scenic+node is rendered by the host in its normal React tree, so plugins contribute no+entry document, DOM, styles, scripts, or actions.+`pi.themes.setVariables(themeId, values)` requires `ui.theme` and accepts values+only for the caller's declared variables, typed as `length`, finite `number`, strict+hex `color`, or fixed `select`, rejecting host-reserved names, undeclared keys,+unsafe CSS fragments, and cross-plugin ids. Accepted values persist in+plugin-private settings, and disable, uninstall, crash, or reload removes every+owned destination.## Consequences-Theme packs can provide bounded controls such as a backdrop blur number without-re-injecting stylesheet text.+- Theme packs can offer bounded controls such as a backdrop blur number without+ re-injecting stylesheet text.+- Settings extensions keep the existing plugin sandbox and lifecycle boundaries.diff --git a/docs/adr/0262-chat-file-refs-open-in-the-file-view.md b/docs/adr/0262-chat-file-refs-open-in-the-file-view.mdindex 7a4c2011f..23fdb1e16 100644--- a/docs/adr/0262-chat-file-refs-open-in-the-file-view.md+++ b/docs/adr/0262-chat-file-refs-open-in-the-file-view.md@@ -10,86 +10,78 @@## Context-ADR 0163 made a file reference in the transcript clickable, but the click-trusted the token as written. An agent that works on `/root/dir/openimage.js`-routinely names only `openimage.js` in its reply, so the reference resolved-against the workspace root, pointed at a path that does not exist, and the work-panel painted an empty state — or, for a `.html` token, opened a blank page in-the side browser.+ADR 0163 made transcript file references clickable but trusted the token as+written, so an agent naming only `openimage.js` resolved at the workspace root and+painted an empty panel or a blank browser page, indistinguishable from a slow+load. The click also always chose the host `file:` tab, while the panel's capable+surface is the vendored `pi.file-manager` view (ADR 0241), which had no way to be+told which file to show.## Decision-1. **Completion runs in Electron main**, as `fs.resolveRef`, because only main- sees both the open project and the session's own scratch store- (`<data_dir>/scratch/<sessionId>/`, ADR 0124).- - an absolute reference that already names a real file inside a known root- wins outright — that is path equality, not a guess;- - an `attachments/<sha256>` blob names a stored file by hash, so it resolves- against the attachment store directly;- - otherwise the roots are searched in priority order — **the open project- first, the session scratch store second, the attachment store last** — and- the first root that answers wins, so the project is searched to exhaustion- before the scratch store is considered;- - inside one root, an exact path beats a shorthand; a shorthand resolves only- when its complete supplied suffix uniquely identifies one safe file.- - the files panel's ignore set applies, so a dependency tree is never- searched;- - a reference that matches nothing opens **nothing** and reports itself.-2. **The destination follows where the reference resolved.** A project file- opens in the `pi.file-manager` view, except a positioned reference (`:line`,- `:line:column`, `:line-range` or `#Lline[-Lend]`), which opens in the host's- read-only `file:` tab so the requested source line can be brought into view.-3. **A contributed view's `location` stops being browser-only.** It travels as- the view entry URL's `piViewOpen` query parameter on creation — the only- channel that cannot race a document that has not run yet — and as the- `view:open` preload event once the document has loaded, through the same- channel every other panel event uses.+1. **Completion runs in Electron main** as `fs.resolveRef`, because only main sees+ the open project and the session scratch store+ (`<data_dir>/scratch/<sessionId>/`, ADR 0124). An absolute reference naming a+ real file inside a known root wins outright; an `attachments/<sha256>` blob+ resolves against the attachment store; otherwise roots are searched in priority+ order — **open project, session scratch, attachment store** — with the project+ exhausted before the scratch store is considered. Inside one root an exact path+ beats a shorthand, which resolves only when its complete supplied suffix+ uniquely identifies one safe file: it never degrades, ambiguous matches resolve+ to nothing, the files-panel ignore set applies, and a reference that matches+ nothing opens **nothing** and reports itself.+2. **The destination follows where the reference resolved.** A project file opens+ in `pi.file-manager`, except a positioned reference (`:line`, `:line:column`,+ `:line-range`, `#Lline[-Lend]`), which opens in the host's read-only `file:` tab+ so the requested source line can be shown — the bundled view has no+ line-navigation contract. Scratch and attachment files open in the host `file:`+ tab because they live outside that view's project root. An unpositioned+ `.html` / `.htm` file in the session's project group or own scratch directory+ opens in the side browser (ADR 0163), with browser roots resolved from the+ owning session. A direct user click on a project file actively ensures the+ bundled view runs — enabling an off plugin or reloading one with no contributed+ view — without restoring a missing `ui.view` grant or widening project scope;+ if either boundary excludes the project, or the plugin still cannot start, the+ host `file:` tab opens with a notice.+3. **A contributed view's `location` stops being browser-only.** It travels as the+ view entry URL's `piViewOpen` query parameter on creation and as the `view:open`+ preload event after load. A location that arrives before the first+ `did-finish-load` restarts the load; a loaded view is never navigated, because a+ plugin may hold unsaved edits, and re-opening the same location does nothing.+ The payload is opaque to the host, and no permission or SDK method is added.4. **The view decides its own presentation.** `pi.file-manager` v0.4.0 opens the- requested file, expands its ancestors, and collapses its own left file list- for a host request — a new persisted state with a keyboard-reachable header- toggle, so the stored split width comes back when it is expanded again.-5. **The bundled copy moves to v0.4.0** through ADR 0241's re-sync procedure,- and the same release is published to the plugin center: the marketplace and- the bundled copy ship the same bytes.+ requested file, expands its ancestors, and collapses its left file list for a+ host request. An absolute path outside the project root is treated as an+ explicitly host-chosen file: raw Node `fs` with the credential deny list applied+ to the raw, normalized and `realpath` forms and no root containment, which its+ `safetyNotes` states. ADR 0339 drops root containment for the host as well:+ `fs/resolveRef`, `fs/read`, `fs/reveal`, and `fs/open` open an exact absolute+ path outside managed roots. The host applies no deny list because it only shows+ the file to the user who clicked it, while the plugin keeps its own.+5. **The bundled copy moves to v0.4.0** through ADR 0241's re-sync procedure and+ ships the same bytes as the plugin-center release.## Consequences-- A click on a shorthand lands on the file the agent meant, or says that nothing- matched.-- The transcript's file surface is the same editable view the launcher offers,- so "show me that file" and "let me change it" are one surface.-- The host now depends on a plugin version for a chat affordance.-- A direct project-file click can re-enable the bundled plugin, because the- click is an explicit request to use it.-- The file view is no longer confined to the project root whenever, and only- when, the host asks it for a path the host itself picked.--## Alternatives considered--### Resolve the shorthand in the renderer--Rejected: the renderer cannot see the session scratch store, and the two roots-have to be ranked against each other in one place for the priority order in-point 1 to hold.--### Add an `ui.openView(pluginId, viewId, payload)` SDK method--Rejected for now: the work-panel tab already carries `location`, and-`PluginViewHost.broadcast` already reaches docked views, so the feature needs no-new public API surface.--### Reload the view with the new location--Rejected: it discards whatever a plugin is holding, including unsaved edits.--### Widen the plugin's declared `fs` root to the scratch store--Rejected: the manifest's root model is `workspace` or a user-selected directory.--### Route workspace HTML through the file view for agent replies--Rejected: the file view renders a page as source.--### Keep the OS default application as the destination--Rejected: it is not the right panel, and it is what the request replaces.+- A shorthand lands on the file the agent meant, or says that nothing matched, so+ the two failure modes ADR 0163 left indistinguishable are distinguishable.+- The transcript's file surface is the same editable view the launcher offers; the+ host now depends on a plugin version for a chat affordance and degrades to the+ host `file:` tab with a notice when the plugin cannot start.+- The view is unconfined to the project root only when the host asks for a path it+ picked itself, extending ADR 0241's trust position by one named case.+- A chat click no longer hands a file to the OS default application, which remains+ in the file view's context menu. `fs.resolveRef` is a new renderer-facing channel+ while `fs/open` (ADR 0163) stays on the IPC surface.++## Alternatives++- Resolve the shorthand in the renderer: rejected, it cannot see the scratch store+ and both roots must be ranked in one place.+- Add a `ui.openView(pluginId, viewId, payload)` SDK method: rejected, the tab+ already carries `location` and no new public API is needed.+- Reload the view with the new location: rejected, it discards plugin state.+- Widen the plugin's declared `fs` root to the scratch store: rejected, it would+ grant every project access to every session's scratch data.+- Route workspace HTML through the file view: rejected, it renders a page as source.+- Keep the OS default application as the destination: rejected, it is not the panel.diff --git a/docs/adr/0263-project-folder-roots-for-plugin-views.md b/docs/adr/0263-project-folder-roots-for-plugin-views.mdindex ea479d877..958fef114 100644--- a/docs/adr/0263-project-folder-roots-for-plugin-views.md+++ b/docs/adr/0263-project-folder-roots-for-plugin-views.md@@ -1,8 +1,8 @@# ADR 0263: Expose a Project's Folder Roots and Complete References Across Them-- **Status**: Accepted-- **Date**: 2026-09-14 (amends [ADR 0262](0262-chat-file-refs-open-in-the-file-view.md))-- **Related**: [ADR 0016](0016-sidebar-organization-and-multi-project-tabs.md) ·+- Status: Accepted+- Date: 2026-09-14 (amends [ADR 0262](0262-chat-file-refs-open-in-the-file-view.md))+- Related: [ADR 0016](0016-sidebar-organization-and-multi-project-tabs.md) ·[ADR 0233](0233-renderer-owned-multi-folder-project-creation.md) ·[ADR 0241](0241-vendored-updatable-file-view-plugin.md) ·[ADR 0249](0249-chatgpt-style-logical-project-groups.md) ·@@ -10,72 +10,52 @@## Context-ADR 0249 made a project a host-owned logical group: a display name, an ordered-list of local folder roots, and a primary root. Two of its clauses matter here.+ADR 0249 made a project a host-owned logical group with an ordered list of local+folder roots and a primary root that stays the visible workspace. None of that+reached a plugin: `pi.workspace.get()` returned only `{ path, name }` for the visible+workspace, so a contributed view could not learn that its project had other folders.+After ADR 0262 a chat file reference opened as a project-root-relative path, which is+ambiguous in a group, so a reference resolving into a sibling folder could only open+as an external file with the jail bypassed.## Decision-1. **`pi.workspace.get()` gains `projectId` and `roots`.** `path` and `name`- keep their meaning — the primary root and its leaf name — so every existing- plugin, including the file view shipped today, behaves exactly as before.-2. **Main answers from a snapshot of the group records.** host-core owns them;- main keeps a copy so the synchronous `workspace:changed` broadcast and the- asynchronous pull cannot disagree.+1. **`pi.workspace.get()` gains `projectId` and `roots`.** `path` and `name` keep their+ meaning, `roots` is `{ path, name, primary }[]` in group order with the primary+ first, and `workspace:changed` carries the same object. This is project metadata the+ sidebar already shows, so it needs no new permission and no new method.+2. **Main answers from a snapshot of the group records.** The authoritative+ `project.groups.list` call fills it and every group mutation refreshes it, so the+ synchronous broadcast and asynchronous pull cannot disagree.3. **Completion searches the whole project.** `fs.resolveRef` walks the group's- folders — primary first, then the group's own order — before the session- scratch store, exactly as it walked the single workspace before.-4. **The address shape follows the folder.** A match in the primary root travels- as a project-relative path, byte-identical to ADR 0262.-5. **The host file tab reaches the group too.** Its extra containment roots gain- the project's other folders, which ADR 0249 §5 already sanctions, so a- reference that resolves into a sibling folder still opens when the file view- is absent or disabled instead of failing containment.-6. **The file view's own jail base becomes the selected folder.** Its reads,- writes, listing and search stay confined to one registered root at a time —- never the whole group — with the same symlink and junction refusals and the- same credential deny list.-7. **The switch is plugin-local.** Choosing another folder changes what that- view browses.+ folders, primary first and then group order, before the session scratch store, and+ the first root that answers wins outright.+4. **The address shape follows the folder.** A primary-root match travels as a+ project-relative path, while a sibling-folder match travels as an absolute path, the+ shape scratch and attachment files already use, so the payload stays one opaque+ string.+5. **The host file tab reaches the group too**, gaining the project's other folders as+ containment roots under ADR 0249 §5.+6. **The file view's jail base becomes the selected folder.** Reads, writes, listing,+ and search stay confined to one registered root at a time, never the whole group,+ with the same symlink refusals and credential deny list.+7. **The switch is plugin-local.** Choosing another folder changes only what that view+ browses, not the visible workspace, the agent's tool roots, a session's primary path,+ project instructions, or project memory.## Consequences-- A short reference now resolves anywhere in the project, and the view that- opens it can show the file in its own folder rather than as an external file.-- A multi-folder project can be browsed folder by folder in the work panel,- remembered per project, without the user changing what the agent works on.-- The container model, the permission model and the session model do not change:- no new permission, no new IPC capability for plugins, one containment base at- a time.-- A plugin that ignores `roots` keeps working; a host that cannot resolve a- group sends the original payload and the view falls back to single-root- behaviour, so the feature degrades rather than breaking.-- `fs.resolveRef` now has a wider notion of "the project".+- A short reference resolves anywhere in the project and opens in its own folder+ instead of as an external file.+- A multi-folder project can be browsed folder by folder in the work panel, remembered+ per project, without changing what the agent works on.+- The container, permission, and session models are unchanged, and a plugin that+ ignores `roots` keeps working because a host that cannot resolve a group sends the+ original payload.-## Alternatives considered+## Alternatives-### Let the renderer push the group into the view payload--Rejected: a view also loads from the launcher with no chat reference at all, and-`location` is a one-shot subject, not metadata a long-lived view can rely on.--### Add a `pi.project.roots()` method instead of extending `workspace.get()`--Rejected: `workspace.get` is already where a plugin learns which root it is-working in.--### Run completion against every group folder with equal weight--Rejected: the primary root is the folder the agent's tools default to, so it-should answer first; the group's order then ranks the rest.--### Make the folder switch activate that folder as the workspace--Rejected: it would move the agent's tool roots, a session's primary path and the-project's instructions, which is exactly the multi-root execution ADR 0233 and-ADR 0249 refused.--### Widen the bundled view's declared `fs` root to the whole group--Rejected: the manifest's root model is one directory, and widening it would give-the view standing access to every folder of every project rather than to the one-the user is looking at.+- Let the renderer push the group into the view payload — rejected: a view also loads+ with no chat reference, and `location` is a one-shot subject.+- Make the folder switch activate that folder as the workspace — rejected: it would+ move the agent's tool roots and the session's primary path.diff --git a/docs/adr/0264-host-mediated-actions-follow-the-browsed-folder.md b/docs/adr/0264-host-mediated-actions-follow-the-browsed-folder.mdindex 866c31ba1..b1cf41d0b 100644--- a/docs/adr/0264-host-mediated-actions-follow-the-browsed-folder.md+++ b/docs/adr/0264-host-mediated-actions-follow-the-browsed-folder.md@@ -1,73 +1,46 @@# ADR 0264: Host-Mediated File Actions Follow the Folder a View Is Browsing-- **Status**: Accepted-- **Date**: 2026-09-15 (amends [ADR 0263](0263-project-folder-roots-for-plugin-views.md))-- **Related**: [ADR 0241](0241-vendored-updatable-file-view-plugin.md) ·- [ADR 0249](0249-chatgpt-style-logical-project-groups.md) ·- [07-plugins/03-plugin-api](../spec/07-plugins/03-plugin-api.md)+- Status: Accepted (amends [ADR 0263](0263-project-folder-roots-for-plugin-views.md))+- Date: 2026-09-15+- Related: ADR 0241, ADR 0249, ADR 0263## Context-ADR 0263 §6 let a contributed view browse one folder of a multi-folder project-at a time, and made the view responsible for remembering which one. It said-nothing about the two actions a view cannot perform itself: opening a file with-the system default application (`fs.openDefault`) and revealing it in the OS-file manager (`fs.reveal`).+ADR 0263 §6 let a contributed view browse one folder of a multi-folder project at a+time, but said nothing about the two host-mediated actions a view cannot perform+itself — `fs.openDefault` and `fs.reveal` — which both resolve a workspace-relative+path against the workspace root (ADR 0241). Once a view can select a sibling folder+that contract silently opens or reports missing the wrong file, because the entry+list is relative to the *selected* folder.## Decision-1. **A view addresses a file by an absolute path when the selected folder is not- the primary one.** A relative path keeps meaning the workspace root, so the- primary-folder case is unchanged, byte for byte.-2. **`fs.openDefault` and `fs.reveal` accept an absolute path inside any- registered folder root of the open project.** That root then becomes the- containment base for the request, which ADR 0249 §5 already sanctions for- tool requests.-3. **The widening is limited to these two actions.** They hand a path to the OS- and return no file content; every other fs mode keeps the workspace root, so- no plugin gains byte access to another folder.-4. **The guards are the ones every other request passes.** The request still- needs the declared `fs.read`; a path inside a project folder that the- declared scope does not cover is refused rather than consented; credential- and repository internals are refused exactly as under the workspace root; and- containment is resolved through links, so a symlink or junction inside a- registered folder cannot carry the request out of it.-5. **The end of a session is the end of its documents.** When a view's open file- closes — on a folder switch, or any other close — its editor buffer is- cleared, not merely hidden: the pane must not keep a document from a folder- the user has left, and a stale buffer must never be what a later save or a- same-named file in another folder meets.+1. A view addresses a file by an absolute path when the selected folder is not the+ primary one; a relative path keeps meaning the workspace root, so the+ primary-folder case is unchanged, matching ADR 0263 §4.+2. `fs.openDefault` and `fs.reveal` accept an absolute path inside any registered+ folder root of the open project, and that root becomes the containment base, as+ ADR 0249 §5 already sanctions for tool requests.+3. The widening is limited to these two actions, which hand a path to the OS and+ return no file content: every other fs mode keeps the workspace root, and a plugin+ whose declared root is `userSelected` stays bound to the directory the user chose.+4. The request still needs the declared `fs.read`, a path outside the declared scope+ is refused rather than consented, credential and repository internals are refused+ as under the workspace root, and containment resolves through links.+5. When a view's open file closes, on a folder switch or otherwise, its editor buffer+ is cleared rather than hidden.## Consequences-- Opening or revealing a file behaves the same in every folder of a project: the- action reaches the file the user right-clicked, in the folder they are- browsing.-- The group grant stays a user-authored list.-- A view that ignores the rule (sends a relative path while browsing a sibling- folder) still gets the old behaviour: it opens the primary folder's file.-- Editing a file remains the plugin's own business: its reads and writes still- go through its own Node fs under its own jail (ADR 0241), and only these two- mediated actions go through the host.+- Opening or revealing a file reaches the file the user right-clicked in the folder+ they are browsing.+- The group grant stays a user-authored list: no plugin can walk to an unregistered+ folder or read a file it could not read before.+- Editing remains the plugin's own business under its own jail (ADR 0241).-## Alternatives considered+## Alternatives-### Widen the plugin's whole `fs` root to the selected folder--Rejected: the host does not know which folder a view is browsing — that choice-is plugin-local by design (ADR 0263 §6) — and a per-call base would let any-plugin claim another project folder for reading and writing, which is a grant-ADR 0249 §5 deliberately tied to a user-visible tool request.--### Have the view send a path relative to the workspace root--Rejected: only computable when the sibling folder sits inside the primary one.--### Resolve the action inside the plugin process--Rejected: the point of the host-mediated route is that the host owns the-decision and the audit.--### Disable the two actions while a sibling folder is selected--Rejected: it turns a fixable addressing mistake into a missing feature.+- Widen the plugin's whole `fs` root to the selected folder: the host does not know+ which folder a view browses (ADR 0263 §6).+- Resolve the action inside the plugin process: the host owns the decision and the+ audit.diff --git a/docs/adr/0265-turn-queue-priority-block-and-row-actions.md b/docs/adr/0265-turn-queue-priority-block-and-row-actions.mdindex 73cddf0c0..f1d4d0914 100644--- a/docs/adr/0265-turn-queue-priority-block-and-row-actions.md+++ b/docs/adr/0265-turn-queue-priority-block-and-row-actions.md@@ -7,43 +7,67 @@## Context-ADR 0213 moved the queue into host-core and gave "Send now" exactly one shape:-`prioritize` rewrites the entry's `position` below the current minimum, so the-entry jumps to the head of the whole queue. The renderer mirrored that as a-single in-memory `sendNowRequested` flag cleared on every other row, which meant-only one row could ever be waiting for the next boundary, and two "Send now"-clicks resolved as "the last click wins".+ADR 0213 moved the queue into host-core, where `prioritize` rewrites an entry's+`position` below the current minimum so it jumps to the head of the whole queue.+The renderer mirrored that as one in-memory `sendNowRequested` flag cleared by+every other row, so only one row could wait for the next boundary and two clicks+resolved as "the last wins". The row also offered only Remove and Send now, so a+prompt could not be corrected without retyping and the plain queue could not be+reordered at all.## Decision1. **A promotion block, ordered by click.** `turn_queue` gains a nullable- `priority` column (schema v18).+ `priority` column (schema v18). Promotion writes+ `COALESCE(MAX(priority), 0) + 1` within the session, so the first promotion is+ delivered first; delivery is `priority ASC, position ASC` for promoted entries+ followed by `position ASC` for the rest.2. **Promotion is one-way and idempotent-hostile.** Promoting an entry thatalready carries a `priority` fails with `CONFLICT`/`ALREADY_PRIORITIZED`- instead of silently moving it again.-3. **Promotion fixes order, but does not prevent cancellation.** A promoted row- disables move up, move down, edit, and Send now.-4. **A reorder operation for the plain queue.** `session.queueReorder` swaps one- entry's `position` with its adjacent non-prioritized neighbour in the- requested direction, and reports `moved: false` for a missing entry, a- promoted entry, or a block/queue edge.-5. **Edit returns the row to the composer.** Editing is renderer-local: the row- is removed (through the existing removal path) and its captured- `ComposerDraftSnapshot` — text plus inline file references — replaces the- composer input through the existing `composerPrefill` channel.+ instead of moving it again, and the renderer's optimistic mirror follows the+ same rule.+3. **Promotion fixes order, not cancellation.** A promoted row disables move up,+ move down, edit, and Send now and reads Waiting to send, while Remove survives+ until delivery and waits for Host confirmation. Cancellation, promotion,+ reordering, and delivery reservation share session admission serialization;+ runtime delivery runs outside that lock and reserves only its own input. Once+ input is reserved or accepted as steering, cancellation returns `CONFLICT`, and+ refused steering keeps the queued input for the next turn. There is no+ un-promote path.+4. **A reorder operation for the plain queue.** `session.queueReorder` swaps an+ entry's `position` with its adjacent non-prioritized neighbour and reports+ `moved: false` for a missing or promoted entry or a block edge, so reordering+ never crosses into the priority block.+5. **Edit returns the row to the composer.** Editing is renderer-local: the row is+ removed through the existing path and its captured `ComposerDraftSnapshot` —+ text plus inline file references — replaces the composer input through+ `composerPrefill`. The token-stripped `content` never rebuilds the prompt, and+ the action is refused while the live editor is non-empty.6. **The promoted block is delivered into the active turn.** Promotion usessteering so the parent handles user input while delegates keep working (issue- #1607).+ #1607): an active `TaskWait` yields to accepted steering while ordinary tools+ keep their boundaries. Immediate delivery accepts only the paired caller's own+ input under the active turn's permission mode — external Desktop turns use the+ stored session mode, module-admitted turns their principal ceiling — and other+ input keeps turn-boundary delivery. Without an active turn the first promoted+ entry starts the turn and later ones join as steering in click order; refusals+ are retried within a bounded budget, and an injected entry's own RACP turn is+ canceled.7. **The turn's owner is authoritative about its end.** A runtime terminal event- is not a reliable release: Main drops one that names a turn it no longer owns- (`isStaleTerminalEvent`), and an abort need not produce one at all.-Session collaboration completion receipts are promoted automatically. A worker's-report is not input the user queued a minute ago: when the receiving session is-busy, the receipt runs at the very next turn boundary instead of behind the-plain queue.--## Consequences and validation--No breaking change to existing channels: `agentQueuePrioritize` /-`session.queuePrioritize` keep their names and gain the block semantics, and-`agentQueueReorder` / `session.queueReorder` are additive.+ is not a reliable release: Main drops one naming a turn it no longer owns+ (`isStaleTerminalEvent`), and an abort need not produce one at all. A turn left+ active in the module would hold its session's queue forever, so the settlement+ reported by `finishTurn` closes the turn and lets the queue run, and the+ module's drain request is remembered while a pass runs instead of dropped.++Session collaboration completion receipts are promoted automatically, so a+worker's report runs at the next turn boundary rather than behind the plain queue,+under the same promotion and steering rules.++## Consequences++- Existing channels keep their names: `agentQueuePrioritize` /+ `session.queuePrioritize` gain the block semantics and `agentQueueReorder` /+ `session.queueReorder` are additive.+- Rows migrate with `priority = NULL`, so an upgraded database keeps its FIFO+ order and eight-entry bound.diff --git a/docs/adr/0266-plugin-fs-root-follows-the-calling-session.md b/docs/adr/0266-plugin-fs-root-follows-the-calling-session.mdindex 71b4c4923..60a91083f 100644--- a/docs/adr/0266-plugin-fs-root-follows-the-calling-session.md+++ b/docs/adr/0266-plugin-fs-root-follows-the-calling-session.md@@ -1,96 +1,59 @@# ADR 0266: Plugin fs Roots Follow the Calling Session-- **Status**: Accepted-- **Date**: 2026-09-16-- **Related**: [ADR 0016](0016-sidebar-organization-and-multi-project-tabs.md) ·+- Status: Accepted+- Date: 2026-09-16+- Related: [ADR 0016](0016-sidebar-organization-and-multi-project-tabs.md) ·[ADR 0249](0249-chatgpt-style-logical-project-groups.md) ·[ADR 0263](0263-project-folder-roots-for-plugin-views.md) ·[ADR 0264](0264-host-mediated-actions-follow-the-browsed-folder.md) ·- [07-plugins/03-plugin-api](../spec/07-plugins/03-plugin-api.md) ·- [07-plugins/13-plugin-permissions-matrix](../spec/07-plugins/13-plugin-permissions-matrix.md)+ [07-plugins/03-plugin-api](../spec/07-plugins/03-plugin-api.md)## Context-D093 gives the sidebar several retained project tabs while the shell keeps one-selected host workspace, and it fixes the rule this ADR extends: **tool-execution resolves its root from the durable session project**, so a background-session keeps its own root when another tab becomes active. ADR 0016 and ADR-0249 carry that separation into the project model, and ADR 0263 / ADR 0264 make-the folder a view browses plugin-local and per project.--```ts-rule.root === "userSelected" ? loaded.userRoot : this.services.getWorkspacePath()-```+D093 lets the sidebar retain several project tabs over one selected host workspace and+fixes the rule this record extends: tool execution resolves its root from the durable+session project. That rule never reached a plugin, because every `pi.fs.*` request+resolved its root from the window-global visible workspace, so two sessions on two+projects measured their calls against whichever project the window showed, and a+temporary chat with no visible workspace failed `NOT_FOUND` for every session at once.## Decision-1. **The `workspace` root resolves the project of the tool session that invoked- the call.** A new private helper `fsRoot(loaded, rule)` in- `plugin-runtime.ts` reads the in-flight tool's `sessionId`, asks the additive- host service `getWorkspacePathForSession(sessionId)`, and uses the project it- answers as the root.+1. **The `workspace` root resolves the project of the tool session that invoked the+ call.** A private `fsRoot(loaded, rule)` helper reads the in-flight tool's+ `sessionId`, asks the additive host service `getWorkspacePathForSession`, and uses+ the project it answers.2. **The session is the dimension the root follows; the fallback is the visible- workspace.** A panel-bridge call has no tool session, and a session the host- does not track -- a runtime that has not launched yet -- resolves the visible- workspace exactly as before.-3. **A `userSelected` mode is unchanged.** It keeps the directory the user- picked through `requestDirectory()`, with the same memory-only lifetime.-4. **`plugin-services.ts` wires the service from the `sessionProjects` map it- already keeps** for D093.+ workspace.** A panel-bridge call has no tool session, and an untracked session+ resolves the visible workspace as before.+3. **A `userSelected` mode is unchanged**, keeping the directory the user picked+ through `requestDirectory()` with the same memory-only lifetime.+4. **`plugin-services.ts` wires the service from the `sessionProjects` map it already+ keeps** for D093, so no new source of truth appears and nothing is cached.5. **Not one path-safety gate changes.** Permission, realpath containment, the- deny-list, and the declared scope with runtime consent still run, in the same- order, over the resolved root.-6. **A session root also resolves when no workspace is visible.** A temporary- chat has no visible workspace, so its plugin tools used to fail all at once;- with a session project they keep working per session.+ deny-list, and declared scope with runtime consent still run in the same order over+ the resolved root.+6. **A session root also resolves when no workspace is visible**, so temporary chats+ keep working, while a panel call in that state still fails closed.### Workspace metadata consistency amendment-The initial implementation scoped ordinary file calls but left `workspace.get`-and registered-folder action metadata tied to the visible project. A plugin-could discover project B while its session-rooted file calls reached A, causing-knowledge-library guards to reject otherwise valid saves.--Discovery and registered-folder actions now use the same host-owned session-mapping as `fsRoot`, through one internal resolver. The existing group snapshot-is queried for that path; a legacy metadata provider answering a different path-cannot attach its roots to the session.+Discovery and registered-folder actions use the same host-owned session mapping+through one internal resolver, so `workspace.get` and registered-folder metadata+cannot point at the visible project while file calls reach the session's. Panel and+untracked-session fallbacks are unchanged, and plugins that enqueue callbacks must+preserve the caller's async context per job.## Consequences-- Two sessions on two projects no longer cross-talk: a plugin agent tool reads- and writes under the project of the session that invoked it, whatever tab is- active.-- Panel-bridge fs calls keep their old meaning: they follow the visible- workspace.-- A plugin that only ever ran one session on one project sees no change at all.-- `NOT_FOUND` for a `workspace` root is now narrower and more precise: neither- the invoking session's project nor a visible workspace resolved.-- The plugin runtime reads session metadata the host already owns, so the change- adds no stored state, no migration, and no new plugin permission.--## Alternatives considered--### Keep the visible workspace and let the tool pass a project id--Rejected: the host already knows the invoking session, so the plugin would have-to learn and forward a project identifier it does not own, and a plugin-supplied-root would be a grant its manifest never declared.--### Resolve the session's project inside the plugin process--Rejected: the session-to-project map is host-owned session metadata (D093), and-copying it into a sandboxed plugin process would move it outside the host-authority that keeps it current.--### Make the visible workspace follow the active session--Rejected: the visible workspace is what the user is looking at, and ADR 0016-with D093 deliberately keep several retained tabs over one selected host-workspace.+- Two sessions on two projects no longer cross-talk, whatever tab is active.+- Panel-bridge calls keep following the visible workspace.+- `NOT_FOUND` now means neither the invoking session's project nor a visible workspace+ resolved, and no stored state, migration, or plugin permission is added.-### Fall back to the last visible workspace for a session the host does not track+## Alternatives-Rejected as no-op: an untracked session plus no visible workspace is exactly the-temporary-chat case the session root exists to keep working, so the fallback-stays "the visible workspace, when there is one".+- Keep the visible workspace and let the tool pass a project id — rejected: a+ plugin-supplied root would be an undeclared grant.+- Resolve the session's project inside the plugin process — rejected: the map is+ host-owned metadata that must stay current.diff --git a/docs/adr/0267-plugin-labels-follow-the-app-language.md b/docs/adr/0267-plugin-labels-follow-the-app-language.mdindex b97efbe3b..ed94a3665 100644--- a/docs/adr/0267-plugin-labels-follow-the-app-language.md+++ b/docs/adr/0267-plugin-labels-follow-the-app-language.md@@ -1,57 +1,47 @@# ADR 0267: Plugin Labels Follow the App Language-- **Status**: Accepted-- **Date**: 2026-09-16-- **Related**: [ADR 0009](0009-english-first-globalization.md) ·+- Status: Accepted+- Date: 2026-09-16+- Related: [ADR 0009](0009-english-first-globalization.md) ·[ADR 0160](0160-shipped-locale-registry-and-language-picker.md) ·[ADR 0182](0182-traditional-chinese-shell-locale.md) ·[ADR 0280](0280-plugin-owned-ui-localizes-from-host-locale.md) ·- [07-plugins/02-plugin-manifest-schema](../spec/07-plugins/02-plugin-manifest-schema.md) ·- [07-plugins/07-plugin-marketplace](../spec/07-plugins/07-plugin-marketplace.md)+ [07-plugins/02-plugin-manifest-schema](../spec/07-plugins/02-plugin-manifest-schema.md)## Context-A plugin's display name and description come from its manifest, and a-marketplace card's from its catalog entry. Both are single strings written in-whatever language the author used, so the Extensions page, the plugin launcher,-and the marketplace drew Chinese names under an English shell and English names-under a Chinese one.+A plugin's display name and description come from its manifest, and a marketplace+card's from its catalog entry, both as single strings in whatever language the author+used, so the Extensions page, launcher, and marketplace showed Chinese names under an+English shell and English names under a Chinese one. The plugin repository's validator+had required a top-level `i18n` block with `name`, `description`, and `safetyNotes` per+locale since its first release, but the desktop shell read none of it.## Decision-1. `manifest.i18n` and the same block on a marketplace catalog entry become part- of the plugin contract, with `name`, `description`, and `safetyNotes`.-2. Every Chinese shell locale reads `zh-CN`; every other locale reads `en`.-3. Resolution happens in the **host**, not the renderer: rows leave the process-3. Resolution happens in the **host**, not the renderer: rows leave the process- as finished strings, exactly like a plugin view title.-4. The desktop shell pushes the app language down (`plugins.setLocale`) whenever- it changes and then emits `pluginChanged`, so the surfaces re-read.-5. A malformed block (not an object of locale → object, or a non-string- `name`/`description`/`safetyNotes`) fails `validateManifest`.+1. `manifest.i18n` and the same block on a catalog entry become part of the plugin+ contract; `en` and `zh-CN` are the contract locales, and a plugin need not translate+ itself into every shipped shell locale.+2. Every Chinese shell locale reads `zh-CN` and every other locale reads `en`, so+ `zh-TW` reads English rather than a half-shared `zh-CN` guess (ADR 0182).+3. Resolution happens in the host, not the renderer: rows leave the process as+ finished strings, and a missing locale, field, or empty string falls back per field+ to the other contract locale and then to the author's flat `name` / `description`.+4. The shell pushes the language down through `plugins.setLocale` on change and emits+ `pluginChanged`, so persisted rows are never rewritten and the `i18n` block is+ neither persisted nor sent over RPC.+5. A malformed block fails `validateManifest`, while unknown locales and unknown fields+ are ignored so a publisher may carry more than the contract requires.## Consequences-- A translated plugin now reads in the user's language on the Extensions page,- the plugin launcher, and the marketplace, and its `safetyNotes` — the text- that explains what an install can touch — reads in that language too.-- Catalog search matches every locale's name and description, so a user who- types what they saw in one language still finds the entry after switching.-- Plugin authors keep shipping a single-language manifest if they want to: the- flat fields remain the fallback, and no field of the block is mandatory to- load.-- The host holds one more piece of state (the display locale).+- A translated plugin reads in the user's language on the Extensions page, launcher,+ and marketplace, `safetyNotes` included.+- Catalog search matches every locale's name and description.+- Authors may keep shipping a single-language manifest, because the flat fields remain+ the fallback and no field of the block is mandatory to load.## Alternatives-- **Resolve in the renderer**: the renderer knows `i18n.language` and would- switch instantly, but it would have to receive every manifest's `i18n` block,- which contradicts the rule that the renderer never reads a manifest, and it- would duplicate the fallback rules the host already owns.-- **Per-request locale parameter on every plugin RPC**: works for `plugins.list`- but leaves the summaries the host itself returns (install results, permission- changes, marketplace update checks) unlocalized, and adds a locale to every- call site.-- **Leave names to the author's language**: the plugin repository already- requires the block, so the shell would keep ignoring data its ecosystem- publishes — the reported bug.+- Resolve in the renderer — rejected: it would receive every manifest's `i18n` block+ and duplicate fallback rules the host owns.diff --git a/docs/adr/0268-remove-quotes-annotations-and-side-chats.md b/docs/adr/0268-remove-quotes-annotations-and-side-chats.mdindex d7061b201..0966523ad 100644--- a/docs/adr/0268-remove-quotes-annotations-and-side-chats.md+++ b/docs/adr/0268-remove-quotes-annotations-and-side-chats.md@@ -1,108 +1,62 @@# ADR 0268: Remove quotes, annotations, and side chats-- Status: Accepted+- Status: Accepted; supersedes ADR message-quotes-and-side-chats, ADR+ response-annotations, and ADR floating-annotation-index; amends ADR 0254- Date: 2026-09-16-- Deciders: PI-Desktop runtime and desktop UI maintainers-- Supersedes: ADR message-quotes-and-side-chats, ADR response-annotations, ADR floating-annotation-index-- Amends: ADR 0254 (its "Amendment: native side-chat forks", 2026-09-14)-- Preserves: D097, D128, D134, D209, D254, D261, D301-- Related: [04-ux/08-component-spec.md](../spec/04-ux/08-component-spec.md) ·- [04-ux/09-interaction-patterns.md](../spec/04-ux/09-interaction-patterns.md) ·- [06-delivery/04-e2e-test-plan.md](../spec/06-delivery/04-e2e-test-plan.md)+- Related: D097, D128, D134, D209, D254, D261, D301, ADR 0023, ADR 0254## Context-Three renderer-owned surfaces grew around the transcript and the composer. ADR-message-quotes-and-side-chats added a **Quote** action to the message action-row, a selected-text overlay, and renderer-owned side chats docked in the work-panel.+Three renderer-owned surfaces grew around the transcript and composer: the quote action+with a selected-text overlay and docked side chats, the response-annotation attachment+sent to the model in a generated `# Response annotations:` block, and the floating+annotation index with badges, highlights, and a comment editor. Two of them recovered+excerpts from rendered DOM, annotations added a second prompt serialization every display+surface must reverse, and a side chat is a second session lifecycle whose only durable+artifact — the forked child — `session.fork` already produces, while copy, edit, fork,+and retry cover the rest.## Decision-1. **Message action row.** Remove **Quote**, **Annotate**, and **Open/Ask in- side chat** from the hover action row of user messages and assistant turns.-2. **Selection overlay.** Remove the selected-text toolbar entirely: selecting- text in the transcript no longer floats an action strip.-3. **Annotations.** Remove annotations as a feature: the comment editor, the- floating annotation index, the answer source badges and highlights, the- composer annotation attachment chip, the annotation store slice, and the- annotation anchor modules are deleted.-4. **Prompt assembly.** The send path no longer composes a `# Response- annotations:` block: `api.prompt` and `enqueuePrompt` use the user's text as- written, with no generated heading, instruction sentence, or- `<response-annotations>` payload.-5. **Side chats.** Remove side chats as a feature: the first-Send draft- lifecycle that created the child session, the renderer transcript projection- (`projectSideChatEvent`), the `sidechat:` work-panel tab type and its- `SideChatTab`, the registration / release / cascade-cleanup rules, and the- availability blocked-reason reporting are all deleted.-6. **Retired identifiers (retired; must never be reused).** Decision IDs- `D-LOCAL-message-quotes`, `D-LOCAL-selection-overlay`,- `D-LOCAL-response-annotations`, `D-native-sidechat-stream`, and E2E IDs- `E2E-CHAT-quote-prefill`, `E2E-CHAT-selection-markdown`,- `E2E-CHAT-selection-side-chat`, `E2E-CHAT-annotation-attachments`,- `E2E-CHAT-annotation-session-state`, `E2E-CHAT-annotation-source-index`,- `E2E-CHAT-annotation-ack-and-steering`, `E2E-CHAT-side-chat-fork`,- `E2E-CHAT-side-chat-stream`, `E2E-CHAT-side-chat-add-to-main`,- `E2E-CHAT-side-chat-promote`, `E2E-CHAT-side-chat-close`, and- `E2E-SESSION-native-side-chat-fork-survives-close` are retired and must never- be reused for another scenario.-7. **Boundaries.** The host protocol stays v11 and the storage schema stays v15:- no new IPC channel, no new permission, no protocol or schema bump, and no- Rust change.--## Preserved behavior--- **D134 / `session.fork`.** Fork still resolves a durable child from an anchor- message and still activates it, including the `native-pi:` route of ADR 0254;- ADR 0023 is unchanged.-- **D209 / D301.** Smart Stop still restores the unanswered send's draft, and- per-session draft slots are untouched.-- **D097 / D128 / D254 / D261.** The work panel keeps role, sizing, identity- keying, neighbor-close, and per-session switching; losing the `sidechat:` tab- type removes one resource kind, not the model.-- **The rest of the action row.** Copy, Edit, Delete, Retry/Regenerate, and Fork- keep their current behavior, tooltips, and accessible names.-- **Child sessions already created.** A session forked earlier from a side chat- stays an ordinary session in the sidebar, lists, search, and stored history.+Remove **Quote**, **Annotate**, and **Open/Ask in side chat** from the message action row+while Copy, Edit and Delete, Fork, and Retry/Regenerate keep their place, behavior,+labels, and shortcuts. Remove the selected-text toolbar and composer quote prefill, the+comment editor, floating index, source badges and highlights, composer annotation chip,+annotation store slice, and anchor modules, so a `:codex-annotation{index="N"}` directive+renders as ordinary Markdown text. `api.prompt` and `enqueuePrompt` send the user's text+as written, with no `# Response annotations:` heading, instruction sentence, or+`<response-annotations>` payload, so an older stored prompt containing the block is shown+verbatim. Remove the side-chat draft lifecycle, the renderer projection, the `sidechat:`+work-panel tab type and `SideChatTab`, its registration, release, and cascade cleanup,+and the availability blocked-reason reporting, leaving `session.fork` with the Fork+action as its only entry point. Host protocol stays v11 and storage schema v15 — no new+IPC channel, permission, protocol or schema bump, and no Rust change — and the retired+identifiers that must never be reused are `D-LOCAL-message-quotes`,+`D-LOCAL-selection-overlay`, `D-LOCAL-response-annotations`,+`D-native-sidechat-stream`, `E2E-CHAT-quote-prefill`, `E2E-CHAT-selection-markdown`,+`E2E-CHAT-selection-side-chat`, `E2E-CHAT-annotation-attachments`,+`E2E-CHAT-annotation-session-state`, `E2E-CHAT-annotation-source-index`,+`E2E-CHAT-annotation-ack-and-steering`, `E2E-CHAT-side-chat-fork`,+`E2E-CHAT-side-chat-stream`, `E2E-CHAT-side-chat-add-to-main`,+`E2E-CHAT-side-chat-promote`, `E2E-CHAT-side-chat-close`, and+`E2E-SESSION-native-side-chat-fork-survives-close`, with the superseded ADR files kept as+history.## Consequences-- A user loses the shortcut of reusing an earlier prompt or answer inside the- composer, and loses the panel for asking a side question beside the main- conversation; reassembling either means copying text or forking a session and- switching to it.-- A stored prompt written while annotations were enabled can show the generated- `# Response annotations:` heading and payload as plain text, because every- display surface now renders the stored string unchanged.-- The renderer sheds roughly 2000 lines — the overlay, quote recovery,- annotation editor, index, badges, and the whole side-chat lifecycle — plus- eleven unit-test files and their E2E scenarios.-- Nothing moves across a process boundary: protocol v11, schema v15, the IPC- surface, the permission set, and the Rust host are untouched.--## Alternatives considered--### Hide the entry points and keep the code--Rejected: dead branches would still own store slices, i18n keys, CSS, and the-generated-block parser, and every later change to the action row or the send-path would have to keep them compiling for nobody.--### Keep a display-layer compatibility downgrade--Rejected: keeping `requestTextWithoutAnnotations` and the directive parser alive-only to prettify old prompts would preserve exactly the second serialization-this ADR removes, and a stored prompt that is not sent is harmless as text.--### Remove annotations and side chats, keep quotes and the selection overlay--Rejected: the overlay, the quote recovery path, and the composer prefill are the-largest single block of renderer-only code here, and quoting a whole message or-a sentence has an exact substitute in the OS clipboard and the composer.--### Turn side chats into an ordinary child-session tab instead of deleting them--Rejected: that is Fork plus the existing session list; a new docked tab kind-would keep the registration, projection, and cleanup lifecycle while adding a-fourth way to reach the same durable child.+- Users lose quote reuse inside the composer and the side-chat panel, substituted by+ copy/paste or forking a session, and a stored annotated prompt shows the generated+ heading as plain text.+- D134 / `session.fork` still resolves a durable child from an anchor message, D209 /+ D301 keep draft restoration, and D097 / D128 / D254 / D261 keep work-panel role,+ sizing, identity keying, neighbor-close, and per-session switching; a session forked+ earlier from a side chat stays an ordinary session.+- The renderer sheds renderer-only code and tests, and nothing crosses a process+ boundary.++## Alternatives++- Hide the entry points and keep the code: dead branches would still own store slices,+ i18n keys, CSS, and the block parser.+- Turn side chats into a child-session tab: that is Fork plus the session list, keeping+ the lifecycle for a fourth route to the same child.diff --git a/docs/adr/0269-capability-level-transfer.md b/docs/adr/0269-capability-level-transfer.mdindex d92f911fb..abf873385 100644--- a/docs/adr/0269-capability-level-transfer.md+++ b/docs/adr/0269-capability-level-transfer.md@@ -2,98 +2,65 @@- Status: Accepted for implementation- Date: 2026-09-16-- Amends: ADR 0112 (agent capability management roots and Settings IA — adds a- cross-level move to the capability surfaces)+- Amends: ADR 0112 (agent capability management roots and Settings IA — adds a cross-level move to the capability surfaces)- Related: ADR 0056 (user-owned MCP servers and skills), D193, D194## Context-ADR 0112 made `.agents` the only capability root and separated file ownership-from app-local activation state: an MCP server or skill lives globally-(`~/.agents/servers`, `~/.agents/skills`) or inside a project-(`<project>/.agents/...`), while `<data>/agent-capabilities/*.json` records-whether it is enabled, with a per-project override for global documents. The two-levels were reachable only as two independent lists.+ADR 0112 made `.agents` the only capability root, with each MCP server or skill+living globally or inside a project while app-local state records enablement and+per-project overrides. The two levels were reachable only as independent lists, so+changing a capability's level meant deleting the document at one level and+recreating it at the other, which lost the enablement decision and risked the only+copy. This record covers the move that `mcp.transfer` and `skills.transfer` expose.## Decision### 1. A level switch moves the document; it does not copy it-The file's level *is* its ownership. A copy would leave the source level holding-a definition the user just said belongs elsewhere, so the same capability would-appear twice with two names until the user cleaned up the old one — and the two-would drift.--The move is one unit per capability: `McpServerRegistry::transfer` relocates the-server's JSON file, and `UserSkillRegistry::transfer` relocates either the-single Markdown document or, for the conventional `<skill>/SKILL.md` shape, the-whole skill directory with the sibling resources a `Skill` invocation resolves-(`directory_skill_root`, `copy_directory_contents`). `move_capability_file`-tries `fs::rename` first so a same-filesystem move is atomic and cheap, and-falls back to copy-then-remove for a project on another mount.+The file's level is its ownership, so the source level stops listing the entry and+the destination holds the only file. `McpServerRegistry::transfer` and+`UserSkillRegistry::transfer` relocate one unit per capability, trying+`fs::rename` first for a same-filesystem move and falling back to copy-then-remove,+and always writing the destination before removing the source.### 2. A destination collision renames the arriving document; it never blocks the move-The destination level may already own the same id, or the same display name /-label compared case-insensitively, the way project-over-global shadowing-compares it. Overwriting an existing document would be data loss, and refusing-the move would make the level switch useless whenever both sides happen to share-a name.--Renaming a skill rewrites only the frontmatter `name` line-(`rewrite_document_name`); every other frontmatter field, the whitespace, the-line endings, and the body are copied byte for byte, because the user asked to-relocate a document, not to reformat it. A document with no parsable frontmatter-block gets a fresh one so the renamed file is still scannable.+A colliding id takes a numeric suffix and a colliding display name takes a+parenthesized one, so both definitions survive and the response returns the record+under the id it landed on. Skill placement replays the catalog's own+`capability_id` for each candidate path and resolves the arrived record by path,+because a skill's identity comes from its frontmatter name rather than its file+name.### 3. Activation state follows the document-State is app-local and ownership-free, so a move that left the old enablement-behind would silently change whether the capability runs, and a move that left-entries at the source level would leave pointers to an id that no longer exists-there. `set_moved_capability_state` therefore drops the source level's state for-the old id — via `CapabilityState::forget`, including every project override a-moved global document had — and writes the value the source row was showing at-the destination:--- moving into a project stores that project's own state;-- moving into global stores that value as the new global default, never another- project's override, because the move says nothing about the projects the- document left behind.--A global source read may carry a `projectPath`, which is exactly the context the-visible value is resolved in; `CapabilityTarget` keeps that field so the two-meanings — "owner" and "state context" — are never confused.+`set_moved_capability_state` drops the source level's state, including every+project override, and writes the value the source row showed at the destination;+moving into global stores a new global default rather than another project's+override.### 4. The two ends are explicit and a same-directory move is a no-op-`mcp.transfer` / `skills.transfer` take `{ id, from, to }`, each end a `{ level,-projectPath? }` target, instead of a single level and an implicit "other side":-the two ends can never be derived from one another wrongly, and a project-level-end without `projectPath` fails with `CAPABILITY_INVALID`.-`CapabilityTarget::same_directory` makes a move whose ends name the same-directory a no-op that returns the current record, so a UI that offers the-action redundantly can never rewrite the file.+`mcp.transfer` and `skills.transfer` take `{ id, from, to }`, each end a+`{ level, projectPath? }` target, a project-level end without `projectPath` fails+with `CAPABILITY_INVALID`, and `CapabilityTarget::same_directory` makes a+same-directory move return the current record unchanged.### 5. The global `.agents` root has a redirect seam-`PI_DESKTOP_AGENTS_DIR` repoints the global capability root, the way-`PI_DESKTOP_DATA_DIR` repoints the app-local data directory; an empty value-falls back to the home directory (`AGENTS_DIR_ENV`, `global_agents_dir`). A-cross-level move spans the real home directory and a project, so without the-seam the global half of the feature can only be tested against the developer's-own `~/.agents`, and an isolated or portable install cannot place its global-capabilities anywhere but the user's home.+`PI_DESKTOP_AGENTS_DIR` repoints the global capability root the way+`PI_DESKTOP_DATA_DIR` repoints the data directory, falling back to the home+directory when empty, so the cross-level move is testable and portable without+touching the user's own `~/.agents`. It is a test and installation seam, not a+user setting.## Consequences-- A capability has exactly one home.-- A directory skill keeps working after the move because its resources travel- with the document; a renamed directory skill is written under its new id.-- Collisions stay productive: both definitions survive under names the user can- tell apart, at the cost of the user having to recognize the `-2` name as the- one they just moved.-- A moved global document drops its other projects' overrides.-- The move is host-owned and does not touch the renderer's level queries:- `mcp.list` / `mcp.active` / `skills.list` / `skills.active` report the result- after the scan, and the document itself never carries `enabled`.+- A capability has exactly one home, so the Settings row disappears from the source+ group and appears in the destination group.+- A directory skill keeps working because its resources travel with the document,+ and a collision leaves two definitions the user can tell apart.+- The move is host-owned, `mcp.list`, `mcp.active`, `skills.list`, and+ `skills.active` report the result after the scan, and the document never carries+ `enabled`.diff --git a/docs/adr/0270-builtin-subagents-can-be-disabled.md b/docs/adr/0270-builtin-subagents-can-be-disabled.mdindex 8f2c1728f..c73fcf0b7 100644--- a/docs/adr/0270-builtin-subagents-can-be-disabled.md+++ b/docs/adr/0270-builtin-subagents-can-be-disabled.md@@ -6,51 +6,41 @@## Context-Settings > Agent > Subagents lists two groups: the five shipped builtins-(`explorer`, `code-reviewer`, `test-runner`, `fixer`, `ui-designer`) and the-user's own `~/.agents/subagents/*.md` documents. Only the user group had an-enablement switch, because only those records are files: the builtins are-constants in `packages/agent-runtime`, and ADR 0063 §2 tied activation to the-document scan that prunes state for deleted files.+Settings > Agent > Subagents lists the shipped builtins next to user documents,+but only user documents had an enablement switch, because the builtins are+runtime constants and ADR 0063 §2 tied activation to the document scan that+prunes state for deleted files. Copying a builtin into `~/.agents/subagents` and+disabling the copy shadowed nothing, so a delegate the instructions steer toward+could not be turned off at all.## Decision-1. **Activation for a handle with no document lives in its own app-local file.**- host-core stores switched-off builtin handles in- `<data>/agent-capabilities/subagent-builtins.json`, keyed by `Task` handle at- the global level.-2. **Two RPCs own that state.** `agents.disabledBuiltins` reads the switched-off- handles (sorted), `agents.setBuiltinEnabled(id, enabled)` writes one and- echoes the normalized handle.-3. **The catalog carries the switch, not the document.** Electron main supplies- the disabled handles to `loadSubagentDefinitions`, which drops them from- `definitions` — what `Task` may offer — and returns every builtin that still- wins its handle in a sibling `builtins` field, switched off ones included, so- Settings can render that row and its switch.-4. **Switching a builtin off is not deleting it.** A user document of the same- handle keeps working and keeps shadowing the shipped definition, and turning- the builtin back on needs no document, because nothing was removed.+Activation for a handle with no document lives in its own app-local file:+host-core stores switched-off builtin handles in+`<data>/agent-capabilities/subagent-builtins.json` because the user-document+scan would prune a builtin exclusion stored in `subagents.json`.+`agents.disabledBuiltins` reads them and `agents.setBuiltinEnabled(id, enabled)`+writes one, storing an unknown handle inertly since host-core does not ship the+builtin list. Electron main passes the disabled handles to+`loadSubagentDefinitions`, which drops them from `definitions` and returns every+builtin that still wins its handle in a sibling `builtins` field, and+`subagent/catalog` answers with both lists. Switching a builtin off is not+deleting it: a user document of the same handle still shadows it, and turning it+back on needs no document.## Consequences-- The Built-in group gains the switch the user rows already have, in the same- place and with the same optimistic flip.+- The Built-in group gains the same optimistic switch as user rows, with no+ reveal or delete because there is still no file.- A switched-off builtin stays listed and dimmed, which is the only way back on.-- Session launch and the Settings catalog read the same state, so the page shows- what `Task` offers — the property E2E-SUBAGENT-settings-lists-builtin-defaults- asserts.-- A host that is unavailable contributes no exclusions: an unreadable state file- offers a delegate the user had turned off rather than removing one they kept.-- No Markdown file is written, no project capability layer appears, and- `~/.agents/subagents` remains the only user-managed subagent source (ADR 0063- §1, ADR 0112 §1).+- An unreadable state file contributes no exclusions, so it offers a delegate+ the user had turned off rather than removing one they kept.+- No Markdown file is written and `~/.agents/subagents` remains the only+ user-managed subagent source (ADR 0063 §1, ADR 0112 §1).## Alternatives-- **A tombstone document in `~/.agents/subagents`.** Switching a builtin off- would write a file the user never asked for, show up in the Global group, and- turn a one-click toggle into visible filesystem state.-- **Keeping the state in `agent-capabilities/subagents.json`.** Cheapest to- write, but the scan-time prune that keeps deleted documents from leaving- orphaned rows would delete a builtin exclusion at the same moment it was- written.+- A tombstone document under `~/.agents/subagents`: rejected, it writes a file+ the user never asked for and shows up in the Global group.+- State in `agent-capabilities/subagents.json`: rejected, the scan-time prune+ would delete a builtin exclusion as it was written.diff --git a/docs/adr/0271-provider-transport-rebuild.md b/docs/adr/0271-provider-transport-rebuild.mdindex 69566e676..35eed72b7 100644--- a/docs/adr/0271-provider-transport-rebuild.md+++ b/docs/adr/0271-provider-transport-rebuild.md@@ -2,70 +2,62 @@- Status: Accepted for implementation- Date: 2026-09-16-- Related: [Error codes](../spec/03-runtime/08-error-codes.md) · [Agent runtime](../spec/03-runtime/02-agent-runtime.md) · [ADR 0212](0212-remove-diagnostic-timing-log-streams.md) · issue #234+- Related: [Error codes](../spec/03-runtime/08-error-codes.md) ·+ [ADR 0212](0212-remove-diagnostic-timing-log-streams.md) · Issue #234## Context-One turn on a long session retried a Codex request ten times over ~112 seconds-and reported `NETWORK_ERROR: fetch failed` for every attempt; a new turn on the-same provider, model, and network succeeded immediately. The log record carried-`phase=stream`, `streamMs=1~2`, and `retryAttempt=10`, and nothing else.--- `phase=stream` with a two-millisecond stream looks like a failure *after* the- response headers arrived, which would mean the connection worked and the retry- hypothesis is empty.-- The pair is actually the fingerprint of the opposite: pi-agent-core emits- `message_start` for a stream that ended **without** ever emitting `start`, so- `streamMs` measures the synthetic start/end pair, not a started stream.+A turn on a long session retried a Codex request ten times and reported+`NETWORK_ERROR: fetch failed` each time, while a new turn on the same provider,+model, and network succeeded at once. The log record showed `phase=stream` with+`streamMs=1~2`, which read like a failure after the response headers arrived; it+is in fact the fingerprint of the opposite, because pi-agent-core emits+`message_start` for a stream that ended without ever starting, so every attempt+died before a response. The shared transport was therefore never touched: one+process-wide undici dispatcher serves all providers and was rebuilt only on+settings change, so a pooled connection that died unnoticed stayed in use for the+whole retry budget, and the first-hand `error.cause` had already been flattened+into an `errorMessage` string, leaving `networkCategory: unknown`.## Decision-1. Describe the rejected provider fetch where the original Error still exists:- the fetch wrapper in `provider-retry.ts` runs `describeNetworkFailure` on the- live cause chain and reports the same validated fields a directly classified- network error carries (`networkCategory`, `networkCode`, `networkSyscall`,- `networkHost`) instead of letting a bare `fetch failed` fall back to- `unknown`.-2. Report the transport route (`networkRoute`: `direct`, `environment-proxy`,- `http-proxy`, `socks5-proxy`) with the diagnosis, so a failure at the proxy- hop is readable without inferring it from an errno.-3. Report `phase: request` for a failure that never received a response.-4. Rebuild the shared transport when one origin fails this way **repeatedly**:- after the second consecutive unanswered failure for the same origin inside a- turn, once per streak, at most once every 30 seconds process-wide, never for- a `dns` failure (name resolution happens before a socket exists).-5. Swap before closing: the replacement dispatcher is installed, then the- previous one is closed with `close()` — never `destroy()` — and the captured- original-dispatcher reference is repointed if the closed pool was it.+1. Describe the rejected provider fetch where the original Error still exists: the+ fetch wrapper in `provider-retry.ts` runs `describeNetworkFailure` on the live+ cause chain and reports the same validated fields a classified network error+ carries (`networkCategory`, `networkCode`, `networkSyscall`, `networkHost`),+ with shapes, bounds, and redaction still owned by `agent-errors.ts`.+2. Report the transport route as `networkRoute` (`direct`, `environment-proxy`,+ `http-proxy`, `socks5-proxy`), so a failure at the proxy hop is readable without+ inferring it from an errno.+3. Report `phase: request` for a failure that never received a response, because+ the phase describes what happened to the attempt rather than which message+ lifecycle surfaced it.+4. Rebuild the shared transport when one origin fails this way repeatedly: after+ the second consecutive unanswered failure for the same origin inside a turn,+ once per streak, at most once every 30 seconds process-wide, and never for a+ `dns` failure.+5. Swap before closing: the replacement dispatcher is installed, then the previous+ one is closed with `close()` rather than `destroy()`, and in-flight requests+ finish on the pool they were dispatched on.## Consequences-- The next occurrence of issue #234 is diagnosable: the log names the layer and- the route, and the retry indicator names the errno.-- A turn can now spend one of its retry attempts on a fresh pool, so a transport- that never recovers on its own stops being reused.-- Other sessions can observe a rebuild: their idle pooled sockets are closed, so- their next request pays a new TCP/TLS handshake.-- A transport failure during a `dns` outage triggers no rebuild, which is- deliberate: throttling the pool would spend the cost for no possible benefit.--## Alternatives considered--- **Rebuild on every failure.** Rejected: the dispatcher is process-wide, so one- session's single transient failure would churn every other session's pool, and- a long outage would rebuild once per attempt.-- **Never rebuild.** Rejected: it leaves a repeated unanswered failure on the- same origin with no recovery path, which is exactly the reported behavior.-- **Per-session dispatchers.** Rejected for this change: it changes the- ownership model of the transport and the proxy/bypass composition for every- provider request, which is a larger and separate architectural decision.-- **Retain the raw cause message and its `name`.** Rejected: it would put- free-form provider text (URLs, header values, query strings) into logs and the- transcript for a small diagnostic gain over the errno, the category, and the- route.+- A later occurrence of issue #234 is diagnosable, because the log names the layer+ and route and the retry indicator names the errno.+- A turn can spend one retry attempt on a fresh pool, while the retry budget,+ backoff curve, and error classification stay unchanged.+- Other sessions may pay a new TCP/TLS handshake after a rebuild, a latency cost+ bounded by the throttle and the per-origin streak.## Amendment: certificate verification (issue #714)Recognized certificate verification errors also skip rebuilding. Unlike the-broader TLS/protocol category, these cannot be repaired by replacing a socket-pool.+broader TLS/protocol category they cannot be repaired by replacing a socket pool;+see [system certificate trust](provider-system-certificates.md).++## Alternatives++- Rebuild on every failure — rejected: the dispatcher is process-wide, so one+ transient failure would churn every session's pool.+- Per-session dispatchers — rejected here: it changes transport ownership and+ proxy composition for every request.diff --git a/docs/adr/0272-connection-time-public-network-route.md b/docs/adr/0272-connection-time-public-network-route.mdindex 70506b034..e0eb59e52 100644--- a/docs/adr/0272-connection-time-public-network-route.md+++ b/docs/adr/0272-connection-time-public-network-route.md@@ -2,113 +2,54 @@- Status: Accepted for implementation- Date: 2026-09-17-- Deciders: PI-Desktop core-- Related: ADR 0177, ADR 0243, ADR 0245, D413, D414, issue #419, PR #473+- Related: ADR 0177, ADR 0243, ADR 0245, ADR 0321, D413, D414, issue #419, PR #473## Context-`createPublicHttpsClient` guards every credential-free public HTTPS fetch the-skill market makes from Electron main (ADR 0243). Before each hop it classified-the target host with **Node's local resolver** (`node:dns`) and refused any hop-whose answers were not public.+`createPublicHttpsClient` guards every credential-free public HTTPS fetch the skill+market makes from Electron main and classified each hop with Node's local resolver.+The request itself dials through Chromium's proxy stack, where a proxied hostname+is resolved by the proxy, so the pre-check judged an address no request would use+and refused working setups: a TUN resolver answering with a synthesized fake-IP in+the RFC 2544 range failed every catalog source even though the transport worked+(issue #419). PR #473 made that refusal legible without moving the boundary, and+this record moves it.## Decision-1. **The address verdict follows the route the request will actually take.** For- every hop, immediately before that hop is dialed, the client asks the session- that carries `fetchImpl` for its own proxy decision on exactly that URL- (`Session.resolveProxy`, wired beside `net.fetch` in- `skill-market-catalog.ts`).--2. **A proxied route replaces the local address verdict; it does not remove- it.** On `proxied`, the shared `isAcceptableResolvedAddress` tolerates- exactly one class the old rule refused: `benchmark` — the RFC 2544 range a- TUN fake-IP resolver synthesizes, i.e. the resolver's own artifact rather- than a target.--3. **`direct` and `unknown` keep the pre-ADR rule by default.** The app dials- the resolved address itself there, so only `public` passes.--4. **The syntactic guard is untouched.** `isSafePublicHttpsUrl` still runs first- for every hop and still refuses non-HTTPS, credential-bearing, non-public- literal, and `localhost` / `.local` / `.internal` URLs.--5. **The route travels with the refusal.** `PublicNetworkRefusal` /- `PublicNetworkRefusalDetail` gain `route`, so the diagnostics line and the- market's `failureDetails` say which route the address was judged on.--## Threat model--What the guard stopped before this ADR:--- Non-HTTPS, credential-bearing, and non-public-literal URLs — unchanged.-- A hop whose **local** resolver answers only with a private, loopback,- link-local, CGNAT, ULA, site-local, multicast, reserved, or documentation- address.--What changes:--- **Still stopped:** every refused address when it is the only possible direct- target; everything above on `unknown`; plus every address class except- `benchmark` on `proxied`.-- **Weakened, precisely:** on a `proxied` route, a public hostname whose *local*- answer is inside `198.18.0.0/15` is no longer refused.- - **SSRF to an internal service through the proxy.** If the proxy — or the TUN- capture behind a fake-IP answer — resolves that name to an internal address,- the app will have carried the request to it.- - **Cloud metadata endpoints.** `169.254.169.254`, `fd00:ec2::254` and similar- are still refused whenever the *local* answer names them (link-local / ULA),- on both routes.- - **`198.18.0.0/15` as an intranet range.** The range is reserved for- benchmarking and is not publicly allocated, but a lab or VPN could address- hosts there; a name answering from it is no longer refused on a proxied- route, and the TUN/proxy decides where it goes.- - **Chromium proxy fallback.** The route is read as the *resolved* proxy list.- - **Who controls the route.** The user does, through Settings → Network (ADR- 0177) or the OS/browser proxy configuration.--- The property the guard protects is "this app never dials an internal address- by itself".-- The one class now tolerated is *by construction* the signature of local- interception rather than of an internal target: `198.18.0.0/15` is RFC 2544- benchmarking space and hosts no service.-- Everything the guard can still verify in-process — URL shape, per-hop- re-validation, every real internal address class, an unanswered resolver — is- still verified, and the verdict is now made about the object the request will- actually use.--- If Electron ever exposes the peer a request actually connected to, and it is- not the proxy, replace the route verdict with that peer check.-- If a report shows a proxied hop reaching a private or metadata target through- a fake-IP answer, or Chromium falling back to a direct connection the route- list did not advertise, restore the strict verdict for that case and keep the- fake-IP case behind an explicit user setting instead.-- If `Session.resolveProxy` stops reporting the configured proxy, the route- collapses to `unknown` and the guard returns to the strict behavior by itself.+1. **The address verdict follows the route the request will actually take.** Before+ each hop is dialed, the client asks the session carrying `fetchImpl` for its+ proxy decision on exactly that URL (`Session.resolveProxy`), and the shared+ `classifyProxyRoute` reduces the answer to `proxied`, `direct`, or `unknown`.+2. **A proxied route replaces the local address verdict; it does not remove it.**+ On `proxied`, `isAcceptableResolvedAddress` tolerates only the `benchmark` class+ that a TUN fake-IP resolver synthesizes, while every other non-public class and+ an unanswered resolver still refuse.+3. **`direct` and `unknown` keep the pre-ADR rule by default.** Only `public`+ passes there; an explicit `allowFakeIp` setting may additionally permit the+ `benchmark` placeholder class for transparent router or TUN deployments and+ never another non-public class, a mixed answer may pin one acceptable address+ (ADR 0321), and `unknown` fails closed.+4. **The syntactic guard is untouched.** `isSafePublicHttpsUrl` still runs first,+ redirects stay `manual` under a hop cap, and every hop re-runs the whole check.+5. **The route travels with the refusal.** `PublicNetworkRefusal` and its detail+ gain `route`, so diagnostics state which route the address was judged on.## Consequences-- A proxied or fake-IP user's skill market works: no source is refused for an- address the request would never dial (issue #419).-- A `direct`-route user keeps the old verdicts by default.-- The MCP market now applies the same route-aware verdict before each hop.-- A TUN user who configured no proxy the app can see is still refused: the- transport reports `DIRECT` while the local resolver answers fake-IP.-- The route is read once per hop, so the market pays one extra `resolveProxy`- round trip per hop — bounded by the same five-hop cap.+- Proxied and fake-IP users get a working skill market, and direct-route users keep+ the old verdicts with an opt-in limited to benchmark placeholders.+- On a proxied route the app's only peer is the user-configured proxy, so reaching+ internal targets is bounded by that proxy's own rule set.+- The MCP market applies the same route-aware verdict and pays one extra+ `resolveProxy` round trip per hop, and a TUN user with no proxy the app can see+ is still refused.## Alternatives-- **Delete the DNS gate for every request.** Rejected: it removes the SSRF guard- for direct users too, and the guard would no longer stop a private answer from- being dialed by the app itself.-- **Relax `198.18.0.0/15` unconditionally.** Rejected: it accepts an answer the- app cannot attribute to an interception layer, and it silently allows a- connection to a host addressed in that range on a direct route.-- **Let the user allowlist a source.** Rejected: it moves a security decision to- a user who cannot see what the address would be used for, needs new settings- and UI for a case the app can decide, and would not have helped in #419, where- every source was refused at once.-- **Check the peer after connecting.** Unavailable, and the honest reason this- ADR exists: Electron's `net.fetch` performs proxy resolution and dialing- inside the network service and exposes no peer address afterwards.+- Delete the DNS gate for every request: rejected, it removes the SSRF guard for+ direct users too.+- Relax the benchmark range unconditionally: rejected, it accepts an answer the app+ cannot attribute to an interception layer.+- Check the peer after connecting: unavailable, because Electron's `net.fetch`+ exposes no peer address.diff --git a/docs/adr/0273-git-checkout-create-project-source.md b/docs/adr/0273-git-checkout-create-project-source.mdindex 9f341048a..359a30d2d 100644--- a/docs/adr/0273-git-checkout-create-project-source.md+++ b/docs/adr/0273-git-checkout-create-project-source.md@@ -1,52 +1,37 @@# ADR 0273: Git Checkout as a Create Project Source-- Status: Accepted for implementation+- Status: Accepted for implementation (amends ADR 0233, ADR 0247)- Date: 2026-09-17-- Deciders: PI-Desktop desktop UI maintainers-- Amends: ADR 0233, ADR 0247## Context-ADR 0233 gave the renderer one Create project surface that collects a name and-local folders, and the home switcher already cloned a git project through-`project/clone` under the public-host rules of ADR 0247. A user with no project-at all still could not start from a repository: the switcher only renders inside-the hero of a project-bound session, and the dialog had no repository source.+ADR 0233 gave the renderer one Create project surface (name plus local folders), and+the home switcher already cloned through `project/clone` under ADR 0247's public-host+rules, but that switcher only renders inside the hero of a project-bound session, so a+fresh installation needed a local folder before any clone entry existed.## Decision-1. The Create project dialog owns a source selector with two equal peers: This- computer (local folders) and Git repository.-2. The git source keeps the dialog's one name field, adds a repository URL field- and one clone destination row, and parses the URL in the renderer with the- same `parseGitCloneUrl` rules the home switcher uses (ADR 0247).-3. Main exposes additive `project/cloneCheckout({ url, parentPath })`: it clones- into an explicit parent folder and returns `{ path, name }` without touching- the active workspace and without opening a picker.-4. Project creation still flows through `project-group/create`.-5. `project/clone` keeps its current behavior for the home switcher; the two- clone entries do not share UI.+The Create project dialog owns a source selector with two equal peers, This computer+and Git repository, where the git source keeps the single name field, adds a+repository URL and one clone destination row, and parses the URL with the same+`parseGitCloneUrl` rules as the home switcher. Main exposes additive+`project/cloneCheckout({ url, parentPath })`, which clones into an explicit parent+folder and returns `{ path, name }` without touching the active workspace, and+creation still flows through `project-group/create` so a checkout becomes the primary+root of one logical group, exactly like a folder pick. `project/clone` keeps its+behavior for the home switcher.## Consequences-- A fresh installation can create its first project directly from a public- repository without opening an unrelated folder first.-- The clone destination is explicit: the dialog collects it before `git clone`- runs, so a checkout never lands in an implicit directory.+- A fresh installation can create its first project from a public repository, and the+ destination is explicit before `git clone` runs.- Private, loopback, link-local, credential-bearing, and malformed remotes stay- rejected before git runs (ADR 0247); the dialog disables Create for them.-- A checkout that succeeds while group creation fails leaves the cloned folder- on disk; the error surfaces as a toast and the folder can be added afterwards.-- No protocol, schema, host RPC, or storage change: the new channel is a narrow- main-process capability, and the host still owns every durable project record.--## Alternatives considered--- **Move the home switcher clone entry to the empty home:** rejected because the- hero without a project-bound session has no switcher surface, and the create- dialog is the documented first-project entry.-- **Reuse `project/clone` inside the dialog:** rejected because its native- parent picker and immediate workspace return would activate a project before- the group is created.-- **Let the main process pick the destination silently:** rejected because a- `git clone` should never choose its own destination folder.+ rejected before git runs (ADR 0247).+- A failed group creation leaves the folder on disk for a retry, and no protocol,+ schema, host RPC, or storage change is needed.++## Alternatives++- Reuse `project/clone` in the dialog: it activates a project before the group exists.+- Let main pick the destination silently: a clone should never choose its own folder.diff --git a/docs/adr/0274-development-plugin-permission-review.md b/docs/adr/0274-development-plugin-permission-review.mdindex 33cf9f616..026f8bc6b 100644--- a/docs/adr/0274-development-plugin-permission-review.md+++ b/docs/adr/0274-development-plugin-permission-review.md@@ -2,46 +2,44 @@- Status: Accepted for implementation- Date: 2026-09-17-- Deciders: PI-Desktop core- Related: [ADR 0005](0005-user-installable-plugin-system.md) ·[ADR 0110](0110-plugin-panel-chrome-spacing-contract.md) ·- [07-plugins/12](../spec/07-plugins/12-plugin-ipc-and-host-services.md) ·[07-plugins/13](../spec/07-plugins/13-plugin-permissions-matrix.md)## Context-A plugin's permissions are approved by the user at load time, and the approval-is the ceiling: hot reload never widens it (`plugin-runtime.ts`,-`reloadDevPlugin`). Two holes sat around that rule.+A plugin's permissions are approved by the user at load time and hot reload+never widens that ceiling, but loading a development folder passed the manifest+declaration straight through as the grant, and manual Reload used the registry+row's list while `watchDevPlugin` recorded the intersection as the new ceiling.+A manifest edit that added a permission therefore reloaded silently with it+dropped, leaving a half-broken plugin behind a `PERMISSION_DENIED` message that+pointed at a picker which reviewed nothing.## Decision-1. Choosing a development plugin folder is a request, not consent.-2. `plugin/loadDevConfirm` commits the answer.-3. `plugin/reload` compares the manifest against the **recorded approval**- (`PluginRuntime.devApproval`), never against the registry row.-4. When something was added, `plugin/reload` returns a review instead of- loading.-5. The scaffold flow (`plugin/createFromTemplate`) writes files and then returns- the same review.-6. Paths and identities in a confirmation come from the host: the renderer sends- an id (or the path it just picked) and the accepted permission list, never a- path of its own choosing for an already-registered plugin.-7. The `PERMISSION_DENIED` text of the hot-reload refusal now names an action- that exists: *reload it from the Plugins page to review*.-8. Both reviews render through one `PermissionGroups` component, so the install- review and the development review cannot drift apart about what is risky.+Choosing a development plugin folder becomes a request, not consent:+`plugin/loadDev` returns the validated `PluginPermissionReview` — id, name,+version, declared permissions, and what is beyond the current approval —+without registering or loading anything, and `plugin/loadDevConfirm` commits it+by registering the folder, loading it with the accepted permissions only, and+arming the watcher on that same set. `plugin/reload` compares the manifest+against the recorded approval (`PluginRuntime.devApproval`) rather than the+registry row, counting a new file glob exactly like a new permission, so an edit+that adds nothing reloads immediately while one that widens returns a review and+keeps the plugin running under its current approval until+`plugin/reloadConfirm` answers. The scaffold flow returns the same review, and+paths and identities in a confirmation come from the host, never from a+renderer-chosen path for an already-registered plugin. Both reviews render+through one `PermissionGroups` component, and the hot-reload refusal now points+at the Plugins page.## Consequences-- A plugin author sees the same permission review a marketplace install shows,- at the moment they choose a folder, and again whenever an edit asks for more.-- A manifest edit that widens silently can no longer produce a half-working- plugin: it is either applied with the user's answer or not applied at all.-- Nothing is granted against an unreadable manifest: the declaration is- validated before it becomes a review, and a failed read refuses the flow.-- The registry row is rewritten on every reviewed load, so it always states the- current declaration rather than the one from first load; the *approval* is the- watcher ceiling, which is the record that matters for reload.-- Widening still requires a user decision even in development, so the security- property the hot-reload guard exists for survives the fix.+- A plugin author sees the same review as a marketplace install, at folder+ selection and whenever an edit asks for more, and the answer rather than the+ manifest is what the runtime enforces.+- Widening can no longer produce a half-working plugin, and nothing is granted+ against an unreadable manifest.+- The registry row always states the current declaration, while the approval is+ the watcher ceiling that reload compares against.diff --git a/docs/adr/0275-plugin-panel-floating-widget.md b/docs/adr/0275-plugin-panel-floating-widget.mdindex 7d7b2dda9..8d1177f28 100644--- a/docs/adr/0275-plugin-panel-floating-widget.md+++ b/docs/adr/0275-plugin-panel-floating-widget.md@@ -2,56 +2,44 @@- Status: Accepted for implementation- Date: 2026-09-17-- Deciders: PI-Desktop core-- Related: [ADR 0081](0081-host-owned-plugin-panel-chrome.md) ·- [ADR 0092](0092-plugin-owned-panel-surface.md) ·- [ADR 0093](0093-plugin-panel-strict-drag-band.md) ·- [ADR 0110](0110-plugin-panel-chrome-spacing-contract.md) ·- [07-plugins/03-plugin-api](../spec/07-plugins/03-plugin-api.md)+- Related: [ADR 0081](0081-host-owned-plugin-panel-chrome.md) · [ADR 0092](0092-plugin-owned-panel-surface.md) · [ADR 0093](0093-plugin-panel-strict-drag-band.md) · [ADR 0110](0110-plugin-panel-chrome-spacing-contract.md)## Context-Every plugin panel is a frameless `BrowserWindow` that reserves a 46px host drag-band and carries one three-control capsule in its top-right corner (ADR 0092,-ADR 0093, ADR 0110). That grammar suits a panel that shows content, and does not-suit a plugin whose whole interface is a small round companion — a voice orb, a-timer, a status light.+Every plugin panel is a frameless `BrowserWindow` with a host drag band and one+three-control capsule in its top-right corner (ADR 0092, ADR 0093, ADR 0110). That+grammar suits a panel showing content but not a plugin whose whole interface is a+small round companion such as a voice orb, a timer, or a status light: the host+paints an opaque background, forces a rectangular minimum size, and draws the+capsule over the page.## Decision-1. A manifest may declare `"ui": { "shape": "widget" }`.-2. A widget window is `transparent: true` with a fully transparent- `backgroundColor`, `hasShadow: false`, `frame: false`, `maximizable: false`,- `fullscreenable: false`, and `skipTaskbar: true`.-3. A widget has no 46px band and no capsule.-4. The capsule is the panel's only close affordance (ADR 0093 §4), so the host- owns an equivalent menu behind the widget surface's own context menu: close,- minimize, and an always-on-top toggle.-5. `ui.width` / `ui.height` are honoured down to 120×120 for a widget (a panel's- minimum stays 360×280).-6. The preload publishes the placement as- `document.documentElement.dataset.piPluginPanelShape` (`panel` | `widget` |- `view`) before page scripts run, so one HTML entry can serve every placement- without a bridge round trip.-7. The plugin surface is otherwise unchanged: same preload, same `pluginBridge`- channels, same permission gate, same per-plugin session partition, same- egress policy, same localization rules.-8. `manifest.ui.shape`, `ui.alwaysOnTop`, and `ui.resizable` are validated at- install by the Plugin SDK, carried in the shared manifest type, and parsed by- host-core's `PluginUiMeta`, so the Rust catalog and the TypeScript host agree- on the contract.+A manifest may declare `"ui": { "shape": "widget" }`; `"panel"` stays the default,+and an absent or `"panel"` value keeps today's behavior. A widget window is+transparent with no shadow, frame, maximize, fullscreen, or taskbar entry, and the+plugin draws its own silhouette, shadow, and glow. A widget has no band and no+capsule: the preload publishes `--pi-plugin-titlebar-height: 0px`, never applies+the legacy additive offset, and installs the ADR 0093 segment-map drag over the+whole window, so empty space drags while standard controls and elements marked+`data-pi-plugin-no-drag` stay clickable. Because the capsule is the panel's only+close affordance, the host owns an equivalent menu behind the widget's context+menu with close, minimize, and an always-on-top toggle, travelling on the existing+sender-validated window-control channel as one new `contextMenu` action, so+`window.pluginBridge` gains no window primitive. `ui.width` and `ui.height` are+honoured down to a widget minimum, `ui.alwaysOnTop` defaults to `false`, and+`ui.resizable` defaults to `false` for a widget. The preload publishes the+placement as `document.documentElement.dataset.piPluginPanelShape` (`panel` |+`widget` | `view`) before page scripts run, and `manifest.ui.shape` is validated at+install by the Plugin SDK and parsed by host-core's `PluginUiMeta` so the Rust+catalog and TypeScript host agree. Nothing else about the plugin surface changes,+and a widget needs no new permission.## Consequences-- A plugin can be a floating orb: transparent, small, always-on-top when it asks- for it, draggable from its empty space, and closable from a host menu even- when the plugin never drew a close button.-- The 46px band, the capsule, and the v2 spacing contract stay exactly as they- are for panels and docked views; existing plugins and installed packages are- unaffected.-- Placement is a per-plugin manifest choice, not a per-page one: the same HTML- entry may serve a panel, a widget, and a docked view by reading the published- placement and the titlebar variable.-- A widget surface has one more pointer rule to document: an element that must- receive clicks is either a standard control or carries- `data-pi-plugin-no-drag`; everything else drags the window.+- A plugin can be a floating orb that is transparent, small, optionally+ always-on-top, draggable from empty space, and closable from a host menu.+- The band, capsule, and spacing contract stay identical for panels and docked+ views, so existing plugins are unaffected.+- One more pointer rule to document: a clickable element is either a standard+ control or carries `data-pi-plugin-no-drag`.diff --git a/docs/adr/0276-official-plugin-channel-and-backup-channels.md b/docs/adr/0276-official-plugin-channel-and-backup-channels.mdindex f06c42fe3..9a4e9318a 100644--- a/docs/adr/0276-official-plugin-channel-and-backup-channels.md+++ b/docs/adr/0276-official-plugin-channel-and-backup-channels.md@@ -1,148 +1,123 @@# ADR 0276: Official plugin channel and backup channels-> Amended 2026-10-08: the marketplace UI and persisted settings now use only-> the official channel; legacy source values are ignored. The resolve request-> is capped at three seconds and falls back to the official catalog URL after-> a timeout, rate limit, or `NO_DOWNLOAD_SOURCE`. Publication refusals remain-> authoritative.+> Amended 2026-10-08: the marketplace uses only the official channel and legacy+> source values are ignored; a resolve request is capped at three seconds and+> falls back to the catalog URL on timeout, rate limit, or `NO_DOWNLOAD_SOURCE`.- Status: Accepted for implementation- Date: 2026-09-17-- Deciders: PI-Desktop plugin and distribution maintainers- Related: ADR 0102, D238, E2E-024P, E2E-PLUGIN-official-channel-resolves-through-the-platform## Context-The client's marketplace source was a three-value union — `official`, `mirror`,-`custom` — mapped to hardcoded catalog URLs, and `official` was-indistinguishable from "never set": both landed on the GitHub default. A package-was fetched by joining the catalog's relative `url` onto `artifactBaseUrl` or-the catalog directory, and the `verified` trust tier was recognized only while-the catalog URL equaled one of two constants.--```text-GET /catalog.json the catalog the client reads-POST /api/v1/download/resolve JSON { deviceId, pluginId, version? }- -> 200 { sha256, sizeBytes, downloads[] }- Cache-Control: no-store-GET /download/{id}/{version} byte route for the marketplace page and- console; not the client's path-```+The marketplace source was a three-value union — `official`, `mirror`, `custom` —+mapped to hardcoded catalog URLs, and `official` was indistinguishable from "never+set". Since ADR 0102 the plugin center at `plugins.aiuo.net` is the publishing+authority and owns the client download contract: `GET /catalog.json`,+`POST /api/v1/download/resolve`, and a byte route the marketplace page uses rather+than clients. The platform hosts no package bytes itself, returns an ordered+`downloads` list, counts one download per device and day, rate-limits per device,+and refuses withdrawn or archived plugins with stable error codes.## Decision### 1. The product uses the official channel-The product always reads `https://plugins.aiuo.net/catalog.json`; the Plugins+The product always reads `https://plugins.aiuo.net/catalog.json` and the Pluginspage has no source selector. `pluginMarketSource` and `pluginMarketCustomUrl`-remain in persisted settings so older settings can be read without migration,-but host-core ignores them.--| Channel | Value | Catalog URL | Install path |-| --- | --- | --- | --- |-| Official channel | `official` | `https://plugins.aiuo.net/catalog.json` | Platform resolve |--`official` means the project's first-party plugin center. A package URL never-crosses providers: the official catalog supplies its package URL, and fallback-downloads remain inside the official channel.+remain readable in persisted settings without a migration, but host-core ignores+them, and the development-only `PI_DESKTOP_PLUGIN_MARKET_URL` override stays+available to tests and local development. A package URL never crosses providers:+the official catalog supplies it, and fallback downloads stay inside the official+channel.### 2. The official channel resolves through the platform-1. Refresh the catalog, then `POST {center origin}/api/v1/download/resolve` with- `{ deviceId, pluginId, version }` — once per install or update.-2. Try the returned `downloads` entries in order.-3. When the request times out or fails at the transport boundary, the platform- rate-limits the device, or it answers `503 NO_DOWNLOAD_SOURCE`, the client- immediately falls back to the catalog's own package URL (`artifactBaseUrl`- plus the relative `url`).-4. The answer is never cached (`Cache-Control: no-store` is the platform's- confirmation of this), so two installs of the same version are two calls.-5. The resolve digest is authoritative on the resolve path; the catalog's- `shasum` stays authoritative on the catalog fallback.-6. Publication refusals are reported, not papered over: `403 NOT_PUBLISHED`,- `403 PLUGIN_ARCHIVED` (hide the plugin from install and update selection),- and `404` (the platform has no such version — including a `+`-suffixed- version the byte route cannot carry).-7. A resolve fallback does not change the selected channel.+Refresh the catalog, then `POST /api/v1/download/resolve` with+`{ deviceId, pluginId, version }` once per install or update, under a three-second+total deadline; POST rather than GET, because the platform documents that a device+id in a query string ends up in access logs. Try the returned `downloads` entries+in order, downloading each to a temporary file and extracting it only after+`sha256` and `sizeBytes` agree, and abandon a failing mirror for the next one.+When the request times out or fails at the transport boundary, the device is rate+limited, or the platform answers `503 NO_DOWNLOAD_SOURCE`, fall back immediately+to the catalog package URL (`artifactBaseUrl` plus the relative `url`) and leave+that install uncounted; a malformed response or an integrity failure never uses+that fallback. The answer is never cached, so two installs of one version are two+calls. The resolve digest is authoritative on the resolve path and the catalog+`shasum` on the fallback. Publication refusals are reported rather than papered+over: `403 NOT_PUBLISHED`, `403 PLUGIN_ARCHIVED` (which also hides the plugin from+install and update selection), and `404`. A fallback never changes the selected+channel.### 3. A stable device identifier, sent as a digest-The resolve request carries a `deviceId` that host-core derives from the machine-identity the operating system exposes — the Windows-`HKLM\SOFTWARE\Microsoft\Cryptography\MachineGuid`, the macOS platform UUID, or-Linux `/etc/machine-id` (falling back to `/var/lib/dbus/machine-id` and-`/sys/class/dmi/id/product_uuid`). What leaves the machine is-`sha256("pi-desktop.device.v1:" + <machine id>)` as 64-character lowercase hex,-never the machine code itself: the platform only needs to compare two requests-for equality, so it has no use for the code, and a raw hardware identifier in a-third-party request is a privacy downgrade the counting feature does not-require.--When no machine identity is readable, host-core generates one random 64-hex id-on first use and persists it under the application data directory-(`plugins/market/device.json`), reusing it from then on. Either way the value is-read once per process, is stable for an installation across restarts, is never-shown in the UI, and is not a setting.+The resolve request carries a `deviceId` derived from the machine identity the+operating system exposes, sent only as+`sha256("pi-desktop.device.v1:" + <machine id>)` in 64-character lowercase hex:+the platform only compares two requests for equality, so a raw hardware identifier+in a third-party request would be a privacy downgrade with no functional gain, and+the fixed prefix domain-separates the digest from every other hash the app+computes. When no machine identity is readable, host-core generates one random id+on first use and persists it at `plugins/market/device.json`. Either way the value+is read once per process, stable across restarts, never shown in the UI, not a+setting, and a counting and rate-limit key rather than an account.### 4. Legacy catalog-source settings are ignored-The legacy `github`, `mirror`, and `custom` settings no longer select a catalog.-The platform may still return GitHub or CNB package mirrors for the official-catalog; these use the platform's digest and the same download allowlist.+The legacy `github`, `mirror`, and `custom` values no longer select a catalog. The+platform may still return GitHub or CNB package mirrors for the official catalog;+those use its digest and the existing download allowlist. The cache stays keyed by+`sourceUrl`, so an older snapshot from another catalog is ignored rather than+deleted, and installed records are not rewritten.### 5. Trust follows the official catalog`verified` renders as written only from the official catalog. A v1 catalog's-boolean `verified` mapping is unchanged.+boolean `verified` mapping is unchanged, and platform-returned package mirrors do+not change the trust source.### 6. The download allowlist does not change-The allowlist stays `github.com`, `githubusercontent.com`, `cnb.cool`, and the-host that served the current catalog. The platform's resolve answers name-mirrors on exactly those hosts today, so no entry is added.--### 7. An install reports progress, and can be cancelled while it downloads--An install or update is a single request, so a download that takes a minute is-otherwise indistinguishable from a frozen window. Host-core therefore reports-where the install is: `plugin.installProgress` carries `pluginId`, `version`,-`phase` (`resolve`, `download`, `verify`, `install`, `enable`), the mirror in-use (`source`) with its 1-based `attempt` / `attempts`, `receivedBytes` /-`totalBytes` (`0` meaning the size is unknown), every mirror tried so far-(`tried[]`, each `{ source, url, error }`), and `error` on the report that ends-a failed install.--The report goes to the interface rather than only to the log. A log line helps-an operator afterwards; the person waiting needs to see that the install moved-on to the second mirror and how far it is.+The allowlist stays `github.com`, `githubusercontent.com`, `cnb.cool`, and the host+that served the current catalog, which already covers every mirror the platform+names. A mirror on any other host is refused like any other package URL and the+next mirror is tried, so moving a mirror outside that set is a client-release+dependency rather than a platform-side change.++### 7. An install reports progress and can be cancelled while it downloads++`plugin.installProgress` carries `pluginId`, `version`, `phase` (`resolve`,+`download`, `verify`, `install`, `enable`), the mirror in use as `source` with its+1-based `attempt` and `attempts`, `receivedBytes` and `totalBytes` (`0` when the+size is unknown), the mirrors tried so far in `tried[]` as+`{ source, url, error }`, and `error` on the terminal report of a failure. Reports+are throttled to a bounded rate plus one per phase change and the terminal report,+so byte-level progress cannot flood the RPC channel. A manual install or update+shows the phase, `mirror n/N · name`, a determinate bar, and a cancel button+enabled only during `resolve` and `download`; a background auto-update stays+silent. `market.cancelInstall { id }` answers `{ cancelled, id }` and cancels only+an install running right now, honoured while bytes arrive, before each mirror is+tried, and at the last safe point before the package is written, because stopping+after unpacking would leave a state no later step can describe. A cancelled+install fails with `PLUGIN_CANCELLED` and the dialog closes quietly.## Consequences-- The official channel gains per-mirror fallback, withdrawal and archive- signals, and download counting, and it acquires a dependency: an install asks- the platform.-- Per-mirror digest verification becomes the reason a divergent mirror cannot- break an install.-- A first third-party service now receives an installation-level identifier.-- A resolve timeout is capped at three seconds.-- An install is no longer opaque: the interface sees the phase, the mirror being- tried, and the byte count, and a user can stop a download without leaving a- half-installed plugin.+- The official channel gains per-mirror fallback, withdrawal and archive signals,+ and download counting, at the cost of a platform dependency that the catalog-URL+ fallback mitigates.+- Per-mirror digest verification absorbs a divergent mirror without failing the+ install, and a first third-party service now receives an installation-level+ digest, never an identity.+- No manifest, catalog parsing, permission-review, or storage-schema change;+ legacy source values are retained but ignored.## Rejected alternatives-- **Keep resolving the catalog's declared base on the client only.** The catalog- is a static file, so it cannot say which mirrors currently serve a version, it- cannot refuse an archived or unpublished plugin, and it is the same list for- every install.-- **Send a per-request identifier.** The platform counts one download per- device, version, and day and rate-limits per device, so a value that changes- per call counts every call as a new installation and degrades the limiter to- the source address.-- **Send the raw machine code, or hash it without a prefix.** The platform only- compares values, so shipping the code itself would hand a third party a- reusable hardware identifier for no functional gain, and an unprefixed digest- could be correlated with other digests of the same machine.-- **Expose the identifier in Settings (show or reset it).** It answers no user- question, it invites treating a counting key as an account, and a reset button- would silently let one machine inflate the platform's counters.+- Resolve from the catalog's declared base only: a static file cannot say which+ mirrors serve a version or refuse a withdrawn plugin.+- A per-request identifier: counting per device needs stability, or the limiter+ degrades to the source address.+- Exposing the identifier in Settings: it answers no user question and invites+ treating a counting key as an account.diff --git a/docs/adr/0277-draggable-chat-content-width.md b/docs/adr/0277-draggable-chat-content-width.mdindex 1d5462bc2..7eca26dcd 100644--- a/docs/adr/0277-draggable-chat-content-width.md+++ b/docs/adr/0277-draggable-chat-content-width.md@@ -2,46 +2,45 @@- Status: Accepted- Date: 2026-09-16-- Deciders: PI-Desktop desktop UI maintainers-- Amends: D058, D101, the collapsed-sidebar 640px band-- Related: [04-ux/01-ui-ia](../spec/04-ux/01-ui-ia.md) ·- [04-ux/07-ui-design-system](../spec/04-ux/07-ui-design-system.md) ·- [04-ux/08-component-spec](../spec/04-ux/08-component-spec.md) ·- [08-meta/decisions-log](../spec/08-meta/decisions-log.md) (D439) ·- E2E-CHAT-content-width-handles · E2E-208+- Amends: D058, D101+- Related: [04-ux/07-ui-design-system](../spec/04-ux/07-ui-design-system.md) · [04-ux/08-component-spec](../spec/04-ux/08-component-spec.md) · [08-meta/decisions-log](../spec/08-meta/decisions-log.md) (D439) · E2E-CHAT-content-width-handles · E2E-208## Context-The conversation column, empty-home stack, and composer were capped at 760–768px-(640px while the sidebar was collapsed) so a wide shell would not become a-low-density reading surface. Code, tables, diagrams, and tool output then-wrapped inside a second 720px assistant cap, and there was no way to spend the-extra pane width when the user wanted it.+The conversation column, empty-home stack, and composer were capped at a fixed+reading width so a wide shell would not become low-density, and the assistant cap+then wrapped code, tables, and tool output inside a second cap. Users had no way to+spend extra pane width on demand, and a two-preset comfort/wide toggle cannot match+monitor size or a one-off wider diff.## Decision-1. The transcript, empty-home stack, and composer share one preferred max width,- default **760px**, persisted as `AppSettings.chatContentMaxWidth`.-2. Two 12px handles sit on the left and right edges of that centered band, from- the top of `.chat-surface` down to the composer dock.-3. Rest: the handles are invisible.--4. User bubbles stay `min(82%, 600px)`.-5. Renderer only: no protocol, storage schema, host, or IPC change.+1. Transcript, empty-home stack, and composer share one preferred max width,+ persisted as `AppSettings.chatContentMaxWidth` with the current column width as+ default for absent or invalid values, and the live band is always that width+ limited by the available pane minus gutters, so a squeezed work panel compresses+ it without rewriting the preference.+2. Two edge handles on the centered band adjust that single width in both+ directions and keep the column centered, with a drag minimum at the smaller of+ the configured floor and the available pane.+3. Handles are invisible at rest, become a capsule on hover or focus, lengthen+ while dragging, and support double-click, arrow-key stepping, Home, End, and+ Escape cancellation.+4. User bubbles and other transcript rows keep their own caps and follow the band+ through `--chat-prose-max-width`, and the collapsed-sidebar ceiling is removed.+5. The change is renderer-only: no protocol, storage schema, host, or IPC change,+ and host-core already preserves unknown settings keys.## Consequences-- Users who never touch the handles keep today's 760px column, including after- collapsing the sidebar (the pane grows; the band does not jump to 640px).-- A saved 1100px preference on a large window compresses cleanly when the work- panel opens, then returns when it closes.-- Handle hit targets can sit near the minimap when the band is almost full pane- width; the 24px gutter keeps both usable.+- Users who never drag keep the current column, including after collapsing the+ sidebar.+- A wide preference compresses when the work panel opens and returns when it+ closes.+- Handles stay usable because the band keeps a gutter from the pane edges.-## Rejected alternatives+## Alternatives-- **Comfort / Wide presets:** cannot match the live pane or a one-off width.-- **Independent left/right insets:** un-centers the column and fights the- composer, which is also centered.-- **Full-bleed to the pane edge by default:** reopens the over-wide reading- surface the 760px cap was there to prevent.+- Comfort / Wide presets: rejected, they cannot match the live pane.+- Independent left/right insets: rejected, they un-center the column and fight the+ centered composer.diff --git a/docs/adr/0278-canonical-application-id.md b/docs/adr/0278-canonical-application-id.mdindex aaebef3a5..86512990d 100644--- a/docs/adr/0278-canonical-application-id.md+++ b/docs/adr/0278-canonical-application-id.md@@ -2,37 +2,37 @@- Status: Accepted- Date: 2026-09-17-- Deciders: PI-Desktop packaging maintainers- Amends: D141, D371, ADR 0204-- Related: issue #524 · E2E-196b ·- [01-product/01-product-scope](../spec/01-product/01-product-scope.md) ·- [06-delivery/06-release-runbook](../spec/06-delivery/06-release-runbook.md)+- Related: Issue #524 · E2E-196b## Context-The product advertised `com.pi-desktop.app` as the application ID, but the owner-domain is `net.aiuo.pi-desktop`. Default unsigned macOS packs also left-Electron's adhoc signature on `PI-Desktop.app` (`Identifier=Electron`,-`Info.plist=not bound`).+The product advertised `com.pi-desktop.app` although the owner domain is+`net.aiuo.pi-desktop`, and default unsigned macOS packs left Electron's adhoc+signature on `PI-Desktop.app`, so `usernotificationsd` refused every request for the+product bundle ID (issue #524). Adhoc signing itself is not the defect: the identifier+must equal `CFBundleIdentifier`.## Decision-1. The canonical application ID is **`net.aiuo.pi-desktop`**.-2. NSIS/AppUserModelID follow the same ID.-3. Unsigned GitHub macOS packs do **not** re-sign the outer bundle.+1. The canonical application ID is **`net.aiuo.pi-desktop`**, used as `APP_ID`,+ electron-builder `appId`, macOS `CFBundleIdentifier`, the unsigned-helper bundle+ ID, and the Windows AppUserModelID, with `net.aiuo.pi-desktop.dev` on development+ macOS hosts.+2. NSIS and AppUserModelID follow the same ID, so existing `com.pi-desktop.app`+ installs become a new identity.+3. Unsigned GitHub macOS packs do not re-sign the outer bundle, because an `afterPack`+ adhoc `codesign` fails while nested helpers are unsigned; issue #524 stays open on+ that lane.## Consequences-- Packaged unsigned macOS artifacts keep Electron's outer identifier.-- Signed/notarized builds use Developer ID with the product bundle ID.-- Windows upgrades from a `com.pi-desktop.app` NSIS install are a new product- identity; users may see a parallel shortcut until the old install is removed.+- Unsigned macOS artifacts keep Electron's outer identifier, while signed builds use+ Developer ID with the product bundle ID.+- Windows upgrades from a `com.pi-desktop.app` install appear as a new product+ identity, possibly with a parallel shortcut.-## Alternatives considered+## Alternatives-- Keep `com.pi-desktop.app` and only re-sign: rejected because the owner domain- is `net.aiuo.pi-desktop`.-- Change only the macOS bundle ID: rejected because D141 requires one ID across- runtime and packaging.-- Adhoc-sign in `afterPack`/`afterSign`: rejected; nested helpers are not signed- yet and the pack fails.+- Keep `com.pi-desktop.app` and only re-sign — rejected: the owner domain is+ `net.aiuo.pi-desktop`.diff --git a/docs/adr/0279-resumable-subagent-delegations.md b/docs/adr/0279-resumable-subagent-delegations.mdindex 31043a29e..211fa6f69 100644--- a/docs/adr/0279-resumable-subagent-delegations.md+++ b/docs/adr/0279-resumable-subagent-delegations.md@@ -2,170 +2,126 @@- Status: Accepted for implementation- Date: 2026-09-17-- Deciders: PI-Desktop core- Related: [ADR 0062](0062-bounded-subagents-behind-a-task-tool.md) ·[ADR 0089](0089-proactive-background-subagent-delegation.md) ·[ADR 0119](0119-event-driven-subagent-timeouts.md) ·[ADR 0165](0165-withdraw-a2a-peer-stack.md) ·[03-runtime/02-agent-runtime.md](../spec/03-runtime/02-agent-runtime.md) §5f- Amends: ADR 0062 (the `Task` tool contract) and ADR 0089 (the delegation- lifecycle). Both are preserved — every existing boundary still holds; this- adds one opt-in parameter and one piece of bookkeeping.+ lifecycle). Both are preserved; this adds one opt-in parameter and one piece+ of bookkeeping.- Tracking: #513## Context-Delegation as built by ADR 0062 and ADR 0089 spawns one `SubagentRun` per `Task`-call. Each run starts with `messages: []`-(`packages/agent-runtime/src/subagent.ts`) and is single-use.+ADR 0062 and ADR 0089 spawn one single-use `SubagentRun` per `Task` call,+starting from `messages: []`. A delegate's rows persist with `parentToolCallId`+and `agentName`, but nothing reads them back into a delegate and the session+runtime skips them when rebuilding model context, so every `Task` call is a cold+start even when the parent delegates the same subagent for the same files twice.## Decision-Add an opt-in `resume` parameter to the `Task` tool. When present, the new-delegation is seeded with the prior delegation's reconstructed context instead-of starting empty.+`Task` gains an opt-in `resume` parameter; when present the new delegation is+seeded with the prior delegation's reconstructed context instead of starting+empty.### 1. `Task` gains `resume?: delegationId`-Resolution is by `delegationId` only — the id the `Task` result already returns-and `TaskWait` already accepts. A second, stable internal key-(`delegateSessionId`) exists solely to chain the runs; it never appears in a-tool parameter, tool result, or prompt.+Resolution is by `delegationId` only, the id `Task` already returns and+`TaskWait` accepts, with a stable internal `delegateSessionId` chaining runs and a+reverse map that also resolves ids from the middle of a chain.### 2. Chains, not records, are the unit of resumability-A **chain** is one `delegateSessionId` plus the ordered `Task` toolCallIds that-belong to it. Each `resume` appends the new toolCallId.--`DelegationRecord` gains `delegateSessionId`, plus `resumedFrom` and-`modelChangedFrom` on a run that continues a chain. Read tracking lives on the-chain, not the record: the registry keeps one entry per `delegateSessionId` and-a secondary index from every `delegationId` on that chain to it.+A chain is one `delegateSessionId` plus its ordered `Task` toolCallIds, and+reconstruction selects every child row whose `parentToolCallId` is in the chain+with a matching `agentName`. `DelegationRecord` gains `delegateSessionId`, plus+`resumedFrom` and `modelChangedFrom` when a run continues a chain.### 3. Context reconstruction is a pure function-A new module (`packages/agent-runtime/src/delegation-history.ts`) owns:--- selecting the chain's rows from the session transcript,-- synthesizing the original `task` as the first user message from the first- `Task` tool row's persisted arguments,-- converting to `AgentMessage[]` with the delegate's own provider/model binding- (a pinned delegation model is not the session model).-- a read-file / line-count budget gate.--`SubagentRun` gains `initialMessages?: AgentMessage[]`; when present it seeds-`initialState.messages` instead of `[]`. The run is otherwise a completely-normal run: it occupies a `MAX_SUBAGENT_CONCURRENCY` slot, inherits the-definition's permission scope, and settles through the existing-`settleDelegation` path with its own `delegationId`, report, and counters.+`packages/agent-runtime/src/delegation-history.ts` selects the chain's rows,+synthesizes the original `task` as the first user message from the first `Task`+row's arguments, converts with the delegate's own binding, and gates on a read+budget. Transport identity is `model.provider` / `model.id`, not the account row+id, which would make restored same-model reasoning look foreign; `SubagentRun`+gains `initialMessages?` and is otherwise a normal run under+`MAX_SUBAGENT_CONCURRENCY` with its own `delegationId`, report, and counters.### 4. Validation is visible, never thrown-`resume` is validated before the run starts; every failure is a tool error the-model can act on:--| Condition | Error |-|---|---|-| unknown or evicted id | `Unknown delegation "<id>"` plus the current resumable list |-| still running | `Delegation <id> is still running`, call TaskWait first — a resume is never queued |-| `stopped` / `aborted` | not resumable; a future revive path (out of scope here) |-| `interrupted` (the app closed mid-run) | not resumable; start a new delegation |-| `Task.agent` differs from the chain's agent | name mismatch, lists available |-| `Task.model` present on a resume | not allowed on a resumed run — start a new delegation to change models |-| chain exceeds the read budget | `Delegation <id> has read too much to resume cheaply` |-| the chain resolves but has no rows left to replay | the chain is dropped and reported as having no recorded history; the same id is never listed as reusable |--No new error codes for "evicted" versus "never existed": both resolve to the-same unknown-id error, because the model's only correct action is identical.+Each pre-run failure is a tool error the model can act on: an unknown id reports+`Unknown delegation "<id>"` with the resumable list, a running chain is never+queued, `stopped` and `aborted` runs are not resumable, a mismatched `Task.agent`+lists alternatives, `Task.model` on a resume is refused, and an over-budget chain+reports `Delegation <id> has read too much to resume cheaply`. No separate code+distinguishes evicted from never-existed, because the model's action is the same.### 5. Only `completed` and `failed` are resumable-A `failed` run's reads and findings still have value; its failed assistant row-is dropped by the converter like any other error row. `stopped` and `aborted`-encode an explicit Stop or runtime disposal, and resuming it would contradict-the cancellation.+A failed run's reads still count and its failed assistant row is dropped like any+error row, while `stopped` and `aborted` encode an explicit Stop or disposal. A+terminal parent error settles interrupted delegates as `failed` with+`SUBAGENT_PARENT_FAILED`, which preserves manual resume eligibility (#680).### 6. One live record per chain, ever-There is no queuing and no message-append. A chain has at most one running-record at a time; a `resume` while the chain is running is rejected with the-TaskWait error above.+There is no queuing and no message append: a resume while the chain runs is+rejected with the `TaskWait` error, so a chain stays a strict straight line.### 7. Resumable chains are bounded, LRU, per agent name-`MAX_RESUMABLE_CHAINS_PER_AGENT = 2`. Chains are exempt from the existing-`pruneFinishedDelegations` oldest-first sweep.+`MAX_RESUMABLE_CHAINS_PER_AGENT = 2`, chains are exempt from+`pruneFinishedDelegations`, and exceeding the bound evicts the least-recently-used+whole chain at settlement, registry entry and reverse-map entries together. A+chain whose latest run still works is never evicted, and no tombstones are needed+because `delegationId` is a random UUID.### 8. Read budget gates chain growth-A delegate has no compaction of its own, so an unbounded chain would eventually-overflow its own context window. Rather than trimming inside the chain, a chain-whose cumulative read volume exceeds `MAX_RESUMABLE_READ_LINES` (50,000)-silently leaves the resumable list — the next delegation for that work is a cold-start, which still works.--Reads are counted from the delegate's read-only tool rows (`Read`, `Glob`,-`Grep`, `BrowserPreview`), accumulated per chain; write-tool targets are not-counted and not listed.+A chain has no compaction of its own, so one whose cumulative read volume exceeds+`MAX_RESUMABLE_READ_LINES` (50,000) silently leaves the resumable list and the+next delegation starts cold. Reads are counted from `Read`, `Glob`, `Grep`, and+`BrowserPreview` rows when the list is built.### 9. The parent discovers a resumable list through `TaskList`-`TaskList` reports the current resumable chains: agent name, delegation id, the-one-line objective, and the files the chain has read (capped at 8, truncated).-Only settled, in-budget chains appear — a running chain is never listed, so the-parent is not lured into resuming one.--The list deliberately stays out of the system prompt. It changes on every-settlement, and rewriting instructions mid-session invalidates the request-prefix providers cache on; ADR 0337 records that trade-off and supersedes the-earlier "compose the list into the prompt" decision.+`TaskList` reports agent name, delegation id, objective, and files read, listing+only settled in-budget chains. The list stays out of the system prompt because it+changes on every settlement and would invalidate the cached request prefix+(ADR 0337), and a failed resume names the reusable ids in its own error.### 10. Same session only-`resume` resolves only against the current session's transcript. There is no-cross-session addressing; sharing facts between conversations stays in the-prompt, as ADR 0165 concluded when it withdrew the peer stack.+`resume` resolves only against the current session's transcript; sharing facts+across conversations stays in the prompt (ADR 0165).### 11. Definition edits take effect on resume, with a diagnostic-A definition edited between two delegations is applied as-is on resume — the-same "editing takes effect on the next prompt" semantics the catalog already has-— and the change is recorded in the delegation's lifecycle details. No-definition snapshot is stored; snapshots would need new persistent state and-would contradict the existing semantics.+An edited definition applies as-is on resume, matching the catalog's "editing+takes effect on the next prompt" semantics, and the change is recorded in the+delegation lifecycle details without storing a snapshot.### 12. Chain index is rebuilt from the transcript on startup-The chain registry is in memory, but the chain relationship is recoverable:-`Task` tool rows are persisted with their arguments, including `resume`. At-session launch the runtime scans the transcript's `Task` rows, groups them by-their `resume` links into chains, and rehydrates the secondary index.--Two details make a rebuilt chain behave like a live one. Agent names are-normalized on rebuild (`Explorer` and `explorer.md` both mean `explorer`), so-the rebuilt chain still selects its own rows and still matches `Task.agent`.+Persisted `Task` row arguments carry the links, so session launch rescans and+rehydrates the index. Agent names are normalized on rebuild, a `running` row+rebuilds as `interrupted`, and the model binding is matched by model id since no+key is persisted.### 13. The transcript renders a chain as one continuous conversation-A resumed delegation's card shows the whole chain's rows as consecutive turns-(task → reply → task → reply) with no special "resumed" badge. The new run's-counters start at zero; `details.resumedFrom` keeps the link auditable.+A resumed card shows the chain's rows as consecutive task and reply turns with no+"resumed" badge, counters start at zero, and `details.resumedFrom` keeps the link+auditable.## Consequences-- `Task`'s parameter schema widens by one optional field.-- The delegate→parent context boundary is untouched.-- No new storage schema, tables, or event types.-- A resumed run is billed and bounded exactly like a fresh one — same- concurrency slot, same permission scope, same fallback models, same abort- sources.-- Failure mode of the read budget is graceful degradation to a cold start, never- a broken or oversized request.--## Out of scope (二期)--- Reviving a `stopped` / `aborted` delegation.-- In-chain compaction or placeholder substitution for old tool results.-- Task queuing / work append on a running delegation.-- Cross-session resumption.-- User-visible settings for the bounds; they stay code constants.+- `Task`'s schema widens by one optional field, and `resume` omitted is exactly+ today's behavior.+- The delegate→parent boundary is untouched: reconstructed rows seed only the+ delegate's context, and `parentToolCallId` rows are still skipped when the+ parent's context is rebuilt.+- No new storage schema, tables, or event types; a resumed run is billed and+ bounded like a fresh one, and an over-budget chain degrades to a cold start.diff --git a/docs/adr/0280-plugin-owned-ui-localizes-from-host-locale.md b/docs/adr/0280-plugin-owned-ui-localizes-from-host-locale.mdindex 3cfbe5344..494c2b7a4 100644--- a/docs/adr/0280-plugin-owned-ui-localizes-from-host-locale.md+++ b/docs/adr/0280-plugin-owned-ui-localizes-from-host-locale.md@@ -1,48 +1,42 @@# ADR 0280: Plugin-Owned UI Localizes from the Host Locale-- **Status**: Accepted-- **Date**: 2026-09-17-- **Related**: [ADR 0009](0009-english-first-globalization.md) ·+- Status: Accepted+- Date: 2026-09-17+- Related: [ADR 0009](0009-english-first-globalization.md) ·[ADR 0082](0082-localized-plugin-panel-chrome.md) ·[ADR 0159](0159-plugin-generated-settings-and-local-shortcuts.md) ·[ADR 0160](0160-shipped-locale-registry-and-language-picker.md) ·- [ADR 0267](0267-plugin-labels-follow-the-app-language.md) ·- [07-plugins/02-plugin-manifest-schema](../spec/07-plugins/02-plugin-manifest-schema.md) ·- [07-plugins/03-plugin-api](../spec/07-plugins/03-plugin-api.md)+ [ADR 0267](0267-plugin-labels-follow-the-app-language.md)## Context-The host already resolves two kinds of plugin copy it renders itself:-`manifest.i18n` for identity (`name` / `description` / `safetyNotes`), and-inline `{ en, "zh-CN" }` on a few chrome labels (`ui.title`, view titles,-settings destinations, session sources). Putting the same maps on generated-`contributes.settings` (and then on commands, tools, themes) would grow a second-incomplete i18n system inside the manifest: only two contract locales, two-declaration shapes, and still no way for a panel or widget to relabel its own-HTML.+The host resolves only the plugin copy it renders itself: `manifest.i18n` for+identity and inline locale maps on a few chrome labels. Extending that to+generated settings, commands, tools, and themes would grow a second incomplete+i18n system inside the manifest.## Decision-1. For **plugin-owned** copy the host publishes the active language and nothing- else: `pi.app.getLocale()`, `getAppearance().locale`, and- `appearance:changed` to open panels **and** loaded plugin processes.-2. Plugin-owned UI (panels, views, widgets, settings destinations, toasts,- runtime command titles) localizes itself from that tag.-3. Do not add more `PluginLocalizedString` maps to contribution fields.-4. Host-owned surfaces that render without plugin code keep the contracts they- already have: `manifest.i18n` (ADR 0267) and the shipped chrome labels in (2)- of the Context.+1. For plugin-owned copy the host publishes the active language and nothing else:+ `pi.app.getLocale()`, `getAppearance().locale`, and `appearance:changed`+ reach open panels and loaded plugin processes.+2. Plugin-owned UI — panels, views, widgets, settings destinations, toasts, and+ runtime command titles — localizes itself from that tag.+3. No further `PluginLocalizedString` maps are added to contribution fields:+ generated `contributes.settings` `title`, `description`, and `enum[].label`+ stay author-language strings, and a plugin needing localized settings ships+ `settingsDestinations`.+4. Host-owned surfaces that render without plugin code keep `manifest.i18n`+ (ADR 0267) and the shipped chrome labels.## Consequences-- A language switch restyles plugin-owned UI live, without a reload and without- rewriting the registry.-- Authors are not required to maintain bilingual maps for every setting.-- Existing host chrome localization is unchanged.+- A language switch restyles plugin-owned UI live, without a reload or a registry+ rewrite, and authors need not maintain bilingual maps per setting.## Alternatives-- **Host-resolved locale maps on every contribution field**: two models in one- manifest, still only `en` / `zh-CN`, and plugin HTML remains unsolved.-- **Resolve plugin copy in the renderer**: rejected in ADR 0267; the renderer- still must not parse a manifest.+- Host-resolved locale maps on every contribution field: rejected; two models in+ one manifest, still only `en` and `zh-CN`.+- Resolve plugin copy in the renderer: rejected in ADR 0267; the renderer must+ not parse a manifest.diff --git a/docs/adr/0281-host-speech-capability.md b/docs/adr/0281-host-speech-capability.mdindex b8ec1dc36..dd27d6ab8 100644--- a/docs/adr/0281-host-speech-capability.md+++ b/docs/adr/0281-host-speech-capability.md@@ -2,31 +2,33 @@- Status: Accepted for implementation (amended by [ADR 0291](0291-remove-speech-settings-ui.md))- Date: 2026-09-17-- Deciders: PI-Desktop core- Related: [ADR 0257](0257-plugin-real-time-capabilities.md) ·[03-runtime/20-speech](../spec/03-runtime/20-speech.md)## Context-Chat models, image generation, transcription, and speech synthesis are different-jobs. `@earendil-works/pi-ai` has no TTS/ASR surface, and Whisper / MIMO TTS-must not appear in the chat model picker.+Chat, image generation, transcription, and speech synthesis are different jobs, yet+`@earendil-works/pi-ai` has no TTS/ASR surface and Whisper or MIMO TTS must not appear+in the chat model picker.## Decision-1. The host owns a speech capability independent of chat: `transcribe(audio) →- text` and `synthesize(text) → audio`.-2. Bindings live on optional `AppSettings.speech` (no schema bump).-3. Built-in protocols: `openai_audio` (REST `/audio/transcriptions` and- `/audio/speech`) and `openai_chat_audio` (chat completions `audio` field;- MIMO `mimo-v2.5-tts`).+1. The host owns a speech capability independent of chat: `transcribe(audio) → text`+ and `synthesize(text) → audio`.+2. Bindings live on optional `AppSettings.speech` with no schema bump, each role+ naming a provider, a model id, and an open protocol id.+3. Built-in protocols are `openai_audio` (`/audio/transcriptions`, `/audio/speech`)+ and `openai_chat_audio`, which uses the chat completions `audio` field for MIMO+ `mimo-v2.5-tts`; a new vendor adds an adapter, not an IPC channel.4. Plugins may register a protocol with `pi.speech.registerAdapter` under- high-risk `speech.adapter.register`.-5. v1 product entry is the host API only: the `speech/*` IPC and plugin- adapters.-6. Out of scope: microphone / `pi.audio` device backend, Realtime, agent- `transcribe`/`speak` tools, audio as LLM content blocks, changing pi-ai.+ `speech.adapter.register`, while the host executes the HTTP plan and built-in ids+ stay reserved.+5. The v1 entry is the host API only — `speech/*` IPC and plugin adapters — with no+ Settings card or Composer control, since ADR 0291 withdrew both.## Consequences-An unconfigured role fails `SPEECH_NOT_CONFIGURED`.+- An unconfigured role fails `SPEECH_NOT_CONFIGURED`, and deleting the bound provider+ makes the binding fail `NOT_FOUND`.+- Unloading a plugin drops its protocols.+- Audio bytes never enter the renderer.diff --git a/docs/adr/0282-compaction-summary-retry-and-sizing.md b/docs/adr/0282-compaction-summary-retry-and-sizing.mdindex 1ac244b41..cbcc9f9fb 100644--- a/docs/adr/0282-compaction-summary-retry-and-sizing.md+++ b/docs/adr/0282-compaction-summary-retry-and-sizing.md@@ -2,97 +2,52 @@- Status: Accepted- Date: 2026-09-18-- Deciders: PI-Desktop runtime maintainers-- Amends: ADR 0049 (decision 1, the preflight guard; the "retry indefinitely"- rejection stands), D203 / ADR 0064 (the summary family only)-- Amended by: ADR 0302 (a prompt that still does not fit after the reduced pass- is summarized in chunks; only a range the planner cannot split falls back)+- Amends: ADR 0049 (decision 1, the preflight guard), D203 / ADR 0064 (the+ summary family only)+- Amended by: ADR 0302 (an oversized prompt is summarized in chunks)- Related: issue #543 · PR #554 (superseded) ·[03-runtime/02-agent-runtime](../spec/03-runtime/02-agent-runtime.md) ·- [03-runtime/01-ipc-protocol](../spec/03-runtime/01-ipc-protocol.md) ·E2E-084## Context-ADR 0049 made an automatic compaction failure survivable: when the summary-request fails, the runtime writes a retained-tail checkpoint (previous summary-if any, a fixed recovery notice, and a bounded tail) and the run continues.-Issue #543 reports that on real long sessions this fallback is the common-outcome rather than the exception: six of ten checkpoints on the reporter's-machine were the ~112-token recovery notice, and the transcript row labelled-every one of them `summary ≈112 tokens`.--1. **No retry on the summary request.** `compact()` was called with no- `RetryPolicy`, so pi-ai returned the first failed response as-is.-2. **The preflight guard measured the wrong thing.** It summed `estimateTokens`- over the raw messages, but pi-agent-core serializes the conversation into one- text prompt and caps every tool result at 2 000 characters while doing so.-3. **The UI could not tell a fallback from a summary.** `ContextCompactionMark`- only distinguishes the `fresh_window` rollover; a retained-tail checkpoint- rendered as a successful summary of N tokens.+ADR 0049 made a failed compaction summary survivable through a retained-tail+checkpoint, but on long sessions that fallback became the common outcome: the+summary request had no `RetryPolicy`, the preflight guard summed raw message+estimates instead of the serialized prompt pi actually sends (which caps tool+results), and the transcript row could not tell a fallback from a real summary.## Decision-1. **The summary request retries transient failures, bounded.**- `generateCompaction` passes pi-ai a `RetryPolicy` of three retries with 2 s /- 4 s / 8 s backoff (`COMPACTION_SUMMARY_RETRY_POLICY`). pi-ai's own classifier- decides what is transient: overload, 429/5xx, dropped streams, timeouts, and- connection resets retry; quota, billing, auth, and malformed requests return- on the first attempt.-2. **The preflight guard sizes the prompt pi will send.**- `compactionSummaryWouldExceedBudget` serializes the input with pi's own- `convertToLlm` + `serializeConversation` (tool results already capped) and- applies the four-characters-per-token heuristic the rest of the runtime uses.-3. **One bounded reduction before giving up.** When the full prompt still- exceeds the limit, the runtime tries exactly one reduced input: every tool- result cut to a 500-character prefix with a visible marker, assistant- thinking dropped.-4. **The mark says when a checkpoint is a fallback.** `ContextCompactionMark`- gains an optional `fallback?: "retained_tail"`, derived from the persisted- `details.fallback` the same way `summarized` is derived from- `details.strategy`.--Manual `/compact` inherits the retry and sizing (it is the same request) and-keeps its fail-fast, no-fallback semantics. The `fresh_window` family issues no-summary request and is untouched.+The summary request retries transient failures through a bounded pi-ai+`RetryPolicy` (`COMPACTION_SUMMARY_RETRY_POLICY`) whose classifier retries+overload, 429/5xx, dropped streams, timeouts, and resets while returning+quota, billing, auth, and malformed requests on the first attempt, with backoff+sleeps that honour the compaction abort signal. The preflight guard+(`compactionSummaryWouldExceedBudget`) serializes the input with pi's own+`convertToLlm` + `serializeConversation` and applies the runtime's+characters-per-token heuristic, counting the larger of the two requests for a+split turn, with the unchanged window limit. When the full prompt still exceeds+the limit the runtime tries exactly one reduced input that cuts tool results to+a 500-character prefix and drops assistant thinking while touching no message,+and only then falls back per ADR 0049. `ContextCompactionMark` gains an optional+`fallback?: "retained_tail"` derived from `details.fallback`, so the row reads+as a failure instead of `summary ≈N tokens`, additively and with no schema or+protocol change. Manual `/compact` inherits retry and sizing but keeps its+fail-fast semantics.## Consequences-- Sessions on a flapping provider keep a real model summary far more often; the- fallback is reserved for sustained failures and inputs that cannot be reduced- under the window.-- Tool-heavy sessions no longer skip the summary because of a raw-size estimate- that pi's serialization would never have sent.-- A compaction can now take up to ~14 s longer on a sustained outage before the- fallback lands.-- The reduced prompt can produce a thinner summary of tool output than the full- one would; it is still a model summary of the complete message range, which is- strictly better than the recovery notice it replaces.-- The transcript row is honest about fallbacks.--### Implementation note (2026-10-03)--The retry, sizing, reduction, and chunking contract remains unchanged.+- Sessions on a flapping provider keep a real model summary, and tool-heavy+ sessions no longer skip summarization on an overestimated size.+- A sustained outage can delay the fallback by the retry window, which Stop+ aborts immediately.+- A reduced prompt may summarize tool output more thinly, but it still covers+ every message behind the checkpoint boundary.## Alternatives-### Outer retry loop around `buildCheckpoint` (PR #554)--Rejected. It re-ran preparation and retried every recoverable failure including-deterministic ones, and could not tell a transient provider error from "no new-context to compact" without re-implementing pi-ai's classifier.--### Shrink by dropping the oldest messages (PR #554)--Rejected. The checkpoint's `throughMessageId` still covered the dropped-messages, so the summary silently claimed a range it had not seen.--### Map-reduce summarization for oversized inputs--Deferred. It is the right answer for inputs that do not fit even reduced, but it-changes the summary prompt contract and needs its own budget model.--### Retry inside the runtime with `provider-retry.ts`--Rejected. That module wraps `streamFn` and classifies streamed events; the-summary is a `completeSimple` call that pi-agent-core builds itself.+- An outer retry loop around `buildCheckpoint` (PR #554): rejected, it retried+ deterministic failures and duplicated pi-ai's classifier.+- Dropping the oldest messages: rejected, the checkpoint still claimed a range+ the summary had not seen.diff --git a/docs/adr/0283-remote-mcp-oauth.md b/docs/adr/0283-remote-mcp-oauth.mdindex 02f57f896..55a999476 100644--- a/docs/adr/0283-remote-mcp-oauth.md+++ b/docs/adr/0283-remote-mcp-oauth.md@@ -2,89 +2,61 @@- **Status**: Accepted- **Date**: 2026-09-18-- **Related**: [ADR 0038](0038-plugin-mcp-bridge.md) ·- [ADR 0098](0098-multiple-vendor-oauth-accounts.md) ·- [ADR 0142](0142-allow-non-loopback-http-mcp.md) ·- [03-runtime/01-ipc-protocol](../spec/03-runtime/01-ipc-protocol.md) ·- [03-runtime/06-host-rpc-protocol](../spec/03-runtime/06-host-rpc-protocol.md)+- **Related**: [ADR 0038](0038-plugin-mcp-bridge.md) · [ADR 0098](0098-multiple-vendor-oauth-accounts.md) · [ADR 0142](0142-allow-non-loopback-http-mcp.md)## Context-Remote HTTP MCP servers (such as Notion, Linear, or custom enterprise servers)-often protect endpoints with OAuth 2.1 authorization rather than static tokens.-Model Context Protocol specifies authorization discovery via RFC 9728 (OAuth-Protected Resource Metadata) and RFC 8414 (Authorization Server Metadata),-dynamic registration via RFC 7591, and resource indicators via RFC 8707.+Remote HTTP MCP servers such as Notion, Linear, or an enterprise server often+protect endpoints with OAuth 2.1 instead of static tokens, and MCP specifies+authorization discovery through RFC 9728 and RFC 8414, dynamic registration+through RFC 7591, and resource indicators through RFC 8707. PI-Desktop supported+only static HTTP headers, so users had to obtain bearer tokens by hand or could not+connect at all.## Decision-1. **Authentication Architecture**:- - OAuth login runs in the Electron main process via `McpOAuthManager`,- mirroring the `VendorOAuth` non-blocking pattern (ADR 0098):- `mcp/oauth/start` returns `{ ok: true, loginId }` immediately and streams- progress, authorization URL, completion, or failure events via- `pi-desktop/mcp/oauth/event`.- - IPC calls are never blocked during the user's browser interaction.-2. **Loopback & Security Boundaries**:- - The loopback callback server binds strictly to IPv4 loopback `127.0.0.1` on- an ephemeral port (`port 0`), and the redirect URI is formatted as- `http://127.0.0.1:<port>/callback` per RFC 8252 (preventing IPv6 loopback- resolution mismatches).- - Inbound query parameters (`error`, `error_description`, `code`, `state`)- rendered on the loopback HTML completion page are strictly HTML-entity- escaped to eliminate reflected XSS.- - Per ADR 0142, discovery and token requests use `redirect: "manual"` to- prevent silent cross-host redirect attacks.-3. **MCP Protocol Compliance**:- - RFC 8707 `resource` indicators are passed on both the authorization- endpoint and token exchange/refresh requests, pointing to the protected- resource URI discovered via RFC 9728.- - Dynamic Client Registration (RFC 7591) credentials (`clientId`,- `clientSecret`) are cached and reused for subsequent logins against the- same registration endpoint.- - Token lifetimes (`expires_in`) are parsed as numbers or strings (e.g.- `"3600"`), computing an absolute expiry time.-4. **Token Storage & Isolation**:- - OAuth tokens never reach the renderer.- - Token refresh operations are serialized per server to prevent race- conditions with rotating refresh tokens.- - Moving or renaming an MCP server (`mcp.transfer`) migrates the- corresponding `secret:mcp:<serverId>:oauth` to the new ID.-5. **Runtime Integration**:- - `UserMcpRuntime` injects the valid OAuth access token as `Authorization:- Bearer <token>` into live HTTP MCP connections.- - Token refreshes or re-authorizations invalidate stale connection entries so- live clients immediately adopt updated credentials.- - If a tool invocation returns a 401 Unauthorized status, the server is- marked with `authRequired: true` and `state: "failed"`.+OAuth login runs in Electron main inside `McpOAuthManager`, mirroring the+non-blocking vendor pattern of ADR 0098: `mcp/oauth/start` returns+`{ ok: true, loginId }` immediately and streams progress, the authorization URL,+completion, and failure through `pi-desktop/mcp/oauth/event`, while+`pi-desktop/mcp/oauth/cancel` closes the loopback listener and aborts the login.+The callback server binds strictly to IPv4 loopback on an ephemeral port with an+RFC 8252 redirect URI, escapes every inbound query parameter on its completion+page, and uses `redirect: "manual"` for discovery and token requests per ADR 0142.+RFC 8707 `resource` indicators are sent on the authorization and token requests,+dynamic-registration credentials are reused for the same registration endpoint, and+`expires_in` is parsed from numbers or strings. Tokens never reach the renderer:+they live in host-core encrypted secrets under `secret:mcp:<serverId>:oauth`,+refresh is serialized per server because refresh tokens rotate, and `mcp.transfer`+migrates the secret to the new id. `UserMcpRuntime` injects+`Authorization: Bearer <token>` into live connections and drops stale entries when+a token refreshes, and a `401` marks the server `authRequired: true` with+`state: "failed"`.## Consequences-- Remote HTTP MCP servers requiring OAuth 2.1 PKCE can be authorized securely- from the Settings UI.-- Long-running browser interactions do not block IPC channels or leave orphan- HTTP listeners upon window reload or quit.-- Token material is kept out of the renderer process and ordinary logs.+- OAuth-protected remote servers can be authorized from Settings, and a long+ browser interaction blocks no IPC channel or leaves an orphan listener on+ reload or quit.+- Token material stays out of the renderer and ordinary logs.+- Endpoints must be HTTPS except for loopback, so a local or LAN-loopback+ authorization server still works while the MCP resource may stay `http://`.## Amendment (2026-09-18) — landing hardening-- Authorization-server endpoints (`authorization_endpoint`, `token_endpoint`,- `registration_endpoint`, discovered `authorization_servers`, and- `resource_metadata`) must be HTTPS.-- Dynamic client registration prefers RFC 8252 portless- `http://127.0.0.1/callback` plus the current exact URI.-- Loopback `/callback` validates `state` before looking at `error` or `code`.-- `invalid_grant` on refresh deletes the stored secret; transient 5xx keeps the- existing access token.-- `mcp/oauth/start` passes the listed `McpServerRecord` through to- `onAuthorized` so a project-level server that is not in the current workspace- runtime can still handshake after login.-- Scope selection initially used an MVP heuristic (`default` if advertised, else- `scopes_supported[0]`); the amendment below supersedes it.+Registration prefers the RFC 8252 portless loopback redirect and reuses a stored+client only when that URI is on file or the exact current redirect matches.+`/callback` validates `state` before reading `error` or `code`, a mismatched+`state` does not abort the login, and a replay of a consumed callback returns+409. `invalid_grant` on refresh deletes the stored secret while a transient 5xx+keeps the access token, and `mcp/oauth/start` passes the `McpServerRecord` through+to `onAuthorized` so a project-level server can handshake after login.## Amendment (2026-09-29) — issuer discovery and resource scopes (#1221)-- Preserve issuer paths when discovering authorization metadata: try OAuth path- insertion, OIDC path insertion, then OIDC path appending.-- Request scopes from the initial 401 Bearer challenge first, otherwise all- valid `scopes_supported` entries from protected-resource metadata.+Issuer paths are preserved during discovery by trying OAuth path insertion, then+OIDC path insertion, then OIDC path appending, with root issuers keeping the root+URLs. Scopes come from the initial 401 Bearer challenge, otherwise from+`scopes_supported` in protected-resource metadata, and `scope` is omitted when+neither supplies one, because an authorization-server scope catalog does not+describe the resource.diff --git a/docs/adr/0284-headless-runtime-boundary.md b/docs/adr/0284-headless-runtime-boundary.mdindex 5f79ea1e7..5f0f04d05 100644--- a/docs/adr/0284-headless-runtime-boundary.md+++ b/docs/adr/0284-headless-runtime-boundary.md@@ -10,73 +10,69 @@## Context-Rollout R1 delivered the headless Agent Host module (`packages/agent-host`):-admission, the turn queue, the approval broker, the event log, and the snapshot-builder run without Electron. Everything underneath it did not.+Rollout R1 delivered the headless Agent Host module (`packages/agent-host`), but+everything underneath it lived in `apps/desktop/electron/main` and was reached+through the desktop's own IPC handlers: the stdio transports to host-core and the+sidecar, the restart supervisor, the durable turn lifecycle, transcript persistence,+the in-flight reply checkpoint, and approved Plan/Goal execution (D189).++R2 needs the same runtime where no Electron exists: the `pi-host` bundle+(`02-architecture/05-remote-agent-control.md` §5.2) must run the Agent Host module,+the sidecar, and host-core behind a RACP server. Re-implementing the turn lifecycle+would create a second source of truth for the invariants the desktop spent a year+fixing — abort locks, stale terminal events, single-flight finalization, queue+release after durable settlement.## Decision1. **A new workspace package, `packages/host-runtime`, owns the- Electron-independent runtime layer.** It depends on `shared`, `agent-host`,- and `agent-runtime` only, and never on `electron` or on `apps/desktop`.- - `HostProcess` and `AgentSidecar`: the stdio NDJSON JSON-RPC transports,- moved from Electron main unchanged in behavior.- - `RuntimeSupervisor`: the restart policy of process-model §4 (0.5s → 1s → 2s- capped at 4s, three restarts per two-minute window, single flight per- child, never during shutdown, stop on the first unrecoverable failure).- - `RuntimeService`: `RuntimePort` for the Agent Host module on top of the two- transports — prompt admission with the durable turn row and the user- message appended before the sidecar starts, steer, stop, abort with the- abort lock, asktool answers, manual compaction, and `finishTurn` with the- same claim-before-await rule, stale-terminal guard, and settlement- announcement as Electron main.- - `TurnEventPipeline` and `TurnPersistence`: the per-event pass (tool-call- tracking, D299 checkpoints, terminal events, completed rows) and an- in-memory ordered append queue with a bounded retry while host-core- restarts.- - `createHeadlessLaunchResolver`: launch resolution from host-core's own- registries (providers and secrets, the effective command shell, project- instructions and memory, user skills, subagent definitions).- - `PlanExecutionDispatcher`: approved Plan/Goal execution (D189) with the- same claim, no-replay, and finalization rules.- - Host-core adapters for the module's `SessionPort`, `QueueStore` (schema- v15), and `permissions.pending`, plus the session-message ledger lookup,- the inflight checkpointer, and the plan-execution decoders, moved out of- Electron main.-2. **Electron main keeps thin adapters.** `electron/main/host-process.ts` and- `agent-sidecar.ts` subclass the package classes and add only what Electron- knows: the packaged binary and bundled-plugin locations, the- `ELECTRON_RUN_AS_NODE` launch, redacted stderr logging, and the- schema-too-new / glibc diagnoses.-3. **`TurnStartRequest` gains an optional `userMessageId`** so a client can keep- its optimistic user row id through the headless runtime, exactly as the- renderer does through IPC (D288).-4. **No wire contract changes.** Electron IPC, the sidecar JSON-RPC, host-core- RPC, and the Plugin SDK are untouched; the desktop's observable behavior,- defaults, and persisted data are unchanged.+ Electron-independent runtime layer**, depending on `shared`, `agent-host`, and+ `agent-runtime` only, never on `electron` or `apps/desktop`:+ - `HostProcess` and `AgentSidecar` — the stdio NDJSON JSON-RPC transports, unchanged+ in behavior but taking their launch as options, with the sidecar's `host.proxy`+ allowlist, local-tool short circuit, Plan-mode gate, vendor-auth check, and+ trusted-extension bridge intact.+ - `RuntimeSupervisor` — the process-model §4 restart policy, single flight per+ child, never during shutdown, stopping on the first unrecoverable failure.+ - `RuntimeService` — `RuntimePort` for the module: prompt admission with the+ durable turn row and user message appended before the sidecar starts, steer,+ stop, the abort lock, asktool answers, manual compaction, and `finishTurn` with+ the desktop's claim-before-await rule, stale-terminal guard, and settlement+ announcement.+ - `TurnEventPipeline` and `TurnPersistence` — the per-event pass (tool-call+ tracking, D299 checkpoints, terminal events, completed rows) and an ordered+ append queue with bounded retry while host-core restarts; a `pi-host` process+ ends only with its supervisor, so no file-backed outbox is duplicated.+ - `createHeadlessLaunchResolver`, `PlanExecutionDispatcher` (D189), and host-core+ adapters for `SessionPort`, `QueueStore` (schema v15), `permissions.pending`, the+ session-message ledger, the inflight checkpointer, and the plan-execution+ decoders. The resolver refuses vendor OAuth accounts and plugin agents.+2. **Electron main keeps thin adapters**: `host-process.ts` and `agent-sidecar.ts`+ subclass the package classes to add packaged locations, `ELECTRON_RUN_AS_NODE`,+ redacted stderr, and schema-too-new / glibc diagnoses, while+ `runtime/lifecycle.ts` drives the shared supervisor and renderer status pushes. The+ local prompt path (`agent-ipc.ts`) stays desktop-owned.+3. **`TurnStartRequest` gains an optional `userMessageId`** so a client keeps its+ optimistic user row id through the headless runtime (D288). Additive.+4. **No wire contract changes**: Electron IPC, sidecar JSON-RPC, host-core RPC, and+ the Plugin SDK are untouched, and desktop behavior, defaults, and persisted data+ are unchanged.## Consequences-- `pi-host` (R2) can compose `HostProcess + AgentSidecar + RuntimeService +- AgentHost + RuntimeSupervisor` in plain Node; the RACP server binds to the- module, never to Electron IPC.-- The restart policy, the turn lifecycle, and the transports now have unit tests- that run without Electron (`packages/host-runtime/src/*.test.ts`).-- The desktop's source-contract tests that pinned `host-process.ts` and- `agent-sidecar.ts` now read the package sources; the renderer-facing status- and diagnosis assertions still read the Electron adapters.-- Local Electron main still runs its own prompt path through IPC.-- The headless resolver deliberately supports less than the desktop: no prompt- attachments, no plugin tools, no desktop MCP relay, no vendor OAuth.+- `pi-host` composes `HostProcess + AgentSidecar + RuntimeService + AgentHost ++ RuntimeSupervisor` in plain Node, and the restart policy, turn lifecycle, and+ transports become testable without Electron; the RACP server binds to the module+ rather than to Electron IPC.+- Local desktop sessions still run their own prompt path, and the headless resolver+ deliberately supports less — no attachments, plugin tools, MCP relay, or vendor+ OAuth — returning typed errors instead of degrading silently.-## Alternatives considered+## Alternatives-- **Extract only the transports and re-implement the turn lifecycle in- `pi-host`.** Rejected: the lifecycle invariants are the hard part, and a- second copy would drift from the desktop's.-- **Keep the modules in `apps/desktop/electron/main` and import them from- `pi-host`.** Rejected: `packages/*` must not depend on desktop implementation- code, and the modules would keep growing Electron imports.-- **Put the runtime into `packages/agent-host`.** Rejected: the module is the- transport-free semantic core with no process or filesystem knowledge, and the- RACP server and integrations depend on it staying that way.+- Extract only the transports and re-implement the lifecycle in `pi-host`: the+ invariants are the hard part and a copy would drift.+- Keep the modules in `apps/desktop/electron/main`: `packages/*` must not depend on+ desktop implementation code.+- Put the runtime into `packages/agent-host`: that module must stay free of process+ and filesystem knowledge.diff --git a/docs/adr/0285-racp-ws-transport.md b/docs/adr/0285-racp-ws-transport.mdindex 880760119..2545df26b 100644--- a/docs/adr/0285-racp-ws-transport.md+++ b/docs/adr/0285-racp-ws-transport.md@@ -2,64 +2,60 @@- Status: Accepted for implementation- Date: 2026-09-18-- Decision: D448-- Related: ADR 0205 (D373 / D374 / D375), ADR 0284 (D447),- `03-runtime/19-remote-agent-control-protocol.md` §3, §4, §8, §11.1, §14a,- `05-security/02-remote-control-security.md` §3.4, §5.1+- Related: D373, D374, D375, D447, D448, ADR 0205, ADR 0284## Context-R0 froze the RACP contract as typebox schemas and R1 delivered the headless-Agent Host module. Nothing yet moved a JSON-RPC frame between two processes: the-module was only driven by Electron IPC.+R0 froze the RACP contract as typebox schemas and R1 delivered the headless Agent Host+module, but nothing moved a JSON-RPC frame between processes: R2 needs the normative+`RACP-WS` binding on both sides of an SSH tunnel — a server the `pi-host` bundle binds on+loopback and a client Electron main runs — plus the device-token pairing of security §3.4.## Decision-1. **A new workspace package, `packages/racp`, holds both ends of the binding.**- It depends on `shared`, `agent-host`, and `ws` only.-2. **The server is a thin catalog over the module.** Every operation in- `RACP_OPERATIONS` is dispatched through the catalog's role rule; the session,- turn, event, approval, and input operations call the Agent Host module- directly; the remote-host profile (session catalog mutations, projects,- workspace reads, terminals) goes through the `RacpHostOperations` interface- that `pi-host` implements.-3. **Header-profile authentication with Host-issued device tokens.** The upgrade- request must carry `Authorization: Bearer`; a token in the URL, a- non-loopback peer, a wrong path, a missing subprotocol, or a binary frame is- refused before any RPC.-4. **Three catalog additions, all in the remote-host profile:**- `connection/pair`, `project/register`, and `project/browse`.-5. **Reconnect is the client's, replay is the Host's.** The client reconnects- with bounded backoff, rejects the dropped connection's in-flight calls with- `HOST_DISCONNECTED`, and never re-sends them; it remembers the last durable- cursor per session so the caller resubscribes with `after`.-6. **`StartTurnParams.input.userMessageId`** is threaded from `turn/start`'s- `input.messageId` through the queue record to the runtime, so a remote client- keeps its optimistic user row id (D288) the way the renderer does over IPC.+1. A new workspace package, `packages/racp`, holds both ends of the binding and depends on+ `shared`, `agent-host`, and `ws` only; `RacpServer` and `RacpClient` take an injected+ transport, so the same code runs over `ws` in production and an in-memory pair in tests,+ with `bindRacpWebSocket` and `wsClientTransport` as the adapters.+2. The server is a thin catalog over the module: every operation in `RACP_OPERATIONS`+ dispatches through the catalog's role rule, core session, turn, event, approval, and input+ operations call the module directly, and the remote-host profile goes through+ `RacpHostOperations`, which `pi-host` implements.+3. Authentication is a header profile with Host-issued device tokens: the upgrade request+ must carry `Authorization: Bearer`, and a token in the URL, non-loopback peer, wrong path,+ missing subprotocol, or binary frame is refused before any RPC; `pdt1.` device and `ppt1.`+ pairing tokens are stored as SHA-256 hashes and compared in constant time, and a pairing+ token is single-use, expiring, and authenticates only `connection/pair`, which mints an+ `owner` device.+4. Three catalog additions, all in the remote-host profile — `connection/pair`,+ `project/register`, and `project/browse` — come with the shared error codes+ `PAIRING_FAILED`, `PAIRING_TOKEN_EXPIRED`, `CAPABILITY_UNAVAILABLE`,+ `REMOTE_PATH_NOT_FOUND`, `REMOTE_PATH_FORBIDDEN`, `HOST_DISCONNECTED`,+ `HOST_BOOTSTRAP_FAILED`, `HOST_VERSION_MISMATCH`, `REMOTE_AUTH_FAILED`,+ `REMOTE_CONNECTION_FAILED`, and `REMOTE_FORWARD_FAILED`; `connection/initialize` gains+ `server.hostId`.+5. Reconnect is the client's and replay is the Host's: the client reconnects with bounded+ backoff, rejects the dropped connection's in-flight calls with `HOST_DISCONNECTED`,+ never re-sends them, and remembers the last durable cursor per session so the caller+ resubscribes with `after`, while the Host answers with a replay or a snapshot plus+ `resyncReason` and a dropped connection releases its subscriptions without touching a+ turn.+6. `StartTurnParams.input.userMessageId` is threaded from `turn/start`'s `input.messageId`+ through the queue record to the runtime, so a remote client keeps its optimistic user row+ id (D288).## Consequences- `pi-host` composes `RacpServer` + `bindRacpWebSocket` over the module and`RuntimeService` (ADR 0284); the desktop adapter composes `RacpClient` +`wsClientTransport`.-- The conformance behaviors of spec §14 that do not need a machine boundary- (handshake, authorization, idempotency, queue ordering, approval decisions,- cursor replay, eviction, epoch change, slow clients, reconnect without- duplicate execution) are tests in `packages/racp` and run without Electron.-- Attachments and the tool relay are advertised as unavailable (`attachments:- false`, `toolRelay: false`) and their operations fail with- `CAPABILITY_UNAVAILABLE`; they land with their own change.-- The server bind refuses a non-loopback address outright rather than offering a- TLS path; a non-loopback deployment is a later decision.+- Attachments and the tool relay are advertised as unavailable (`attachments: false`,+ `toolRelay: false`) and fail with `CAPABILITY_UNAVAILABLE` until their own change.+- The server bind refuses a non-loopback address rather than offering a TLS path.-## Alternatives considered+## Alternatives-- **Run RACP inside Electron main first (development loopback endpoint).**- Rejected for this change: the only scheduled client is the desktop, and the- first server is `pi-host`; a desktop-side listener would add a network surface- with no consumer.-- **Cookie profile alongside the header profile.** Rejected: it belongs to the- unscheduled browser milestone (D375).-- **Static shared secret instead of pairing.** Rejected by security §3.2 and- §3.4: a pairing token must be single-use and become a per-device credential- that can be revoked on its own.+- Run RACP inside Electron main first: the only scheduled client is the desktop, so a+ desktop listener would add network surface with no consumer.+- Static shared secret instead of pairing: security §3.2 and §3.4 require a single-use+ token that becomes a revocable per-device credential.diff --git a/docs/adr/0286-remote-host-desktop-kernel.md b/docs/adr/0286-remote-host-desktop-kernel.mdindex 30bd7d5d6..ba4ec29e6 100644--- a/docs/adr/0286-remote-host-desktop-kernel.md+++ b/docs/adr/0286-remote-host-desktop-kernel.md@@ -4,122 +4,72 @@- Date: 2026-09-18- Decision: D449- Related: ADR 0205 (D373 / D374 / D375), ADR 0285 (D448),- `03-runtime/19-remote-agent-control-protocol.md` §3.4, §4, §5, §7, §8,- `05-security/02-remote-control-security.md` §3.4,- `06-delivery/07-remote-control-rollout.md` §2 R2+ `03-runtime/19-remote-agent-control-protocol.md` §3.4## Context-ADR 0285 delivered the `RACP-WS` transport and pairing on both ends. The-`pi-host` bundle now binds a real WebSocket server on loopback and speaks the-frozen contract; a `RacpClient` in `packages/racp` reaches it with header-authentication.--- The renderer must never learn the transport.-- The frozen architecture pins `apps/desktop/electron/main/index.ts` at 1500 LOC- (`scripts/check-architecture.mjs`).-- The desktop cannot open a network listener of its own (security §7).+ADR 0285 delivered the `RACP-WS` transport and pairing on both ends, but the+desktop still lacked the kernel that lets the renderer treat a remote session+exactly like a local one (spec §3.4). The renderer must not learn the transport,+`index.ts` is pinned at 1500 LOC by the architecture gate, and the desktop cannot+open a network listener, so every outbound flow goes through the RACP client to a+paired host.## Decision-The desktop-side R2 kernel is five modules and one boot hook, all under-`apps/desktop/electron/main/remote/` (module state) and-`apps/desktop/electron/main/bootstrap/` (boot state), and one new workspace-dependency (`@pi-desktop/racp`).-1. **A single interception seam: `backend-router.ts`.** The router is consulted- from `ipc/register.ts`'s `handle()` wrapper; it returns the sentinel- `ROUTE_LOCAL` when no `RemoteBackend` is registered for the call's session- id, and the local handler runs unchanged.-+ from `ipc/register.ts`'s `handle()` wrapper and returns `ROUTE_LOCAL` when no+ `RemoteBackend` is registered for the call's session id, so a session turns+ remote only once its `remote:<hostKey>:<hostSessionId>` id is registered.2. **A stateless per-request session id.** `sessionIdForCall` recovers the- session from either the first positional argument, `first.sessionId`,- `first.id` (`sessionGet` uses this shape), or a- `<remoteSessionId>#racp-approval:<hostApprovalId>` requestId used by tool- approval.--3. **A transport-agnostic backend: `remote-backend.ts`.** One- `createRemoteBackend({hostKey, client, ...})` instance serves every session- of a paired host — the router registers it under each id.-+ session from the first positional argument, `first.sessionId`, `first.id`, or+ the `<remoteSessionId>#racp-approval:<hostApprovalId>` requestId used by tool+ approval, so approval routing needs no correlation map.+3. **A transport-agnostic backend: `remote-backend.ts`.** One instance per paired+ host serves all of its sessions, translating 17 channels into RACP requests+ and reshaping results into the shapes `api.ts` already returns; channels the+ remote profile does not cover report false from `handles()` or throw+ `CAPABILITY_UNAVAILABLE` and fall back to the local handler.4. **Two synthesis rules to reconcile schema mismatches without a round-trip.**- - Tool-approval resolution has no session id in its wire payload, so the- backend encodes `<remoteSessionId>#racp-approval:<hostApprovalId>` into the- requestId (§ Decision 2) and decodes it back for `approval/respond`.- - `plansResolve` returns `PlanResolutionResult` to the renderer, but RACP's- `approval/respond` returns only `RacpApprovalResult`.--5. **A pure event bridge: `remote-event-bridge.ts`.** RACP events are translated- into `IPC.event.agentMessage` / `IPC.event.sessionsChanged` for the renderer.--6. **A coordinator per paired host: `remote-host-connection.ts`.**- `createRemoteHostConnection({hostKey, client, router, emit})` composes the- backend, the bridge, and the router.--7. **A `RemoteHostClient` seam with multi-listener `subscribe`.** The connection- consumes `{request, subscribe}`.--8. **Encrypted-at-rest registry: `remote-host-registry.ts`.** Paired hosts live- in `<dataDir>/remote-hosts.json`.+ Tool approval encodes the session into its requestId, and `plansResolve`+ synthesizes a minimal `PlanProposal` that the follow-up `session.changed` event+ replaces with the authoritative snapshot.+5. **A pure event bridge: `remote-event-bridge.ts`.** RACP events become+ `IPC.event.agentMessage` / `IPC.event.sessionsChanged`, forwarding the+ `AgentEvent` in `payload.event`, turning `tool` kind `approval.requested` into+ `tool_permission_request`, dropping plan and goal approvals in favour of+ `planning_state`, and signalling `session.created` / `archived`.+6. **A coordinator per paired host: `remote-host-connection.ts`.** Its `open()`+ sequence of attach listener, subscribe host scope, `session/list`,+ per-session subscribes closes the create race, and `close()` is idempotent and+ safe before `open()`.+7. **A `RemoteHostClient` seam with multi-listener `subscribe`.**+ `racp-remote-host-client.ts` is the only remote module importing+ `@pi-desktop/racp`; it fans the client's single callback out to every listener+ and swallows listener throws.+8. **Encrypted-at-rest registry: `remote-host-registry.ts`.** Paired hosts live in+ `<dataDir>/remote-hosts.json` with device tokens encrypted through+ `safeStorage` behind an `EncryptionPort`, `upsert` refuses to write when the+ keychain is unavailable, and `list` drops records it cannot decrypt.+9. **Boot hook: `bootstrap/remote-hosts.ts`.** It opens one adapter and one+ connection per registered host, logging and skipping a failing host, with an+ empty registry as a full no-op; `startup.ts` opens in the background and+ `shutdown.ts` closes paired sockets before host-core is disposed.-9. **Boot hook: `bootstrap/remote-hosts.ts`.** `createRemoteHostsBoot(...)`- reads the registry, opens one adapter + one connection per host, and returns- `{open, closeAll}`.--## Invariants the kernel keeps--- **Renderer transport-agnosticism.** The renderer's `api.ts` code does not- mention "remote".-- **Router-off default.** With no `RemoteBackend` registered, `route()` returns- `ROUTE_LOCAL` for every call and the existing handler runs unchanged.-- **Least privilege at rest.** No plaintext device token ever touches disk.-- **Bounded shutdown.** `closeAll` closes every paired socket inside the same- `Promise.allSettled` block that handles plugin, sidecar, and MCP disposals,- before `host-core` is disposed, so in-flight remote turns can send their abort- over a live socket.--## Out of scope--The kernel is complete for a paired host to answer renderer calls and stream-events. What is scheduled for later stages of R2:+## Consequences-- **Pairing UX (renderer + IPC).** Settings surfaces to enter a URL and pairing- token, exchange it, and store the device token.-- **SSH bootstrap (Stage 4).** A supervisor that detects system `ssh`, downloads- the `pi-host-bundle` (verified by SHA-256 from ADR 0285's release pipeline),- starts the remote binary, and opens the `-L` tunnel.-- **Terminal work-panel client (Stage 5).** RACP terminal events are dropped by- the event bridge; the work-panel session client will consume them.-- **Reverse tool relay (Stage 6).** A `RelayToolPort` bridge that lets the agent- host run local desktop tools against a remote session.-- **Resync watchdog.** `resync.required` events are dropped today; the- connection layer will eventually rebuild subscriptions from the last cursor- per session (`RacpClient.cursorFor`).-- **Multi-listener contract.** `subscribe()` is used by exactly one consumer- today (the event bridge); Stage 3b's resync watchdog will be the second.+- Adding an encrypted host entry to `<dataDir>/remote-hosts.json` is enough for+ the desktop to connect and stream events into the existing renderer.+- With no pairing the kernel is a zero-behavior change: `route()` returns+ `ROUTE_LOCAL` for every call and existing handlers run unchanged.+- `apps/desktop` gains an additive `@pi-desktop/racp` dependency, `index.ts` stays+ at 1500 LOC, and later stages plug into the router, bridge, and registry seams.## Alternatives considered-- **Route from each per-domain IPC handler.** Every one of 17 handlers would- need to know about "remote" and duplicate the same dispatch.-- **Bake remote knowledge into the renderer.** A `remote:` prefix visible to the- renderer forces `api.ts` to branch, and every store slice ends up aware of the- transport.-- **Have the connection layer own its own RacpClient construction.** It would- couple the coordinator to `packages/racp` and prevent unit tests from running- without a real client.-- **A single-listener `RemoteHostClient`.** Simpler, but forces the resync- watchdog and the event bridge to share the same callback.--## Consequences--- The desktop can host a paired remote `pi-host` today; adding a URL and device- token to `<dataDir>/remote-hosts.json` (encrypted-at-rest through- `safeStorage`) makes the kernel connect, register sessions, and stream events- into the existing renderer, no other flag or setting required.-- `apps/desktop` now depends on `@pi-desktop/racp`, and the racp package- publishes a `./test-harness` export subpath.-- `apps/desktop/electron/main/index.ts` stays at exactly 1500 LOC.-- Any Stage 4–7 work (SSH bootstrap, terminal work-panel client, reverse tool- relay, pairing UX) plugs into existing seams — the router, the event bridge,- the registry — and does not need to revisit the transport layer.+- Route from each per-domain IPC handler: every handler would duplicate the same+ dispatch and every new channel would need wiring twice.+- Bake remote knowledge into the renderer: a `remote:` prefix in `api.ts` forces+ every store slice to know the transport, which spec §3.4 forbids.+- A plain-text registry: a compromised backup would hand out device tokens that+ authenticate against a real `pi-host`.diff --git a/docs/adr/0287-host-rendered-plugin-scenic-settings-surfaces.md b/docs/adr/0287-host-rendered-plugin-scenic-settings-surfaces.mdindex e5e85c45f..66a6786c9 100644--- a/docs/adr/0287-host-rendered-plugin-scenic-settings-surfaces.md+++ b/docs/adr/0287-host-rendered-plugin-scenic-settings-surfaces.md@@ -6,27 +6,23 @@## Context-An Electron `WebContentsView` and a sandboxed iframe each create an independent-compositing surface. Although an extension document can make its own background-transparent, its page canvas remains an opaque rectangle between the root scenic-backdrop and the Settings content.+An Electron `WebContentsView` and a sandboxed iframe each composite their own+surface, so an extension document with a transparent background still paints an+opaque rectangle between the root scenic backdrop and the Settings content, and+native child surfaces can intercept the renderer-drawn Windows and Linux controls.## Decision-The generic plugin Settings document surface is retired for appearance-extensions. `contributes.scenicThemes` supplies declarative localized card-metadata only.--Card selection is immediate. The bounded 0–20 integer blur control is a local-draft until the user presses Apply; the host then uses the existing typed theme-variable persistence boundary.+The generic plugin Settings document surface is retired for appearance extensions:+`contributes.scenicThemes` supplies declarative localized card metadata only, and+Electron main validates the permissions, same-plugin theme ownership, declared+preview image, and the exact `--nexus-backdrop-blur` `length` variable. The host+React tree renders every control inside its existing transparent scenic canvas,+card selection is immediate, and the bounded blur control stays a draft until+Apply. There is no iframe, page protocol, bridge, or second canvas.## Consequences-- A single root scenic backdrop remains visible through Settings surfaces.-- Host-owned layout, focus, search, narrow-window behavior, drag regions, and- native controls cannot be changed or intercepted by plugins.-- Plugins cannot contribute Settings HTML, CSS, JavaScript, selectors, DOM, or- arbitrary actions through this capability.-- This deliberately narrow destination does not replace isolated work-panel- views or plugin panels.+- One root scenic backdrop stays visible through Settings surfaces.+- Host-owned layout, focus, search, drag regions, and native controls cannot be+ changed or intercepted, and plugins contribute no Settings HTML, CSS, or actions.diff --git a/docs/adr/0288-package-local-theme-assets.md b/docs/adr/0288-package-local-theme-assets.mdindex 6ed98d671..22cdae4e1 100644--- a/docs/adr/0288-package-local-theme-assets.md+++ b/docs/adr/0288-package-local-theme-assets.md@@ -7,28 +7,26 @@## Context-ADR 0255 made external absolute paths available to theme contributions. That-supports a theme whose plugin owns a user-selected image outside its package,-but an absolute path cannot identify an image in an installed marketplace-archive on another machine.+ADR 0255 allowed external absolute paths for theme contributions, which cannot+identify an image inside an installed marketplace archive on another machine, while+host-rendered scenic Settings destinations need images that travel with the theme+package.## Decision-1. A declared theme asset may be either an extension-whitelisted absolute path- or an extension-whitelisted package-relative path.+1. A declared theme asset may be an extension-whitelisted absolute path, keeping+ ADR 0255's validation and percent-encoded URL keys, or a package-relative path.2. The host resolves a package-relative path with `resolveInsidePlugin`, rejects- traversal and `node_modules`, verifies existence and the shared asset budget,- then records the resolved file under its package-relative key.-3. Absolute assets retain ADR 0255's existing validation, percent-encoded URL- keys, and runtime registration behavior.-4. The `plugin-asset:` protocol remains the sole renderer access path.-5. Scenic card previews must name one declared asset owned by the same plugin.+ traversal and `node_modules`, checks existence and the shared asset budget, then+ records the file under its package-relative key.+3. `plugin-asset:` remains the sole renderer access path: it serves only registry+ files with the extension MIME allowlist, no-store and nosniff, and is revoked on+ disable, unload, or crash.+4. Scenic card previews must name a declared asset of the same plugin and add no+ filesystem, network, or renderer-DOM authority.## Consequences-- Marketplace theme packs can ship portable local art without exposing arbitrary- filesystem reads.-- Existing themes that intentionally name an external absolute path keep- working.-- Theme authors must declare every image and font; an undeclared CSS `url()` is- rejected before it reaches the renderer.+Marketplace theme packs ship portable local art without arbitrary filesystem reads,+themes naming an absolute path keep working, and an undeclared CSS `url()` is+rejected before it reaches the renderer.diff --git a/docs/adr/0289-signed-macos-github-releases.md b/docs/adr/0289-signed-macos-github-releases.mdindex a5ff23311..d7cc6337f 100644--- a/docs/adr/0289-signed-macos-github-releases.md+++ b/docs/adr/0289-signed-macos-github-releases.md@@ -2,56 +2,59 @@- Status: Accepted- Date: 2026-09-18-- Deciders: PI-Desktop core- Decision: D450- Amends: ADR 0022, ADR 0145, ADR 0191, ADR 0204, D078- Related: D120, D126, D164, D364, ADR 0197, ADR 0232, ADR 0257, ADR 0278, E2E-196a, E2E-196c, E2E-067A## Context-Official GitHub tag releases already produce native macOS arm64 and Intel x64-DMG/ZIP artifacts, merge `latest-mac.yml`, and ship `electron-updater`. The-default CI lane still disabled identity discovery, skipped notarization, and-kept packaged macOS on notify-and-link delivery because unsigned artifacts-cannot provide a qualified in-app upgrade.+Tag releases already produced native arm64 and x64 DMG/ZIP artifacts with a+merged `latest-mac.yml`, but the CI lane skipped identity discovery and+notarization, so packaged macOS stayed on notify-and-link delivery because+unsigned artifacts cannot support a qualified in-app upgrade. Local packaging+without a certificate must stay possible (D078), and contributors must not+commit certificate material, yet a Developer ID certificate for team+`DUV63RKYTW` is now available for the official release lane.## Decision-1. Every GitHub tag release (`vX.Y.Z`) Developer ID-signs the app through- electron-builder 26 and notarizes it with `xcrun notarytool`- (`-c.mac.notarize=true`).-2. The signing certificate is `Developer ID Application: XingYu Liu- (DUV63RKYTW)`; Apple team id `DUV63RKYTW`.-3. Certificate material stays in GitHub Actions secrets: `CSC_LINK` (p12, file- path or base64), `CSC_KEY_PASSWORD`, `APPLE_ID`,- `APPLE_APP_SPECIFIC_PASSWORD`, and `APPLE_TEAM_ID`.-4. Local `pnpm dist:mac` / `pnpm pack` remain unsigned when no identity is- configured.-5. Packaged macOS uses the existing in-app `electron-updater` lane (ZIP + merged- `latest-mac.yml` + `quitAndInstall`), same as Windows NSIS and Linux- AppImage.-6. Do not reintroduce `afterPack` / `afterSign` adhoc codesign (ADR 0278).- electron-builder's Developer ID pass signs the app, helpers, and the- `pi-desktop-host-core` sidecar.-7. The unsigned first-launch note and ZIP helper remain for trusted local or- debug unsigned builds.-8. Hardened runtime stays on.+1. Every `vX.Y.Z` tag release Developer ID-signs the app through electron-builder+ 26 and notarizes it with `xcrun notarytool`, submitting the DMG separately+ because electron-builder notarizes only the app, and requiring+ `status: Accepted` before stapling and before verification of the stapled+ tickets. Only stapling and ticket validation retry, and only after Apple+ accepts the matching submission; missing secrets fail the job and unsigned+ artifacts are never published from a tag.+2. CI pins the identity as `CSC_NAME=XingYu Liu (DUV63RKYTW)`, the bare common+ name electron-builder accepts, while verification re-adds the+ `Developer ID Application:` prefix when comparing the `codesign` authority.+3. Certificate material lives only in the GitHub Actions secrets `CSC_LINK`,+ `CSC_KEY_PASSWORD`, `APPLE_ID`, `APPLE_APP_SPECIFIC_PASSWORD`, and+ `APPLE_TEAM_ID`, and none of that set is committed, echoed, or written into+ electron-builder config.+4. Local `pnpm dist:mac` and `pnpm pack` stay unsigned without a configured+ identity, `scripts/release-macos.sh` remains the local signed lane, and+ `sign_macos: false` exists only for debug artifacts.+5. Packaged macOS uses the existing `electron-updater` lane (ZIP, merged+ `latest-mac.yml`, `quitAndInstall`) like Windows NSIS and Linux AppImage,+ while deb/rpm and Windows portable stay notify-and-link.+6. Ad-hoc `afterPack` / `afterSign` codesign is not reintroduced (ADR 0278), and+ hardened runtime stays on with the minimum entitlements: V8 JIT, unsigned+ executable memory, library-validation disable, and microphone input for the+ plugin capture permission (ADR 0257).## Consequences-- Users who download a tagged DMG should open PI-Desktop without a Gatekeeper- “unidentified developer” or quarantine-damaged warning.-- Packaged macOS installs can check GitHub Releases, download the arch ZIP, and- restart into the new version.-- Windows and Linux packaging, artifact names, and updater modes are unchanged.-- Operators must create the five Actions secrets before the next tag.+- A downloaded tagged DMG opens without a Gatekeeper unidentified-developer or+ quarantine-damaged warning.+- Packaged macOS installs update in-app; existing unsigned installs may still+ need one manual signed DMG first.+- Windows and Linux packaging and updater modes are unchanged, but operators+ must create the five Actions secrets before the next tag.-## Alternatives considered+## Alternatives-- Keep unsigned tag artifacts and opt-in signing: rejected; it leaves production- users on the Gatekeeper warning path.-- Hard-code the identity in `apps/desktop/package.json`: rejected; local+- Keep unsigned tag artifacts with opt-in signing: rejected, it leaves+ production users on the Gatekeeper warning path.+- Hard-code the identity in `apps/desktop/package.json`: rejected, localpackaging without the certificate must keep working (D078).-- Apple API key (`APPLE_API_KEY`) instead of Apple ID + app-specific password:- deferred; the existing electron-builder 26 Apple ID path is already wired.-- Separate macOS updater implementation: rejected; reuse `electron-updater`.diff --git a/docs/adr/0290-resizable-sidebar-collapse-threshold.md b/docs/adr/0290-resizable-sidebar-collapse-threshold.mdindex b0aaec015..9b6edf693 100644--- a/docs/adr/0290-resizable-sidebar-collapse-threshold.md+++ b/docs/adr/0290-resizable-sidebar-collapse-threshold.md@@ -5,50 +5,42 @@- Decision: D459- Amends: [ADR 0141](0141-sidebar-width-resize.md) ·[ADR 0238](0238-three-column-width-priority.md)-- Related: [01-ui-ia](../spec/04-ux/01-ui-ia.md) ·- [07-ui-design-system §10](../spec/04-ux/07-ui-design-system.md) ·- [08-component-spec](../spec/04-ux/08-component-spec.md) ·- [09-interaction-patterns §8](../spec/04-ux/09-interaction-patterns.md) ·- E2E-168+- Related: [01-ui-ia](../spec/04-ux/01-ui-ia.md) · E2E-168## Context-ADR 0141 made the expanded sidebar a persisted `240px..520px` column. D408 / ADR-0238 later pinned that column at 275px and hid the handle so the three-column-budget could treat the left dock as a constant while MainChat kept a 450px-floor.+ADR 0141 made the expanded sidebar a persisted `240px..520px` column, and D408 /+ADR 0238 pinned it at 275px with the handle hidden so the three-column budget+could treat the left dock as a constant. Users still need to widen it for long+labels and reclaim space, and dragging past a usable minimum should fold the+sidebar instead of leaving a cramped strip.## Decision-1. Restore ADR 0141's renderer-owned handle on the expanded sidebar's right- edge.-2. A pointer width below `160px` collapses the sidebar immediately.-3. The live maximum is the three-column remainder after MainChat's 450px floor- and, when the work panel occupies space, its requested width.-4. Renderer only. No IPC, native-window bounds, host protocol, or storage schema- change.+The renderer-owned handle returns on the expanded sidebar's right edge: pointer+motion previews a width anchored at press, clamped to `240px..520px` with the+`275px` default, release persists it, ArrowLeft/ArrowRight step, Home and End+jump to the live bounds, and Escape, lost capture, or unmount restore the+press-time width. A pointer width below `160px` collapses the sidebar as a user+action without recording an automatic-yield or persisting the in-progress width,+while keyboard resize never collapses and `Cmd/Ctrl+B` stays the keyboard fold.+The live maximum is the three-column remainder after MainChat's 450px floor and+the work panel's requested width, so a chosen width cannot trip D408's yield,+while work-panel growth and window shrink still collapse the sidebar. Nothing+but the renderer changes, and `pi.desktop.sidebarWidth` remains the persistence+key.## Consequences-- Long labels and compact workspaces share one persisted width instead of a- fixed 275px column.-- Dragging the handle left past the snap threshold folds the sidebar the same- way the explicit collapse control does, without writing a sub-minimum width.+- Long labels and compact workspaces share one persisted width instead of a fixed+ 275px column.+- Dragging past the snap threshold folds the sidebar without writing a+ sub-minimum width.- MainChat's 450px floor and the work-panel yield order stay intact.## Alternatives rejected-### Keep the D408 fixed 275px column--Rejected because it blocks the same inspection and space-reclaiming need ADR-0141 already recorded, and the live budget can cap a user-chosen width without-freezing it.--### Collapse at 240px with no snap zone--Rejected because hitting the minimum during a small adjustment would fold the-sidebar.--### Persist the in-progress width on collapse--Rejected because collapse is a cancel of the current gesture plus a fold.+- Keep the fixed 275px column: rejected; it blocks a need ADR 0141 already+ recorded, and the budget can cap a chosen width without freezing it.+- Persist the in-progress width on collapse: rejected; collapse cancels the+ gesture, so the preferred width stays what it was at pointer-down.diff --git a/docs/adr/0291-remove-speech-settings-ui.md b/docs/adr/0291-remove-speech-settings-ui.mdindex 0d1ce8fd2..5a5e2d49c 100644--- a/docs/adr/0291-remove-speech-settings-ui.md+++ b/docs/adr/0291-remove-speech-settings-ui.md@@ -2,72 +2,54 @@- Status: Accepted- Date: 2026-09-19-- Deciders: PI-Desktop core- Amends: [ADR 0281](0281-host-speech-capability.md) (its v1 product entry)-- Related: [04-ux/06-settings-ia.md](../spec/04-ux/06-settings-ia.md) ·- [04-ux/08-component-spec.md](../spec/04-ux/08-component-spec.md) ·- [03-runtime/20-speech.md](../spec/03-runtime/20-speech.md) ·- [06-delivery/04-e2e-test-plan.md](../spec/06-delivery/04-e2e-test-plan.md)+- Related: [04-ux/06-settings-ia.md](../spec/04-ux/06-settings-ia.md) · [03-runtime/20-speech.md](../spec/03-runtime/20-speech.md) · [06-delivery/04-e2e-test-plan.md](../spec/06-delivery/04-e2e-test-plan.md)## Context-ADR 0281 added the host speech capability: `transcribe` / `synthesize` over an-optional `AppSettings.speech`, two built-in protocols, a high-risk-`speech.adapter.register` plugin adapter, and no audio bytes in the renderer.-Its item 5 named the v1 product entry as a **Voice** card in Settings → AI plus-Composer transcription and draft speech.+ADR 0281 added the host speech capability and named its v1 product entry as a+**Voice** card in Settings → AI plus Composer transcription and draft speech. The+Composer controls were later removed (PR #555) while the host services stayed, so+the card became the only renderer consumer of `speech/getStatus`,+`speech/transcribe`, and `speech/synthesize`, and its locale keys and spec claims+outlived the controls they described. The product does not want a speech+configuration surface in Settings for a capability whose only customers are+plugins and direct IPC callers.## Decision-1. **Remove the Voice card.** Settings → AI renders no speech surface.-2. **Remove the renderer leftovers.** The AI destination in- `lib/settings-search.ts` no longer indexes `settings.speechTitle`,- `settings.speechTranscribe`, or `settings.speechSynthesize`; the- `.settings-row:has(.settings-speech-fields)`, `.settings-speech-fields`, and- `.settings-speech-lead` rules leave `styles/settings.css`; the thirteen- `settings.speech*` keys leave all eight shipped locale catalogs; and the- seven unreferenced `chat.transcribe*` / `chat.speak*` keys written for the- withdrawn Composer controls leave them too.-3. **Keep the capability.** ADR 0281 items 1–4 and 6 stay in force:+1. Remove the Voice card: Settings → AI renders no speech surface, and the card+ component and its mount are deleted.+2. Remove the renderer leftovers: the AI destination stops indexing+ `settings.speechTitle`, `settings.speechTranscribe`, and+ `settings.speechSynthesize`, the speech styles leave the settings stylesheet,+ and the `settings.speech*` keys plus the unreferenced `chat.transcribe*` and+ `chat.speak*` keys leave every shipped catalog.+3. Keep the capability: ADR 0281 items 1–4 and 6 stay in force, so`speech/getStatus`, `speech/transcribe`, `speech/synthesize`,- `validateSpeechSettings`, the built-in `openai_audio` / `openai_chat_audio`- protocols, the plugin `speech.adapter.register` permission, and the renderer- API bridge in `lib/api.ts` are unchanged.-4. **Bindings stay written by a caller.** `AppSettings.speech` keeps its shape,- validation, and persisted semantics; a binding is written through the host- settings API (`settings/set`), and its consumers are plugins and IPC calls.-5. **Keep the Composer entry points withdrawn and correct their claims.** ADR- 0281 item 5's Composer transcription and draft-speech actions stay withdrawn:- the controls they describe were already removed in `344ef4ec2`, so their copy- is retired and `04-ux/08-component-spec.md` §2.5 no longer describes them.+ `validateSpeechSettings`, the built-in `openai_audio` and+ `openai_chat_audio` protocols, the `speech.adapter.register` permission, and+ the renderer API bridge are unchanged, and audio bytes still never enter the+ renderer.+4. Bindings stay caller-written: `AppSettings.speech` keeps its shape, validation,+ and persisted semantics, a binding is written through `settings/set`, and no+ migration runs and no stored binding is dropped.+5. Keep the Composer entry points withdrawn and correct their claims: ADR 0281+ item 5's Composer actions stay withdrawn, and the settings and component specs+ now state that speech is not a Settings surface.## Consequences-- A user can no longer configure a transcription or speech provider from the- app.-- Removing the renderer's only speech consumer also removes its use of the- protocol catalog: `speech/getStatus` is now called by no renderer module,- while the IPC channel and its contract stay.-- The renderer sheds the card, its styles, its search keywords, and its locale- keys in eight catalogs; no host, protocol, permission, or schema change- accompanies it.-- The user-visible speech vocabulary (Whisper, TTS, voices) no longer appears in- the app shell at all, so the chat model picker is the only model surface.+- Users can no longer configure a transcription or speech provider in the app,+ although plugins, IPC callers, and already stored bindings keep working.+- The renderer drops its only speech consumer together with its styles, search+ keywords, and locale keys, with no host, protocol, permission, or schema change.+- Speech vocabulary no longer appears in the app shell, leaving the chat model+ picker as the only model surface.-## Alternatives considered+## Alternatives-### Keep the card and hide it behind a developer flag--Rejected: a hidden surface still owns styles, locale keys, and a provider-protocol catalog, and it would keep a second provider picker alive in an app-whose speech consumers are plugins.--### Remove the host capability with the UI--Rejected: the capability is a shipped contract with an ADR, an IPC surface, and-a high-risk plugin permission.--### Keep the card and ship the Composer actions--Rejected: the Composer controls were built and deliberately removed in the same-release cycle (`344ef4ec2`, PR #555).+- Hide the card behind a developer flag: rejected, a hidden surface still owns+ styles, locale keys, and a provider picker.+- Remove the host capability with the UI: rejected, it would break plugin adapters+ and stored bindings for a change that only touches Settings.diff --git a/docs/adr/0292-ssh-remote-host-bootstrap.md b/docs/adr/0292-ssh-remote-host-bootstrap.mdindex 57cbfbf24..68d5a0070 100644--- a/docs/adr/0292-ssh-remote-host-bootstrap.md+++ b/docs/adr/0292-ssh-remote-host-bootstrap.md@@ -11,116 +11,94 @@This record describes the original bootstrap decision, not the current candidateinstallation contract. ADR 0326 permits a verified release upload only after-`download-failed`, bundles matching Node, and separates daily startup from pairing.-The historical constraints and alternatives below remain context for that amendment.+`download-failed`, bundles matching Node, and separates daily startup from pairing;+the constraints below remain context for that amendment.## Context-ADR 0286 delivered the desktop-side R2a kernel and left the bootstrap explicitly-out of scope: "Every paired host today assumes the loopback URL already exists."-Reaching another machine meant the user installed `pi-host` there, started it,-opened `ssh -L` themselves, and pasted the resulting URL and a pairing token-into Settings.--- `release.yml` publishes `pi-host-<version>-<platform>-<arch>.tar.gz` and its- `.sha256` to the `v<version>` GitHub Release, and the bundle matrix is Linux- x64 only.-- A paired host is a URL in `remote-hosts.json`, but a bootstrapped host has no- stable URL: the local port of a forward is chosen per launch.-- `bootstrap/remote-hosts.ts` already owns every host's lifecycle, so the- bootstrap plugs into that layer instead of beside it.+ADR 0286 left bootstrap out of scope: every paired host assumed the loopback URL+already existed, so reaching another machine meant installing `pi-host` by hand,+opening `ssh -L`, and pasting the URL and pairing token into Settings. R2's exit+criteria do not accept that (rollout §2 R2b, security §3.4). The desktop must+install and pair a host on a machine the user already reaches over SSH while never+uploading executable bytes and never holding an SSH secret. Three properties shaped+the design: the release publishes `pi-host-<version>-<platform>-<arch>.tar.gz` with+a `.sha256` for Linux targets only; a bootstrapped host has no stable URL because the+forward's local port is chosen per launch; and `bootstrap/remote-hosts.ts` already+owns every host's lifecycle.## Decision-The bootstrap is five modules under `apps/desktop/electron/main/remote/`, one-extended boot hook, and one new IPC channel.--1. **The system `ssh` client is the transport.** Shelling out to `ssh` beats- linking an SSH library because the user's `~/.ssh/config`, agent, jump hosts,- and `known_hosts` then apply unchanged, and the app never holds a secret to- leak.--2. **Pure release coordinates (`pi-host-release.ts`).** The artifact is resolved- for the *remote* platform at the *desktop's* version, and the SHA-256 the- release publishes is the trust anchor.--3. **One script runs remotely (`pi-host-bootstrap-script.ts`).** It downloads- the pinned URL, verifies the digest, installs under- `$HOME/.pi-desktop/pi-host`, (re)starts the host on loopback with `--pair`,- and echoes `PI_HOST_READY` / `PI_HOST_PAIRING_TOKEN`.--4. **`ssh-transport.ts` is a port, not a dependency.** `exec` / `execWithInput`- / `forward` / `dispose` let the orchestrator be tested end to end against a- fake with no process spawned; `createSystemSshTransport` is the only- implementation that spawns.--5. **Forwards are durable and owned, not incidental (`ssh-tunnel.ts`).** The- persisted record stores the SSH descriptor, not a URL; the manager reserves a- loopback port, runs `ssh -N -L 127.0.0.1:<local>:127.0.0.1:<remotePort>`, and- derives `ws://127.0.0.1:<port>/v1/racp/ws` per launch, so a restart- re-establishes the tunnel before connecting instead of dialling a stale port.--6. **Version parity is checked before a forward exists.** The desktop's version- is what gets downloaded — there is no version negotiation — and- `PI_HOST_READY.version` must equal it (`v` prefix tolerated either way).--7. **The registry keeps a descriptor, not a URL.** `metadata.transport = "ssh"`- plus `metadata.ssh` (host, optional port / user / identity file,- `remotePort`, `version`).-+1. **The system `ssh` client is the transport.** It keeps `~/.ssh/config`, the+ agent, jump hosts, and `known_hosts` in force and leaves the app holding no+ secret. `BatchMode=yes` fails an interactive-password host immediately with a+ typed error instead of hanging a hidden prompt, and `StrictHostKeyChecking=accept-new`,+ `ConnectTimeout=15`, and `ExitOnForwardFailure=yes` are always set.+2. **Pure release coordinates (`pi-host-release.ts`).** The artifact resolves for the+ *remote* platform at the *desktop's* version, and the published SHA-256 is the+ trust anchor. `PUBLISHED_TARGETS` (`linux-x64`, `linux-arm64`) refuses other+ targets with `HOST_BOOTSTRAP_FAILED` before a download. URL derivation, `uname`+ parsing, checksum parsing, digest comparison, and version parity are pure.+3. **One script runs remotely (`pi-host-bootstrap-script.ts`).** It downloads the+ pinned URL, verifies the digest, installs under `$HOME/.pi-desktop/pi-host`,+ (re)starts the host on loopback with `--pair`, and echoes `PI_HOST_READY` /+ `PI_HOST_PAIRING_TOKEN` under `umask 077`, so the single-use token exists only in+ a work file and on stdout. Failures exit non-zero after+ `PI_HOST_BOOTSTRAP_FAILED <step>`, and every input is quoted by `shellQuote`.+4. **`ssh-transport.ts` is a port, not a dependency.** `exec` / `execWithInput` /+ `forward` / `dispose` allow tests against a fake, with+ `createSystemSshTransport` the only spawning implementation. `execWithInput` pipes+ the script into `sh -s`, and `assertSshArgument` refuses empty values or those+ starting with `-`.+5. **Forwards are durable and owned (`ssh-tunnel.ts`).** The record stores the SSH+ descriptor, not a URL; the manager reserves a loopback port, runs+ `ssh -N -L 127.0.0.1:<local>:127.0.0.1:<remotePort>`, and derives+ `ws://127.0.0.1:<port>/v1/racp/ws` per launch. The bootstrap's own forward is+ adopted rather than reopened, and a forward counts as ready only once its local+ port accepts a connection.+6. **Version parity is checked before a forward exists.** A `PI_HOST_READY.version`+ mismatch raises `HOST_VERSION_MISMATCH` (D375) and the desktop tears down the SSH+ processes it spawned.+7. **The registry keeps a descriptor**: `metadata.transport = "ssh"` plus+ `metadata.ssh` (host, optional port / user / identity file, `remotePort`,+ `version`). Because `remote-hosts.json` is user-editable it is re-validated on+ every read, degrading to "not an SSH host" rather than spawning `ssh` with+ garbage, and records without `transport` read as `direct`.8. **One IPC channel and one pairing exchange.**- `pi-desktop/remoteHost/bootstrap` joins `list` / `pair` / `remove` and- carries a host, never a credential.+ `pi-desktop/remoteHost/bootstrap` joins `list` / `pair` / `remove` and carries a+ host, never a credential. `connection/pair` was factored into+ `exchangePairingToken`, shared with the pasted-URL path and closing its throwaway+ connection on every path; `bootstrapHost` adopts the forward before persisting the+ record.-## Invariants+## Consequences-- No SSH secret is stored, prompted for, or transmitted by the app.-- No executable bytes travel over the SSH channel.-- `pi-host` keeps binding loopback only.-- The renderer stays transport-agnostic.-- An empty registry stays a full no-op: nothing connects and no tunnel opens.-- A failed bootstrap leaves nothing running: its transport is disposed unless- the caller adopts the forward, and an SSH host whose connect fails has its- tunnel closed rather than left idle.+- No SSH secret is stored, prompted for, or transmitted, and no executable bytes+ travel over the channel: the remote script downloads the bundle and the desktop+ sends only script text on stdin. `pi-host` keeps binding loopback only, and the+ renderer stays transport-agnostic with `RemoteHostSummary.transport` as a label.+- `remote-hosts.json` gains a second record shape and stays backward compatible. The+ desktop now spawns `ssh` processes, visible to endpoint-security tooling, and the+ new `settings.remoteHosts` i18n keys must be translated in every shipped locale.+ No SSH library, HTTP client, or archive tool enters `apps/desktop`.+- A failed bootstrap leaves nothing running, an empty registry is a no-op, and a+ machine without outbound GitHub access still cannot be bootstrapped (D375).## Out of scope-Still open for R2b and later:-- **Terminal work-panel client (Stage 5)** and **reverse tool relay (Stage 6)**- from ADR 0286.-- **Provider configuration over the SSH channel.** Spec §3.4 and §5.2 name it as- part of the bootstrap step, but it needs host-side provider schema work and is- not in this change, so a freshly bootstrapped host still fails `turn/start`- closed with `MODEL_NOT_CONFIGURED` until a provider is configured on it.-- **The resync watchdog**: `resync.required` events are still dropped.-- **Non-Linux remote targets, and Windows as a *remote* target.** Only- `linux-x64` and `linux-arm64` are published (D638 / ADR 0318), so both are- refused before a download starts.--## Alternatives considered--- **An `ssh2`-style library instead of the system client.** Rejected: it- re-implements config, agent, and jump-host semantics the user already has, and- asks them to re-enter credentials the app should never hold.-- **Download the artifact on the desktop and upload it.** Rejected by security- §3.4: the desktop never uploads executable bytes.-- **Let the script read the published `.sha256` itself.** Rejected: the desktop- should hold the trust anchor, and this keeps the script's only input a URL- plus a digest.-- **Store the forwarded URL in the registry.** Simpler read path, but the local- port is not stable across launches, so a restart would dial a port nothing- listens on.--## Consequences--- `remote-hosts.json` gains a second record shape and stays backward compatible:- existing records have no `transport` and are read as `direct`.-- A machine without outbound GitHub access still cannot be bootstrapped (D375).-- The desktop now spawns `ssh` processes, which is new and visible to- endpoint-security tooling; until now the remote stack only opened outbound- WebSocket connections.-- The 16 new `settings.remoteHosts` i18n keys must be translated in every- shipped locale, because the catalog type is exhaustive.-- No new runtime dependency: the bootstrap adds no SSH library, no HTTP client,- and no archive tool to `apps/desktop`.+ remain unbuilt, and `resync.required` events are still dropped.+- **Provider configuration over SSH** needs host-side schema work, so a freshly+ bootstrapped host still fails `turn/start` closed with `MODEL_NOT_CONFIGURED`.+- **Non-Linux remote targets** are refused before a download starts, since only+ `linux-x64` and `linux-arm64` are published (D638 / ADR 0318).++## Alternatives++- An `ssh2`-style library: re-implements config, agent, and jump-host semantics and+ asks users to re-enter credentials the app should never hold.+- Download on the desktop and upload: rejected by security §3.4.+- Let the script read the published `.sha256`: the desktop holds the trust anchor.+- Store the forwarded URL: the local port is not stable across launches.+- Install into a user-level service manager: `$HOME` plus a pidfile stays+ privilege-free.diff --git a/docs/adr/0293-ssh-password-authentication.md b/docs/adr/0293-ssh-password-authentication.mdindex 313803655..e449643d7 100644--- a/docs/adr/0293-ssh-password-authentication.md+++ b/docs/adr/0293-ssh-password-authentication.md@@ -1,124 +1,67 @@# ADR 0293: SSH password authentication for the remote-host bootstrap-- Status: Accepted+- Status: Accepted (D454; amends [ADR 0292](0292-ssh-remote-host-bootstrap.md), whose+ no-SSH-secret clause is narrowed to the default key/agent path)- Date: 2026-09-19-- Decision: D454-- Amends: [ADR 0292](0292-ssh-remote-host-bootstrap.md) — its "no SSH secret is-- Related: [ADR 0286](0286-remote-host-desktop-kernel.md) (D449), ADR 0205 (D373),- `02-architecture/05-remote-agent-control.md` §5.2,- `05-security/02-remote-control-security.md` §3.4+- Related: D373, D449, D454, ADR 0205, ADR 0286, ADR 0292## Context-ADR 0292 bootstraps a `pi-host` on a machine the user already reaches over SSH-by shelling out to the system `ssh` client. That choice was made deliberately-and its main argument was that the app holds no SSH secret at all:-`~/.ssh/config`, the agent, and `known_hosts` decide the login, so there is-nothing for the app to leak.--- The transport spawns `ssh` with no terminal, so a password cannot simply be- handed over; OpenSSH must be given a way to ask for one.-- A secret that must survive a restart to keep reconnecting is a secret at rest,- and the app already has exactly one encrypted-at-rest store it trusts.-- The transport is a port (`SshTransport`) with the bootstrap and the tunnel- manager on the other side of it, so whatever carries the secret has to be- expressible through that seam.+ADR 0292 bootstraps a `pi-host` by shelling out to the system `ssh` client with+`BatchMode=yes` enforcing that the app holds no SSH secret, but that does not cover a+fresh cloud instance, NAS, or container host reachable from a terminal after one+password prompt — the user would have to install a key first, which is the detour the+bootstrap exists to remove. Accepting a password means the app holds a secret, so the+decision is what shape that takes.## Decision-1. **Password auth is opt-in, and a key or agent stays the default.** Absent- credentials, the argv is byte-for-byte what ADR 0292 produced,- `BatchMode=yes` included.--2. **The secret reaches `ssh` through OpenSSH's own askpass helper**- (`remote/ssh-askpass.ts`).--3. **`BatchMode=yes` becomes `BatchMode=no` only when a password is supplied,- together with `NumberOfPasswordPrompts=1` and `PubkeyAuthentication=no`.**- The helper answers every prompt with the same secret, so a retry could only- repeat a wrong password, and repeated failures are what trip a server's own- lockout.--4. **The credential is short-lived.** Material is written when a child is about- to authenticate and deleted once it cannot still be prompting: after an- `exec` / `execWithInput` child has closed, after a forward's local port is- up, or on `dispose`.--5. **The password is persisted encrypted, in a new record field.**- `RemoteHostRecord.sshSecret` is written to `remote-hosts.json` as- `encryptedSshSecret` through the same `safeStorage`-backed `EncryptionPort`- the device token already uses, and read back the same way.--6. **The secret never reaches the renderer.** `RemoteHostSshMetadata` stays- secret-free by construction: it is plaintext metadata, it is stored in- `metadata`, and it is echoed to the renderer inside- `RemoteHostBootstrapResult`.--7. **A password that cannot work is refused before anything runs.** A line break- cannot survive the askpass round trip, so `assertSshPassword` rejects one- with `INVALID_ARGUMENT` in the bootstrap rather than letting it become a- failed authentication.--8. **The Settings surface says what it does.** The SSH form gains an- authentication mode with a masked password field and a reveal toggle, and its- description states that the login password is saved in the OS keychain so the- host reconnects after a restart.--## Invariants--- With no password supplied, nothing changes: same argv, same `BatchMode=yes`,- no credential file created, no askpass variables set.-- The password is never an `ssh` argument, never an environment variable value,- never in a URL, never in a log line, and never in a renderer payload.-- Credential files exist only inside a `0700` directory, only for the interval- in which an `ssh` child can still prompt, and are removed on every path —- including `dispose` and a failed `forward`.-- Nothing but the system `ssh` client consumes the secret; no library, no second- credential store, and no keychain entry of its own.-- A malformed or absent descriptor still degrades to "not an SSH host" rather- than to a spawn with junk arguments.--## Out of scope--- **Interactive (non-persisted) prompting.** The password is supplied once by- the user in Settings and either remembered encrypted or not at all; there is- no "ask me each time" mode, which would need a main-process prompt surface.-- **Keyboard-interactive auth as a separate mode.** `ssh` treats it as the same- prompt, so the helper answers both with one secret and there is no second- switch to expose.-- **Windows support**, as above, and **non-Linux remote targets**, unchanged- from ADR 0292.-- **Key passphrase storage.** A passphrase unlocks a local key; the askpass- helper answers that prompt only as a side effect of the same secret being- supplied for the login.--## Alternatives considered--- **`sshpass`, or `SSH_ASKPASS` with the secret in the environment.** Rejected:- `sshpass` is a third-party dependency that must be installed, and either form- exposes the secret to anything that can read the process environment or- arguments — including other users on a shared machine.-- **A PTY and a scripted `expect`-style dialog.** Rejected: it reintroduces a- pseudo-terminal whose prompts and timing the desktop would have to parse, and- it makes an interactive prompt possible again on a path that was designed to- fail closed.-- **Store the password unencrypted in `metadata`.** Rejected: `metadata` is- plaintext, is user-editable, and is not covered by the keychain, so it would- put a reusable credential into a file the app cannot protect.-- **Keep nothing at rest and ask on every launch.** Rejected for now: it would- make an SSH host the only paired host that needs a human at startup, so a- restart would silently leave it offline.+1. Password auth is opt-in and a key or agent stays the default: absent credentials the+ argv is byte-for-byte what ADR 0292 produced, `BatchMode=yes` included.+2. The secret reaches `ssh` through OpenSSH's own askpass helper+ (`remote/ssh-askpass.ts`): `SSH_ASKPASS` names a generated `/bin/sh` script and+ `SSH_ASKPASS_REQUIRE=force` makes `ssh` use it without a terminal, with the script+ reading the secret from a `0600` file in a `0700` `mkdtemp` directory, so the secret+ is never an `ssh` argument or environment value.+3. Password mode alone sets `BatchMode=no` with `NumberOfPasswordPrompts=1` and+ `PubkeyAuthentication=no`: the helper answers every prompt with the same secret, so a+ retry could only repeat a wrong password and trip a server lockout.+4. The credential is short-lived: material is written just before a child authenticates+ and deleted once it cannot still be prompting — after an `exec` / `execWithInput`+ child closes, after a forward's local port is up, or on `dispose` — with a reference+ count keeping a shared copy alive across concurrent children.+5. The password is persisted encrypted: `RemoteHostRecord.sshSecret` is written as+ `encryptedSshSecret` through the same `safeStorage`-backed `EncryptionPort` the device+ token uses, and `metadata.ssh` gains `auth: "password"` as its only new value, so key+ descriptors and earlier records keep their shape.+6. The secret never reaches the renderer: `RemoteHostSshMetadata` stays secret-free by+ construction, the password travels beside it from the IPC request into+ `SshTarget.password` and back out as `SshBootstrapOutcome.sshSecret` for the caller to+ encrypt, and `RemoteHostSummary` is unchanged.+7. A password that cannot work is refused before anything runs: `assertSshPassword`+ rejects a line break with `INVALID_ARGUMENT` because it cannot survive the askpass+ round trip, Windows is refused with `HOST_BOOTSTRAP_FAILED` naming the remedy, and a+ host recorded as `auth: "password"` without a usable secret reports as disconnected+ rather than as a rejected login.+8. The Settings SSH form gains an authentication mode with a masked password field and+ reveal toggle, states that the password is saved in the OS keychain so the host+ reconnects after a restart, and the copy promising no password was ever stored is+ replaced in all shipped locales.## Consequences-- The desktop can now be asked to hold an SSH password, which is a real widening- of what the app is trusted with.-- `remote-hosts.json` gains an optional `encryptedSshSecret` and- `metadata.ssh.auth`.-- Users can now bootstrap a host whose only credential is a password, which- removes the terminal detour that ADR 0292's `BatchMode=yes` left in place.-- Server-side lockout policy becomes reachable through the app: one wrong saved- password produces one failed attempt per connect.-- The `settings.remoteHosts` copy that claimed no password is ever stored had to- change in eight locales, and the claim in ADR 0292 needed an explicit- amendment rather than a quiet edit.+- The desktop can now be trusted with an SSH password — a real widening, bounded by being+ opt-in per host, encrypted with the existing store, and never exposed to the renderer,+ the process table, a URL, or a log line.+- `remote-hosts.json` gains an optional `encryptedSshSecret` and `metadata.ssh.auth`; both+ are additive and the file version stays `1`.+- A host whose only credential is a password can be bootstrapped, removing the terminal+ detour; nothing but the system `ssh` client consumes the secret, and a malformed+ descriptor degrades to "not an SSH host".++## Alternatives++- `sshpass` or `SSH_ASKPASS` with the secret in the environment: a third-party dependency+ that exposes the secret to anything reading process state.+- Store the password unencrypted in `metadata`: plaintext, user-editable, and outside the+ keychain.diff --git a/docs/adr/0294-project-archive-list-inspector.md b/docs/adr/0294-project-archive-list-inspector.mdindex e790ad521..3b67b181e 100644--- a/docs/adr/0294-project-archive-list-inspector.md+++ b/docs/adr/0294-project-archive-list-inspector.md@@ -2,49 +2,37 @@- Status: Accepted- Date: 2026-09-20-- Decision: D455+- Related: D133, D257, D455, E2E-038- Amends: D267 / D168 (row anatomy and inline expansion)-- Related: D133 (archive always visible), D257 (capability workbench),- [04-ux/06-settings-ia.md](../spec/04-ux/06-settings-ia.md),- [06-delivery/04-e2e-test-plan.md](../spec/06-delivery/04-e2e-test-plan.md)- (E2E-038)## Context-D267 collapsed Project archive to one workbench: a quiet intro, one toolbar, and-one panel whose Pinned / All projects / Archived groups were in-panel strips.-Each row still carried a disclosure control, two lines of metadata, state tags,-a hover action pair, and an inline session list.+D267 collapsed Project archive into one workbench with in-panel Pinned, All+projects, and Archived groups, but each row still carried a disclosure control,+two metadata lines, tags, a hover action pair, and an inline session list. Adding+projects made the destination hard to scan, expanding a row pushed the rest of the+index, and clicking a name activated the project and left Settings.## Decision-1. **Keep the intro and toolbar.** One description line, Recent/Name sort,- search with a live match count, and Add project.-2. **Replace the single expanding list with a list + inspector.** The index- keeps Pinned / All projects / Archived as labelled regions with per-section- counts.-3. **Click selects; activation is explicit.** A click (or ArrowUp/ArrowDown)- selects the row and keeps Settings open.-4. **The inspector owns management, in one column.** Folders, chats (latest- first, batches of eight), New task, and the existing menu (instructions,- memory, edit, pin, archive/restore, two-step delete, close) open under the- selected row at full content width.-5. **Search still matches session titles.** A session-title hit keeps the owning- project in the index, selects it, and lists the matching chats in the- inspector.-6. **Presentation and renderer-local archive state.** No IPC, host-owned- storage, or host protocol changes.+The intro and toolbar stay: one description line, Recent or Name sort, search with+a live match count, and Add project, with no hero or page-level counters (D267).+The expanding list becomes a list plus inspector: Pinned, All projects, and+Archived stay labelled regions with per-section counts, and compact rows show the+color glyph, name, one status tag, session count, and relative time. A click or+ArrowUp/ArrowDown selects a row and keeps Settings open, while double-click, Enter,+or the inspector Open action activates the project and returns to chat. The+inspector owns management in one column under the selected row at full content+width — folders, chats, New task, and the existing menu — with no side-by-side pane+and no visibility toggle (D133). Search still matches session titles. Everything is+renderer-local: no IPC, storage, or protocol change, and explicitly activating an+archived project clears its presentation state while mere selection does not.## Consequences-- Compact rows stay scannable; only the selected project opens its full-width+- Compact rows stay scannable and only the selected project opens its full-widthdetail.-- A single click no longer leaves Settings, which is the management path; the- chat path is Open / double-click / Enter / opening a session.-- Source-contract tests for the archive destination now cover the workbench and- the extracted `project-archive` helpers.--## Alternatives--- Keep inline expansion and add a density toggle.-- Hide archived records behind a filter.+- A single click no longer leaves Settings, so the chat path is Open,+ double-click, Enter, or opening one of its sessions.+- Source-contract tests now cover the workbench and the extracted+ `project-archive` helpers.diff --git a/docs/adr/0295-session-thinking-parameter-omission.md b/docs/adr/0295-session-thinking-parameter-omission.mdindex d8421bfe7..0b4458e28 100644--- a/docs/adr/0295-session-thinking-parameter-omission.md+++ b/docs/adr/0295-session-thinking-parameter-omission.md@@ -2,34 +2,36 @@- Status: Accepted- Date: 2026-09-20-- Deciders: PI-Desktop runtime and UX maintainers- Amends: ADR 0194, ADR 0144, ADR 0221-- Related: D456, E2E-203a+- Related: D456## Context-Subagents already offer `thinkingLevel: omit` (ADR 0194): the agent bookkeeping-state stays `off`, but the request uses the low-level provider stream so no-thinking override is synthesized. Sessions only accepted the seven canonical-levels.+Subagents already offer `thinkingLevel: omit` (ADR 0194): bookkeeping stays `off`+while the request uses the low-level provider stream, so no thinking override is+synthesized. Sessions accepted only the canonical levels, yet explicit `off` is+not equivalent to omission because adapters serialize it as+`reasoning_effort: "none"` or `thinking: disabled`, and users wanted that third+choice on the Composer reasoning menu.## Decision-1. Persist `omit` as a session `thinkingLevel` alongside the seven canonical- levels.-2. The Composer reasoning menu prepends `omit` whenever the selected model- exposes at least one enabled canonical level.-3. Runtime clamping preserves `omit` on a reasoning model and maps it to `off`- otherwise.-4. Schema v19 rebuilds `sessions` so the CHECK includes `omit`.-5. Settings `defaultThinkingLevel` accepts `omit` when the binding enables any- canonical reasoning level, so new sessions can start without a thinking- override.+A session `thinkingLevel` may persist `omit` alongside the seven canonical levels,+while binding `thinkingLevels` and catalog capability lists stay canonical:+`omit` is a client selector, not a published capability. The Composer reasoning+menu prepends `omit` whenever the selected model exposes at least one enabled+canonical level and stays `off`-only for non-reasoning models, runtime clamping+preserves `omit` on a reasoning model and maps it to `off` otherwise, and the+parent stream uses the same low-level path as subagents+(`thinkingLevelMap.off = null`). Schema v19 rebuilds `sessions` so the CHECK+includes `omit`, the handshake version is unchanged, and Settings+`defaultThinkingLevel` accepts `omit` when the binding enables any canonical+reasoning level.## Consequences-- Composer can leave the provider adapter's default thinking behavior in control- without disabling thinking.-- Existing sessions keep their stored canonical levels.-- Subagent inherit of a parent `omit` continues to omit.-- A reasoning model's Settings default can be `omit`; new sessions inherit it.+- Composer can leave the adapter's default thinking behavior in control without+ disabling thinking.+- Existing sessions keep their stored canonical levels, and a subagent inheriting+ a parent `omit` continues to omit.+- A reasoning model's Settings default can be `omit`, which new sessions inherit.diff --git a/docs/adr/0296-macos-signed-dmg-two-icon-install.md b/docs/adr/0296-macos-signed-dmg-two-icon-install.mdindex 7cc394160..c1704f4f2 100644--- a/docs/adr/0296-macos-signed-dmg-two-icon-install.md+++ b/docs/adr/0296-macos-signed-dmg-two-icon-install.md@@ -8,30 +8,23 @@## Context-Official GitHub Release DMGs are Developer ID-signed and notarized (ADR 0289).-The DMG still showed `If app won't open, read this.txt` from ADR 0232, which was-the unsigned first-launch fallback.+Official GitHub Release DMGs are Developer ID-signed and notarized (ADR 0289), yet+they still showed the unsigned first-launch note from ADR 0232, which is no longer+the install path for tagged builds and made the installer look like an error dialog.## Decision-1. The macOS DMG contains only `PI-Desktop.app` and the Applications link, on a- branded 720×440 dark plate with 128px icons.-2. The macOS ZIP package still ships both `PI-Desktop-macOS-opening-help.txt`- and the executable helper at its root, for trusted unsigned local or debug- artifacts.-3. The DMG artwork is generated by `scripts/make-dmg-background.py` from the- canonical app icon.+1. The macOS DMG contains only `PI-Desktop.app` and the Applications link on a+ branded dark plate: no opening-help note and no+ `PI-Desktop-macOS-open.command`.+2. *(D634 / ADR 0309)* The ZIP ships neither artifact, and no other bundled+ quarantine-clearing helper, in signed releases and unsigned local or debug builds+ alike.+3. The DMG artwork is generated from the canonical app icon by+ `scripts/make-dmg-background.py`; the PNG pair is never hand-edited.## Consequences-- A tagged DMG is a single drag-to-Applications gesture.-- Unsigned local DMGs no longer carry the in-volume note; use the ZIP helper or- the documented `xattr` command.-- Finder still localizes the Applications alias; the plate caption is English- plus a quiet Chinese line.--## Amendment (D634 / ADR 0309)--The ZIP no longer ships the opening note or executable helper. Neither macOS-format includes first-launch guidance in signed releases or unsigned debug-builds; the two-icon DMG layout remains unchanged.+A tagged artifact installs with one drag-to-Applications gesture, unsigned local+builds fall back to the documented `xattr` command, and the plate caption stays+English with a quiet Chinese line.diff --git a/docs/adr/0297-provider-hosted-web-search-adapter-capability.md b/docs/adr/0297-provider-hosted-web-search-adapter-capability.mdindex ddb6bc699..a4d696d3a 100644--- a/docs/adr/0297-provider-hosted-web-search-adapter-capability.md+++ b/docs/adr/0297-provider-hosted-web-search-adapter-capability.md@@ -5,77 +5,68 @@## Context-Some providers execute web search server-side: Anthropic Messages ships a-`web_search_20250305` server tool, and OpenAI Responses (plus compatible-gateways) ships a `web_search` tool. Unlike an MCP search server, the search-runs inside the provider request, is billed by the provider per search, and-returns structured blocks (`server_tool_use` + `web_search_tool_result`,-`web_search_call`, `url_citation` annotations) that the client must keep in the-conversation for multi-turn grounding.--- pi-ai 0.86.1 drops vendor search blocks in both adapters: the Anthropic stream- loop has no `server_tool_use` / `web_search_tool_result` / `citations_delta`- branches, and the Responses item loop has no `web_search_call` slot or- annotation handling.-- Anthropic requires `server_tool_use` + `web_search_tool_result` blocks- (including `encrypted_content`) to be replayed verbatim on later turns.+Some providers run web search server-side — Anthropic Messages ships a+`web_search_20250305` server tool and OpenAI Responses ships `web_search` — and+that search runs inside the provider request, is billed per search, and returns+structured blocks the client must keep for multi-turn grounding. PR #570 added it+as a composer toggle with runtime SSE re-parsing and was reverted in #608,+because a plugin-shaped version would need four new SDK extension points and+pi-ai 0.86.1 drops vendor search blocks in both adapters.## Decision-1. **Capability is declared data and gated by the resolved wire API.** The- per-model opt-in is `ModelBinding.nativeWebSearch` (settings UI: a checkbox- in the model's advanced sheet, disabled unless its resolved search route is- `responses`, `openai_codex_responses`, or `anthropic_messages`). models.dev- publishes no hosted-tool capability, so there is no catalog default; absent- means off.--2. **Attachment and extraction live in pi-ai adapters**, delivered by extending- `patches/@[email protected]`:- - `anthropic-messages.js` appends `web_search_20250305` when opted in,- captures search blocks as `hostedSearch`, collects citations, and replays- both halves of each pair on later turns.- - `openai-responses(-shared).js` and Azure's `buildParams` append- `web_search`, request `web_search_call.action.sources`, capture search- items/citations, and replay the item for the same model.- - `openai-codex-responses.js` uses a separate Codex request builder and- ChatGPT subscription endpoint.-All three adapter paths push `hosted_search_update` transitions. The-`pi-agent-core` patch forwards them as `message_update`, so activity renders-while a search is in flight instead of only at turn completion.--3. **The flag travels the existing model-config channel.**- `ModelConfigWithBinding` copies `nativeWebSearch` into- `ModelConfig.webSearch`; `buildProviderModel` spreads catalog fields into the- pi-ai `Model`, so no new IPC, sidecar parameter, or runtime rebuild hook is- needed.--4. **Display data and replay data are separated, and both persist.** The runtime- normalizes `hostedSearch` blocks into `UiMessage.hostedSearch`- (`status/rounds[]` for activity rows; `replay[]` for the adapter's raw- content parts, stripped of streaming scratch).--5. **UI is a transcript activity row per round, not a composer control.** Each- round of a `hostedSearch` activity renders as a `HostedSearchRow` on the- tool-row idiom (icon + name + query summary, chevron disclosure): searching- state while the round is in flight, sources when expanded.+### 1. The capability is declared data gated by the resolved wire API-## Consequences+The per-model opt-in is `ModelBinding.nativeWebSearch`, offered only when the+resolved route is `responses`, `openai_codex_responses`, or+`anthropic_messages`; absent means off, because models.dev publishes no+hosted-tool capability. Runtime `resolveNativeWebSearch` keys on the final adapter+API, never on vendor names or model-id substrings.++### 2. Attachment and extraction live in the pi-ai adapters++A `patches/@earendil-works__pi-ai` patch appends the vendor tool, captures search+blocks and citations, and replays each request and result pair on later turns in+the Anthropic, OpenAI Responses (including Azure), and Codex Responses adapters,+each pushing `hosted_search_update` transitions that the `pi-agent-core` patch+forwards as `message_update`. The patches are a stopgap to propose upstream and+remove once released.++### 3. The flag travels the existing model-config channel++`ModelConfigWithBinding` copies `nativeWebSearch` into `ModelConfig.webSearch` and+`buildProviderModel` spreads it into the pi-ai `Model`, so no new IPC, sidecar+parameter, or runtime rebuild hook is needed.-- Enabling the tool is per model, always-on while enabled, and takes effect on- the next turn (runtime rebuild follows from modelConfig change).-- Gateways that mangle replay blocks surface as provider errors on the next- turn; the user-visible remedy is unchecking the model's opt-in.-- `pause_turn` keeps pi-ai's existing mapping to `stop`; a long searching turn- may end early on the official Anthropic wire.-- The original implementation omitted search from compaction serialization.-- Search executes on the provider.+### 4. Display data and replay data are separated, and both persist-## 2026-09-24 amendment: one service entry for official search+The runtime normalizes `hostedSearch` into `UiMessage.hostedSearch` with+`status/rounds[]` for activity rows and `replay[]` for the adapter's raw content+parts, persisted as an additive `hostedSearch` transcript block with no SQL+migration; `historyToEntries` restores `replay` after thinking and before text so+later turns stay grounded. Transcripts written without `replay` still render, they+just cannot ground.-DeepSeek's saved Completions configuration cannot carry the hosted search tool-available on its published Anthropic interface. Keep the existing per-model-search opt-in and resolve the request through a shared published-route table-instead.+### 5. The UI is a transcript activity row per round, not a composer control++Each round renders as a `HostedSearchRow` on the tool-row idiom with a searching+state and an expandable list of plain text source links, so reading a transcript+never fetches favicons or leaks source hostnames (the #579 rule). Citation badges+in message text are out of scope for v1.++Amended 2026-09-24: an opted-in request may be resolved through a shared+published-route table before the final wire gate, so DeepSeek Completions uses its+same-origin Anthropic interface and xAI and legacy OpenAI Completions use+same-origin Responses while search is enabled. Only exact official HTTPS origins+and paths match, saved provider settings are never rewritten, and the model,+registry, history restoration, and delegation all use the same effective API.++## Consequences-Only exact official HTTPS origins and paths match; vendor/model labels do not.-Unknown relays and explicit non-Completions protocols stay unchanged.+- Enabling the tool is per model, always-on once enabled, and effective on the+ next turn; a session toggle can layer on later without touching the adapters.+- A gateway that mangles replay blocks surfaces as a provider error whose remedy+ is unchecking the opt-in; nothing silently strips the tool.+- Search runs on the provider with no local fetch and no allow prompt, so the+ model-level opt-in is the consent surface, and compaction replays search+ projections through the 2026-09-22 contract repair.diff --git a/docs/adr/0298-remove-bundled-fonts.md b/docs/adr/0298-remove-bundled-fonts.mdindex b905120a9..3ee2f524a 100644--- a/docs/adr/0298-remove-bundled-fonts.md+++ b/docs/adr/0298-remove-bundled-fonts.md@@ -2,80 +2,46 @@- Status: Accepted- Date: 2026-09-20-- Deciders: PI-Desktop UX and desktop maintainers-- Baseline: `0.15.1-beta.7` (frozen baseline `0.4.18`)-- Protocol: v11 (unchanged; the `pi-desktop/app/systemFonts` channel is untouched)-- Storage schema: v19 (unchanged; `AppSettings.fontFamily` keeps its shape and semantics)-- Amends: [ADR 0083](0083-custom-global-ui-font.md) — its §2 bundled families, its- `@font-face`/offline-rendering clauses, and its installer-size consequence — and D232+- Amends: [ADR 0083](0083-custom-global-ui-font.md) — its §2 bundled families,+ its `@font-face`/offline-rendering clauses, and its installer-size+ consequence — and D232- Related: D598, E2E-126, E2E-092,- [04-ux/06-settings-ia.md](../spec/04-ux/06-settings-ia.md) ·- [04-ux/07-ui-design-system.md](../spec/04-ux/07-ui-design-system.md) ·- [06-delivery/06-release-runbook.md](../spec/06-delivery/06-release-runbook.md)+ [04-ux/07-ui-design-system.md](../spec/04-ux/07-ui-design-system.md)## Context-ADR 0083 shipped the global UI font picker together with four bundled `woff2`-families — Geist, Inter, Noto Sans SC, and LXGW WenKai — all under the SIL Open-Font License 1.1, with their license texts under-`apps/desktop/src/assets/fonts/licenses/` and a `@font-face` layer in-`apps/desktop/src/styles/fonts.css` imported before the token layer. Every-custom stack was prefixed with `Noto Sans SC` so Chinese text stayed readable-offline, and the picker gained a **Bundled** group whose rows carried the-license badge.+ADR 0083 shipped the font picker with four bundled `woff2` families and a+`@font-face` layer, which became the bulk of the renderer's weight and carried+OFL notice obligations, while every target platform already resolves the same+coverage from its own fonts. The product wants the picker, not the payload.## Decision-1. **Nothing is bundled.** `apps/desktop/src/assets/fonts/` (the four `woff2`- files and their `licenses/` texts), `apps/desktop/src/styles/fonts.css`, and- the `@import "./fonts.css";` line in `apps/desktop/src/styles/globals.css`- are deleted.--2. **The picker keeps two kinds of option.** `buildFontOptions` returns **System- default** — persisted as the empty string `""`, which every consumer treats- as the built-in `--font-sans` token stack — followed by installed system- families.--3. **The CJK fallback tier is system-only.** Every stack generated by the picker- appends `"PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif`.--4. **Stored stacks are preserved, not migrated.** A `AppSettings.fontFamily`- written while a bundled option existed (for example `"Geist", "PingFang SC",- "Hiragino Sans GB", "Microsoft YaHei", sans-serif`) stays byte for byte.+Nothing is bundled: the font assets, their license texts, `fonts.css` and its+import, `BUNDLED_FONTS`, the `license` field, the license badge, and the+`settings.fontBundled` key are deleted. `buildFontOptions` returns **System+default**, persisted as the empty string and treated as the built-in+`--font-sans` stack, followed by installed families enumerated exactly as+ADR 0083 §3 describes through `pi-desktop/app/systemFonts`, and a stored stack+matching no option is re-added first under **Saved**. Every generated stack+appends the system-only CJK tier, and stored `AppSettings.fontFamily` values are+preserved byte for byte rather than migrated, so no storage migration runs and+`settings.set`, the protocol version, and the schema version are untouched.## Consequences-- `out/renderer` no longer emits an application font face; the only `woff2`- files left are KaTeX's math glyphs.-- A face the app used to supply now comes from the operating system.-- Chinese text still renders on every supported platform through the fallback- tier, and no part of it reads a file the app ships.-- The app no longer redistributes OFL-licensed font files, so the four shipped- license texts and their notice obligations leave the bundle with the faces.-- The picker's option list becomes "System default plus whatever this machine- has", which is the same list every other System-style picker in the app shows;- the license badge and the **Bundled** group heading go away.--## Alternatives considered--### Keep the bundled families and subset them--Rejected: subsetting would drop glyphs from user-supplied content, which is why-ADR 0125 kept the CJK faces unsubset in the first place, and it leaves the-`@font-face` layer, the license tree, and the build wiring in place for a saving-the platform fonts already provide.--### Keep the bundled families behind a build flag or setting--Rejected: the files would still be built and shipped, so the installer cost and-the notice obligations stay, and the app would gain a second font configuration-surface for a four-item list.--### Keep `Noto Sans SC` at the head of the CJK fallback tier--Rejected: the tier must not name a family the app pretends to provide.--### Migrate stored bundled stacks to a system equivalent--Rejected: there is no honest mapping from a removed face to a system face, and-rewriting the value would change the user's rendering without their action.+- `out/renderer` emits no application font face, leaving KaTeX's glyphs as the+ only `woff2` files, and the installer drops the four faces.+- A face the app used to supply now comes from the OS, so LXGW WenKai is no+ longer available out of the box, while Chinese text still renders through the+ fallback tier.+- The picker shows "System default plus whatever this machine has", the license+ badge and **Bundled** group disappear, and the OFL notice obligations leave+ the bundle.++## Alternatives++- Subset the bundled families: rejected, subsetting drops glyphs from+ user-supplied content and keeps the license tree and build wiring.+- Migrate stored bundled stacks to a system equivalent: rejected, there is no+ honest mapping and it would change rendering without user action.diff --git a/docs/adr/0299-subagent-context-budget.md b/docs/adr/0299-subagent-context-budget.mdindex 0ad62037b..07246e10b 100644--- a/docs/adr/0299-subagent-context-budget.md+++ b/docs/adr/0299-subagent-context-budget.md@@ -2,98 +2,84 @@- Status: Accepted for implementation- Date: 2026-09-20-- Deciders: PI-Desktop core- Amends: ADR 0064 (extends its compaction contract to delegates); extendsADR 0062 / ADR 0279-- Related: ADR 0030 (hard boundary), ADR 0049 (retained-tail recovery),- ADR 0136 (active task boundary), ADR 0246, ADR 0253,+- Related: ADR 0030, ADR 0049, ADR 0136, ADR 0210, ADR 0246, ADR 0253,ADR subagent-model-fallback## ContextEvery context protection the session Agent has is wired for the session Agent-only. A delegate (`Task`, ADR 0062) runs the same pi `Agent` class with none of-it:--- `SubagentRun`'s constructor (`packages/agent-runtime/src/subagent.ts:214`)- passes `streamFn`, `getApiKey`, `convertToLlm`, `afterToolCall` and- `initialState`.-- `subagent.ts` has no notion of `contextWindow`, holds no token budget, and- calls no compaction primitive.-- The parent has three layers the delegate lacks: `contextBudget()`- (`runtime.ts:5652`, `hardLimit = contextWindow − requestHeadroom`), a- pre-flight compaction in `prompt()` (`runtime.ts:7434`), and turn-boundary- compaction in `prepareNextTurn()` (`runtime.ts:5839`, ADR 0064).-- A delegate cannot compact on its own initiative either: `new_context` is on- `SUBAGENT_INHERIT_DENY_TOOLS`- (`packages/shared/src/subagent-definition.ts:117`), because executing it sets- the *parent* runtime's `pendingModelCompaction` flag.+only. A delegate (`Task`, ADR 0062) runs the same pi `Agent` class without+`prepareNextTurnWithContext`, `contextBudget()`, pre-flight or turn-boundary+compaction, and cannot compact on its own because `new_context` is deny-listed+for it. Its context therefore grows until the provider rejects the request with+an unactionable `CONTEXT_TOO_LARGE`, and `fallbackModels` cannot help because+the carried context moves across unchanged. ADR 0064 never mentions delegates;+this is an omission, and it leaves the feature built to keep large reads out of+the session window as the one path with no window protection.## Decision-1. **One budget formula, shared.** The parent's budget derivation moves verbatim- into a pure module, `packages/agent-runtime/src/context-budget.ts`, and both- `PiRuntime` and `SubagentRun` call it.+### 1. One budget formula, shared-2. **A delegate budget derives from the delegate's own model.** The window and- output cap come from the model the run actually resolved — a `Task.model`- override, a definition pin, or the inherited session model (§5f) — not from- the session model and not from the definition.+The parent's derivation moves verbatim into a pure module,+`packages/agent-runtime/src/context-budget.ts`, used by both `PiRuntime` and+`SubagentRun`, so `hardLimit = contextWindow − requestHeadroom` and its clamps+behave identically and the two callers cannot drift.-3. **Turn-boundary compaction for delegates.** `SubagentRun` wires- `prepareNextTurnWithContext`.+### 2. A delegate budget derives from the delegate's own model-4. **Degradation before failure.** When a summary cannot be generated, or the- compacted context still exceeds `hardLimit`, the run keeps the original task- brief plus the most recent message(s) and discards the rest of its history.+The window and output cap come from the model the run resolved — a `Task.model`+override, a definition pin, or the inherited session model — not from the session+or the definition, with a per-definition `maxTokens` cap (ADR 0210) as its output+budget.-5. **A terminal code the parent can act on.** When even the degraded context- does not fit, the run fails with `SUBAGENT_CONTEXT_OVERFLOW` (`retriable:- no`) carrying guidance the parent model can execute: narrow the task,- delegate to a model with a larger context window, or read less at once.+### 3. Turn-boundary compaction for delegates-6. **Fallback models are re-evaluated against their own window.** Before- advancing to an alternative, the controller checks the carried context- against that alternative's budget.+`SubagentRun` wires `prepareNextTurnWithContext`, re-estimates its own context,+and compacts from `floor(hardLimit * 0.9)` before the next request using the+`prepareCompaction` and `generateSummary` primitives of+`@earendil-works/pi-agent-core`. The hard limit stays a final guard that rejects+an over-budget request, and retention follows ADR 0136's active-task boundary.-7. **Resume seeds within the budget.** `seedDelegateMessages()` truncates the- seeded chain against the delegate's budget.+### 4. Degradation before failure-8. **`new_context` stays denied to delegates.** Delegate compaction is entirely- automatic.+When a summary cannot be generated or the compacted context still exceeds+`hardLimit`, the run keeps the original task brief and the most recent messages,+discards the rest, and records that it was degraded. A summary that is empty or+whitespace-only counts as a summarization failure, not a successful checkpoint.++### 5. A terminal code the parent can act on++When even the degraded context does not fit, the run fails with+`SUBAGENT_CONTEXT_OVERFLOW` (`retriable: no`) and guidance to narrow the task,+delegate to a larger-window model, or read less at once, replacing the provider's+raw overflow text.++### 6. Fallback models are re-evaluated against their own window++Before advancing, the controller checks the carried context against the+alternative's budget and records an unsuitable alternative in `modelFailures`+instead of attempting it, leaving ordering, duplicate skipping, and retry budgets+unchanged.++### 7. Resume seeds within the budget++`seedDelegateMessages()` truncates the seeded chain against the delegate's budget,+keeping the task brief and recent turns and dropping the oldest tool results+first, so a resume starts below `hardLimit`.++### 8. `new_context` stays denied to delegates++Delegate compaction is entirely automatic, because the tool mutates parent+runtime state and inheriting it would let a delegate compact its parent.## Consequences-- A long delegate no longer ends in a provider overflow error.-- A compacted delegate is lossier in exactly the way a compacted session is:- assistant reasoning and tool output survive only through the summary.-- Compaction costs the delegate a summary request at the moment it is already- working, so a delegate that crosses the boundary is slower and more expensive- than one that does not.-- Sharing one budget module makes the parent's formula load-bearing for two- callers.-- Fallback re-evaluation can leave a configured alternative unused.--## Not decided here / out of scope--- **Transcript rows.** Delegate compaction affects the delegate's model context- only.-- **Durable checkpoints.** No host-core compaction record is written for a- delegate.-- **Transcript presentation.** No compaction divider row, no warning toast, and- no context-inspector line for a delegate.-- **`new_context` for delegates.** Denied, per clause 8.-- **Parent behavior.** Clause 1 is an extraction, not a change.-- **Cross-run budget accounting.** Concurrent delegates are budgeted- independently, each against its own model.--## References--- `docs/adr/0064-codex-parity-context-compaction.md`-- `docs/adr/0062-bounded-subagents-behind-a-task-tool.md`-- `docs/adr/0279-resumable-subagent-delegations.md`-- `docs/adr/0136-active-task-boundary-across-compaction.md`-- `docs/adr/subagent-model-fallback.md`-- `docs/spec/03-runtime/02-agent-runtime.md` §5.1, §5f-- `docs/spec/03-runtime/08-error-codes.md` §3.2-- `docs/spec/06-delivery/04-e2e-test-plan.md`+- A long delegate compacts, then degrades, and only then fails with a code the+ parent can act on.+- A compacted delegate is lossy in the way a compacted session is, and a degraded+ run must say so or the parent reads a partial answer as complete.+- One shared budget module makes the parent's formula load-bearing for two+ callers: its existing budget tests are the regression surface for delegates.diff --git a/docs/adr/0300-host-owned-encrypted-portable-configuration-sync.md b/docs/adr/0300-host-owned-encrypted-portable-configuration-sync.mdindex 5f5edfe5b..29a101947 100644--- a/docs/adr/0300-host-owned-encrypted-portable-configuration-sync.md+++ b/docs/adr/0300-host-owned-encrypted-portable-configuration-sync.md@@ -3,56 +3,62 @@- Status: Partially superseded by [S3-only configuration backup and sync](s3-only-configuration-backup-sync.md)- Date: 2026-09-22-The ownership and encryption rationale below remains historical context. The-WebDAV transport, append-only fallback, and endpoint-specific missing-status-decisions no longer describe current behavior. See the S3 decision and current-configuration-sync spec for the implemented contract.+The ownership and encryption rationale below remains historical context. The WebDAV+transport, append-only fallback, and endpoint-specific missing-status decisions no+longer describe current behavior; see the S3 decision and the configuration-sync+spec for the implemented contract.## Context-PI-Desktop has portable preferences and user-owned capabilities spread across-Rust-owned SQLite, capability files, the host secret store, project groups, and-plugin metadata. Copying the database or the local secrets directory would-export device state, break ownership boundaries, and could activate executable-content on another machine.+Portable preferences and user-owned capabilities are spread across Rust-owned+SQLite, capability files, the host secret store, project groups, and plugin+metadata. Copying the database or the secrets directory would export device state,+break ownership boundaries, and could activate executable content on another+machine, while a cloud backup must still converge concurrent edits without trusting+remote timestamps or silently replacing local data.## Decision-Add a host-core configuration-sync subsystem. It uses explicit per-domain-capture and apply adapters, encrypted immutable revision/resource objects, an-encrypted CAS head, and the existing host secret store for the WebDAV password-and local vault-key reference.+Host-core gains a configuration-sync subsystem built from per-domain capture and+apply adapters, encrypted immutable revision and resource objects, an encrypted CAS+head, and the existing host secret store for the remote password and local vault-key+reference. Argon2id derives a wrapping key from a separate backup password, and+AES-256-GCM authenticates every stored object with purpose/vault-derived keys and+domain-separated associated data. The renderer receives only typed status, preview,+conflict, and activation summaries; Electron Main is a thin lifecycle and transport+bridge.-The renderer receives only typed status, preview, conflict, and activation-summaries. Electron Main is a thin lifecycle/transport bridge.+Portable secrets need explicit opt-in, and OAuth sessions, cookies, local encryption+keys, readiness flags, plugin binaries, arbitrary files, and local paths are not+portable. App-managed instructions cover only the fixed global+`~/.pi/agent/AGENTS.md` and registered project-root `AGENTS.md` files. Imported+executable or security-sensitive content stays staged until the receiving device+approves the entity digest, and project and workspace bindings are local overlays+needing explicit mapping. Project groups use the portable group identity plus+ordered root position, so absolute folder paths never become cross-device identity.++Strict WebDAV initialization and head publication require reliable conditional+writes — `If-None-Match: *` to create, a strong-ETag `If-Match` to update, and a CAS+failure restarts reconciliation — and ADR 0301 defines the separately confirmed+append-only mode for servers that fail the probe, never a silent downgrade to+last-writer-wins. HTTPS is the default; the settings UI may acknowledge LAN HTTP+risk, which Host limits to localhost, `.local`, or private and link-local addresses.## Consequences-Positive:--- The renderer and Agent Runtime never gain direct access to WebDAV, encryption- keys, or raw exported secrets.-- Existing local persistence owners remain authoritative; no parallel provider,- MCP, skill, or subagent database is introduced.-- Immutable revisions allow authenticated recovery and deterministic three-way- merge, while category opt-out remains subscription policy rather than a remote- delete.-- A fresh device cannot activate a synchronized command, endpoint, script, or- automation without local review.--Costs and limits:--- A malicious WebDAV server can still deny availability or roll back a fresh- device that has no trusted head history; this design protects confidentiality- and integrity, not availability.--## Alternatives rejected--1. Exporting SQLite or the application data directory: violates ownership, leaks- device-specific state, and cannot express approval or merge policy.-2. Uploading a plaintext JSON backup: exposes all configuration and secrets to- the WebDAV server and every transport intermediary.-3. Last-writer-wins based on wall-clock timestamps: loses edits under clock skew- and cannot safely resolve delete-versus-edit or executable changes.-4. Scheduling synchronization in Electron Main or the renderer: creates a second- owner for sync lifecycle and weakens host durability guarantees.+- The renderer and Agent Runtime never touch remote storage, keys, or raw exported+ secrets, existing persistence owners stay authoritative, and immutable revisions+ allow authenticated recovery and deterministic three-way merge.+- Category opt-out stays subscription policy rather than a remote delete, and a fresh+ device cannot activate synchronized executable content without local review.+- A malicious server can still deny availability or roll back a device with no+ trusted head history, and restore cannot revoke a copied vault key.++## Alternatives++- Export SQLite or the data directory, or upload a plaintext JSON backup: leaks+ device state and secrets and cannot express approval or merge policy.+- Last-writer-wins on wall-clock timestamps: loses edits under clock skew and cannot+ resolve delete-versus-edit or executable changes.+- Schedule sync in Electron Main or the renderer: creates a second owner for the+ lifecycle and weakens host durability.diff --git a/docs/adr/0301-explicit-append-only-webdav-compatibility-mode.md b/docs/adr/0301-explicit-append-only-webdav-compatibility-mode.mdindex b1ccbfb67..57502ef45 100644--- a/docs/adr/0301-explicit-append-only-webdav-compatibility-mode.md+++ b/docs/adr/0301-explicit-append-only-webdav-compatibility-mode.md@@ -4,21 +4,25 @@- Date: 2026-09-22- Amends: ADR 0300-This document records the removed WebDAV compatibility design. It is not a-current contract: S3 requires reliable conditional writes, and there is no-append-only fallback. Existing WebDAV data is preserved without migration.-## Context-Some WebDAV servers accept `If-None-Match` and `If-Match` headers but ignore-their preconditions.+Some WebDAV servers accept `If-None-Match` and `If-Match` but ignore the+preconditions, so treating an unconditional `PUT` as a compare-and-swap would let+two devices overwrite a shared head without detecting the race. A server's WebDAV+support does not by itself prove conditional-write semantics.## Decision-Keep strict conditional-write mode as the default. Add an explicitly selected-append-only compatibility mode for servers that fail the conditional-write probe-but prove that they can list a WebDAV collection with `PROPFIND`.--## Consequences--Superseded (Superseded by [S3-only configuration backup and sync](s3-only-configuration-backup-sync.md)). The full record is in git history.+Strict conditional writes stayed the default, and an explicitly selected+append-only compatibility mode existed for servers that failed the+conditional-write probe but could list a collection with `PROPFIND`. Each device+received a random stable identifier and published only its own encrypted pointer+under `vault/<vault-id>/heads/<device-id>`; a sync listed every device pointer,+walked their bounded parent graph, dropped ancestor pointers, and merged the+remaining tips against the last acknowledged base. Revisions and resources used+unique immutable identifiers, the mode retained remote history without cleanup, and+all devices sharing a vault had to select the same mode.++This design is retired. S3-only configuration backup and sync requires reliable+conditional writes and keeps no append-only fallback; existing WebDAV data is+preserved without migration.diff --git a/docs/adr/0302-compaction-fallback-recent-window-and-chunked-summary.md b/docs/adr/0302-compaction-fallback-recent-window-and-chunked-summary.mdindex 31a81650d..76bc13430 100644--- a/docs/adr/0302-compaction-fallback-recent-window-and-chunked-summary.md+++ b/docs/adr/0302-compaction-fallback-recent-window-and-chunked-summary.md@@ -5,68 +5,56 @@- Amends: ADR 0049 (the retained tail is the recent window, not one usermessage; a prompt that does not fit is chunked rather than skipped) / ADR 0282(the reduced pass is no longer the last attempt before the fallback)-- Related: issue #827 · ADR 0064 (the `fresh_window` family, unchanged) ·- [03-runtime/02-agent-runtime](../spec/03-runtime/02-agent-runtime.md)+- Related: ADR 0064 (the `fresh_window` family, unchanged), issue #827## Context-ADR 0049 decided that an automatic compaction failure installs a deterministic-retained-tail checkpoint, and described that checkpoint as preserving "the-recent provider-valid message tail". ADR 0282 then made the runtime retry a-failed summary and reduce an oversized prompt once before the fallback ran.+ADR 0049 installs a deterministic retained-tail checkpoint when automatic+compaction fails, and ADR 0282 retried the summary and reduced an oversized prompt+once before that fallback. The shipped contract was narrower: the tail was+rebuilt as at most the latest user message, so a failed summary left the model+without the decisions, paths, and unfinished work of the turn it continued while+the transcript and UI row looked healthy. A prompt that still did not fit was+skipped rather than summarized, and the checkpoint recorded no reason for the+degradation.## Decision-A retained-tail fallback retains the real recent window: the newest contiguous-messages of the compacted range, every role, bounded by the keep-recent target-and by what the safe budget leaves once the carried-forward summary and the-recovery notice are paid for. It records `details.retainedTailShape` as-`recent_window`, and a checkpoint without that marker — every successful-checkpoint, and every record written before the marker existed — still-normalizes to its latest user message, so a restart cannot restore a sequence of-executable-looking old requests.+A retained-tail fallback keeps the newest contiguous messages of the compacted+range across every role, bounded by the keep-recent target and by what the safe+budget leaves after the carried summary and recovery notice are paid for, and it+records `details.retainedTailShape` as `recent_window`. A checkpoint without that+marker still normalizes to its latest user message, so a restart cannot restore a+sequence of executable-looking old requests.-A budget too small for one prompt no longer skips the model. The range is split-into contiguous chunks that each fit the request budget — at most 16 requests,-each carrying the previous chunk's summary through pi's update-the-summary-prompt, with the range's file list appended on the last one — so the checkpoint-still covers every message behind its boundary, and the summary reports the-summed usage of the requests that produced it.+The fallback drops error, aborted, and deferred assistant messages and any tool+result whose call is outside the window, because a provider rejects an orphaned+result, and an `active_turn` fallback also keeps the active task's user message+ahead of the window when the window cannot hold it, so a continuation never loses+its goal.-## Consequences--- A failed summary no longer costs the active turn: the degradation is bounded- by the same recent-context budget a successful checkpoint respects.-- A fallback checkpoint is larger than it was, and so is the continuation- request it authorizes.-- A summary of a very large range costs several provider requests and reports- their summed usage.-- Provider validity is unchanged: a retained tail never carries an orphaned tool- result or an unanswered tool call.-- Manual `/compact` keeps its fail-fast contract, the `fresh_window` family- still carries an empty tail, and no setting, protocol field, or persisted- record schema changed.--## Alternatives--### Keep the one-user-message tail and rely on the carried summary+A range too large for one prompt is split into contiguous chunks that each fit the+request budget, chained through pi's update-the-summary prompt and summarized once+for the whole range, with the summed usage of those requests reported. Only an+empty range, or one beyond the chunk bound, still falls back on budget grounds.-Rejected: the failed summary is the carried one, so the range after it has no-representation at all.+The checkpoint records `details.failureReason` from a closed vocabulary —+`no_new_history`, `summary_budget`, `summary_provider`, `checkpoint_oversized` —+instead of provider error text, which ADR 0049 keeps out of the persisted record.-### Retain the window only for `active_turn`--Rejected: a completed turn that fails loses the same delta, and the window ends-on a finished assistant message, so it reads as history rather than as a pending-request — which is what the older normalization guarded against.--### Summarize an oversized range by concatenating partial summaries with no-second request per chunk+## Consequences-Rejected: each chunk needs its own request regardless, and any merge step either-costs another request or leaves several sections that disagree.+- A failed summary no longer costs the active turn, because the degradation stays+ inside the same recent-context budget a successful checkpoint respects.+- Fallback checkpoints and their continuation requests are larger, and a summary+ of a very large range costs several provider requests and reports their sum.+- Provider validity is unchanged, manual `/compact` keeps its fail-fast contract,+ the `fresh_window` family still carries an empty tail, and no setting, protocol+ field, or persisted record schema changed.-### Raise the hard limit or keep skipping the shot summary+## Alternatives-Rejected: the failure is the summarizer's, not the window's, and the guard is-what keeps the next request inside the provider limit.+- Keep the one-user-message tail and rely on the carried summary: rejected because+ the carried summary is the one that failed, which is the reported defect.+- Skip the oversized summary: rejected because the failure is the summarizer's,+ not the window's, and only the chunked path still covers the range.diff --git a/docs/adr/0303-skill-package-resource-limits.md b/docs/adr/0303-skill-package-resource-limits.mdindex b6668d1a5..f8620901c 100644--- a/docs/adr/0303-skill-package-resource-limits.md+++ b/docs/adr/0303-skill-package-resource-limits.md@@ -6,50 +6,45 @@sync baseline now have concrete values, separate from the document cap, and areceiver bound that matches the packager)- Related: [03-runtime/22-config-sync](../spec/03-runtime/22-config-sync.md) ·- `crates/host-core/src/user_skills.rs` · ADR 0243 (the document cap the market- path enforces, unchanged)+ ADR 0243 (the document cap the market path enforces, unchanged)## Context-A directory-shaped skill is a `SKILL.md` document plus sibling resources. One-constant bounded both: `MAX_SKILL_BYTES` (128 KiB) was the document limit and,-at the same time, the limit on one resource.+A directory-shaped skill is a `SKILL.md` document plus sibling resources, and one+constant bounded both: `MAX_SKILL_BYTES` was the document limit and the limit on+one resource, while the packager added its own resource count and total and the+receiver kept a third copy of the per-resource number. The document limit exists+because a document can be handed to the model; a resource is data or a script+read from disk on demand, so it has no reason to inherit a prompt-sized bound. The+failure was not graceful either: `package_files` returns `Err`, the skills capture+propagates it, and one oversized skill failed the whole capture and every sync+domain with `SKILL_LIMIT_EXCEEDED`.## Decision-The document bound and the package bounds are separate:--- `MAX_SKILL_BYTES` (128 KiB) remains the cap on a skill document.-- `MAX_SKILL_RESOURCE_BYTES` (2 MiB) is the new cap on one package resource.-- `MAX_SKILL_PACKAGE_FILES` is 256 and `MAX_SKILL_PACKAGE_BYTES` is 16 MiB.--Capture and apply both compare a resource against `MAX_SKILL_RESOURCE_BYTES`,-and `read_remote_revision` uses that same constant, so an upload the packager-accepted is always readable back. Capture compares a resource against its-metadata length before reading it, so an oversized file is refused without being-loaded into memory first.+The document bound and the package bounds are separate: `MAX_SKILL_BYTES` stays+the cap on a skill document, `MAX_SKILL_RESOURCE_BYTES` is 2 MiB for one package+resource, `MAX_SKILL_PACKAGE_FILES` is 256, and `MAX_SKILL_PACKAGE_BYTES` is+16 MiB. Capture, apply, and `read_remote_revision` all compare against+`MAX_SKILL_RESOURCE_BYTES`, so an upload the packager accepted is always readable+back, and capture compares a resource against its metadata length before reading+it so an oversized file is refused without being loaded. Package paths, symlinks,+collisions, the document cap, and the resource-per-object transport are unchanged.## Consequences-- A package may now be 32× larger than before (512 KiB → 16 MiB) and hold 4×- more files.-- Resources share the existing 4096-object ceiling for one revision across all- domains; roughly sixteen maximum-size packages fill it, and the existing- `CONFIG_SYNC_LIMIT_EXCEEDED` error is what a user sees beyond that.-- A bound is still all-or-nothing.-- The descriptor list of a package travels in the entity payload, which keeps- its own 512 KiB bound.-- No migration. The bounds are checked at capture and apply, never stored, so- existing packages and revisions keep working; only previously refused packages- start being accepted.+- A package may be far larger and hold more files, while each resource is still one+ WebDAV object and shares the existing per-revision object ceiling, beyond which+ `CONFIG_SYNC_LIMIT_EXCEEDED` is reported.+- A bound is still all-or-nothing: an oversized resource, too many resources, or+ too much total resource data still fails the capture and every sync domain.+- No migration is needed because bounds are checked at capture and apply rather+ than stored, the prompt-facing 128 KiB document limit and ADR 0243 stand, and a+ device on an older build still enforces its own per-resource bound on read.## Alternatives-- **Raise the single shared constant.** Rejected: a 2 MiB `SKILL.md` is a prompt- problem, not a package problem, and the market path inlines sibling resources- into a document that must stay prompt-sized.-- **Raise only the packager bounds.** Rejected: it splits the packager from the- receiver and converts a local refusal into a cross-device sync failure.-- **Filter junk directories and skip symlinks instead of raising bounds.**- Rejected for this record: filtering changes which bytes a package carries, so- it is a packaging-semantics decision on its own, not a bound to widen.+- Raise the single shared constant — rejected: a 2 MiB `SKILL.md` is a prompt+ problem, and the market path inlines resources into a prompt-sized document.+- Raise only the packager bounds — rejected: it turns a local refusal into a+ cross-device sync failure.diff --git a/docs/adr/0304-user-supplied-endpoint-trust.md b/docs/adr/0304-user-supplied-endpoint-trust.mdindex d10f1650f..41c569199 100644--- a/docs/adr/0304-user-supplied-endpoint-trust.md+++ b/docs/adr/0304-user-supplied-endpoint-trust.md@@ -6,57 +6,55 @@## Context-ADR 0243, ADR 0245, ADR 0247 and ADR 0272 built one public-network boundary and-applied it to every request the app makes on its own behalf: a market source, a-redirect hop, a git remote, a resolved address. That boundary is load-bearing.+ADR 0243, 0245, 0247, and 0272 built one public-network boundary for every+request the app makes on its own behalf, which is load-bearing and must stay. The+same boundary also refused addresses the user typed into a settings field — a+self-hosted GitLab, a LAN ComfyUI, an MCP OAuth server on a private address —+which removed the request without removing the work and left three surfaces+(ADR 0142, ADR 0300, ADR 0257) already making the distinction, so one boundary+carried two meanings.## Decision-1. A **user-supplied endpoint** may reach loopback, RFC1918, CGNAT, link-local,- ULA, site-local and `.local` addresses, as well as any public address.-2. One host-owned switch, **Relaxed network mode**- (`settings.networkPolicy.mode`, `relaxed` | `strict`), **defaults to- `relaxed`**.-3. **Third-party content keeps the strict policy.** A registry record, a market- catalog body, a document URL inside a catalog, and every HTTP redirect target- are still judged by the public-only rule, with the resolved address pinned to- the connection.-4. An OAuth authorization server reached over plaintext is trusted only when it- sits on the same host as the MCP server the user typed.-5. `unspecified`, `multicast`, `reserved`, `documentation`, `invalid` and cloud- metadata stay refused on **every** input, including a user-supplied one.-6. The default proxy bypass list gains the private ranges, so a configured proxy- does not swallow the user's own LAN services.-7. The syntactic judgement stays in `packages/shared`, and the authoritative one- stays at the connection: a DNS answer outside the policy is refused before- the socket, and an acceptable address is pinned to it (ADR 0245, ADR 0272).+1. A user-supplied endpoint may reach loopback, RFC1918, CGNAT, link-local, ULA,+ site-local, and `.local` addresses as well as public ones; it is an address+ the person typed, such as a model base URL, an MCP server, a market source, a+ git remote, or a generated-image URL.+2. One host-owned switch, relaxed network mode (`settings.networkPolicy.mode`,+ `relaxed` | `strict`), defaults to `relaxed`, which allows those resolutions,+ plain `http`, and a transparent proxy's fake-IP answers; per-surface+ acknowledgements fold into it and a stored+ `allowInsecureUserEndpoints: false` migrates to `strict`, with the first+ plaintext hop to a user endpoint announced once.+3. Third-party content keeps the strict policy: a registry record, a catalog+ body, a document URL inside a catalog, and every redirect target are still+ public-only with the resolved address pinned to the connection, so the shared+ client records whether each hop's origin is `user` or `third-party`.+4. An OAuth authorization server over plaintext is trusted only on the same host+ as the MCP server the user typed, since every other endpoint in that flow+ arrives inside server metadata; loopback stays allowed (RFC 8252).+5. `unspecified`, `multicast`, `reserved`, `documentation`, `invalid`, and cloud+ metadata stay refused on every input, including a user-supplied one.+6. The default proxy bypass list gains the private ranges, and the syntactic+ judgement stays in `packages/shared` while the authoritative one stays at the+ connection (ADR 0245, ADR 0272).## Consequences-- A model endpoint, an MCP server, a market source, a git remote and a- generated-image URL can all point at the user's own machine or LAN from inside- the app, instead of only from a shell next to it.-- The main process gains an SSRF-shaped capability whose targets the user typed- on purpose.-- A plaintext hop to a LAN service is on by default and announced once: whatever- credentials that endpoint accepts travel unencrypted across the local network,- so the user is told the first time it happens and can turn the mode off.-- ADR 0247's consequence — "clone a private-host repository with an- application-external git remote" — no longer applies.+- A model endpoint, MCP server, market source, git remote, and generated-image+ URL can point at the user's own machine or LAN from inside the app.+- The main process gains an SSRF-shaped capability aimed at addresses the user+ typed, while paths the user did not type stay public-only and refusals still+ name the address class (issue #419).+- ADR 0247's external-git-remote consequence no longer applies; the+ user-supplied items in ADR 0243, 0245, and 0247 are amended here, and their+ third-party rules stand.## Rejected alternatives-- **Keep refusing LAN addresses for user-supplied endpoints, and document the- workaround.** Rejected: the workaround is the same request from a different- process, so the refusal buys no security and costs the feature.-- **Trust every address everywhere, including third-party content.** Rejected:- that is the SSRF path the guard exists for — a catalog body, a registry record- or a redirect is content the app received from someone else, and DNS rebinding- makes a pre-flight check alone insufficient (ADR 0245).-- **Permit cloud metadata as well, since the user typed it.** Rejected: the- metadata service returns instance credentials to anything that asks, it is- never a service a user runs, and an address that appears in a settings field- is far more likely to be an injected payload than a deliberate choice.-- **Per-source acknowledgement stored with the source list.** Rejected: the- source list lives in renderer storage, where a flag is exactly as trustworthy- as the URL next to it, so it would add UI without adding a boundary.+- Keep refusing LAN addresses and document the workaround: the workaround is the+ same request from another process, so the refusal buys no security.+- Trust every address everywhere: that is the SSRF path the guard exists for,+ and a pre-flight check alone cannot stop DNS rebinding (ADR 0245).+- Permit cloud metadata as well: the metadata service returns instance+ credentials and is never a service a user runs.diff --git a/docs/adr/0305-scheduled-task-execution-settings.md b/docs/adr/0305-scheduled-task-execution-settings.mdindex cda638aa0..3ff8086cc 100644--- a/docs/adr/0305-scheduled-task-execution-settings.md+++ b/docs/adr/0305-scheduled-task-execution-settings.md@@ -6,39 +6,42 @@## Context-Scheduled tasks already own their prompt, cadence and project binding, but they-did not own the rest of their execution configuration. Automatic runs always-used Ask permission mode and resolved the app's current default provider/model-when each run started.+Scheduled tasks owned their prompt, cadence, and project binding but not the rest+of their execution configuration: automatic runs always used Ask permission mode+and resolved the app's current default provider/model at start, so editing a+global default could silently change an unrelated task and the Scheduled form+could not move a task to another saved project.## Decision-Store optional `permissionMode`, `providerId` and `modelId` fields alongside the-existing `workspacePath` in each task's Host-owned `config_json`. Provider and-model are an all-or-nothing pair.--New tasks default to the current project, Ask permission mode and the current-default provider/model when those values exist. Users may explicitly choose-another saved project, permission mode or configured model.--- a task without `providerId`/`modelId` continues to resolve the app defaults at- run time;-- a legacy automatic task without `permissionMode` continues to use Ask;-- a legacy manual task without `permissionMode` keeps its previous inherited- permission behavior;-- existing workspace-capture and project-removal rules remain unchanged;-- an unavailable saved model remains visible and preserved instead of silently- changing to another model.+Each task's host-owned `config_json` gains optional `permissionMode`,+`providerId`, `modelId`, and `thinkingLevel` beside the existing+`workspacePath`, with provider and model as an all-or-nothing pair. The Scheduled+form reuses the conversation composer's model filtering, aliases, permission+labels, and model/reasoning picker while writing a separate copy to the selected+task, and both Run now and automatic runs create their session from the+task-owned values. Only the trusted desktop management surface may retarget a+task; conversation tools stay scoped to their calling session's project and gain+no project, model, or permission parameters.++Compatibility stays additive: a task without `providerId`/`modelId` keeps+resolving app defaults, a legacy automatic task without `permissionMode` keeps+Ask, a legacy manual task keeps its inherited permission behavior, an+unavailable saved model stays visible and preserved, and a missing+`thinkingLevel` retains `off` without a migration.## Consequences-No table migration is required because `config_json` is the existing extension-boundary.--The public scheduled-task projection and desktop IPC gain optional fields, so-Host, shared types, renderer and contract tests must change together.+- No table migration is needed because `config_json` is the existing extension+ boundary, and older versions ignore the additive fields.+- Selecting Auto is an explicit per-task choice that can run restricted actions+ without approval; Ask remains the default for new and legacy tasks.+- The scheduled-task projection and desktop IPC gain optional fields, so host,+ shared types, renderer, and contract tests change together.## Alternatives-Keeping global defaults as the only source was rejected because changing one-setting can retarget every automation.+- Keep global defaults as the only source: one setting change can retarget every+ automation.+- Add physical columns: the validated JSON boundary already owns optional task+ configuration.diff --git a/docs/adr/0306-portuguese-brazil-shell-locale.md b/docs/adr/0306-portuguese-brazil-shell-locale.mdindex e9ff2465f..f45ae1f37 100644--- a/docs/adr/0306-portuguese-brazil-shell-locale.md+++ b/docs/adr/0306-portuguese-brazil-shell-locale.md@@ -2,45 +2,36 @@- Status: Accepted- Date: 2026-09-23-- Decision owners: PI-Desktop desktop/i18n maintainers- Related: ADR 0160, ADR 0182, ADR 0183, ADR 0185, D314, D605## Context-The searchable locale registry already supports complete shell catalogs, but-Brazilian Portuguese users were still limited to English or another shipped-locale. Brazilian Portuguese is a major world language with distinct-orthography, grammar, and technical terminology that should not be represented-by an English fallback or by European Portuguese.+The locale registry supports complete shell catalogs, but Brazilian Portuguese+users were limited to English or another shipped locale, although Portuguese+orthography, grammar, and technical terminology are served by neither an+English fallback nor European Portuguese.## Decision-1. Ship a complete Brazilian Portuguese shell catalog at- `packages/i18n/src/locales/pt-BR`, with native name `Português (Brasil)` and- English name `Portuguese (Brazil)`.-2. Resolve `pt-BR`, `pt_BR`, and generic `pt` / regional `pt-*` OS locale tags- to the Brazilian Portuguese catalog.-3. Ship a Brazilian Portuguese product changelog catalog with the same stable- version and highlight-count set as English so release notes follow the active- shell locale.-4. Preserve the existing English-first catalog contract: identical keys,- interpolation variables, searchable picker behavior, and English fallback for- plugin-contributed labels.+Ship a complete Brazilian Portuguese shell catalog at+`packages/i18n/src/locales/pt-BR`, named `Português (Brasil)` /+`Portuguese (Brazil)`. Resolve `pt-BR`, `pt_BR`, and generic `pt` / regional+`pt-*` OS tags to it, add `pt-BR` to persisted `AppSettings.language` and+`pt-BR` / `pt_BR` to the Electron Chromium locale allowlist, and ship a+Brazilian Portuguese changelog catalog with the same version and+highlight-count set as English. Catalog keys, interpolation variables, picker+behavior, and the English fallback for plugin labels stay unchanged, and no+host protocol, storage schema, or IPC version changes.## Consequences-- Brazilian Portuguese users can select `Português (Brasil)` or use Auto- detection without reloading the renderer.-- Catalog, placeholder, and changelog parity tests cover `pt-BR` alongside the- existing shipped locales.-- Regional Portuguese variants currently resolve to this base catalog; European- Portuguese (`pt-PT`) can be added later as an independent catalog without- breaking the picker or storage contract.+- Users select `Português (Brasil)` or rely on Auto detection without a+ renderer reload.+- Parity tests cover `pt-BR` alongside the existing locales.+- Regional variants resolve here; `pt-PT` can later ship independently.## Alternatives-- Register `pt-BR` while falling back to English: rejected because the picker- would advertise an untranslated shell.-- Add generic `pt` without regional distinction: rejected because `pt-BR` is the- predominant standard expected by the community and Chromium/Electron- conventions.+- Register `pt-BR` with an English fallback: rejected, the picker would+ advertise an untranslated shell.+- Add generic `pt` only: rejected, `pt-BR` is the convention users expect.diff --git a/docs/adr/0307-pi-ai-api-key-provider-sync.md b/docs/adr/0307-pi-ai-api-key-provider-sync.mdindex 8bd9762c4..883618413 100644--- a/docs/adr/0307-pi-ai-api-key-provider-sync.md+++ b/docs/adr/0307-pi-ai-api-key-provider-sync.md@@ -2,73 +2,47 @@- Status: Accepted- Date: 2026-09-24-- Decision owners: PI-Desktop core-- Related: ADR 0012, ADR 0020, ADR 0116, ADR 0155, D620+- Related: D620, ADR 0012, ADR 0020, ADR 0116, ADR 0155## Context-The Model configuration service list has two halves with different sources of-truth. Vendor accounts are derived at runtime from pi-ai-(`models.getProviders().filter(p => p.auth.oauth)`), so a subscriptions vendor-added to the library shows up in the app without a code change.+The Model configuration service list derives vendor accounts from pi-ai at runtime, so+a subscription vendor needs no code change, but the API-key half is hand-maintained in+`NAMED_ENDPOINT_PRESETS` and had drifted: fifteen ids that take a plain API key had no+preset, so users had to know the base URL, the vendor key stayed `custom`, and the+models.dev binding was lost.## Decision-Add fifteen named endpoint presets so every pi-ai built-in API-key provider is-reachable from the Service select:--```text-id baseUrl apiStyle-ant-ling https://api.ant-ling.com/v1 chat_completions-baseten https://inference.baseten.co/v1 chat_completions-cerebras https://api.cerebras.ai/v1 chat_completions-huggingface https://router.huggingface.co/v1 chat_completions-meta https://api.meta.ai/v1 responses-minimax https://api.minimax.io/anthropic/v1 anthropic_messages-moonshotai https://api.moonshot.ai/v1 chat_completions-nvidia https://integrate.api.nvidia.com/v1 chat_completions-opencode https://opencode.ai/zen/v1 chat_completions-vercel https://ai-gateway.vercel.sh/v1 chat_completions-alibaba-token-plan https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1 chat_completions-alibaba-token-plan-cn https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1 chat_completions-xiaomi-token-plan-cn https://token-plan-cn.xiaomimimo.com/v1 chat_completions-xiaomi-token-plan-ams https://token-plan-ams.xiaomimimo.com/v1 chat_completions-xiaomi-token-plan-sgp https://token-plan-sgp.xiaomimimo.com/v1 chat_completions-```--Rules that follow from the existing preset contract:--- `id` / `vendorKey` use the models.dev provider key when the snapshot has one,- so the catalog binding and the model list work; the pi-ai provider id is kept- as an alias when the two differ (`vercel-ai-gateway`, `qwen-token-plan`,- `qwen-token-plan-individual`, `qwen-token-plan-cn`, `opencode-zen`, `hf`,- `hugging-face`, `nim`).-- `apiStyle` follows the wire style this app can actually drive with discovery- and catalog metadata.-- `minimax` (international, `api.minimax.io`) and `minimax-cn`- (`api.minimaxi.com`) stay separate rows; `moonshotai` and `moonshotai-cn` too.--- Amazon Bedrock, Azure OpenAI: request signing / per-resource endpoint and- deployment id rather than a base URL plus API key.-- Cloudflare AI Gateway, Cloudflare Workers AI, Google Vertex AI: the base URL- embeds an account, gateway, project, or location.-- GitHub Copilot, OpenAI Codex: offered as vendor-account (OAuth) rows here.-- Radius: `pi_messages` is an account-only style in this app and the gateway- publishes no model list for discovery.+Add one named endpoint preset per pi-ai built-in API-key provider: `ant-ling`,+`baseten`, `cerebras`, `huggingface`, `meta`, `minimax`, `moonshotai`, `nvidia`,+`opencode`, `vercel`, `alibaba-token-plan`, `alibaba-token-plan-cn`,+`xiaomi-token-plan-cn`, `xiaomi-token-plan-ams`, and `xiaomi-token-plan-sgp`. Each+carries its base URL and an `apiStyle` the app can drive with discovery and catalog+metadata: `chat_completions` for the OpenAI-compatible face, including Vercel AI Gateway+and OpenCode Zen, `anthropic_messages` for `minimax`, and `responses` for `meta`. `id`+and `vendorKey` use the models.dev provider key when the snapshot has one, so the+catalog binding and model list work, with the pi-ai id left as an alias when they differ+(`vercel-ai-gateway`, `qwen-token-plan`, `qwen-token-plan-individual`,+`qwen-token-plan-cn`, `opencode-zen`, `hf`, `hugging-face`, `nim`), and `minimax` /+`minimax-cn` and `moonshotai` / `moonshotai-cn` stay separate rows. Eight built-in+providers intentionally stay without a preset and are recorded in the+`pi-ai-provider-sync` guard, which fails when the list goes stale: Bedrock and Azure+OpenAI need request signing or a per-resource endpoint, Cloudflare AI Gateway, Cloudflare+Workers AI, and Vertex AI embed an account or location in the base URL, GitHub Copilot+and OpenAI Codex are OAuth vendor rows, and Radius uses the account-only `pi_messages`+style.## Consequences-The Service select grows by fifteen API-key rows in the international and China-groups; each row prefills name, base URL, and format, and `vendorKey` binds it-to its models.dev catalog entry.--The sync guard now fails on a pi-ai upgrade that adds a provider, which turns-silent drift into a build-time signal.+- The Service select gains fifteen API-key rows with prefilled name, base URL, and+ format, and aliases map rows storing a pi-ai id to the same preset.+- A pi-ai upgrade that adds a provider becomes a build-time signal, while+ multi-protocol providers still need a human decision recorded in the guard.+- No protocol, IPC, storage schema, permission, or default-selection change.## Alternatives-- **Derive the API-key list from pi-ai at runtime**, as vendor accounts do.-- **Custom endpoint only.** Rejected: it hides the services, loses the- models.dev binding, and leaves the drift invisible.-- **Group providers by library id, ignoring models.dev keys.** Rejected: the- catalog lookup and the model list are keyed by `vendorKey`.+- Derive the API-key list at runtime: pi-ai providers carry no display ordering, some+ need account-scoped URLs, and the table also carries `apiStyle` and `zhipuCompat`.+- Custom endpoint only: hides the services and leaves the drift invisible.diff --git a/docs/adr/0308-remove-pull-requests-destination.md b/docs/adr/0308-remove-pull-requests-destination.mdindex 020d57726..cc3bcf6e8 100644--- a/docs/adr/0308-remove-pull-requests-destination.md+++ b/docs/adr/0308-remove-pull-requests-destination.md@@ -2,29 +2,26 @@- Status: Accepted- Date: 2026-09-27-- Decision owners: PI-Desktop core## Context-PI-Desktop had a Pull requests destination that ran `gh pr list` in the active-workspace and exposed the same listing through the optional local MCP control-catalog as `pulls/list`. The UI depended on the GitHub CLI and authentication-available to the Electron process; listing failures could leave the page with no-usable PR data.+A Pull requests destination ran `gh pr list` in the active workspace and also+exposed that listing as `pulls/list` in the local MCP control catalog, so the UI+depended on GitHub CLI authentication in the Electron process. Removing only the+page would have left an undocumented, otherwise unused GitHub capability in the+MCP surface.## DecisionRemove the Pull requests route, its global-search entry and page copy, the`gh`-backed IPC handler, the `pulls/list` MCP catalog entry, the shared PR-summary type, and their dedicated tests and screenshots. Keep the general MCP-control plane, GitHub references in development workflows, and generic plugin-view icons unchanged.+summary type, and their tests, while keeping the general MCP control plane,+GitHub references in development workflows, and generic plugin view icons.## Consequences-- Users can no longer open a PR destination or call `pulls/list` through- PI-Desktop's MCP control catalog.-- The change requires no data migration: PR summaries were fetched on demand and- were not persisted.-- This decision does not remove user-directed GitHub work through other- configured Agent tools, a terminal, or a browser.+- Users can no longer open a PR destination or call `pulls/list` through the+ MCP control catalog, so existing local clients must stop relying on it.+- No data migration is needed because PR summaries were fetched on demand.+- User-directed GitHub work through other Agent tools, a terminal, or a browser+ is unaffected.diff --git a/docs/adr/0309-remove-macos-first-launch-artifacts.md b/docs/adr/0309-remove-macos-first-launch-artifacts.mdindex 549a286e5..2243b59f6 100644--- a/docs/adr/0309-remove-macos-first-launch-artifacts.md+++ b/docs/adr/0309-remove-macos-first-launch-artifacts.md@@ -2,25 +2,26 @@- Status: Accepted- Date: 2026-09-27-- Deciders: PI-Desktop release maintainers-- Amends: D457 / [ADR 0296](0296-macos-signed-dmg-two-icon-install.md), the macOS distribution provisions of [ADR 0232](0232-macos-dmg-text-only-opening-guidance.md) and [ADR 0204](0204-unsigned-macos-first-launch-helper.md)+- Amends: D457 / [ADR 0296](0296-macos-signed-dmg-two-icon-install.md), the macOS+ distribution provisions of [ADR 0232](0232-macos-dmg-text-only-opening-guidance.md)+ and [ADR 0204](0204-unsigned-macos-first-launch-helper.md)- Related: D634, E2E-196b## Context-The signed and notarized macOS release lane no longer needs an unsigned-first-launch workaround. The executable helper and its text note add files to-macOS packages and imply that users should bypass Gatekeeper for unsigned-builds, including local debug artifacts.+The signed and notarized macOS lane no longer needs an unsigned first-launch+workaround, and the bundled helper and text note imply that users should bypass+Gatekeeper.## Decision-Neither macOS DMG nor ZIP includes `PI-Desktop-macOS-open.command`,-`PI-Desktop-macOS-opening-help.txt`, or another bundled quarantine-clearing-helper or opening note. The ZIP contains `PI-Desktop.app` at its root.+Neither the macOS DMG nor the ZIP includes `PI-Desktop-macOS-open.command`,+`PI-Desktop-macOS-opening-help.txt`, or any other quarantine-clearing helper or+opening note, and the ZIP contains `PI-Desktop.app` at its root. Signing,+notarization, stapling, and updater behavior stay unchanged.## Consequences- Both macOS package formats omit the two first-launch guidance files.-- Unsigned debug builds do not ship a Gatekeeper workaround and must not be- represented as equivalent to signed, notarized releases.+- Unsigned debug builds ship no Gatekeeper workaround and are not equivalent to+ signed releases.diff --git a/docs/adr/0310-local-permission-approvals-without-deadline.md b/docs/adr/0310-local-permission-approvals-without-deadline.mdindex 5a1acf831..fab2fea41 100644--- a/docs/adr/0310-local-permission-approvals-without-deadline.md+++ b/docs/adr/0310-local-permission-approvals-without-deadline.md@@ -2,35 +2,29 @@- Status: Accepted for implementation- Date: 2026-09-29-- Deciders: PI-Desktop maintainers- Amends: D005 / [ADR 0011](0011-host-rpc-and-storage-defaults.md)- Related: D636, issue #1214, E2E-017## Context-The local `ask` permission flow displayed a 120-second countdown and then denied-a request in host-core. The same deadline was copied into the renderer card, the-pending-permission snapshot, and the RPC transport budgets.+The local `ask` flow showed a 120-second countdown and then denied the request+in host-core, with the same deadline copied into the renderer card, the+pending-permission snapshot, and the transport budgets, so a user who missed the+card made an unintended decision.## Decision-Local permission-gated `tools.execute` requests remain pending until one of-these explicit lifecycle events occurs:--- the user chooses Allow once, Allow for session, or Deny;-- the tool call or turn is cancelled; or-- the host / sidecar process shuts down.--The renderer shows no countdown. Host-core does not expire or sweep local-permission requests, and `permissions.pending` returns every open request-without `timeoutMs`, `expiresAt`, or `remainingMs`.+A local permission-gated `tools.execute` request stays pending until the user+chooses Allow once, Allow for session, or Deny, until the tool call or turn is+cancelled, or until the host or sidecar shuts down. The renderer shows no+countdown, host-core never expires these requests, `permissions.pending` returns+every open request without `timeoutMs`, `expiresAt`, or `remainingMs`, and the+transport sets no deadline for `tools.execute`. Tool execution budgets,+Plan/Goal approval lifetimes, and RACP broker lifetimes are unchanged.## Consequences-- Users can leave a permission card unanswered without an automatic denial.-- An unattended permission request can keep its agent turn paused, so explicit- cancellation remains available and must continue to wake the host waiter.-- The local permission wire shape is simplified and no longer carries a- misleading expiry time.-- A lost host response is still bounded by process-close handling; ordinary- non-tool RPCs retain their finite transport deadlines.+- Users can leave a permission card unanswered without an automatic denial, at+ the cost of a turn that stays paused until explicit cancellation.+- The local permission wire shape loses its misleading expiry, while other RPCs+ keep their finite transport deadlines.diff --git a/docs/adr/0311-live-work-workspace-admission-guard.md b/docs/adr/0311-live-work-workspace-admission-guard.mdindex a975fc81e..07c051522 100644--- a/docs/adr/0311-live-work-workspace-admission-guard.md+++ b/docs/adr/0311-live-work-workspace-admission-guard.md@@ -6,25 +6,21 @@## Context-Live Work binds a call to a local session and workspace in Electron Main. That-scope can become stale while a request is being classified.+Live Work binds a call to a local session and workspace in Electron Main, but that+scope can go stale while a request is classified, and rechecking in Main still+leaves a gap before the Host persists a message or admits a turn.## DecisionAdd an optional `expectedWorkspaceIdentity` to the local AgentHost turn-start-request. When supplied by trusted Main code, AgentHost compares it with the-fresh workspace identity returned by its session port before admission.--Existing non-Live callers omit the field and keep their current behavior. The-identity uses the existing Host session summary canonicalization; this change-does not create a second path-normalization rule or a database migration.+request, which AgentHost compares with the fresh identity from its session port+before admission and rejects as `WORKSPACE_CHANGED` before any turn or queue entry+exists; the value stays out of provider input, Renderer DTOs, RACP, and+persistence, and non-Live callers omit it.## Consequences-- Live work is checked at its final local admission owner as well as in Main.-- A workspace move during classification fails closed and requires a new- explicitly bound work call.-- The AgentHost start-turn TypeScript contract gains one optional local field;- no IPC or persisted data format changes.-- Tests must cover both unchanged identity admission and changed identity- rejection without prompt or queue side effects.+- Live work is checked at its final local admission owner, and a workspace move+ during classification fails closed.+- The start-turn contract gains one optional local field; no IPC or persisted+ format changes.diff --git a/docs/adr/0312-session-scoped-todo-checklist.md b/docs/adr/0312-session-scoped-todo-checklist.mdindex 09b3d004e..a64cec9c8 100644--- a/docs/adr/0312-session-scoped-todo-checklist.md+++ b/docs/adr/0312-session-scoped-todo-checklist.md@@ -2,30 +2,33 @@- Status: Accepted for implementation- Date: 2026-09-29-- Deciders: PI-Desktop maintainers- Related: Issue #1177## Context-Multi-step Agent work needs a durable, session-scoped progress checklist that-can be shown to the user without making the renderer a second source of truth.-The checklist must remain ordered, survive restart, and be isolated from-Plan/Goal contract negotiation and delegated subagent calls.+Multi-step Agent work needs a durable, ordered, session-scoped checklist that+survives restart and stays isolated from Plan/Goal contract negotiation and+delegated subagent calls, without making the renderer a second source of truth.## Decision-`TodoWrite` is an Agent-only builtin tool. Its arguments contain the complete-ordered checklist and are validated by host-core.--The tool call is authorized against the calling session and its running turn-inside that transaction. The host emits `todos.changed` only after commit and-serves the complete committed snapshot through `todos.get`.+`TodoWrite` is an Agent-only builtin tool whose arguments carry the complete+ordered checklist, validated by host-core, which owns persistence in SQLite+schema v21: `session_todo` stores the rows while `sessions.todo_revision` and+`sessions.todo_updated_at` order populated and empty snapshots, each write+replacing the rows and incrementing the revision in one transaction. The call is+authorized against the calling session and its running turn inside that+transaction, the host emits `todos.changed` only after commit, and `todos.get`+serves the committed snapshot, which the renderer keys by session id and filters+by revision. The Composer TodoDock shows bounded progress and the complete+ordered list scrolled inside its own box, and remote RACP sessions stay+local-only because RACP v1 has no Todo snapshot operation.## Consequences-- Empty checklist writes remain observable through revision advancement.-- Session deletion cascades checklist rows; forks start with an empty checklist.-- Plan, Goal, delegated, plugin, and MCP execution paths cannot write the- checklist through this contract.-- Context-compaction injection is deliberately deferred to a follow-up change.-- Remote Todo parity requires an additive RACP contract in a later change.+- Empty checklist writes stay observable through revision advancement, session+ deletion cascades the rows, and forks start empty.+- Plan, Goal, delegated, plugin, and MCP paths cannot write the checklist+ through this contract.+- Context-compaction injection and remote parity are deferred, the latter+ needing an additive RACP contract.diff --git a/docs/adr/0313-live-voice-default-session-target.md b/docs/adr/0313-live-voice-default-session-target.mdindex a1085526e..18a9bb87a 100644--- a/docs/adr/0313-live-voice-default-session-target.md+++ b/docs/adr/0313-live-voice-default-session-target.md@@ -6,26 +6,27 @@## Context-Live Voice must be useful from the current Composer without requiring the user-to opt into work requests or select a session before speaking. The target may be-a Desktop, Native Pi, or Remote session, and users may switch targets by voice-during a call.+Live Voice must be useful from the current Composer without asking the user to opt+into work requests or pick a session before speaking. The target may be a Desktop,+Native Pi, or Remote session and can change by voice during a call, without+expanding the voice provider's authority or bypassing the target backend's policies.## Decision-- When Composer has an active session, use it as the initial work target.-- Treat a renderer-provided session ID only as a target hint.-- Do not require a per-call work-access toggle.-- A target switch applies only to subsequent requests.-- Keep bounded history sharing as a separate, unchecked call consent.+When Composer has an active session it becomes the initial work target; with none,+the call starts unbound and voice can list and select one. A renderer-provided+session id is only a hint: Electron Main resolves it against the fresh combined+session catalog and fails closed when it is missing or ambiguous, and voice+selection travels as call-scoped opaque references, so provider payloads never+choose raw session ids, paths, modes, or permissions. There is no per-call+work-access toggle, because candidates still pass through the selected backend's+identity, admission, authorization, permission, and approval paths. A target switch+applies only to later requests, and bounded history sharing stays a separate,+unchecked consent that grants no execution authority.## Consequences-- Composer starts are direct and predictable while session selection remains- available by voice; an empty Composer target never causes implicit guessing.-- Main and backend-specific fixtures must cover fresh resolution, ambiguous or- stale targets, all three sources, target switching, and fail-closed behavior.-- Permission and approval behavior remains owned by Desktop, Native Pi, and- Remote backends; Live Voice does not expose arbitrary IPC or tools.-- Context privacy remains independent from execution authorization and must be- tested separately.+- Composer starts are predictable, and an empty target never makes Main guess.+- Permission and approval behavior remains owned by the Desktop, Native Pi, and+ Remote backends; Live Voice exposes no arbitrary IPC or tools.+- Context privacy stays independent of execution authorization.diff --git a/docs/adr/0315-live-voice-spoken-asktool-answers.md b/docs/adr/0315-live-voice-spoken-asktool-answers.mdindex 19699531b..d812863e5 100644--- a/docs/adr/0315-live-voice-spoken-asktool-answers.md+++ b/docs/adr/0315-live-voice-spoken-asktool-answers.md@@ -2,57 +2,50 @@- Status: Accepted for implementation- Date: 2026-10-01-- Related: Live Voice Work Session Integration, [ADR 0313](0313-live-voice-default-session-target.md), ADR 0311, ADR 0310+- Related: [ADR 0313](0313-live-voice-default-session-target.md), ADR 0310,+ ADR 0311## Context-A Live Voice work call could already report that the bound session is waiting on-an asktool question, but it could not act on it: the answer existed only in that-session's own Composer card, and a user talking through a call had to leave the-call flow, find the session, and answer by hand. The Live Voice Work Session-spec accordingly said that "Permission, Plan, Goal, and AskTool decisions stay-in their existing UI and policy paths".--- A permission, Plan, or Goal approval grants *authority*.-- An asktool question is the agent asking the user to choose.+A Live Voice work call could report that the bound session was waiting on an+asktool question but could not act on it, so a user talking through a call had to+find the session and answer by hand. A permission, Plan, or Goal approval grants+authority and must stay a desktop-UI decision; an asktool question only asks the+user to choose among options the agent itself produced.## Decision-- Add one classifier intent, `respond-input`, whose payload is `{ answers: [{- questionIndex, options[] }] }`: one entry per question of the session's open- asktool question, each naming the chosen option labels.-- Live Voice may resolve the bound session's open asktool question through the- same Host input path the desktop card uses.-- A spoken answer may only select among the labels the question itself offered.-- Fail closed and report honestly when: the session has no open question, it has- more than one open question (the answer cannot be attributed), a label does- not match, a question index is missing, repeated, or out of range, or the- input is malformed.-- The question and its own options are delivered to the live provider as- interaction-required work feedback so it can read them out, and the same- bounded question is part of the classifier input, so the option labels the- answer is checked against are the ones the user heard.-- Bounds: at most 8 questions, 8 options per question, 300 characters per- question, 120 characters per option, and a feedback message that stays inside- the existing delivery budget, truncated on question boundaries.-- The resolution goes through the Host-owned input path, so the input's- `input.resolved` event records who answered and the operation is a control- acknowledgement, not a task or a result row.--## Alternatives considered--- **A provider function per adapter** (`answer_pending_question`): rejected.-- **Free-text spoken answers**: rejected.-- **Keep answers desktop-only**: rejected as the state the user reported.+Add one classifier intent, `respond-input`, whose payload is+`{ answers: [{ questionIndex, options[] }] }` with one entry per question of the+session's open asktool question, and let Live Voice resolve that question through+the same Host input path the desktop card uses; nothing else changes, so permission,+Plan, and Goal approvals stay desktop-only and a spoken "yes" is never approval. An+answer may only select among the question's own labels, never free text, and every+question must be answered exactly once because the Host reads a missing answer as+skipped. The path fails closed when there is no open question, more than one open+question, a label mismatch, a missing, repeated, or out-of-range index, or+malformed input: the refusal is never retried, it points the user at the desktop+card, and an unanswered dispatch stays `unknown`.++The question and its options reach the live provider as interaction-required work+feedback and are part of the classifier input, so the labels checked are the ones+the user heard. Because resolution goes through the Host-owned input path, its+`input.resolved` event records who answered and the operation is a control+acknowledgement rather than a task or result row.## Consequences-- An asktool question can be answered hands-free during a work call, while- permission, Plan, and Goal approvals keep their desktop-only decision path.-- Residual risk: a provider (or a spoofed audio source) could answer a question- as if the user had.-- Remote and Native Pi sessions are unchanged: this path is Electron Main plus- the local AgentHost input path, and both remote backends keep their own- approval and input transports.-- The live panel and the compact bar still carry no approve or answer control;- they show the pending request and open the session that owns it.+- An asktool question can be answered hands-free mid-call while approvals keep+ their desktop-only path.+- A provider or spoofed audio source could answer as if it were the user, bounded+ to choosing among offered options, one open question, no authority, recorded+ with voice provenance, and rejectable at the card's resolution boundary.+- Remote and Native Pi sessions keep their own approval and input transports.++## Alternatives++- A provider function per adapter (`answer_pending_question`): rejected because it+ needs three wire declarations for the same validation the existing channel+ already carries.+- Free-text spoken answers: rejected because unverifiable content could reach a+ question the user was never asked.diff --git a/docs/adr/0316-live-voice-docked-widget.md b/docs/adr/0316-live-voice-docked-widget.mdindex b98afd604..fdda638fc 100644--- a/docs/adr/0316-live-voice-docked-widget.md+++ b/docs/adr/0316-live-voice-docked-widget.md@@ -2,58 +2,48 @@- Status: Accepted- Date: 2026-10-01-- Deciders: PI-Desktop core-- Related: [ADR 0086](0086-macos-regular-activation-policy.md) ·- [ADR 0275](0275-plugin-panel-floating-widget.md) ·- [03-runtime/live-voice](../spec/03-runtime/live-voice.md) ·- [03-runtime/01-ipc-protocol](../spec/03-runtime/01-ipc-protocol.md) ·- [04-ux/08-component-spec](../spec/04-ux/08-component-spec.md)+- Related: ADR 0086, ADR 0275## Context-The compact call bar was AppShell chrome inside the main window. That satisfies-"in-app navigation cannot hide the call controls", but not the case users-actually hit: working in another application while a call is running.+The call bar was AppShell chrome inside the main window, which keeps controls reachable+during in-app navigation but not while the user works elsewhere, since a bar painted+inside the app window is invisible once the app is not foreground. The call cannot move+with it: the main window owns renderer-side capture gating, the WebRTC/PCM media, the+microphone lease, and call-scoped work, and every owner-validated Live Voice channel+rejects another window with `PERMISSION_DENIED`, while `isTrustedRendererUrl` treats a+renderer URL with a query string as untrusted.## Decision-1. The call chrome is drawn by its own frameless, transparent, always-on-top- `panel` window, following the plugin launcher's window recipe — with its- activation-policy constraint from ADR 0086: it joins every Space, floats- above other applications, and never lets Electron transform the process type.-2. The bar is its own drag handle (`app-region: drag` on the bar, `no-drag` on- its controls).-3. The widget never owns the call.-4. A failure only the owner frame can observe — a refused mute, a playback retry- that failed — is reported back (`voice/live/widget/issue`) so the bar can- name it in place next to its verbatim `LIVE_*` code.-5. The main window draws no call bar.-6. The widget's channels are validated as the widget window and never enter- owner derivation: any other renderer using them is refused exactly like any- other untrusted caller.+The chrome is drawn by its own frameless, transparent, always-on-top `panel` window+following the plugin launcher's recipe plus ADR 0086's activation-policy constraint, so+it joins every Space, floats above other applications, and never lets Electron transform+the process type, and it loads the existing renderer bundle through+`?surface=live-voice-widget`, needing no second HTML entry, preload, or build change. The+bar is its own drag handle (`app-region: drag`, `no-drag` on controls), placement is+remembered in `live-voice-widget.json` and clamped to the measured work area, and the+window is sized to the box the widget reports so no invisible hit area covers the+desktop. The widget never owns the call: main pushes the authoritative view over+`voice/live/event/widgetState` and every press returns as `voice/live/widget/action` to be+executed by the main window's controller in the owner frame, so mute still gates capture+before the IPC request, and a failure only the owner frame can observe is reported back+over `voice/live/widget/issue` beside its verbatim `LIVE_*` code. The main window draws+no call bar, its details surface opens from the widget's Details action, and the widget's+channels are validated as the widget window and never enter owner derivation.## Consequences-- A call stays visible and controllable while the user works in another- application, and the chrome can be placed anywhere on the desktop.-- One additional renderer process appears with the first call and stays warm- while the widget is hidden; that idle cost buys a bar that appears without a- navigation or load delay mid-call.-- The widget is not the app shell, so it does not boot the settings store.-- New IPC surface: two widget channels, one owner-report channel and two events.-- The details surface lost its in-window trigger; it is opened from the widget- and hangs from a fixed anchor above the composer.+- A call stays visible and controllable while the user works elsewhere, and the chrome+ can be placed anywhere on the desktop.+- One more renderer process appears with the first call and stays warm while hidden, and+ being no app shell it applies the persisted language when visible instead of booting+ the settings store.+- New IPC surface is two widget channels, one owner-report channel, and two events, and+ the preload whitelist derives from `IPC` so only `packages/shared` needs the names.## Alternatives-- Keep the bar in AppShell and make it draggable inside the window: it can never- leave the app rectangle or survive another app owning the foreground, which is- the whole request (rejected).-- Let the widget window own the call: it would have to hold media, the- microphone lease and the work scope, duplicating the owner contract and- breaking the single-owner rule (rejected).-- Capture media in an offscreen renderer while the widget draws chrome: it- contradicts the existing ownership model without buying anything the owner- frame does not already provide (rejected).-- Draw the details surface inside the widget: its work actions need the main- window's session, project and navigation store (rejected).+- Keep the bar in AppShell and make it draggable: it can never leave the app rectangle.+- Let the widget own the call: it would duplicate the owner contract and break the+ single-owner rule.diff --git a/docs/adr/0317-windows-borderless-window-resize.md b/docs/adr/0317-windows-borderless-window-resize.mdindex 7dcf4038e..2d11db102 100644--- a/docs/adr/0317-windows-borderless-window-resize.md+++ b/docs/adr/0317-windows-borderless-window-resize.md@@ -2,48 +2,47 @@- Status: Accepted- Date: 2026-09-29-- Deciders: PI-Desktop maintainers-- Related: D635, D637, E2E-167, ADR 0025, ADR 0248+- Related: D635, D637, ADR 0025, ADR 0248## ContextElectron 43 paints a visible region on the left, bottom, and right of a-frameless, resizable Windows window with the default thick frame. The renderer-cannot paint into that native area.+frameless resizable Windows window with the default thick frame, and the renderer+cannot paint into it. Disabling `WS_THICKFRAME` removes the rim and the window+animations, and although the public option description warns about losing edge+dragging, the pinned Electron 43.6 frameless hit test still resizes on native+edges and corners.## Decision-Disable the Windows thick frame on the main window only. Retain Electron's-native frameless edge/corner hit testing and the current minimum-size contract;-the renderer adds no resize handles or geometry IPC.+Disable the Windows thick frame on the main window only, keeping Electron's+native frameless edge and corner hit testing plus the existing minimum-size+contract, with no renderer resize handles or geometry IPC; macOS and Linux keep+native edge resizing and the work-panel width stays a separate renderer-owned+interaction. Because `thickFrame: false` changes fullscreen display bounds+without setting the value `isFullScreen()` returns, main tracks that fallback so+fullscreen toggles, renderer events, and persisted normal bounds stay correct.++On Windows builds before 22000 the existing 12 DIP `--radius-md` `contentView`+clip and native `setShape()` hit region stay, and a plugin with+`ui.window.appearance` may declare an integer `cornerRadius` from 0 to 24 DIP+that the selected theme supplies through the window-appearance IPC, with main+validating the value and the caller. On build 22000 and later ADR 0325 replaces+both with the system DWM corner preference, which keeps zero square, treats any+positive radius as system-rounded, and requires an opaque top-level window.-macOS and Linux keep native edge resizing. Work-panel width remains a separate-renderer-owned interaction; the window resize changes only application bounds.--### Proposed rendering amendment+## Consequences-ADR 0325 proposes the DWM path for Windows 11 and later while keeping the-existing shape path for older Windows builds. It keeps this ADR's native resize-and minimum-size contracts.+- The Windows main window has no painted left, bottom, or right native rim, and+ edge resizing and minimum size stay owned by Electron on every platform.+- Native shadow, minimize/maximize animation, and snap may differ with+ `WS_THICKFRAME` removed, so they need native qualification before landing and+ no shadow setting is added.+- The Plugin SDK gains one optional permission-gated appearance property; old+ manifests stay valid and no host RPC, schema, or persisted format changes.## Alternatives-- Keep the thick frame: leaves the visible rim.-- Make the window transparent: changes the opaque background and theme contract- without removing the need to qualify native resizing.-- Use only renderer CSS rounding: leaves the opaque native background visible in- the corners and cannot change the window's native hit region.-- Pin an older Electron: trades away newer security and runtime fixes for a- historical rendering behavior.--## Consequences--- The Windows main window has no painted left, bottom, or right native rim.-- Native edge resizing and minimum size remain owned by Electron on every- platform; there is no parallel renderer/Main resize path.-- Windows native shadow, minimize/maximize animation, and snap behavior may- differ with `WS_THICKFRAME` removed.-- The native shadow cannot be made theme-configurable through Electron while- this thick-frame-free window retains its current bounds.-- Windows builds before 22000 retain the non-antialiased pixel-row `setShape()`- curve and its native hit region.+- Keep the thick frame: it leaves the visible rim.+- Make the window transparent: it changes the opaque background and theme+ contract without removing the need to qualify resizing.diff --git a/docs/adr/0318-linux-arm64-release-lane.md b/docs/adr/0318-linux-arm64-release-lane.mdindex 8eab23ef4..ac8766630 100644--- a/docs/adr/0318-linux-arm64-release-lane.md+++ b/docs/adr/0318-linux-arm64-release-lane.md@@ -2,74 +2,52 @@- Status: Accepted (D638)- Date: 2026-10-01-- Deciders: PI-Desktop core-- Related: D126, D285, D375, D603, ADR 0022, ADR 0145, ADR 0284, ADR 0292, issue #1281, E2E-192a+- Related: D126, D285, D375, D603, ADR 0022, ADR 0145, ADR 0284, ADR 0292, Issue #1281## Context-Tag releases publish Linux x64 only. Issue #1281 asks for a Linux arm64 build:-the reporter runs PI-Desktop inside a Linux container on a rooted arm64 Android-tablet, where no x64 artifact can execute and emulation is not a usable path for-an Electron app.--1. The Rust `pi-desktop-host-core` sidecar and the native voice modules are- packaged from the runner's own build output.-2. The Linux electron-builder targets pinned `arch: ["x64"]`, and- electron-builder prefers a target's configured arch list over the CLI `--x64`- / `--arm64` flag.-3. The AppImage target's default artifact name carries no architecture, so two- Linux lanes would publish the same `PI-Desktop-<version>.AppImage` file name- and the publish job's merged download would keep only whichever lane arrived- last.+Tag releases publish Linux x64 only, and issue #1281 asks for arm64 because the+reporter runs the app inside a Linux container on an arm64 Android tablet where no+x64 artifact executes. Adding arm64 is a packaging change: the Rust `host-core`+sidecar and native voice modules are packaged from the runner's own build output,+the Linux targets pinned `arch: ["x64"]`, and the AppImage artifact name carries no+architecture.## Decision-1. The release matrix publishes two native Linux lanes: `ubuntu-22.04` for x64- and GitHub's arm64 `ubuntu-22.04-arm` runner for arm64.-2. The static Linux targets stay AppImage, deb, and rpm without a pinned `arch`.+1. The release matrix publishes two native Linux lanes, `ubuntu-22.04` for x64 and+ GitHub's `ubuntu-22.04-arm` runner for arm64, both verifying `uname -m` and both+ keeping the documented glibc floor.+2. The static Linux targets stay AppImage, deb, and rpm without a pinned `arch`, and+ the workflow passes the matching `--x64` or `--arm64` flag, as ADR 0145 set for+ macOS.3. `build.linux.artifactName` becomes- `PI-Desktop-${version}-linux-${arch}.${ext}`, so the AppImage assets are- `PI-Desktop-<version>-linux-x64.AppImage` and- `PI-Desktop-<version>-linux-arm64.AppImage`.-4. Each Linux job verifies the updater feed it is about to publish —- `latest-linux.yml` on x64, `latest-linux-arm64.yml` on arm64.- electron-builder already writes that architecture-suffixed name- (`getArchPrefixForUpdateFile`), so no rename is needed and the publish job- merges both lanes' artifacts without one feed overwriting the other.-5. `scripts/export-linux-asar.mjs` takes the lane architecture, reads the- archive from electron-builder's own unpacked directory (`linux-unpacked` for- x64, `linux-arm64-unpacked` for arm64), and publishes+ `PI-Desktop-${version}-linux-${arch}.${ext}`, so each lane's AppImage carries its+ architecture.+4. Each Linux job verifies the updater feed it publishes — `latest-linux.yml` on x64+ and `latest-linux-arm64.yml` on arm64 — so both lanes' artifacts merge without one+ feed overwriting the other.+5. `scripts/export-linux-asar.mjs` takes the lane architecture, reads+ electron-builder's unpacked directory, and publishes`PI-Desktop-<version>-linux-<arch>.asar`.-6. `release.yml`'s `pi-host-bundle` job builds both Linux architectures, and- `PUBLISHED_TARGETS` in `apps/desktop/electron/main/remote/pi-host-release.ts`- lists `linux-x64` and `linux-arm64`.-7. No updater ownership, signing, or delivery-mode change: the arm64 AppImage- uses the same in-app `electron-updater` lane as x64, and deb/rpm stay- notify-and-link.+6. `release.yml`'s `pi-host-bundle` job builds both architectures, and+ `PUBLISHED_TARGETS` lists `linux-x64` and `linux-arm64`, so an arm64 desktop can+ bootstrap an arm64 remote host (ADR 0292).+7. Updater ownership, signing, and delivery mode do not change.## Consequences-- arm64 Linux users install native AppImage, deb, and rpm packages from every- tag release, and the AppImage updates in place through its own feed.-- The x64 AppImage asset is renamed from `PI-Desktop-<version>.AppImage` to- `PI-Desktop-<version>-linux-x64.AppImage`.-- Every tag release carries one `pi-host-<version>-linux-arm64.tar.gz` bundle- and one extra arm64 system-Electron ASAR asset beside the existing x64 ones.-- Microphone capture stays unavailable on arm64 Linux devices other than- Raspberry Pi boards: `@picovoice/pvrecorder-node` classifies Linux arm64 by- `/proc/cpuinfo` CPU part and only knows Raspberry Pi parts.-- Release cost grows by one Linux packaging job and one pi-host bundle job.+- arm64 Linux users install native AppImage, deb, and rpm packages from every tag+ release, and the AppImage updates in place through its own feed.+- The x64 AppImage is renamed to `PI-Desktop-<version>-linux-x64.AppImage`, so+ download links carrying the old name need updating.+- Every tag release carries one arm64 `pi-host` bundle and one extra arm64 ASAR+ asset, while microphone capture stays unavailable on arm64 devices other than+ Raspberry Pi boards.-## Alternatives considered+## Alternatives-- **Cross-compile the arm64 packages on the existing x64 runner.** Rejected: the- packaged Rust sidecar and the native voice modules come from the runner's own- build output, so a cross-compiled lane needs a second toolchain and a separate- architecture verification to stay honest.-- **Emulate arm64 on the x64 runner.** Rejected: an emulated build both hides- architecture mistakes and turns a bounded packaging job into a long one.-- **Ship only the AppImage for arm64.** Rejected: deb and rpm are the formats- arm64 Linux distributions install, and FPM publishes a native linux-arm64- build, so the lane costs nothing extra.-- **Keep Linux x64 only.** Rejected: the request is a supported platform that- cannot run the published artifact at all.+- Cross-compile arm64 on the x64 runner — rejected: the sidecar and voice modules+ come from the runner's own build output.+- Pin both architectures on each Linux target — rejected: the arch list outranks the+ CLI flag, so each lane would build the other architecture around its own sidecar.diff --git a/docs/adr/0319-settings-inline-imports.md b/docs/adr/0319-settings-inline-imports.mdindex 3a4990020..b2ebfffe8 100644--- a/docs/adr/0319-settings-inline-imports.md+++ b/docs/adr/0319-settings-inline-imports.md@@ -9,25 +9,19 @@ Accepted## Context-Settings had one Import destination combining four independent workflows:-session import, model configuration import, external skill import, and external-MCP import. The model and agent capability destinations already own the records-those imports create.+Settings had one Import destination combining four independent workflows — session,+model configuration, external skill, and external MCP import — although the capability+destinations already own the records those imports create.## Decision-Remove the standalone Settings Import destination and move external model,-skill, and MCP scan panels into their corresponding Settings pages. Each scan-remains explicit.--Remove the Settings session-import UI. Keep existing plugin session import, host-RPC, IPC, and persistence behavior unchanged.+Remove the standalone Settings Import destination and move the external model, skill,+and MCP scan panels into their owning Settings pages, each staying explicit and using+the selected global or project filter. The Settings session-import UI is removed while+plugin session import, host RPC, IPC, and persistence stay unchanged.## Consequences- The Settings rail and search no longer expose an Import destination.-- Models, Skills, and MCP each expose their importer from their owning page.-- Import candidates and selected rows stay within one capability scope; a scope- change clears the panel state.-- Existing plugin session import contracts continue to own session ingestion.-- No host protocol, plugin API, permission, or database migration is required.+- Each capability exposes its importer from its owning page.+- No host protocol, plugin API, permission, or migration is required.diff --git a/docs/adr/0320-plugin-oauth-provider-callbacks.md b/docs/adr/0320-plugin-oauth-provider-callbacks.mdindex f6adf13fa..da0284321 100644--- a/docs/adr/0320-plugin-oauth-provider-callbacks.md+++ b/docs/adr/0320-plugin-oauth-provider-callbacks.md@@ -3,62 +3,55 @@- Status: Accepted for implementation- Date: 2026-10-06- Decision: D647-- Related: ADR 0008, ADR 0095, ADR 0259, `07-plugins/02-plugin-manifest-schema.md`, `07-plugins/03-plugin-api.md`, `07-plugins/04-plugin-security.md`, `07-plugins/13-plugin-permissions-matrix.md`, `03-runtime/14-secrets-storage.md`+- Related: ADR 0008, ADR 0095, ADR 0259,+ `07-plugins/13-plugin-permissions-matrix.md`,+ `03-runtime/14-secrets-storage.md`## Context-ADR 0259 gives plugins manifest-owned provider rows, but its first version-supports only API keys and no-auth providers. Some providers can only be used-through OAuth.+ADR 0259 gives plugins manifest-owned provider rows with API-key and no-auth+support only, yet some providers need OAuth. The host already owns provider+account UI, encrypted secrets, request authentication, and cancellation, and a+plugin adding a provider must not move those responsibilities into its panel or+into Electron main, while a general secret API would create a second secret+owner.## Decision-1. Add `authKind: "oauth"` and bounded `oauth` display metadata to- `contributes.providers`.-2. The Host owns the sign-in surface and lifecycle.-3. `onProviderOAuth` handles `login` and `refresh`, and receives an abort signal- for cancellation, plugin unload, and timeout.-4. Electron main stores the credential under the existing encrypted- `secret:provider:<providerRowId>:oauth` reference and serializes refreshes by- provider row.-5. `provider.oauth` is a separate high-risk permission from `provider.register`- and `net.fetch`.-6. One credential is stored per provider contribution.-7. Existing `api_key` and `none` provider contributions keep their behavior; old- plugins receive no OAuth grant by default.+`contributes.providers` gains `authKind: "oauth"` and bounded `oauth` display+metadata, requiring `provider.register`, `provider.oauth`, an absolute HTTP(S)+`baseUrl`, and an `onProviderOAuth` export that runs in the existing isolated+plugin process (ADR 0008). The host owns the sign-in surface, prompts,+progress, and authorization URL, and the plugin uses `pi.providers.oauth.prompt`+and `.notify` only during its active login. `onProviderOAuth` handles `login`+and `refresh` with an abort signal for cancellation, unload, and timeout, and+refresh sees only the credential of its own declared contribution, because no+general secret read API is added. Electron main stores the credential under the+encrypted `secret:provider:<providerRowId>:oauth` reference and serializes+refreshes by provider row, the host validates token, header, and result sizes,+renderer events carry only login UI state and a non-secret account label, and+the Agent Runtime receives only the access token through the normal+per-request auth resolver. `provider.oauth` is a separate high-risk permission+from `provider.register` and `net.fetch`, host-mediated callback egress still+needs `net.fetch` and `manifest.net.domains`, and one credential is stored per+contribution, with sign-out clearing the secret but keeping the manifest row.+Existing `api_key` and `none` contributions keep their behavior, and missing+permissions or a missing callback fail closed.## Consequences- A plugin can integrate an OAuth-only provider into the native provider and- model selection paths without adding a second provider registry.-- The trusted callback sees its own access and refresh tokens.-- Host-owned prompts, secret storage, refresh serialization, renderer- projection, and request-auth delivery remain under their existing owners.-- Each contribution has one account at a time.-- The OAuth callback is plugin-authored code and remains subject to the plugin- process trust boundary documented in the security specification.--## Alternatives considered--### Give plugins a general secret-store API--Rejected: it would expose unrelated provider credentials, require a new-secret-reference authorization model, and let a plugin become a second secret-owner.--### Run plugin OAuth code inside Electron main--Rejected: loading third-party OAuth libraries into Electron main would break the-existing process boundary and put arbitrary plugin code beside renderer, window,-and host-process capabilities.--### Store OAuth tokens in plugin-private storage--Rejected: the Host could not serialize refreshes, clear credentials on sign-out-or provider removal, report a connected account without reading plugin data, or-keep the runtime auth resolver authoritative.--### Create one provider row per plugin OAuth account--Deferred: it changes provider identity, manifest reconciliation, default-model-selection, and uninstall cleanup.+ model selection paths without a second provider registry.+- The trusted callback sees its own access and refresh tokens, an exposure the+ high-risk permission review states explicitly and encryption cannot mitigate+ once delivered.+- Host-owned prompts, secret storage, refresh serialization, and request-auth+ delivery stay with their existing owners, and each contribution holds one+ account at a time.++## Alternatives++- A general secret-store API: rejected, it exposes unrelated credentials and+ creates a second secret owner.+- Running plugin OAuth code inside Electron main: rejected, it puts arbitrary+ plugin code beside renderer, window, and host capabilities.diff --git a/docs/adr/0321-skill-market-direct-dns-pinning.md b/docs/adr/0321-skill-market-direct-dns-pinning.mdindex 8269c9aec..d8a862afb 100644--- a/docs/adr/0321-skill-market-direct-dns-pinning.md+++ b/docs/adr/0321-skill-market-direct-dns-pinning.md@@ -7,38 +7,37 @@## Context-The Skill Market validates each address returned by the local resolver, then-uses Chromium `net.fetch`. On a direct route, a DNS response that contains a-usable public IPv4 address plus a synthetic ULA IPv6 address is rejected, even-though Main can safely connect to the public IPv4 address.+The Skill Market validates every address the local resolver returns and then uses+Chromium `net.fetch`. On a direct route a response carrying a usable public IPv4+address plus a synthetic ULA IPv6 address is rejected even though Main could use the+IPv4 one, and under a TUN fake-IP resolver `net.fetch` can select a rejected IPv6+placeholder after the guard accepted an IPv4 result.## Decision-1. On a `direct` route only, if at least one DNS result is rejected and an- acceptable result exists, the Skill Market may select one acceptable result- and pin the direct request to that exact address.-2. The pinned transport preserves the original hostname for TLS SNI and the HTTP- `Host` header, disables automatic redirects, and respects the existing- request abort signal.-3. A ULA-only DNS result, or any other answer with no acceptable address,- remains refused.+1. On a `direct` route only, when at least one result is rejected and an acceptable+ one exists, the Skill Market may select one acceptable result and pin the request+ to that address. Third-party content prefers a public address; the `benchmark`+ range is eligible only under the existing fake-IP opt-in, and a user-supplied+ first-hop endpoint keeps its own address policy.+2. The pinned transport keeps the original hostname for TLS SNI and HTTP `Host`,+ disables automatic redirects, respects the abort signal, and re-checks and repins+ at every redirect.+3. A ULA-only answer or any answer without an acceptable address stays refused, and+ proxied or `unknown` routes keep ADR 0272's verdict.## Consequences-- Dual-stack and transparent-proxy answers no longer fail solely because an- unused ULA result accompanies a public address or an explicitly permitted- benchmark fake-IP.-- Direct mixed-answer requests use Node's HTTP(S) transport with the selected- address pinned.-- This does not permit internal destinations, alter the persisted network- policy, or change the URL/redirect rules.+- Dual-stack and transparent-proxy answers no longer fail because an unused ULA+ result accompanies a usable address, and Main never connects to the ignored one.+- Direct mixed-answer requests use Node's HTTP(S) transport while proxied requests+ stay on Chromium's `net.fetch`, and no persisted network policy, URL, or redirect+ rule changes.## Alternatives-- Permit all ULA answers on a direct route: rejected because ULA can name a real- LAN or VPN service and would weaken the third-party network boundary.-- Keep using `net.fetch` after accepting one address: rejected because Chromium- may resolve the hostname again and connect to the rejected address.-- Require users to disable IPv6 or change proxy DNS: rejected as the sole fix- because Main can safely pin an already acceptable address without requiring- system network changes.+- Permit all ULA answers on a direct route: ULA can name a real LAN or VPN service.+- Keep `net.fetch` after accepting one address: Chromium may resolve again and+ connect to the rejected address.+- Require users to disable IPv6 or change proxy DNS: Main can pin an already+ acceptable address.diff --git a/docs/adr/0322-plugin-providers-in-add-service.md b/docs/adr/0322-plugin-providers-in-add-service.mdindex 7028424f0..4f6d3fd64 100644--- a/docs/adr/0322-plugin-providers-in-add-service.md+++ b/docs/adr/0322-plugin-providers-in-add-service.md@@ -3,50 +3,43 @@- Status: Accepted for implementation- Date: 2026-10-08- Decision: D650-- Related: ADR 0259, ADR 0320, `07-plugins/02-plugin-manifest-schema.md`, `07-plugins/03-plugin-api.md`, `07-plugins/04-plugin-security.md`, `07-plugins/13-plugin-permissions-matrix.md`, `04-ux/06-settings-ia.md`+- Related: ADR 0259, ADR 0320, `07-plugins/02-plugin-manifest-schema.md`, `07-plugins/03-plugin-api.md`, `07-plugins/04-plugin-security.md`## Context-ADR 0259 lets plugins declare Host-owned provider rows, but a user must leave-the ordinary Add Service flow and find each row in the provider list before-entering its API key. Community catalogs need to group several API services-under a category and make them discoverable in the same place as built-in-services.+ADR 0259 lets plugins declare Host-owned provider rows, but users must leave the+ordinary Add Service flow and find each row in the provider list before entering+an API key, and community catalogs need to group several services under a+category beside built-in ones.## Decision-1. Add an optional `category` field to `PluginProviderContrib`.+1. `PluginProviderContrib` gains an optional `category` accepting a non-empty+ string or an `{ en, "zh-CN" }` pair, falling back to the plugin name.2. The Host projects metadata from loaded plugins whose `provider.register`- grant is active.-3. The chooser groups rows under the declared category.-4. Selecting a row opens a Host-owned key form for the existing provider row.-5. Once a key is saved, the row stays in the provider list and is removed from- Add Service.+ grant is active, and only API-key declarations with an endpoint and no saved+ key appear in Add Service; OAuth and no-auth rows do not.+3. The chooser groups rows under the declared category, shows the provider name+ with an optional one-sentence `description` in a tooltip, and searches+ category, provider name, plugin name, endpoint, model ids, and description.+4. Selecting a row opens a Host-owned key form that stores the key through the+ existing provider secret API and, when `models` is empty, triggers Host-owned+ endpoint model discovery. Plugin code receives no key and gains no permission.+5. A saved row leaves Add Service and stays in the provider list, with provider+ ownership, reconciliation, credential retention, and uninstall cleanup+ unchanged.## Consequences-- Users can discover community provider entries during ordinary service setup- and group them with localized custom categories.-- Existing manifests remain valid because the new field is optional.-- A provider may omit model declarations only when it is an API-key provider- with a `baseUrl`.-- The same Host-owned row and secret lifecycle remains authoritative; saving a- key does not create a duplicate provider or require data migration.-- A category or description does not make an endpoint trustworthy.+- Community providers are discoverable during ordinary service setup.+- Existing manifests stay valid, because `category` is optional display metadata+ that falls back to the plugin name.+- A category does not make an endpoint trustworthy; the key form keeps plugin+ and endpoint visible for review.-## Alternatives considered+## Alternatives-### Let plugins inject arbitrary chooser UI--Rejected: executing plugin UI in the provider setup dialog would add a new-renderer boundary and duplicate the Host's credential and validation flow.--### Create another provider row when a user selects a catalog tile--Rejected: that would fork row identity, credential migration, model selection,-and uninstall cleanup from the existing manifest-owned provider lifecycle.--### Require a new permission for chooser visibility--Rejected: `provider.register` already approves the plugin's authority to-contribute provider rows.+- Let plugins inject chooser UI: rejected, it adds a renderer boundary and+ duplicates the Host credential flow.+- Create a new provider row from a catalog tile: rejected, it forks row identity,+ credential migration, and uninstall cleanup.diff --git a/docs/adr/0323-plugin-owned-session-titles.md b/docs/adr/0323-plugin-owned-session-titles.mdindex b659854cd..a5b8dd8e3 100644--- a/docs/adr/0323-plugin-owned-session-titles.md+++ b/docs/adr/0323-plugin-owned-session-titles.md@@ -4,53 +4,52 @@- Date: 2026-10-08- Supersedes: ADR 0186- Amended: 2026-10-08 (D654 restores the deterministic first-prompt fallback)-- Amended: 2026-10-20 (ADR 0340 adds `session.read.all`, so the rejected- "give the plugin a broader session read" alternative below no longer fails- for the reason recorded here)+- Amended: 2026-10-20 (ADR 0340 adds `session.read.all`, so the rejected "give+ the plugin a broader session read" alternative below no longer fails for the+ reason recorded here)## Context-The core currently derives a prompt fallback in the renderer and runs a-main-owned one-shot completion after a turn. That couples title policy to the-agent lifecycle and gives users no prompt or model controls.+Core derived a prompt fallback in the renderer and ran a main-owned one-shot+completion after a turn, which coupled title policy to the agent lifecycle and+gave users no prompt or model controls. The plugin still needs a safe way to name+a normal Desktop session, and removing every automatic write also removed the+deterministic label a new session got from its first prompt.## Decision-- Keep one deterministic core title path: sending the first prompt into a- session whose stored title is still a recognized placeholder writes a- whitespace-collapsed, 48-character fallback through the host's- `session.deriveTitle`.-- The derived text keeps the `default` source.-- Remove the built-in title completion.-- Provide `session.autoTitle`, a dedicated high-risk permission for a narrow- first-turn context and a compare-and-set title update.-- Store `title_source` in host-core schema v23. Manual renames set `manual`;- plugin updates set `generated`; a placeholder or a first-prompt fallback- remains `default`.-- Ship title generation as the standalone `pi-desktop-session-title-plugin`- repository.+One deterministic core title path stays: sending the first prompt into a session+whose stored title is still a recognized placeholder writes a whitespace-collapsed+48-character fallback through `session.deriveTitle`, applied only while the title+is still a placeholder with the `default` source and without touching+`updated_at`. The built-in model completion is removed, so no core flow waits on a+composed title.++`session.autoTitle` is a dedicated high-risk permission granting a narrow+first-turn context — the bounded first user message and first assistant reply,+available only while the source is `default` — plus a compare-and-set title+update. Host-core schema v23 stores `title_source`, where a manual rename sets+`manual`, a plugin update sets `generated`, and a placeholder or fallback stays+`default`, so a manual change wins races and survives renderer restarts.++Title generation ships as the standalone `pi-desktop-session-title-plugin`, which+listens for completed turns and uses the existing `agent.complete` and+`models.list` APIs, with settings for an editable prompt template, model+selection, and thinking level.## Consequences- Without the plugin, a new session shows its localized default title until the- first prompt derives a label from it, and keeps that label afterwards.-- The plugin can customize title policy without adding a second title engine- inside Electron or the renderer.-- The new permission allows the plugin to see bounded excerpts from any active- default-titled Desktop session.-- Schema v23 leaves pre-existing v22 titles as `legacy` to protect deliberate- renames from automatic replacement; newly created sessions receive `default`- or `manual` as appropriate.+ first prompt derives a label, and keeps that label afterwards.+- Title policy is customizable without a second title engine in Electron or the+ renderer.+- The permission exposes bounded first-turn excerpts from default-titled sessions+ and nothing else, and pre-existing v22 titles become `legacy` to protect+ deliberate renames.## Alternatives considered-- Remove the first-prompt fallback together with the completion: rejected after- review because readability would then depend on installing an optional plugin,- and an untouched session would show a placeholder forever.-- Keep the completion in the core: rejected because it would still automatically- spend model tokens and mutate titles when the optional plugin is absent.-- Give the plugin `session.read` or `session.read.own`: rejected because those- permissions either expose a general transcript projection or only imported- sessions and do not match the required boundary.-- Run a second title flow in Electron main: rejected because title policy and- user-configured prompts/models belong to the plugin after this change.+- Remove the first-prompt fallback with the completion: rejected; readability+ would then depend on an optional plugin.+- Keep the completion in core: rejected; it would spend model tokens and mutate+ titles whenever the plugin is absent.diff --git a/docs/adr/0324-plugin-owned-composer-prompt-enhancement.md b/docs/adr/0324-plugin-owned-composer-prompt-enhancement.mdindex e05a1360f..4d1e3cd11 100644--- a/docs/adr/0324-plugin-owned-composer-prompt-enhancement.md+++ b/docs/adr/0324-plugin-owned-composer-prompt-enhancement.md@@ -6,47 +6,42 @@## Context-Prompt enhancement was implemented as host-owned UI, settings, IPC, and a-provider completion path. It is useful but optional product behavior; keeping it-in the host makes every user carry a specialized feature and couples Composer to-its settings and runtime logic.+Prompt enhancement shipped as host-owned UI, settings, IPC, and a provider+completion path, so every user carried a specialized feature and the Composer+stayed coupled to its settings and runtime logic. Users asked for it in a+separate repository behind an explicit install, and the host still needs a+narrow way to let a plugin transform a draft without receiving the transcript,+attachments, or local paths.## Decision-- Remove the host-owned prompt-enhancement UI, Settings card, direct enhancement- IPC, MCP action, and dedicated completion implementation.-- Add `contributes.composerTransforms`, `onComposerTransform`, and the explicit- `composer.transform` permission to the Plugin SDK.-- Send only the draft text and optional current model key to the plugin.-- Keep prompt enhancement in the separate `vastsa/pi-prompt-enhancement`- repository.-- On the first load of `pi.prompt-enhancement`, copy valid legacy model,- thinking, and enabled custom-template values into unset plugin settings before- `onLoad`.+Remove the host-owned enhancement UI, Settings card, direct IPC, MCP action, and+completion path, and add `contributes.composerTransforms`, `onComposerTransform`,+and the explicit `composer.transform` permission to the Plugin SDK, with actions+shown only for loaded plugins holding a current grant and invoked only after a+user action. Dispatch sends only the draft text and optional model key, strips+inline file-reference markers before the call and restores them after a+successful transform, enforces the input/output limit, plugin tool timeout,+manifest and permission checks, and call auditing, and returns text with+one-step undo plus stale-draft and stale-session protection. The feature lives+in the separate `vastsa/pi-prompt-enhancement` repository, which the host+neither bundles nor enables, and the first load of `pi.prompt-enhancement`+copies valid legacy model, thinking, and enabled custom-template values into+unset plugin settings behind a private one-time marker while keeping existing+plugin values authoritative and the old host settings for rollback.## Consequences-- Users without the plugin no longer see or carry the enhancement action or- settings surface.-- The Plugin SDK and manifest gain an additive contribution and permission; no- plugin manifest schema version or host-core database schema changes.-- Plugins receiving `composer.transform` can see the draft only when their- action is explicitly invoked.-- Legacy prompt-enhancement values remain stored and config-syncable until- migration.-- A plugin release that uses the new contribution must declare a compatible- `engines.piDesktop` range; older hosts cannot display or invoke it.--## Alternatives considered--- Keep the host implementation and publish a second plugin: rejected because- users would still receive the feature by default and the host and plugin could- drift into two enhancement paths.-- Use a renderer slot callback: rejected because the transform needs an isolated- plugin-process handler and a bounded, audited host invocation; a renderer- module runs in the host document and is a different trust surface.-- Send session history or attachment data for better context: rejected because- the feature rewrites the current draft and does not need those capabilities.-- Delete the old settings immediately: rejected because users need them for- first-install migration and because keeping them supports downgrade and- configuration rollback.+- Users without the plugin no longer see the action or its settings surface.+- The SDK and manifest gain an additive contribution and permission, with no+ manifest schema version or database schema change.+- A plugin sees the draft only when its action is invoked, never session+ identity, history, attachments, or paths, and a plugin release using the+ contribution must declare a compatible `engines.piDesktop` range.++## Alternatives++- Keep the host implementation and also publish a plugin: rejected, users would+ still receive it by default and two enhancement paths could drift.+- A renderer slot callback: rejected, the transform needs the isolated plugin+ process and a bounded, audited host invocation.diff --git a/docs/adr/0325-windows-window-corner-compositing.md b/docs/adr/0325-windows-window-corner-compositing.mdindex 0efbb59a4..086e63eb5 100644--- a/docs/adr/0325-windows-window-corner-compositing.md+++ b/docs/adr/0325-windows-window-corner-compositing.md@@ -2,40 +2,45 @@- Status: Proposed; implementation candidate awaits Windows native qualification- Date: 2026-10-10-- Deciders: PI-Desktop maintainers- Related: D635, D637, E2E-167, ADR 0248, ADR 0317## Context-The Windows main window currently uses a transparent outer window,+The Windows main window relies on a transparent outer window,`contentView.setBorderRadius()` for the visible clip, and `setShape()` for the-native hit region. This keeps child views inside one clip, but depends on-Electron transparency and a window region.+native hit region, but Windows 11's DWM corner API may ignore its rounding hint+for windows that use per-pixel alpha or a window region, so that path cannot+guarantee the system-rendered curve.## Decision-For the Windows main window only:--1. On Windows build 22000 and later, create an opaque, frameless window and- request the native DWM corner preference through the existing Electron Main- to Host Core process boundary.-2. Host Core accepts only the HWND whose owning PID matches the Electron PID- injected by Electron Main when it starts Host Core.-3. Map radius `0` and maximized/fullscreen states to `DWMWCP_DONOTROUND`.-4. Keep the existing transparent content clip and native shape path on Windows- builds before 22000.-5. On the Windows 11 path, keep the top-level surface opaque.-6. Keep the existing `window/setBackgroundColor` request and response,- validation, theme fallback, geometry persistence, and native frameless edge- resize behavior.+For the Windows main window only, builds from 22000 onward create an opaque,+frameless window and request `DWMWA_WINDOW_CORNER_PREFERENCE` through the+existing Electron Main to Host Core boundary, without `setShape()` or+`contentView.setBorderRadius()`. Host Core accepts only the HWND whose owning+PID matches the Electron PID injected at startup, so no plugin, renderer, or+standalone-window API is added. Radius `0` and maximized or fullscreen states map+to `DWMWCP_DONOTROUND` and every positive authorized radius maps to+`DWMWCP_ROUND`, with Windows 11 choosing the visible radius while the public+range and default stay unchanged. A contributed `#rrggbbaa` background is+flattened over the resolved theme background so alpha never creates per-pixel+window transparency, and the existing `window/setBackgroundColor` contract,+theme fallback, geometry persistence, and native frameless edge resize are kept.+Windows builds before 22000, macOS, Linux, plugin standalone windows, and+floating components are unchanged.## Consequences-- Windows 11 uses the system's antialiased corner rendering and native corner- hit behavior.-- Positive theme radii keep their range and meaning as “rounded,” but Windows 11- chooses the radius.-- DWM may decline to round a window based on its style or environment, and- Windows may keep snapped or virtualized windows square.-- The Windows 11 background stays opaque; alpha colors are composited against- the built-in palette.+- Windows 11 uses the system's antialiased corners and native corner hit+ behavior instead of transparent pixels or an integer region.+- Positive radii keep their meaning as "rounded" while Windows picks the value,+ and older Windows builds keep their exact DIP clip.+- DWM may decline to round based on window style or environment, so native+ qualification must confirm the result before any release claim.++## Qualification gate++The decision stays proposed until a Windows desktop running Electron 43.6.0+proves the rounded opaque window, theme and alpha flattening, child-view+containment, state transitions, native resize and bounds persistence, and the+unchanged pre-22000 path.diff --git a/docs/adr/0326-verified-ssh-host-installation.md b/docs/adr/0326-verified-ssh-host-installation.mdindex 1641e85bc..737ff2ea7 100644--- a/docs/adr/0326-verified-ssh-host-installation.md+++ b/docs/adr/0326-verified-ssh-host-installation.md@@ -2,57 +2,61 @@- Status: Accepted for experimental implementation; Linux SSH qualification and release publication pending- Date: 2026-10-11-- Deciders: PI-Desktop maintainers (user-authorized Remote SSH optimization plan)-- Amends: [ADR 0292](0292-ssh-remote-host-bootstrap.md), specifically the executable-upload prohibition and remote GitHub-access prerequisite; the corresponding D375 deployment choice-- Related: [ADR 0293](0293-ssh-password-authentication.md), [Local Agent remote workspace tools](local-agent-remote-workspace-tools.md), [architecture §5.2](../spec/02-architecture/05-remote-agent-control.md#52-remote-host-over-an-ssh-tunnel-first-remote-topology), [security §3.4](../spec/05-security/02-remote-control-security.md#34-ssh-bootstrap-pairing-first-remote-topology)+- Related: [ADR 0292](0292-ssh-remote-host-bootstrap.md), [ADR 0293](0293-ssh-password-authentication.md), [Local Agent remote workspace tools](local-agent-remote-workspace-tools.md)+- Amends: [ADR 0292](0292-ssh-remote-host-bootstrap.md), specifically the executable-upload prohibition and the remote GitHub-access prerequisite, plus the corresponding D375 deployment choice## Context-The original bootstrap required system Node 22+ and outbound GitHub access on-the remote machine. Reusing installation/pairing for daily connection also risks-unnecessary downloads, process restarts and credential churn.+The original bootstrap required system Node 22 or newer and outbound GitHub access+on the remote machine, and reusing installation and pairing for daily connection+risks unnecessary downloads, process restarts, and credential churn. Users already+hold SSH shell authority, so a blanket ban on executable upload blocked a useful+fallback without protecting against a compromised release source.## Decision-1. Keep system OpenSSH, its host-key checks, configured identities/agent/jump- hosts, and RACP-WS over loopback forwarding.-2. Resolve the matching Desktop version and published Linux x64/arm64 target.-3. Verify the archive before extraction/install on the remote machine.-4. Bundle native-target Node >=22, the complete Agent runtime and host-core,- launcher, installer and `SHA256SUMS`.+1. Keep system OpenSSH with its host-key checks, configured identities and jump+ hosts, and RACP-WS over loopback forwarding. No SSH stdio RPC, public listener,+ elevated privileges, or mandatory systemd service.+2. Resolve the matching Desktop version and published Linux x64 or arm64 target,+ and take the named archive SHA-256 from the trusted GitHub Release. A remote+ download is preferred; only an explicit `download-failed` permits one bounded+ Desktop download and SSH stdin upload of the same archive, while integrity,+ authentication, and version failures never authorize that fallback.+3. Verify the archive before extraction on the remote machine, and verify the+ fallback locally before uploading it under a bounded size and time limit, using+ private temporary directories with cleanup on success and failure.+4. Bundle native-target Node 22 or newer, the Agent runtime, host-core, launcher,+ installer, and `SHA256SUMS`. Staged files are verified, unsafe manifest paths+ rejected, version directories installed content-addressed, and the `current`+ symlink replaced atomically under kernel-owned locks. A failed stage never+ overwrites the previous install, and a legacy real `current` directory is+ refused rather than converted.5. Bootstrap reuse requires an external `.release.sha256` receipt matching the- version, trusted archive digest and installed manifest digest, plus- successful read-only `install.sh --verify`.-6. Separate install/pair from daily readiness.-7. New remote workspace projects keep Agent execution, models, API credentials,- permissions and sessions on Desktop.-8. Recovery never replays Write/Edit/Bash.--## Trust and compatibility--SHA-256 authenticates bytes relative to the trusted release descriptor; it is-not an independent cryptographic signature. The candidate does not add signed-manifest verification or protect against compromise of the release publisher,-the SSH account, or its installed files/receipt.--No database migration or model-key synchronization is introduced. Existing-direct connections, SSH authentication modes and legacy remote-Agent sessions-retain ownership.--## Alternatives--- Remote-only download: retains the original offline-network failure.-- Always upload: adds unnecessary local transfer and discards the working remote- path.-- Trust version alone or a self-modifiable manifest: accepts damaged/different- bytes; verified reuse needs the release-bound external receipt and file- checks.-- Reinstall/re-pair on reconnect: changes credentials and process lifecycle for- an ordinary connection failure.--## Consequences and qualification--Desktop may now send verified release executable bytes through the user's SSH-session.--This remains Experimental.+ version, trusted archive digest, and installed manifest digest, plus a+ successful read-only `install.sh --verify`. Bundles without a manifest do not+ qualify.+6. Install and pairing are separate from daily readiness: the supervisor starts the+ installed Host only when needed, prefers bundled Node, uses `--port 0` without+ `--pair`, preserves Host identity and device credentials, validates loopback+ readiness, version, and the saved Host id before forwarding, and revalidates the+ RACP identity on reconnect. An ordinary disconnect does not kill a Host another+ client may use.+7. New remote workspace projects keep Agent execution, models, credentials,+ permissions, and sessions on Desktop; remote tools, files, and root repository+ instructions use owner-only workspace services.+8. Recovery never replays `Write`, `Edit`, or `Bash`. A lost transport reply yields+ the non-retriable `REMOTE_MUTATION_OUTCOME_UNKNOWN` and requires inspection+ before an explicit retry.++## Consequences++- SHA-256 authenticates bytes against the trusted release descriptor but is not a+ signature, so host authentication and workspace containment stay mandatory.+- No migration appears, existing connections keep ownership, and legacy Host+ installations may need an explicit reinstall to gain the bundled runtime.+- Desktop may now send verified release bytes through the user's SSH session: a+ limited amendment to ADR 0292, not permission to upload arbitrary+ model-generated executables.+- The change stays Experimental; Linux kernel-lock crash recovery, fresh+ installation, and reboot recovery are gated by E2E-REMOTE-SSH-OPTIMIZATION.diff --git a/docs/adr/0327-remote-host-version-realignment.md b/docs/adr/0327-remote-host-version-realignment.mdindex 8edffbc3a..e366abab0 100644--- a/docs/adr/0327-remote-host-version-realignment.md+++ b/docs/adr/0327-remote-host-version-realignment.md@@ -2,71 +2,60 @@- Status: Accepted for experimental implementation (amends ADR 0326 item 6: daily startup is still not an installer, but a version mismatch is now repaired instead of only reported)- Date: 2026-10-12-- Deciders: PI-Desktop maintainers (user-authorized fix for a paired Host that could not be upgraded)- Related: [ADR 0326](0326-verified-ssh-host-installation.md), [ADR 0292](0292-ssh-remote-host-bootstrap.md), [ADR 0293](0293-ssh-password-authentication.md), [architecture §5.2](../spec/02-architecture/05-remote-agent-control.md#52-remote-host-over-an-ssh-tunnel-first-remote-topology), [security §3.4](../spec/05-security/02-remote-control-security.md#34-ssh-bootstrap-pairing-first-remote-topology)## Context-A paired Host is pinned to the desktop release that installed it. The bundle is-reused only when its external receipt and every installed file still match, and-the daily readiness probe refuses a Host whose reported version differs from the-one the desktop expects.--1. The probe compared the running Host against the version **recorded when the- host was paired**, not against the desktop release.-2. Nothing in the product could upgrade a paired Host.+A paired Host is pinned to the desktop release that installed it, but the readiness+probe compared the running Host against the version recorded at pairing time+instead of the release this desktop expects, so the refusal was wrong in both+directions. Nothing in the product could upgrade a paired Host either: the only+remedy was to remove and re-pair, discarding a working SSH descriptor and its+encrypted credential, which left the reported upgrade toast with no action behind+it. A same-version bundle can also predate an additive capability, observable only+in the RACP handshake.## Decision-1. Readiness compares the running Host against the release **this desktop**- expects, never against the version recorded at pairing time.-2. After `connection/initialize`, the live handshake capabilities are checked- once per connection.-3. On `HOST_VERSION_MISMATCH`, the boot layer re-runs the **same verified SSH- bootstrap** the pairing path uses, from the stored SSH descriptor and the- encrypted login password, then adopts the forward it opened and reconnects- with the refreshed record (new loopback URL, new device token, new Host ID).-4. Automatic attempt receipts are persisted as non-secret Host registry- metadata, keyed by the desktop release, so an app restart does not reboot a- Host again after a successful realignment.-5. A Host that cannot be realigned is left alone: a direct URL pairing has no- SSH descriptor, and a password descriptor whose stored secret is gone is- never replayed.-6. A realignment that does not help surfaces the **original** mismatch- unchanged, and the host stays `action-required`.-7. Credential, sandbox and ownership boundaries are unchanged: the secret is- read only from the encrypted record, never returned to the renderer, never- logged, and the remote artifact is still fetched against the published- SHA-256.--## Trust and compatibility--No new trust decision. The desktop still installs only a release artifact that-matches its own version and the published digest, and the remote side still-verifies it before installing.--The visible cost is deliberate: realigning a Host restarts its remote process,-so another client of that Host is briefly disconnected. This occurs only after a-version/capability mismatch, not ordinary connection failures.+1. Readiness compares the running Host against the release this desktop expects,+ never against the pairing-time record, and a saved Host ID is validated first,+ with an identity mismatch staying `HOST_AUTH_FAILED` and never authorizing+ automatic realignment.+2. After `connection/initialize`, live handshake capabilities are checked once per+ connection; a Host that advertises no workspace tools and files, or reports no+ capabilities at all, fails closed with `HOST_VERSION_MISMATCH`.+3. On that failure the boot layer re-runs the same verified SSH bootstrap the+ pairing path uses, from the stored descriptor and encrypted login password,+ adopts the forward it opened, and reconnects with the refreshed record. No new+ trust anchor, download path, or install script is introduced.+4. Automatic attempt receipts persist as non-secret Host registry metadata keyed by+ the desktop release, so a restart does not reboot a realigned Host, and a failed+ attempt cools down before another automatic try while an explicit reconnect+ bypasses the throttle.+5. A Host that cannot be realigned is left alone, because a direct URL pairing has+ no SSH descriptor and a descriptor whose stored secret is gone is never+ replayed.+6. A realignment that does not help surfaces the original mismatch unchanged and+ leaves the host action-required.+7. Credential, sandbox, and ownership boundaries are unchanged: the secret is read+ only from the encrypted record, never returned to the renderer, never logged,+ and the remote artifact is still verified against the published SHA-256.++## Consequences++- A desktop release drags its paired Hosts forward on first use without the user+ re-adding them, while operators that must pin a release can keep using direct URL+ pairing.+- Realignment restarts the remote process and briefly disconnects other clients of+ that Host, and only a version or capability mismatch triggers it.+- Record compatibility is additive with no database migration and no RACP change,+ and a release that is not published yet still fails with the upgrade message.## Alternatives-- Manual "upgrade Host" button only: leaves the reported failure unfixed,- because the user's next folder selection still fails until they act.-- Compare against the recorded descriptor version (status quo): a stale record- makes the check wrong in both directions.-- Re-pair on every reconnect: churns credentials and restarts a remote process- for ordinary connection failures.-- Trust the version alone and skip the capability check: a same-version bundle- without workspace services would connect and then fail every `workspace/*`- call, which is what the user saw.--## Consequences and qualification--A desktop release now drags its paired Hosts forward on first use, without the-user re-adding them.--Qualification is limited to automated coverage: the boot-level tests in-`apps/desktop/test/remote-host-realign.test.mjs` exercise the decision table,-the record replacement, the failed-forward cleanup and the full stale-host path-with injected SSH transports.+- Manual "upgrade Host" button only: rejected, the reported failure stays until the+ user acts.+- Re-pair on every reconnect: rejected, it churns credentials and restarts a remote+ process for ordinary connection failures.+- Trust the version and skip the capability check: rejected, a same-version bundle+ without workspace services would fail every `workspace/*` call.diff --git a/docs/adr/0328-browser-arbitrary-local-files.md b/docs/adr/0328-browser-arbitrary-local-files.mdindex 48c4350fe..b1a60575a 100644--- a/docs/adr/0328-browser-arbitrary-local-files.md+++ b/docs/adr/0328-browser-arbitrary-local-files.md@@ -2,47 +2,34 @@- Status: Accepted- Date: 2026-10-13-- Deciders: PI-Desktop core-- Related: issue #1627 · [ADR 0170](0170-work-panel-browser-as-bundled-plugin.md) ·- [ADR 0028](0028-session-scoped-work-panel-contexts.md)+- Related: [ADR 0170](0170-work-panel-browser-as-bundled-plugin.md) · [ADR 0028](0028-session-scoped-work-panel-contexts.md) · issue #1627## Context-The embedded Browser accepted only files below the active session workspace.-That restriction also blocked a user from opening an existing local HTML file by-absolute path or `file:` URL, and prevented local pages from following links to-files elsewhere on the machine.+The embedded Browser accepted only files below the active session workspace, which+blocked opening a local HTML file by absolute path or `file:` URL and stopped local+pages from following links to files elsewhere on the machine. `BrowserPreview` and+the runtime sidecar also validate workspace-rooted paths, but those agent-facing+tools must keep their scope.## Decision-1. The embedded Browser accepts an absolute path or `file:` URL for any existing- regular local file.-2. A local-file page may navigate to other existing local files.-3. File URLs with a remote authority, missing paths, directories, and other- unsupported schemes remain blocked.-4. The public `pi.browser.navigate` API receives the same local-file behavior- under the high-risk `browser.cdp` permission.+The embedded Browser accepts an absolute path or `file:` URL for any existing+regular local file, while relative address-bar paths stay rooted in the session+workspace. A local-file page may navigate to other existing local files, whereas+HTTP(S) pages keep the in-workspace file-link allowance. File URLs with a remote+authority, missing paths, directories, and unsupported schemes remain blocked, and+popups still open externally only for `http:`, `https:`, and `mailto:`. The public+`pi.browser.navigate` API gets the same behavior under the high-risk `browser.cdp`+permission, while `BrowserPreview` and the sidecar keep using `resolveLocalFile()`+with workspace scope.## Consequences-- Users can preview local HTML and related files outside the project from the- Browser address bar.-- A plugin granted `browser.cdp` can navigate the visible Browser to an- explicitly supplied local path and inspect its page through the existing- browser API.-- A remote web page cannot use a top-level file link to escape the session- workspace.-- No IPC schema, persisted state, or user setting changes.--## Alternatives considered--### Allow address-bar entry but keep local-page links workspace-scoped--Rejected because a local HTML page can reference or link to sibling files-outside the project, which is the same preview workflow the Browser already-supports within a workspace.--### Add a separate opt-in toggle--Rejected because issue #1627 explicitly asks the Browser to stop imposing the-workspace boundary.+- Users can preview local HTML and its sibling files outside the project from the+ address bar.+- A plugin granted `browser.cdp` can navigate and inspect a supplied local path, so+ local content stays high-risk even though the Browser remains a sandboxed+ `WebContentsView` with Node integration disabled.+- A remote page still cannot escape the workspace by link, and no IPC schema,+ persisted state, or setting changes.diff --git a/docs/adr/0329-session-worktree-isolation.md b/docs/adr/0329-session-worktree-isolation.mdindex 09b423ea7..ecf3e8653 100644--- a/docs/adr/0329-session-worktree-isolation.md+++ b/docs/adr/0329-session-worktree-isolation.md@@ -2,74 +2,70 @@- Status: Accepted- Date: 2026-10-12-- Deciders: PI-Desktop maintainers- Related: ADR 0062 (parallel delegates), ADR 0089 (delegation tools),D114 (per-session scratch), `docs/spec/03-runtime/03-tools-and-permissions.md` §4d## Context-Several sessions of one project can run at the same time, but they all resolve-the same tool root (`resolve_tool_workspace`,-`crates/host-core/src/rpc/mod.rs`). Writes are serialized only per session; two-sessions editing one file are guarded only by the Edit content tag, and they-share one build tree and one git state.+Several sessions of one project can run at once but all resolve the same tool root,+so two sessions editing one file are guarded only by the Edit content tag and they+share one build tree and one git state, as do their subagents. Every mainstream agent+product that offers parallel local work isolates it in a git worktree.## Decision-1. An isolated session is opt-in per new session, default off.-2. host-core owns all git execution, worktree paths, and the `worktrees`- registry (schema v24).-3. Tool containment is unchanged in mechanism: the isolated session's root is- its worktree (or `<worktree>/<prefix>` when the project is a repository- subdirectory), so the main checkout is "outside workspace" and needs the- existing permission.-4. "Merge into project" preserves the session's commits.-5. Inside an isolated session, a subagent whose tools include Write or Edit gets- its own temporary worktree and is merged back automatically with the same- algorithm; a conflict is reported to the parent, which can resume the- subagent to resolve it.+1. An isolated session is opt-in per new session and owns one worktree on branch+ `pi-desktop/<id>` under `~/.pi-desktop/worktrees/<project-key>/`, created from the+ project's current branch tip; uncommitted project changes are not carried over.+2. host-core owns all git execution, worktree paths, and the `worktrees` registry, and+ the renderer and runtime send only a session id or delegation id.+3. Containment is unchanged in mechanism: the session's root is its worktree (or+ `<worktree>/<prefix>` for a repository subdirectory), while project identity stays+ keyed by the project path.+4. "Merge into project" shows the commit count and changed files, merges the project+ branch into the session branch inside the worktree so conflicts stay there, then+ fast-forwards the project branch, so the project never enters a merge-in-progress+ state. The preview token covers the project branch tip and untracked content, every+ write re-checks both branches, and the session's tools are held for the merge (then+ `WORKTREE_BUSY`).+5. A subagent whose tools include Write or Edit gets its own temporary worktree and is+ merged back with the same algorithm, with conflicts reported to the parent; other+ subagents share the session worktree.6. Deleting an isolated session removes its worktrees and branches after a loss- warning; there is no separate discard.-7. Every git command host-core runs disables hooks and `core.fsmonitor` and sets- `safe.bareRepository=explicit`.-8. New worktrees copy ignored files listed in `.worktreeinclude` (the format- Claude Code and Conductor read), then run an optional per-project setup- command with `PI_PROJECT_ROOT`, `PI_WORKTREE_ROOT`, and `PI_PORT` (a block of- 10 ports per worktree, after Conductor's `CONDUCTOR_PORT`).-9. Minimum git version is 2.29 (`git worktree repair`).-10. "Sync from project" merges the project branch into an isolated session's- worktree with the rules of decision 4 (pending session work is committed- first, conflicts stay in the worktree) and never touches the project.-11. The conflict status follows the worktree, not only the next merge: after- each Write, Edit, or Bash call of a conflicted session, after a failed merge- or sync, when the session menu opens, and in the background behind check,- host-core clears the status once every conflict is resolved (by the rule the- merge uses to conclude it) or the merge was aborted.-12. While host-core commits or merges in a session worktree for a subagent, it- holds the session's own tools (new calls queue, also while the hold is- awaited).+ warning, deleting links as links before calling git because Git for Windows follows+ directory junctions during `git worktree remove --force`.+7. Every git command disables hooks and `core.fsmonitor` and sets+ `safe.bareRepository=explicit`, so a relative `core.hooksPath` hook cannot bypass+ the Bash permission.+8. New worktrees copy ignored files listed in `.worktreeinclude` and then run an+ optional per-project setup command with `PI_PROJECT_ROOT`, `PI_WORKTREE_ROOT`, and+ `PI_PORT`.+9. Minimum git version is 2.29, and relative worktree links are not used because they+ raise the repository format version.+10. "Sync from project" merges the project branch into the session worktree under+ decision 4's rules and never touches the project; the sidebar marks a session that+ lacks project commits (`↓N`) from one `worktree.behindAll` call.+11. Conflict status follows the worktree: host-core clears it once every conflict is+ resolved by the merge's own rule, with text conflicts counted as resolved when+ their markers are gone and binary or add/delete conflicts needing an explicit+ `git add` or `git rm`.+12. While host-core commits or merges for a subagent it holds the session's own tools,+ waiting at most five seconds for running tools before falling back to the write+ permit.-## Alternatives considered+## Consequences-- Worktrees inside the project (`.pi/worktrees/`, Claude Code's choice):- rejected after verification; test runners (vitest default `exclude`), `tsc`- (default `include: **/*`), watchers, and `git clean -ffdx` see or delete the- copies.**-- Apply changes as uncommitted edits instead of merging the branch: rejected by- the user in favor of keeping history.-- Merging directly in the project: rejected; a conflict would leave the project- half-merged.-- No automatic subagent merge-back (Claude Code, VS Code, Codex): rejected by- the user in favor of zero-click integration, with serialization and a no-force- fallback as safeguards.+- Project history gains merge and checkpoint commits, and automatic commits do not run+ the project's pre-commit hooks.+- MCP stdio servers stay per project with the main checkout as cwd, so MCP tools are+ not isolated.+- Isolation is a development boundary, not a security boundary: Bash can still reach+ the main checkout through absolute paths.-## Consequences+## Alternatives-- Project history contains "Merge branch …" and checkpoint commits.-- Automatic commits do not run the project's pre-commit hooks.-- MCP stdio servers stay per project with the main checkout as cwd, so MCP tools- are not isolated.-- Builds that reach outside the repository by relative path need links made by- the setup command.-- Isolation is a development boundary, not a security boundary; Bash can still- reach the main checkout through absolute paths.+- Worktrees inside the project, or per-project file locks without worktrees —+ rejected: test runners, `tsc`, watchers, and `git clean -ffdx` would see or delete+ the copies, and locks isolate neither builds nor git state.+- Merging directly in the project — rejected: a conflict would leave the project+ half-merged.diff --git a/docs/adr/0330-open-html-files-in-work-panel-browser-from-plugins.md b/docs/adr/0330-open-html-files-in-work-panel-browser-from-plugins.mdindex 8d03ac283..2594b039a 100644--- a/docs/adr/0330-open-html-files-in-work-panel-browser-from-plugins.md+++ b/docs/adr/0330-open-html-files-in-work-panel-browser-from-plugins.md@@ -2,53 +2,42 @@- Status: Accepted- Date: 2026-10-16-- Deciders: PI-Desktop maintainers- Related: [ADR 0109](0109-open-files-with-the-os-associated-application.md) ·[ADR 0170](0170-work-panel-browser-as-bundled-plugin.md) ·[ADR 0264](0264-host-mediated-actions-follow-the-browsed-folder.md) ·- [ADR 0328](0328-browser-arbitrary-local-files.md) ·- [07-plugins/03-plugin-api](../spec/07-plugins/03-plugin-api.md) · E2E-153+ [ADR 0328](0328-browser-arbitrary-local-files.md) · E2E-153## Context-The bundled File Manager can open files with the OS application or reveal them-in the file manager. HTML previews need the bundled work-panel Browser, but its-public `pi.browser.*` API is gated by high-risk `browser.cdp` and also exposes-page inspection and control.+The bundled File Manager can open files with the OS application or reveal them,+but HTML previews need the work-panel Browser, whose public `pi.browser.*` API is+gated by the high-risk `browser.cdp` permission that also exposes page inspection+and control.## Decision-1. Add the additive `pi.fs.openInBrowser(pathFromRoot)` API and panel bridge- channel `fs.openInBrowser`, covered by the existing `fs.read` permission.-2. Resolve the path with the same real-path, protected-path, credential- deny-list, declared-scope, and project-group root checks as the other- host-mediated file actions.-3. After validation, Electron Main sends a dedicated Browser-open event to the- renderer.-4. This action does not grant `browser.cdp`, expose Browser actions or page- contents, broaden `BrowserPreview`, or change the Browser's existing local- file navigation policy (ADR 0328).+Add the additive `pi.fs.openInBrowser(pathFromRoot)` API and panel bridge channel+`fs.openInBrowser`, covered by the existing `fs.read` permission. The path is+resolved with the same real-path, protected-path, credential deny-list,+declared-scope, and project-group root checks as other host-mediated file actions,+accepting only existing regular `.html`, `.htm`, or `.xhtml` files and auditing+successes and refusals. After validation Electron Main sends a Browser-open event+and the renderer creates a Browser resource tab for the active local session,+failing with `UNAVAILABLE` when the bundled Browser plugin is disabled. The action+grants no `browser.cdp`, does not broaden `BrowserPreview`, and leaves the+Browser's local file navigation policy (ADR 0328) and every protocol and persisted+format unchanged.## Consequences-- A File Manager user can preview an authorized HTML file without leaving the- work panel or granting the plugin Browser control.-- The Browser continues to apply its established policy for local HTML and- linked local resources after the host has checked the file-tree selection.-- Plugins cannot use this API to open directories, non-HTML files, credentials,- protected app data, or paths outside their declared read scope.+- A File Manager user previews an authorized HTML file without leaving the work+ panel or granting Browser control.+- Plugins cannot use the API for directories, non-HTML files, credentials,+ protected data, or paths outside their declared read scope.## Alternatives considered-### Grant `browser.cdp` to the File Manager--Rejected: that high-risk capability also permits page inspection and browser-actions, while this interaction only needs the host to open one scoped file.--### Reuse `BrowserPreview`--Rejected: `BrowserPreview` is workspace-rooted and session-originated.--### Open through `shell.openExternal(file:)`--Rejected: external URL opening intentionally excludes local file URLs.+- Grant `browser.cdp` to the File Manager: rejected; it also allows page+ inspection and browser actions.+- Reuse `BrowserPreview` or `shell.openExternal(file:)`: rejected; both are+ scoped differently and external opening excludes local file URLs.diff --git a/docs/adr/0331-plugin-session-follow-and-work-panel-reveal.md b/docs/adr/0331-plugin-session-follow-and-work-panel-reveal.mdindex 4fd11c5fc..8df113001 100644--- a/docs/adr/0331-plugin-session-follow-and-work-panel-reveal.md+++ b/docs/adr/0331-plugin-session-follow-and-work-panel-reveal.md@@ -2,58 +2,65 @@- Status: Accepted- Date: 2026-10-18-- Deciders: PI-Desktop maintainers- Related: [ADR 0104](0104-plugin-contributed-work-panel-views.md) ·[ADR 0263](0263-project-folder-roots-for-plugin-views.md) ·- [ADR 0330](0330-open-html-files-in-work-panel-browser-from-plugins.md) ·- [07-plugins/03-plugin-api](../spec/07-plugins/03-plugin-api.md)+ [ADR 0330](0330-open-html-files-in-work-panel-browser-from-plugins.md)## ContextPlugins that follow the conversation — a diff view, a running-task overlay, a-side panel that reacts to the selected session — need three facts the public API-did not expose: which session the user is looking at, which host turn that-session is running, and how to show the plugin's own view beside that session.+panel reacting to the selected session — need three facts the public API did not+expose: which session the user is looking at, which host turn it is running, and+how to show the plugin's own view beside it. Importing host internals is refused+by the packaging check as dynamic module loading, and host-store access is the+boundary the plugin SDK exists to keep.## Decision-1. Add the additive `pi.session.getActive(): Promise<PluginActiveSession |- null>` with `{ sessionId, projectPath, activeTurn: { turnId, startedAt } |- null }`, and deliver the same payload on the `session:activated` event- whenever that snapshot changes.-2. Assemble the snapshot from two owners rather than one.-3. Add the additive `pi.ui.revealView({ viewId?, location?, sessionId? })`- requiring `ui.view`.-4. Expose both on the panel bridge as `session.getActive` and `ui.revealView`,- so a docked view reads the same snapshot and reveals itself.-5. No host-core protocol, persisted data, manifest schema, or permission list- changes.+### 1. A bounded active-session snapshot-## Consequences+Add the additive `pi.session.getActive(): Promise<PluginActiveSession | null>`+with `{ sessionId, projectPath, activeTurn: { turnId, startedAt } | null }`,+delivered on `session:activated` whenever that snapshot changes; it takes no+session id and needs no permission because it reports what the shell shows.-- A plugin can follow the selected session, name its running turn, and open its- own view beside that session without touching host internals, which makes such- plugins publishable again.-- The selection stays shell-owned: a plugin cannot address a session the user is- not looking at, and a reveal naming a session the user left is refused instead- of opening a tab nobody sees.-- The snapshot is a value, not a subscription handle.-- Session selection now crosses one more IPC hop on every switch.+### 2. Two owners assemble the snapshot-## Alternatives considered+The renderer pushes its selection and the session's project path over a dedicated+IPC invoke, while the main process dates turn start from the existing+`recordTurnStart` seam and validates every reported turn id against `activeTurns`+before publishing, so a turn that ended without notice ages out.++### 3. A host-owned reveal++Add the additive `pi.ui.revealView({ viewId?, location?, sessionId? })` requiring+`ui.view`, which resolves the plugin's own `contributes.views`, caps the location,+compares `sessionId` with the active session, and reuses the existing `piViewOpen`+/ `view:open` transport so a live view is never reloaded.-### Expose the renderer store to `renderer.extension` plugins+### 4. Both are exposed on the panel bridge-Rejected: it makes host internals a contract, has no permission boundary, and-would freeze every store refactor.+`session.getActive` and `ui.revealView` let a docked view read the same snapshot+and reveal itself.-### Let the plugin read `pi.session.list` and infer the selection+### 5. Nothing else changes-Rejected: it exposes sessions the user is not looking at, and `session.list` is-scoped to plugin-owned sessions; inference from `session:turnEnded` and draft-changes is what produced the wrong-turn overlay this ADR removes.+No host-core protocol, persisted data, manifest schema, or permission list+changes, and older hosts reject the new calls with `UNSUPPORTED`.-### A separate `session:turnStarted` event+## Consequences++- A plugin can follow the selected session and open its own view beside it+ without touching host internals, so such plugins are publishable again.+- A plugin cannot address a session the user is not looking at, and a reveal for+ a session the user left is refused instead of opening an unseen tab.+- The snapshot is a value rather than a subscription: a missed event is repaired+ by one `getActive()` call, at the cost of one more IPC hop per switch.++## Alternatives considered-Rejected: the snapshot already carries the turn, so a second event would give-plugins two ways to learn one fact and two chances to disagree.+- Expose the renderer store to `renderer.extension` plugins: rejected; it makes+ host internals a contract with no permission boundary.+- Let the plugin infer the selection from `session.list` and turn events:+ rejected; it exposes other sessions and produced the wrong-turn overlay this+ change removes.diff --git a/docs/adr/0332-macos-opaque-window-surface.md b/docs/adr/0332-macos-opaque-window-surface.mdindex b02768d20..6dbc9edd6 100644--- a/docs/adr/0332-macos-opaque-window-surface.md+++ b/docs/adr/0332-macos-opaque-window-surface.md@@ -2,80 +2,57 @@- Status: Accepted- Date: 2026-10-16-- Deciders: PI-Desktop maintainers-- Related: issue #1064, D665, D666, D667, D304, D348, ADR 0248 (theme assets and window- background), ADR 0260 (plugin runtime theme APIs),- `docs/spec/04-ux/07-ui-design-system.md`,- `docs/spec/04-ux/08-component-spec.md`+- Related: issue #1064, D665, D666, D667, D304, D348, ADR 0248, ADR 0260,+ `docs/spec/04-ux/07-ui-design-system.md`## Context-The macOS main window was created as a frameless `hiddenInset` window with-`vibrancy: "sidebar"`, `visualEffectState: "followWindow"`, `transparent: true`-and a `#00000000` backing. WindowServer composited the vibrancy material behind-the translucent Electron surface, and the renderer painted a thin tint plus-sheen over it to read as glass (D348).--```text-desktop idle baseline avg 3.6% max 9.3%-PI-Desktop focused, idle avg 40.9% max 55.6%-PI-Desktop minimized avg 3.2% max 6.1%-```+The macOS main window combined a frameless `hiddenInset` titlebar with+`vibrancy: "sidebar"`, `visualEffectState: "followWindow"`, `transparent: true`,+and a `#00000000` backing, so WindowServer re-composited the material whenever+the visible focused window stayed dirty — an idle focused window held GPU at+roughly 41% average on Apple Silicon against a 3.6% desktop baseline, while a+minimized window returned to baseline. Bounding idle-reachable animations+(#1064, D348) reduced but could not remove that cost, because the material itself+keeps the window in the compositor's per-frame path.## Decision-macOS keeps the translucent native surface the product has always shipped, and-the opaque surface is now the opt-out. The main window keeps its frameless-`hiddenInset` titlebar, its inset traffic-light position, its vibrancy material,-and the renderer's glass tint and sheen.--- `macosWindowSurfaceOptions(translucent, color)` is the single place that- declares the macOS surface: `true` keeps `vibrancy: "sidebar"`,- `visualEffectState: "followWindow"`, and the transparent `#00000000` backing;- `false` paints an opaque `{ transparent: false, backgroundColor }` window that- stays out of WindowServer's per-frame recomposition path (#1064).-- `AppSettings.macosWindowTranslucency` is the stored preference.-- A translucent window owns its pixels: the post-creation background paint, the- `window.setBackgroundColor` IPC, and `applyMainWindowBackground` all leave it- alone.-- `applyNativeThemeSource` re-applies `setVibrancy("sidebar")` for a translucent- window when the theme source changes; an opaque one has no material to reset.-- `mainWindowBackgroundOptions("darwin", color)` still describes the opaque- surface, so a caller that only knows a platform never gets the material.--The renderer-side sidebar treatment is unchanged: `--ds-sidebar-glass-tint` and-the sheen paint the sidebar, splash, and rail over whichever surface the window-has, so the glass reads the same and the setting only changes what shows through-it.+macOS keeps the translucent native surface it has always shipped and the opaque+surface becomes the opt-out. `macosWindowSurfaceOptions(translucent, color)` is+the single declaration of the surface: `true` keeps `vibrancy: "sidebar"`,+`visualEffectState: "followWindow"`, and the transparent backing, while `false`+paints an opaque `{ transparent: false, backgroundColor }` window outside+WindowServer's recomposition path. `AppSettings.macosWindowTranslucency` stores+the preference, absent and `true` meaning translucent, and it is read once before+`new BrowserWindow` because Electron fixes `transparent` at creation, so a change+applies on the next launch and the darwin-only Settings switch shows a restart+hint while the stored value differs from the running surface.++A translucent window owns its pixels: the post-creation background paint, the+`window.setBackgroundColor` IPC, and `applyMainWindowBackground` leave it alone,+because painting a palette over a transparent backing flattens the material. The+opaque surface takes the colour on darwin like other platforms, so a plugin+theme's `windowAppearance.backgroundColor` (ADR 0248) applies there, and+`applyNativeThemeSource` re-applies `setVibrancy("sidebar")` only for a+translucent window. The renderer's `--ds-sidebar-glass-tint` and sheen are+unchanged, so the glass reads the same on either surface.## Consequences-- Default installs still pay the compositor cost of the material: translucency- is the shipped look, so the per-frame recomposition described in Context- remains for anyone who leaves the switch on.-- Turning the switch off paints the opaque surface and returns an idle focused- window to the desktop GPU baseline measured under #1064.-- The renderer tint, sheen, and layout are identical on both surfaces, so the- switch changes only whether the desktop shows through; no other visual,- persisted-data, or plugin contract changes.-- Plugins with a granted `ui.window.appearance` permission have their- `windowAppearance.backgroundColor` applied on the opaque surface, matching- Windows and Linux, and keep the vibrancy material on the translucent one — the- same rule as before the setting existed (ADR 0248).-- The bounded-animation contract from #1064 stays in force on both surfaces.+- Default installs still pay the compositor cost, which is a product decision:+ a silent default change would remove the desktop blur existing users expect.+- Turning the switch off returns an idle focused window to the desktop GPU+ baseline measured under #1064, one launch away.+- Only what shows through the window changes; no other visual, persisted-data, or+ plugin contract is affected, and the bounded-animation contract stays in force+ on both surfaces.## Alternatives rejected-- **Keep vibrancy and bound every animation that can reach an idle screen.**- This was the #1064 approach and it did reduce the load, but it cannot remove- it: the material keeps the window in the compositor's per-frame path while it- is visible and focused, independently of what the renderer paints.-- **Drop only `visualEffectState: "followWindow"`.** The window already used- `followWindow`, so this was a no-op; the material behaviour is what costs.-- **Drop transparency but keep vibrancy.** A vibrancy material without a- transparent surface still has WindowServer composite the material; the- transparent backing is what let it blend, not what made it expensive.-- **Make the setting live on a running window.** `transparent` is fixed when- Electron creates the window, so a live change would either leave a transparent- window with an opaque colour (keeping the compositor cost) or an opaque window- that can never show the material.+- Bound every idle-reachable animation instead: the material keeps the window in+ the per-frame path independently of what the renderer paints.+- Make the opaque surface the default: tried and reverted, because every+ existing user lost the material their window was designed around.+- Change the setting on a running window: `transparent` is fixed at creation, so+ it would leave a half-applied state.diff --git a/docs/adr/0333-plugin-composer-suggestion.md b/docs/adr/0333-plugin-composer-suggestion.mdindex 521fbf6f5..0752c91ca 100644--- a/docs/adr/0333-plugin-composer-suggestion.md+++ b/docs/adr/0333-plugin-composer-suggestion.md@@ -2,80 +2,64 @@- Status: Accepted- Date: 2026-10-24-- Deciders: PI-Desktop maintainers- Related: [ADR 0324](0324-plugin-owned-composer-prompt-enhancement.md) ·[ADR 0331](0331-plugin-session-follow-and-work-panel-reveal.md) ·- [07-plugins/03-plugin-api](../spec/07-plugins/03-plugin-api.md) ·- [07-plugins/13-plugin-permissions-matrix](../spec/07-plugins/13-plugin-permissions-matrix.md)+ [07-plugins/03-plugin-api](../spec/07-plugins/03-plugin-api.md)## Context-After a turn ends, a plugin often knows something the user would plausibly type-next: a follow-up question, a "continue" instruction, a correction. The only-surfaces a plugin has today are announcements that interrupt (a toast, a-notification, a work-panel view) or a rewrite of text the user already wrote-(`composer.transform`).+After a turn ends a plugin often knows what the user would plausibly type next,+but its only surfaces are announcements that interrupt (toast, notification,+work-panel view) or a rewrite of text the user already wrote+(`composer.transform`). A suggestion must be visible where the user is looking+and trivial to ignore, yet producing one is slow — listen for+`session:turnEnded`, read with `pi.session.getLlmContext`, run a+`pi.agent.complete` — so by the time text arrives the user may have typed,+switched session, or started another turn.## Decision1. Add `pi.composer.suggest({ sessionId, turnId?, text, ttlMs? })` and- `pi.composer.clearSuggestion({ sessionId? })` to the Plugin SDK, gated by the- new `composer.suggest` permission.-2. Split the decision by ownership instead of centralizing it:- - Main refuses what it can see without the renderer — a session that is not- the one on screen, and a `turnId` that a later `onTurnStarted` overtook —- and relays the rest, then waits for the renderer's answer.- - The renderer refuses the rest — no composer, a blocked composer, a draft- with text or an attachment — and answers over a dedicated invoke.-Main never writes renderer state; it sends a message, exactly like-`pi.ui.revealView` (ADR 0331).-3. Model the suggestion as a slot beside the draft, not inside it.-4. Keep the existing key owners.-5. Draw it brighter than the shell's own placeholder (62% primary ink versus 72%- secondary) with a `Tab` / `Esc` hint beside it, on one line with an ellipsis,- and announce it once through an `sr-only` polite live region.-6. Classify `composer.suggest` as **medium** risk and confirm it at install.+ `pi.composer.clearSuggestion({ sessionId? })` under a new `composer.suggest`+ permission, where `suggest` resolves `{ shown: true }` or+ `{ shown: false, reason }` with `session-not-visible`, `draft-not-empty`,+ `stale-turn`, `replaced`, or `unsupported`, and only malformed input throws+ `INVALID_PARAMS`.+2. Split the decision by ownership: main refuses what it can see without the+ renderer, meaning a session that is not on screen or a `turnId` a later+ `onTurnStarted` overtook, then relays the rest and waits for the renderer,+ which refuses a missing or blocked composer and a draft with text or an+ attachment over a dedicated invoke. Main never writes renderer state.+3. Model the suggestion as a slot beside the draft, not inside it: the text is+ drawn in the existing `.composer-placeholder` layer while `value` is empty,+ `Tab` writes it into the draft, and `Esc`, a first character, a send, a+ session switch, a new turn, a plugin stop, a reload, or a window close drops+ it, with one suggestion per session and a newer offer replacing the older one.+4. Keep the existing key owners: an open `@` / `/` completion list keeps `Tab`+ and `Esc`, and the suggestion acts only when neither claims the key, decided+ by a pure function so ordering is testable without a DOM.+5. Draw it brighter than the shell placeholder with a `Tab` / `Esc` hint on one+ ellipsized line, announce it once through an `sr-only` polite live region, and+ leave `aria-placeholder` describing the input.+6. Classify `composer.suggest` as medium risk and confirm it at install: it+ cannot read the draft, cannot send, and cannot outlive an empty draft.## Consequences-- A plugin can propose the next message where the user is already looking,- without a notification, a bubble, or a panel, and it learns immediately- whether the suggestion was taken up.-- The shell keeps the composer authoritative: a suggestion is decorative state- that the Composer discards on its own terms and that a plugin cannot promote- into a draft.-- The answer to `suggest` costs one renderer round trip and a bounded wait- (`answerTimeoutMs`, 2 s).-- Suggestion text is capped at 200 characters after line breaks and runs of- whitespace are folded, so a plugin that asked for a paragraph still gets a- usable result instead of an error it cannot repair inside a turn.-- The permission list, the manifest schema page, the permissions matrix, the- plugin API spec, and the nine shipped catalogs all gain one entry; no plugin- manifest schema version, host-core schema, or persisted format changes.+- A plugin can propose the next message where the user is looking without a+ notification or panel, and learns immediately whether it was taken up.+- The shell keeps the composer authoritative, since a suggestion is decorative+ state the Composer discards on its own terms and a plugin cannot promote.+- The answer costs one renderer round trip with a bounded 2 s wait reporting+ `unsupported` rather than hanging, text is capped at 200 characters after+ whitespace folding, and no manifest schema, host-core schema, or persisted+ format changes.## Alternatives considered-### Let the plugin's own renderer module call `pi.dispatch("composer.setSuggestion")`--Rejected as the primary path.--### A message, a toast, or an inline transcript row--Rejected: all three interrupt or occupy transcript space for a hint the user may-ignore, and none of them can become the user's own text.--### Store the suggestion as a draft value the user deletes--Rejected: it makes plugin text indistinguishable from typed text, breaks the-"empty draft" invariant other features rely on, and would let a suggestion be-sent without an explicit accept.--### Report `shown` optimistically and clear later--Rejected: the point of the answer is that the plugin can stop spending-completions on a user who is not looking at that session.--### Change `aria-placeholder` while a suggestion is shown--Rejected: the field's purpose does not change with the suggestion, and a-placeholder change is announced differently across screen readers.+- Let a plugin renderer module set the suggestion directly: the SDK has no+ process → renderer-module channel for text produced by a long completion.+- Store the suggestion as a draft value the user deletes: it makes plugin text+ indistinguishable from typed text and breaks the empty-draft invariant.+- Report `shown` optimistically: `draft-not-empty` and `session-not-visible` are+ exactly the cases where a guess would be wrong.diff --git a/docs/adr/0334-openai-fast-mode.md b/docs/adr/0334-openai-fast-mode.mdindex 7bbc3f0dd..39d1e8415 100644--- a/docs/adr/0334-openai-fast-mode.md+++ b/docs/adr/0334-openai-fast-mode.md@@ -2,50 +2,54 @@- Status: Accepted- Date: 2026-10-17-- Deciders: PI-Desktop maintainers- Related: [ADR 0329](0329-session-worktree-isolation.md) ·[03-runtime/11-provider-model-system](../spec/03-runtime/11-provider-model-system.md) ·- [04-ux/04-builtin-commands](../spec/04-ux/04-builtin-commands.md) ·- issue #1657 · E2E-FAST-MODE+ issue #1657## Context-OpenAI serves a faster priority tier that Codex CLI and the OpenAI API call Fast-mode. On the wire it is the Responses body field `service_tier: "priority"`; the-Codex backend rejects `"fast"`.+OpenAI's faster priority tier, Fast mode, is the Responses body field+`service_tier: "priority"` (the Codex backend rejects `"fast"`) and it costs more+in plan limits or per-token price, while PI-Desktop never asked for a tier.+pi-ai's adapters already accept `serviceTier` and price the reported tier, but+`streamSimple` dropped the option. Issue #1657 asks for the speed-up and+maintainers asked that the capability be configured in model settings.## Decision1. **Model settings own capability.** `ModelBinding.fastModeAllowed` is an- opt-in, stored in the existing provider `config_json` like `nativeWebSearch`,- so it needs no migration.-2. **`/fast` owns the session switch.** A new builtin `builtin.session.fast`- (`/fast`) toggles a persisted `sessions.fast_mode` column (schema v27,- additive, v25 backup).-3. **`/fast` only works on a configured model.** When the selected model's wire- cannot carry the tier or the model is not allowed, `/fast` stores nothing and- points to Settings → Models → Advanced, in either direction.-4. **The launcher resolves; the runtime only stamps the wire.** Session launch- sends `fastMode: true` to the sidecar only when the session switch is on and- the user's stored binding allows it.--## Alternatives--- **Per-model switch only (no session state).** Avoids a migration, but turns a- per-conversation cost into a global one: enabling Fast for one task speeds up- and costs every conversation on that model.-- **Hard-coded capability rule (official OpenAI host only).** Removes a setting,- but excludes relays the user knows support the field and hides the decision in- code.-- **Generic request-parameter injection with presets.** More flexible, but an- arbitrary body-field channel needs its own validation and permission story,- which is larger than this need.+ opt-in stored in the existing provider `config_json` like+ `nativeWebSearch`, needing no migration, enabled only for the+ `openai_codex_responses` and `responses` wires including relays, with a hint+ naming that wire's cost.+2. **`/fast` owns the session switch.** The `builtin.session.fast` builtin+ toggles a persisted `sessions.fast_mode` column (schema v27, additive), and+ `session.create` / `session.configure` accept an optional `fastMode` where+ omission keeps the stored value, forks copy it, scheduled runs and delegated+ workers start off, and a draft carries it into the session its first prompt+ creates.+3. **`/fast` only works on a configured model.** When the selected wire cannot+ carry the tier or the model is not allowed, `/fast` stores nothing and points+ to Settings → Models → Advanced, and a stale switch is inert because launch+ also requires the opt-in.+4. **The launcher resolves; the runtime only stamps the wire.** Launch sends+ `fastMode: true` only when the session switch is on and the binding allows it,+ and the runtime passes `serviceTier: "priority"` on main turns whose resolved+ wire is `openai-codex-responses` or `openai-responses`; subagents, compaction,+ and one-shot plugin requests keep the default tier, and a trusted extension+ switching to its own model clears the switch until the next launch.## Consequences-- Schema v27 adds one column; older apps opening a v27 database refuse it as- newer, the existing downgrade behavior.-- The capability can be wrong for a relay that ignores or rebills the field; the- settings hint states that risk, and the user owns the opt-in.+- Schema v27 adds one column, and older apps refuse a v27 database as newer.+- The capability can be wrong for a relay that ignores or rebills the field, so+ the settings hint states that risk and the user owns the opt-in.- The Composer model chip shows a Fast mark while the switch is on for an- allowed model, so the cost is visible at send time.+ allowed model, keeping the cost visible at send time.++## Alternatives++- A per-model switch without session state: it turns a per-conversation cost+ into a global one for every conversation on that model.+- A hard-coded official-host-only rule: it excludes relays the user knows+ support the field and hides the decision in code.diff --git a/docs/adr/0337-stable-prompt-prefix-across-delegation.md b/docs/adr/0337-stable-prompt-prefix-across-delegation.mdindex 14f9e25d6..227be713e 100644--- a/docs/adr/0337-stable-prompt-prefix-across-delegation.md+++ b/docs/adr/0337-stable-prompt-prefix-across-delegation.md@@ -2,63 +2,56 @@- Status: Accepted- Date: 2026-10-25-- Deciders: PI-Desktop maintainers-- Related: ADR 0279 (resumable subagent delegations), ADR 0089 (delegation- tools), `docs/spec/03-runtime/02-agent-runtime.md`+- Related: ADR 0279 (resumable subagent delegations), ADR 0089 (delegation tools)- Amends: ADR 0279 §9## Context-ADR 0279 §9 put the resumable-chain list into the parent's **system prompt**,-and recomposed that prompt every time a delegation settled. The intent was that-the parent sees what it can continue without calling a tool.--- A model with `supportsMidConvoSystemMessages` keeps the appended system- message in place, so only the tail is new.-- Every other model goes through `collapseSystemMessages`- (`@earendil-works/pi-ai`, `utils/transcript.js`), which replays all system- messages into **the first** one.+ADR 0279 §9 put the resumable-chain list into the parent's system prompt and+recomposed that prompt whenever a delegation settled, so the parent would see what+it can continue without a tool call. Providers cache a conversation by the exact+byte prefix of the request, and PI-Desktop appends changed system sections rather+than rewriting the first one (`syncSystemSections`). Only a narrow DeepSeek route+supports `supportsMidConvoSystemMessages`; every other model replays all system+messages into the first block through `collapseSystemMessages`, so each settlement+could invalidate the whole cached prefix rather than its tail.## Decision-1. **The system prompt never carries delegation state.** `composeSystemPrompt`- no longer composes a resumable block, and the runtime no longer recomposes- the prompt on settlement.-2. **`TaskList` is the discovery path.** Its result now carries the resumable- chains — agent name, `delegationId`, objective, and up to- `MAX_RESUMABLE_LISTED_FILES` files read — as both text (the existing- `formatResumableList` rendering) and a structured `details.resumable` array.-3. **Tool errors stay authoritative.** Unknown, mismatched, over-budget, and- history-less resume ids still return a tool error that names the reusable ids- inline (`DelegationChainRegistry.unknownResumeError` /- `noHistoryResumeError`), so a failed resume never depends on the parent- having called `TaskList` first.-4. **The registry keeps its own gate.** `resumableList` still excludes running,- non-resumable, and over-budget chains, so a listing never advertises an id- the resume path would reject.--The `resumablePromptStale` deferral, the `refreshResumablePrompt` hook, and the-two `applyPendingResumablePrompt` calls in the silent-turn and progress-turn-recovery paths are removed with their reason: there is no prompt-level resumable-state left to defer.+1. The system prompt never carries delegation state. `composeSystemPrompt` no+ longer composes a resumable block and the runtime no longer recomposes the+ prompt on settlement; instructions change only for reasons the user controls,+ such as mode, project instructions, memory, skills, or a custom prompt.+2. `TaskList` is the discovery path. Its result carries the resumable chains —+ agent name, `delegationId`, objective, and up to `MAX_RESUMABLE_LISTED_FILES`+ files read — as text through `formatResumableList` and as a structured+ `details.resumable` array, and its description names `Task(resume: ...)` as the+ reason to call it.+3. Tool errors stay authoritative. Unknown, mismatched, over-budget, and+ history-less resume ids still return a tool error naming the reusable ids inline+ (`DelegationChainRegistry.unknownResumeError` and `noHistoryResumeError`), so a+ failed resume never depends on a prior `TaskList`.+4. The registry keeps its own gate: `resumableList` still excludes running,+ non-resumable, and over-budget chains, so a listing never advertises an id the+ resume path would reject.++The `resumablePromptStale` deferral, `refreshResumablePrompt`, and the+`applyPendingResumablePrompt` recovery calls are removed with their reason, since+no prompt-level resumable state remains.## Consequences-- Delegation settlements are invisible to the request prefix.-- The parent must call `TaskList` to learn ids proactively.-- `TaskList` grows with the reusable chain count (bounded by- `MAX_RESUMABLE_CHAINS_PER_AGENT`), not with the conversation.-- This ADR fixes one source of prefix churn, not all of them.-- ADR 0279 §9 is superseded by decision 2 here; its other decisions stand.+- Delegation settlements are invisible to the request prefix, so a long session+ keeps one cache lineage until something the user changed does.+- The parent pays for a `TaskList` call only when it needs ids, and a blind resume+ still gets them back in its error; the listing grows with chain count+ (`MAX_RESUMABLE_CHAINS_PER_AGENT`), not with the conversation.+- This fixes one source of prefix churn only: `TOOL_ACTIVATION_SECTION` and the+ context-budget reminder still append system messages mid-turn, and ADR 0279 §9+ is superseded by decision 2 while its other decisions stand.-## Alternatives Considered+## Alternatives-- **Refresh the list only at turn start.** Cheap and would cut the churn to one- rewrite per turn, but it still rewrites the collapsed first system block- whenever the settled set grew, so a turn after every delegation misses the- whole prefix.-- **Move the list into the last user message.** Keeps the head stable and needs- no new tool surface, but it rewrites conversation history the transcript owns- and would make the persisted rows disagree with the request.-- **Keep the list in the prompt and mark it cache-friendly.** Providers cache- bytes, not sections; no marker changes the invalidation.+- Refresh the list at turn start: still rewrites the collapsed first block after+ each delegation.+- Move the list into the last user message: rewrites history the transcript owns.diff --git a/docs/adr/0338-user-supplied-startup-animation.md b/docs/adr/0338-user-supplied-startup-animation.mdindex d9dcbc8ae..cb092f417 100644--- a/docs/adr/0338-user-supplied-startup-animation.md+++ b/docs/adr/0338-user-supplied-startup-animation.md@@ -2,64 +2,54 @@- Status: Accepted- Date: 2026-11-03-- Deciders: PI-Desktop maintainers-- Related: D679, D348, D665, ADR 0248 (theme assets and window background),- ADR 0332 (macOS window surface), issue #831 (startup watchdog),- `docs/spec/04-ux/09-interaction-patterns.md`,- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-076)+- Related: D679, D348, D665, ADR 0248 (theme assets and window background), ADR 0332 (macOS window surface), issue #831 (startup watchdog), [E2E-076](../spec/06-delivery/04-e2e-test-plan.md)## Context-The window has always shown one boot surface: `StartupSplash`, a brand mark with-a tagline and an indeterminate bar, mounted until the shell publishes its-initial state and then faded out over 280ms after a 420ms minimum dwell. Issue-#831 added the two bounds that keep it from being permanent — a slow hint at 30s-and a recovery surface at 180s.--- **The file.** The renderer is sandboxed, `contextIsolation` is on, and the- page CSP has no `file:` source.-- **The timing.** The animation has to be in the renderer's *first* frame or the- user sees the splash flash before it.-- **The failure modes.** A splash is code the product controls; a video is a- file a user produced.+The window has always shown one boot surface, `StartupSplash`, mounted until the+shell publishes its initial state and bounded by the watchdog hint and recovery+surfaces from issue #831. Letting users put their own launch video there touches+three boundaries at once: the renderer is sandboxed with no `file:` source in its+CSP, the video must be in the very first frame or the splash flashes first, and a+user-produced file can be unplayable or loop forever without ever firing `ended` or+`error`.## Decision-A video in `<dataDir>/startup/` replaces the brand splash for that launch, plays-to its last frame, then holds the window under the same opaque black it played-on until the shell is ready, then fades that black out over one second.--**Discovery is filesystem-only and creates nothing.** `resolveStartupAnimation`-reads `<dataDir>/startup/`, keeps entries whose extension is in-`STARTUP_ANIMATION_EXTENSIONS`, confines each by realpath to that directory, and-picks deterministically: most-decodable container first (`webm`, then `mp4`,-`m4v`, `mov`), ties broken by file name. Dot-prefixed entries, non-files, empty-files, and files over `STARTUP_ANIMATION_MAX_BYTES` (64 MB) drop out.+A video in `<dataDir>/startup/` replaces the brand splash for that launch, plays to+its last frame, holds the window under the same opaque black until the shell is+ready, then fades that black out. `resolveStartupAnimation` reads only that+directory, keeps entries with a known container extension confined by realpath to+it, and picks the most-decodable container with a deterministic tie-break, dropping+dot-prefixed, non-file, empty, and oversized entries while creating nothing. The+bytes travel over the host-owned `pi-startup:` scheme with exactly one URL,+`pi-startup://animation`, which carries no caller-controlled path, host, or query,+is registered with `standard`, `secure`, and `stream` privileges and no CORS,+answers `Range`, and needs only `media-src pi-startup:` added to the CSP. The+descriptor arrives as a window creation argument readable before first paint and+carries the file's name, extension, length, and `skipWhenReady`, never a path, with+the preload re-validating every field. First-frame, whole-animation, watchdog, and+Escape bounds all end through the same clean transition, exactly one of the three+boot surfaces is mounted with the recovery surface ranked first, and the animation+plays once per process for the first window, with no replay from the tray or a+reload and no playback under reduced motion. `AppSettings.startupAnimation` holds+`enabled` and `skipWhenReady`, both read before window creation so a change lands+on the next launch.## Consequences-- An installation with no `startup/` directory behaves exactly as before: same- splash, same dwell, same fade, same watchdog bounds.-- A launch with an animation is slower to reach the shell by design: the video- plays to its last frame unless the user turns on `skipWhenReady`.-- The host now owns a fourth privileged scheme.-- `--motion-startup-reveal: 1000ms` is the one duration outside the motion ramp- (150/200/300ms).-- The surface is literal `#000`, not `--ds-bg-primary`, so a video's own- letterboxing and fades meet the same colour under either theme.--## Alternatives rejected--- **A dedicated splash `BrowserWindow`.** It would let the video appear before- the main renderer boots at all, but it adds a second window with its own- focus, z-order, Dock, and vibrancy behaviour; it conflicts with the main- window's `ready-to-show` gate; and it cannot express what was asked for — a- mask *over the main interface* that fades away — without cross-window- choreography.-- **`file://` or a `data:`/`blob:` URL.** `file:` is not in the page CSP and- would disclose the data directory; a `data:` URL means base64 (a third larger)- for a file capped at 64 MB, read into memory before the first frame.-- **Reusing `plugin-asset:`.** That scheme takes a plugin id and an asset path- from the URL, so it exists to serve a caller-selected file.-- **Letting a plugin contribute the startup animation.** This hands an untrusted- source the full-window first paint before any UI exists.+- An installation with no `startup/` directory behaves exactly as before, so the+ feature is dormant rather than defaulted off.+- A launch with an animation reaches the shell later by design unless+ `skipWhenReady` is enabled, and the bounds cap that wait.+- The host gains a fourth privileged scheme whose attack surface is smaller than+ the plugin schemes', and the video plays over literal `#000` so letterboxing+ matches under either theme.++## Alternatives++- A dedicated splash `BrowserWindow`: rejected, it adds a second window with its+ own focus, z-order, and Dock behavior and cannot mask the main interface.+- `file://`, `data:`, or a reused `plugin-asset:` URL: rejected, `file:` is outside+ the page CSP and discloses the data directory, `data:` inflates a capped file,+ and `plugin-asset:` serves a caller-selected path.diff --git a/docs/adr/0339-chat-file-refs-open-absolute-files-outside-managed-roots.md b/docs/adr/0339-chat-file-refs-open-absolute-files-outside-managed-roots.mdindex 2c002ee7a..e164ffc2d 100644--- a/docs/adr/0339-chat-file-refs-open-absolute-files-outside-managed-roots.md+++ b/docs/adr/0339-chat-file-refs-open-absolute-files-outside-managed-roots.md@@ -2,60 +2,57 @@- Status: Accepted- Date: 2026-11-03-- Deciders: PI-Desktop maintainers-- Related: ADR 0262 (chat file refs open in the file view), ADR 0172 (fs read- containment), ADR 0249 / ADR 0263 (project folder groups),+- Related: ADR 0172, ADR 0249, ADR 0262, ADR 0263,`docs/spec/03-runtime/01-ipc-protocol.md` § fs, issue #1837- Amends: ADR 0262 §4## Context-The agent is instructed to reference files by their exact absolute path, and it-routinely works on files outside the open project: a download, a chat client's-folder, the system temporary directory, or any path in a session with no project-at all. The main process answered `fs/resolveRef`, `fs/read`, `fs/reveal`, and-`fs/open` by **root containment** — the project folders, the session scratch-store, the whole scratch store, and the attachment store.+The agent references files by exact absolute path and routinely works outside the+open project: downloads, a chat client's folder, the temporary directory, or any+path in a session with no project. Because `fs/resolveRef`, `fs/read`, `fs/reveal`,+and `fs/open` answered by root containment, every correct absolute link outside+the project, scratch, and attachment roots reported "outside the locations this+app can access" (#1837). The restriction protected nothing: the agent already+reads those files with its own tools, and opening a clicked file shows the user+their own bytes, which reach neither the model nor the network.## Decision-1. For a **user-initiated open of an exact absolute path** outside every managed- root, the host replaces containment with one shape check: the path is- absolute (no `~`, no relative shorthand, no `attachments/<sha256>`) and its- real path is an existing regular file.-2. The rule lives in one module, `packages/host-runtime/src/external-files.ts`- (`resolveExternalFile`, `resolveUserOpenablePath`, `readUserOpenableFile`),- and is applied by `fs/read`, `fs/reveal`, and `fs/open`.+1. A user-initiated open of an exact absolute path outside every managed root+ needs one shape check instead of containment: the path is absolute, with no+ `~`, relative shorthand, or `attachments/<sha256>`, and its real path is an+ existing regular file.+2. The rule lives in `packages/host-runtime/src/external-files.ts`+ (`resolveExternalFile`, `resolveUserOpenablePath`, `readUserOpenableFile`) and+ is applied by `fs/read`, `fs/reveal`, and `fs/open`, while containment still+ answers first and `fs/resolveRef` reports an outside match through+ `resolveExternalChatRef` as `root: "external"`, `matchedBy:+ "exact-absolute"`, or `match: null`.3. A shorthand never resolves outside the managed roots, and an outside absolutepath never falls back to a same-name file inside a root.-4. A Markdown link whose destination is an absolute path reaches the opener even- without a file extension (`/etc/hosts`, `.ssh/config`); the host, not a- renderer filename heuristic, decides.-5. Unchanged: `fs/list` (project only), `fs/readImageDataUrl` (inline chat- images load without a click, so a model-written image reference must not- render an arbitrary local image), remote and headless-host file reads- (`apps/pi-host`), the `pi.file-manager` plugin's own deny list (plugin code- receives the bytes), and the renderer routing, which already sends a- non-project match to the host `file:` tab.+4. A Markdown link with an absolute destination reaches the opener without a file+ extension, because the host decides instead of a renderer filename heuristic;+ bare prose tokens keep the extension heuristic.+5. `fs/list`, `fs/readImageDataUrl`, remote and headless-host reads, the+ `pi.file-manager` plugin's own deny list, and renderer routing are unchanged,+ and an external `.html` file opens as source in the `file:` tab, never in the+ side browser.## Consequences-- Clicking a correct absolute link to an ordinary file anywhere on the machine- opens it; sessions without a project and temporary directories work.-- An exact absolute path to an existing outside file now verifies as a chip in- user messages too.-- `fs/open` can hand any such file to its OS default application, including a- script or application bundle that the OS runs when "opened".-- `FsChatRefRoot` gains `"external"`.+- A correct absolute link to an ordinary file anywhere on the machine opens,+ including in sessions without a project and inside temporary directories.+- `fs/open` can hand such a file to its OS default application, the same+ capability the agent's shell already has, and still only when the user chooses+ that destination.+- `FsChatRefRoot` gains `"external"` for consumers that switch on it, and+ `reason: "outside-allowed-roots"` remains only for an outside reference that is+ not an exact absolute path.## Alternatives considered-- **Credential deny list on the host.** Rejected: showing a user their own file- discloses nothing, the agent can already read it, and the list made correct- links to dotfiles fail.-- **Ask the user to grant each outside folder.** Rejected: the user asked for- links that simply open, and `fs/resolveRef` also runs automatically for chip- verification, so a grant prompt would fire without a click.-- **Keep containment and add the temp directory and downloads as roots.**- Rejected: it fixes only the reported folders and leaves every other location- (chat clients, mounted drives) broken.+- Credential deny list on the host: rejected; showing a user their own file+ discloses nothing and made correct links to dotfiles fail.+- Ask the user to grant each outside folder: rejected; verification runs without+ a click, so the prompt would fire anyway.diff --git a/docs/adr/0340-plugin-session-all-scope.md b/docs/adr/0340-plugin-session-all-scope.mdindex 19759e736..ff1b38241 100644--- a/docs/adr/0340-plugin-session-all-scope.md+++ b/docs/adr/0340-plugin-session-all-scope.md@@ -4,84 +4,65 @@- Date: 2026-10-20- Decision: D680- Amends: ADR 0200, ADR 0323-- Related: [spec 07-plugins/03 §plugin-owned and host-wide sessions](../spec/07-plugins/03-plugin-api.md) · [13-plugin-permissions-matrix](../spec/07-plugins/13-plugin-permissions-matrix.md)+- Related: [07-plugins/03-plugin-api](../spec/07-plugins/03-plugin-api.md) ·+ [13-plugin-permissions-matrix](../spec/07-plugins/13-plugin-permissions-matrix.md)## Context-`pi.session` was built for external conversation import (ADR 0200): every read-and write is filtered by `session_import_origins.plugin_id`, so a plugin can-only reach sessions it imported itself. That boundary was correct for the-feature it shipped with, and it is now a capability gap.+`pi.session` was built for external conversation import (ADR 0200), so every read+and write is filtered by `session_import_origins.plugin_id` and a plugin can only+reach sessions it imported itself. The composer-suggestion flow (ADR 0333) needs+`pi.session.getLlmContext` and `pi.session.listMessages` refuses a session no+plugin imported, which is why ADR 0323 had to invent the narrower+`session.autoTitle` permission instead of describing "a plugin may read a user's+session".## Decision-1. Add three permissions — `session.read.all`, `session.update.all`,- `session.delete.all` — that carry the same three verbs as the `.own` family- over **every live session**, including the conversations the user created in- this app.--2. Keep `.own` exactly as it is.--3. Split the enforcement so the ownership predicate stops being a second,- implicit permission.-+1. Add `session.read.all`, `session.update.all`, and `session.delete.all`, which+ carry the same three verbs as the `.own` family over every live session,+ including conversations the user created in this app.+2. Keep `.own` exactly as it is, since `.all` is an addition and never a+ widening; a manifest may declare both and `.all` wins.+3. Split enforcement so the ownership predicate stops being an implicit second+ permission: Electron main resolves the scope from the granted permissions and+ sends the literal `scope` (`"own"` | `"all"`) to host-core, which enforces+ exactly what it is handed, reads an absent parameter as `"own"`, rejects an+ unknown value with `INVALID_PARAMS`, and still holds no permission data.4. Fix the queries that only worked because the boundary was narrow: `list`- becomes a `LEFT JOIN` on the origin sidecar so a session with no origin row- is reachable; `get` reports the real `originKind`, `modelId`, `providerId`,- and `bound.model` instead of the import projection; messages report `origin:- "external"` or `"desktop"`; and the `EXISTS` predicates inside the `purge`- and `trash` statements follow the scope instead of hard-coding ownership.--5. Expose message-level writes for the first time, because "modify any content"- was not a capability `pi.session` had: `appendMessage` and `replaceMessages`- under `session.update.all`, `deleteMessage` and `truncateFrom` under- `session.delete.all`.--6. Keep the brakes that are not about ownership: session delete stays at 20- calls/minute per plugin, the four message-level writes share a 60- calls/minute budget, and the existing import limits are untouched.--7. Keep `session.autoTitle` as it is.+ becomes a `LEFT JOIN` on the origin sidecar, `get` reports the real+ `originKind`, `modelId`, `providerId`, and `bound.model`, messages report+ `origin: "external"` or `"desktop"`, and the `EXISTS` predicates in `purge`+ and `trash` follow the scope.+5. Expose message-level writes for the first time — `appendMessage` and+ `replaceMessages` under `session.update.all`, `deleteMessage` and+ `truncateFrom` under `session.delete.all` — delegating to the existing+ host-core transcript operations, with a rewrite refused by `TURN_RUNNING`+ while a turn owns the session and `appendMessage` exempt.+6. Keep the brakes that are not about ownership: session delete stays at 20 calls+ per minute per plugin, the four message-level writes share a 60+ calls-per-minute budget, and `session.autoTitle` stays the narrow title path+ that implies no read grant.## Consequences-- A plugin can now read, rename, rewrite, and delete the user's own- conversations.-- `rename` now claims the manual title source.-- A session outside the caller's scope is `NOT_FOUND`, not `PERMISSION_DENIED`.-- `PluginSessionListItem.externalId` and `PluginSessionGetResult.externalId`- widen to `string | null`, and `PluginSessionMessageResult.origin` widens to- `"external" | "desktop"`.-- Audit records now name the scope that authorised a session call.+- A plugin can read, rename, rewrite, and delete the user's own conversations, a+ genuinely high-risk grant that the matrix, `HIGH_RISK_PERMISSIONS`, and the+ runtime-risk map all classify as `high`.+- `rename` claims the manual title source so a later `session.autoTitle` cannot+ overwrite a chosen title, and a session outside the caller's scope is+ `NOT_FOUND` rather than `PERMISSION_DENIED` so an `.own` plugin cannot probe for+ sessions it may not see.+- `externalId` widens to `string | null` and `origin` to `"external" | "desktop"`+ for `.all` holders only; every session call now audits one line with `scope`,+ and `sessionsChanged` carries an optional `sessionId` so the shell re-reads a+ rewritten active transcript.## Alternatives considered-### Widen the existing `.own` permissions instead of adding `.all`--Rejected. The install review is the consent surface, and a user who approved-"only the sessions this plugin imported" did not approve "every conversation I-ever had".--### Route plugin reads through `session.read` (the `getLlmContext` projection)--Rejected. That permission is scoped to an in-flight tool invocation and returns-a compaction-aware projection of the prompt, not a session.--### Give the plugin direct session RPC access--Rejected. It hands the plugin a generic host channel and removes the pluginId-provenance the audit relies on.--### Loosen the ownership filter and let the permission name alone carry the risk--Rejected. Removing the check without a scope would make every existing `.own`-grant a full-grant, which is the first alternative again.--### Keep message-level writes out of scope--Rejected for this change.--### Publish an `expectedRevision` precondition for message writes--Rejected for now. No session-wide revision counter exists; `revision` in this-codebase names a regenerate family, not a transcript version.+- Widen `.own` instead of adding `.all`: a user who approved "only the sessions+ this plugin imported" never approved every conversation.+- Route plugin reads through `session.read` / `getLlmContext`: that grant is+ scoped to an in-flight tool invocation and returns a prompt projection.+- Give the plugin direct session RPC access: it removes the pluginId provenance+ the audit relies on.diff --git a/docs/adr/0341-explicit-reviewed-file-actions.md b/docs/adr/0341-explicit-reviewed-file-actions.mdindex ad313860c..b6dba70f3 100644--- a/docs/adr/0341-explicit-reviewed-file-actions.md+++ b/docs/adr/0341-explicit-reviewed-file-actions.md@@ -6,39 +6,42 @@## Context-Review records approved Write/Edit operations outside the workspace, but the-normal file-open APIs deliberately accept only project and host-owned roots.-Widening those APIs would change unrelated filesystem authorization.+Review records approved Write/Edit operations outside the workspace, but the normal+file-open APIs deliberately accept only project and host-owned roots, and widening+them would change unrelated filesystem authorization. Rendering one footer per+operation also makes a file with several edits look like several independently+actionable files.## DecisionExternal open and folder reveal for a non-workspace review row use a dedicated-main-window-only IPC request containing session ID, snapshot ID and destination.-No renderer-supplied path is accepted.--The Review panel renders recorded hunks continuously with one copy/rollback-footer per file. Copy includes all recorded operations in order and does not-claim a net diff.+main-window-only IPC request carrying session id, snapshot id, and destination, so+no renderer-supplied path is accepted. The Rust host verifies that the snapshot+belongs to a successful persisted tool message in that session and resolves its+exact recorded file, and host plus main reject missing files, directories, sensitive+paths, and replacement symlinks before main opens the system default application or+reveals the file. That action grants no directory access and no capability to a+tool or plugin, generic `fsOpen`, `fsReveal`, and permission evaluation are+unchanged, and non-workspace file menus offer no internal open.++The Review panel renders recorded hunks continuously with one copy/rollback footer+per file: copy includes every recorded operation in order without claiming a net+diff, and file rollback selects the anchor snapshot's owning round and file on the+host, so the renderer cannot omit intermediate operations. Before restoring a file+the host validates the active hash chain, captured root, restoration bytes, and+current hash, conflicts leave both states untouched, and success updates each+participating snapshot and transcript state.## Consequences-- Recorded external files can be opened without relaxing the general path- sandbox.-- One file has one action bar, while individual immutable snapshots remain- intact.-- Discontinuous or conflicted chains cannot be partially rolled back.-- External snapshots remain non-reversible; explicit opening is not write- permission.-- Scope/history retain native selection behavior without changing shared- defaults.--## Alternatives rejected--- Add snapshot roots to general filesystem roots: grants more than the clicked- file.-- Accept a raw external path from Renderer: loses binding to native recorded- evidence.-- Repeatedly call single-snapshot rollback: can stop halfway through a file's- edits.-- Merge cached hunks into a purported net diff: bounded historical hunks do not- contain arbitrary complete after-images, so they cannot establish that claim.+- Recorded external files can be opened without relaxing the general path sandbox.+- One file has one action bar while individual immutable snapshots stay intact.+- A conflicted chain cannot be partially rolled back, and explicit opening is not+ write permission.++## Alternatives++- Add snapshot roots to general filesystem roots — rejected: it grants more than the+ clicked file.+- Accept a raw external path from the renderer — rejected: it loses the binding to+ native recorded evidence.diff --git a/docs/adr/0342-os-computer-use-capability.md b/docs/adr/0342-os-computer-use-capability.mdindex 03f903f7f..cf79408fb 100644--- a/docs/adr/0342-os-computer-use-capability.md+++ b/docs/adr/0342-os-computer-use-capability.md@@ -16,112 +16,155 @@## Context-The agent can drive web content: `pi.browser` owns a `WebContentsView` guest and-the bundled `Browser` tool reaches it over an allowlisted subset of CDP, using-the accessibility tree for element identity and `click(uid)` / `fill(uid)` for-input. Everything outside that guest is unreachable.+The agent drives web content only: `pi.browser` owns a `WebContentsView` guest and+the bundled `Browser` tool reaches it over an allowlisted CDP subset. Everything+outside that guest is unreachable, and because Live Voice reaches the Agent Runtime+through `delegate_to_work_session`, what a user can ask for is exactly the agent's+tool set — which stops at the workspace and the embedded browser.++"Computer Use browser takeover" was item 9 of the MVP non-goals, which froze only+what the MVP would not ship. The request now is a bounded, revocable, auditable way+to operate the machine, driven by a model the user picks, without taking the mouse+out of the user's hand. Nothing supports it today — there is no capture, synthetic+input, window enumeration, or accessibility client, and `enigo`, `robotjs`, and+`nut-js` are absent by design. The dangerous part is not capture: synthetic input+is indistinguishable from the user and can approve dialogs, including this+application's own permission cards.## Decision-1. **Native authority is host-core's; the decision loop is not.**- `crates/host-core` gains a `computer.*` RPC domain and owns target- enumeration, accessibility inspection, event synthesis, the grant broker, the- per-action re-validation, and the audit record — it is the only component- that can refuse.--2. **One high-risk tool, `Computer`, gated by the host and executed above it.**- It follows the `GenerateImages` shape: host-core classifies it `high`,- `tools.execute` performs the permission evaluation, and the handler runs in- Electron main once the host authorises.-+1. **Native authority is host-core's; the decision loop is not.** `crates/host-core`+ gains a `computer.*` RPC domain owning target enumeration, accessibility+ inspection, event synthesis, the grant broker, per-action re-validation, and the+ audit record — the only component that can refuse. The perceive-decide-act loop+ and capture live above it, needing a model provider and Chromium+ (`05-host-core-rust` §3). The renderer never receives a window handle, native+ element, or input primitive, and the sidecar reaches it only through the existing+ `host.proxy` `tools.execute` entry.+2. **One high-risk tool, `Computer`, gated by the host and executed above it.** Host+ classification marks it `high`, `tools.execute` evaluates the permission, and the+ handler runs in Electron main after authorisation. It is not a plugin tool, so no+ manifest can request that blast radius, and `computer.*` is not a public plugin+ API. It takes an instruction plus optional steps and exposes no list, focus, or+ switch-target operation.3. **Accessibility first, pixels as an explicit fallback.** `computer.inspect`returns a structured tree for the granted scope — role, name, value presence,- enabled, focused, bounds, and a per-grant opaque `uid` — and every action- addresses an element by `uid`, dispatched through the platform accessibility- action where one exists (`AXUIElement` actions, UIA patterns, AT-SPI- actions).-+ enabled, focused, bounds, and a per-grant opaque `uid` — and actions address a+ `uid` through the platform accessibility action (`AXUIElement`, UIA patterns,+ AT-SPI). Capture is scope-cropped and produces a `basis` of grant revision plus+ measured window geometry, re-validated immediately before coordinate synthesis and+ refused on mismatch, so a blind click is impossible and a moved window fails+ closed.4. **A scope grant is the unit of authority, and only the user can mint one.**- *(Amended by [ADR 0344](0344-computer-use-whole-desktop-grant.md): the grant- is minted automatically and covers the desktop, one window bound at a time;- the picker is gone and the model may switch between windows the host does not- refuse. The revision, budget, expiry, single-grant rule, and session- ownership below are unchanged.)* A grant names exactly one target — one- window, or one application's windows — chosen by the user in a host-driven- picker.--5. **Two refusals are absolute and not reachable by any permission mode,- setting, grant, or `auto` policy.** First, the capability never targets- PI-Desktop's own windows — its approval cards, its settings, its secrets- surfaces, its Live Voice widget — because synthetic input into this- application is a direct permission-broker bypass.-+ *(Amended by [ADR 0344](0344-computer-use-whole-desktop-grant.md): the grant is+ minted automatically for the desktop, one window bound at a time, and the picker is+ gone; the revision, budget, expiry, single-grant rule, and session ownership below+ stand.)* A grant names exactly one user-chosen target and carries a revision, an+ action budget, an idle expiry, and an input policy. The model cannot name,+ request by title, enumerate, or widen a target, and a call outside scope is an+ error rather than a prompt to expand. At most one grant is active per instance,+ mirroring the single Live Voice slot, bound to the session and turn chain that+ owns it, so a subagent inherits it but cannot mint a second.+5. **Two refusals are absolute and reachable by no permission mode, setting, grant,+ or `auto` policy.** The capability never targets PI-Desktop's own windows —+ approval cards, settings, secrets surfaces, Live Voice widget — because input+ there is a direct permission-broker bypass. Capture and synthesis both refuse+ while the OS reports a secure input state or the focused element is a password+ field. A user-editable application denylist sits on top, with non-removable+ credential-surface entries.6. **The permission mode governs the grant, not each keystroke.** *(Amended by- [ADR 0344](0344-computer-use-whole-desktop-grant.md): `autonomous-in-scope`- is the default under every mode, `confirm-each` is specified but unbuilt, and- Stop both revokes the grant and aborts the turn, with a cooldown on the- agent's next automatic mint.)* Creating a grant is always an explicit- desktop-UI decision with no deadline, like every other local approval (ADR- 0310); `auto` does not mint grants, and a spoken request cannot.--7. **Plan and Goal hard-deny `Computer` before permission evaluation**, exactly- like `Write` and `Edit`.--8. **The agent is the only caller in the first release; voice comes later.** The- spoken path is specified and deliberately not built: Live Voice would reach- `Computer` as an ordinary work request through the existing- delegate/classifier/Agent-turn path and would gain no authority of its own,- but nothing in the first release wires it, and the voice feature ships- unchanged.--9. **The agent's own model does not have to drive the machine.** Computer use- carries its own model binding — one `{ providerId, modelId }` the user picks- in settings from the existing provider rows, following the `imageGeneration`- precedent — and a bounded perceive-decide-act loop uses that model to turn- one instruction into validated steps.--10. **The agent's pointer is drawn, not stolen.** Every action is dispatched- through an accessibility action or a window-targeted event, so the real- system cursor never warps and the user keeps their mouse and keyboard while- the agent works.--11. **Supported platforms are declared, and the unsupported ones fail closed.**- macOS uses `AXUIElement` behind the Accessibility TCC grant, with- `CGEventPostToPid` for key input into the granted application only.--12. **Every grant and every action is audited; content is not.** The existing- `audit.*` sink records the grant identity, target identity, action kind,- element role and `uid`, and outcome.--13. **Delivery is staged, and each stage is independently shippable.** Stage 1- is the MVP: contracts, the grant broker and its refusals, the macOS backend,- the bounded loop with its own model binding, the virtual-cursor overlay, the- picker, the indicator, settings, and audit — agent-callable, no voice.+ [ADR 0344](0344-computer-use-whole-desktop-grant.md): `autonomous-in-scope` is the+ default under every mode, `confirm-each` is specified but unbuilt, and Stop both+ revokes the grant and aborts the turn.)* Minting is always an explicit desktop-UI+ decision with no deadline (ADR 0310); `auto` does not mint grants and neither does+ a spoken request. Inside a grant `inspect` and `screenshot` need no approval,+ while input follows the grant policy — `confirm-each` raises a card per input+ batch and `autonomous-in-scope` requires opt-in at mint time — always inside the+ budget, the expiry, scope re-validation, and a kill switch: the indicator's Stop,+ a global shortcut, and revocation.+7. **Plan and Goal hard-deny `Computer` before permission evaluation**, like `Write`+ and `Edit`: it mutates state outside the workspace that the host cannot snapshot,+ diff, or roll back.+8. **The agent is the only caller in the first release; voice comes later.** Live+ Voice would reach `Computer` as an ordinary work request and gain no authority of+ its own, but nothing wires it yet, and grant creation plus every approval card stay+ desktop-UI decisions (ADR 0315).+9. **The agent's own model need not drive the machine.** Computer use carries its own+ `{ providerId, modelId }` binding after the `imageGeneration` precedent, and a+ bounded perceive-decide-act loop turns one instruction into validated steps. The+ loop is a pure module in `packages/computer-use` that receives an observation,+ asks for one action against a strict schema, and refuses anything else; the main+ agent sees a bounded summary. With no binding the tool reports a configuration+ error instead of falling back to the conversation model.+10. **The agent's pointer is drawn, not stolen.** Actions dispatch through an+ accessibility action or a window-targeted event, so the real cursor never warps+ and the user keeps their mouse and keyboard. A frameless, transparent,+ click-through, always-on-top overlay draws a virtual cursor; it owns no part of+ the action, receives no input, and its failure never blocks one. A path that+ could only act by warping the real pointer is refused.+11. **Supported platforms are declared, and the rest fail closed.** macOS uses+ `AXUIElement` behind the Accessibility TCC grant with `CGEventPostToPid` for key+ input into the granted application; Windows uses UI Automation with+ window-targeted messages and refuses higher-integrity windows; Linux/X11 is+ best-effort over AT-SPI; Wayland refuses input with an explicit code while+ capture stays available through the portal. Capture is Chromium's+ `desktopCapturer`, scope-cropped in main. Every unsupported path is a distinct+ error code, never a hang or a silent no-op, and a partial-fidelity backend says+ so in its own `inspect` result.+12. **Every grant and action is audited; content is not.** The `audit.*` sink records+ grant identity, target identity, action kind, element role and `uid`, and the+ outcome. Typed text is recorded as a length, never a value, and pixels never+ enter the audit log; screenshots follow the existing lossless tool-image path,+ and an `a11y-only` grant captures no pixels, which the grant card states before+ approval.+13. **Delivery is staged and each stage ships independently.** Stage 1 is the MVP:+ contracts, grant broker and refusals, the macOS backend, the bounded loop with its+ binding, the overlay, the picker, the indicator, settings, and audit.+ Stage 2 adds Windows and Linux behind the same contract and refusals, Stage 3 the+ voice-facing refinements. Non-goal item 9 is amended, not deleted: unattended+ full-desktop takeover and model-chosen targets remain non-goals.## Consequences-- A new, genuinely dangerous privilege enters the product.+- A genuinely dangerous privilege enters the product, mitigated by structure rather+ than prompting: one user-picked target, a revision checked per action, two absolute+ refusals, a budget, an expiry, one grant per instance, and an audit trail. The+ refusals in decision 5 must be covered by tests before shipping.- host-core gains its first platform-specific native surface beyond process- spawning, and with it three per-OS implementations.-- The inner loop spends tokens on a model the conversation did not choose, so- the bound model, its step count, and its cost are the user's decision and have- to be visible: the binding is explicit in settings, the loop is bounded by the- grant's action budget, and the tool result names how many steps ran.-- A drawn cursor is not the system cursor, so it can disagree with reality — a- window that moves mid-step leaves the overlay briefly wrong.-- The product acquires OS permission prompts it never had.+ spawning; the macOS backend uses hand-declared framework FFI rather than new+ crates, each later backend carries its own dependency review, and unimplemented+ targets must compile to a clean "unsupported on this platform".+- The loop spends tokens on a model the conversation did not choose, so the binding,+ step count, and cost must be visible: the binding is explicit, the loop is bounded+ by the grant budget, and the tool result names the steps run.+- A drawn cursor can disagree with reality when a window moves mid-step, so the+ overlay is never the source of truth; the host's re-measurement is.+- The product acquires OS permission prompts it never had, so a doctor view reports+ Screen Recording and Accessibility state per platform. Native trust stays+ host-core's `accessibility` reading; an application-level grant is display-only and+ a disagreement is shown rather than copied into native authority.+- Screenshots of the desktop can enter a transcript and therefore SQLite — a real+ privacy change that `a11y-only` grants avoid — and five UX surfaces are added:+ target picker, grant indicator with Stop, grant card, settings page with binding+ and doctor, and the cursor overlay.## Alternatives-- **Extend the `Browser` tool to the whole desktop.** It is a bundled plugin on- a public permission; any plugin declaring `browser.cdp` would inherit desktop- input.-- **Expose computer use as a plugin host API.** It makes the most dangerous- privilege in the product requestable by a third-party manifest, and plugin- grants are reviewed once at install rather than per target.-- **Pixels only, with a computer-use provider model choosing coordinates.** It- works anywhere, including canvas and custom-drawn UI, but every step ships the- user's screen to a provider, costs a vision call per action, and breaks on any- reflow.-- **Accessibility only, with no capture at all.** Safest, and it is exactly what- an `a11y-only` grant is.+- **Extend the `Browser` tool to the whole desktop.** Any plugin declaring+ `browser.cdp` would inherit desktop input. Rejected.+- **Expose computer use as a plugin host API.** Makes the most dangerous privilege+ requestable by a manifest reviewed once at install. Rejected.+- **Pixels only, with the model choosing coordinates.** Ships the screen to a+ provider every step and breaks on reflow; kept as the fallback in decision 3.+- **Accessibility only, with no capture.** Exactly what an `a11y-only` grant is, but+ it cannot operate canvas apps or custom toolkits.+- **A real-time voice teleoperation loop driving input directly.** Bypasses the+ classifier, session policy, approval cards, and transcript. Rejected.+- **Let the model pick the target window.** Removes the only guarantee that the agent+ operates on what the user meant. Rejected.+- **Drive the real system pointer with `SendInput`/XTEST/`CGWarpMouseCursorPosition`.**+ Fights the user for their mouse and is hard to stop; rejected.+- **Reuse the conversation model, or run the loop in host-core or the renderer.**+ Forces a vision chat model on everyone, or gives the authority to a component with+ no provider SDK and no Chromium, or to the process that must never hold it.+ Rejected.diff --git a/docs/adr/0343-plugin-launcher-local-apps.md b/docs/adr/0343-plugin-launcher-local-apps.mdindex 0995f7920..343814ce6 100644--- a/docs/adr/0343-plugin-launcher-local-apps.md+++ b/docs/adr/0343-plugin-launcher-local-apps.md@@ -2,75 +2,60 @@- Status: Accepted- Date: 2026-11-05-- Deciders: PI-Desktop maintainers- Related: ADR 0072 (global plugin launcher), ADR 0080 (prewarm), ADR 0090(main-process shell state), ADR 0092 (plugin-owned panel surface),- ADR 0214 (trusted extensions), `docs/spec/07-plugins/18-plugin-launcher.md`,- `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-268), issue #2085+ ADR 0214 (trusted extensions), issue #2085## Context-The plugin launcher (`Alt+Space` / `⌥+Space`) opens panel plugins. Users who-press that shortcut are usually reaching for "the thing I want to open now", and-in practice that is as often an installed application as it is a plugin panel.--- It reads the machine's Start Menu / `.app` bundles / `.desktop` entries.-- It starts a child process outside the app's own sandbox and permission- gateway.-- A plugin declaring a launcher pattern would, if it could reach this, be able- to turn "the user typed `1+1`" into "start any program on this machine".+A user pressing Alt+Space is reaching for whatever they want to open now, which is+as often an installed application as a plugin panel. Enumerating and starting+local applications has a much wider blast radius than opening a panel: it reads+platform application entries and starts child processes outside the app's own+sandbox and permission gateway, so neither a renderer-side launch API nor a+plugin-visible one may exist.## Decision-1. The plugin launcher may enumerate installed applications and open them, and- only that window may do so.-2. The capability is never exposed to plugins.-3. The renderer never receives a launchable path.-4. Discovery is bounded and non-invasive.-5. The launcher's size and position live in main-process shell state (`<data- dir>/plugin-launcher-state.json`), not in host-core.+1. Only the launcher window may enumerate and open applications, through one IPC+ surface (`pi-desktop/pluginLauncher/catalog`,+ `pi-desktop/pluginLauncher/openApp`) whose handler compares+ `event.sender.id` with the launcher's own `webContents` and rejects anything+ else with `PERMISSION_DENIED`; a missing launcher window means "not the+ launcher".+2. The capability is never exposed to plugins. No channel joins `pluginBridge` or+ the panel bridges and no application-launch member joins the Plugin SDK, so a+ plugin can receive the user's text through a launcher trigger but cannot learn+ what applications exist or start one.+3. The renderer never receives a launchable path. The catalog carries a display+ name, executable name, source tag (`start-menu` / `app-bundle` /+ `desktop-entry`), a small icon, and an opaque `app:<slug>` id, and `openApp`+ resolves that id against the host's own scan and re-checks that the target+ still exists instead of falling back.+4. Discovery is bounded and non-invasive: Main reads only well-known locations,+ never spawns a probe, caches the scan, caps the entry count and icon budget,+ drops entries whose target is gone, and draws a letter tile for plugin panels+ because `manifest.icon` is not consumed by the host.+5. Launcher size and position live in main-process shell state under the app data+ directory, following the `window-state.json` precedent from ADR 0090:+ best-effort, debounced, defensively parsed, and re-centred when a remembered+ position fits no current work area, with no host RPC, schema, or migration.## Consequences-- One shortcut opens "anything openable" — plugin panels and installed- applications — in one grid that renders every source as the same rounded- square.-- The privilege boundary is a window, not a permission: revoking it means- removing the channel, not editing a plugin manifest.-- Because the renderer only ever holds opaque ids, the catalog is display-safe:- it can be logged or inspected without leaking filesystem layout, and the same- id space works on all three platforms.-- Application entries can be stale between scans.-- A user who does not want applications in the launcher still gets the scan.--## Alternatives considered--### Expose application launch to plugins--Rejected. A plugin with a panel would gain the ability to start arbitrary-programs on the user's machine, which no permission in-`13-plugin-permissions-matrix.md` describes and which install-time review could-not make safe.--### Let the renderer supply the executable path--Rejected. Even with a sender check, accepting a path makes the IPC a-general-purpose process launcher: the check protects against other renderers,-not against a compromised launcher page, and the launcher page renders-plugin-supplied names and icons.--### Store launcher geometry in host-core settings--Rejected as the wrong owner.--### Reuse the main window for the launcher instead of a second `BrowserWindow`--Rejected: the panel must float above other applications, stay focusable while-the main window is hidden, and hide on blur without touching the main window's-lifecycle.--### Fold applications into global search (`Cmd/Ctrl+K`)--Rejected. Global search owns sessions, files, settings, and commands, and is a-modal over the main window; local applications are a machine-local, potentially-600-entry list that would dominate any mixed result set.+- One shortcut opens both plugin panels and applications in one grid, at the cost+ of no longer distinguishing them before opening.+- The privilege boundary is a window rather than a permission, and the catalog is+ display-safe because the renderer only ever holds opaque ids.+- Application entries can go stale between scans, and the launcher becomes+ platform-sensitive with its own parsers and tests; shell state gains a second+ file that is deliberately excluded from configuration export.++## Alternatives++- Expose application launch to plugins: rejected because no permission in the+ matrix describes starting arbitrary programs, and install-time review could not+ make it safe.+- Let the renderer supply the executable path: rejected because a sender check+ protects other renderers, not a compromised launcher page, and path acceptance+ would make the IPC a general-purpose process launcher.diff --git a/docs/adr/0344-computer-use-whole-desktop-grant.md b/docs/adr/0344-computer-use-whole-desktop-grant.mdindex 3d264c53c..3fb68c886 100644--- a/docs/adr/0344-computer-use-whole-desktop-grant.md+++ b/docs/adr/0344-computer-use-whole-desktop-grant.md@@ -1,80 +1,59 @@# ADR 0344: Computer use grants the whole desktop automatically, and Stop is the boundary-- Status: Accepted+- Status: Accepted (amends ADR 0342 §4 and §6; the rest of ADR 0342 stands)- Date: 2026-11-04-- Decision: D682-- Deciders: PI-Desktop core-- Related: [ADR 0342](0342-os-computer-use-capability.md) ·- [ADR 0310](0310-local-permission-approvals-without-deadline.md) ·- [03-runtime/computer-use](../spec/03-runtime/computer-use.md) ·- [05-security/01-security](../spec/05-security/01-security.md) ·- [03-runtime/08-error-codes](../spec/03-runtime/08-error-codes.md)+- Related: D682, ADR 0310, ADR 0342## Context-This amends [ADR 0342](0342-os-computer-use-capability.md) §4 (the user-minted-scope grant) and §6 (the input policy). Everything else in 0342 stands.+ADR 0342 built computer use around one user-picked window, where the picker was the only+way to mint a grant and the model could not name, enumerate, or widen a target, which+fails the capability it exists for: a request like "find the invoice in Mail, then enter+it in the spreadsheet" spans applications. Reducing a security boundary needs its own+decision, so the picker's weight moves to the refusals, the Settings enable switch, and+Stop, while host-core still owns every refusal, the renderer holds no handle or input+primitive, and the absolute refusals stand.## Decision-1. **A grant has a scope, and the default scope is the desktop.** `Grant` gains- `scope: desktop | window`.--2. **The agent mints its own grant; there is no picker.** The `Computer` tool- handler in Electron main calls `computer.grantCreate` with no `targetId` on- the first call of a session that has no live grant.--3. **Rebinding is a refusal path, not a convenience.** `computer.inspect` takes- an optional `targetId`.--4. **A closed window does not end a desktop grant, but it does end the action.**- If the bound window disappears, a desktop grant falls back to the frontmost- usable window through the same refusals.--5. **The model may move between windows, and is told what it may not touch.**- The observation lists the host's own enumeration — including refused windows- with their reason — and the answer schema gains exactly one new kind,- `{"kind":"switch","window":"<id>"}`.--6. **Runs are autonomous by default.** `COMPUTER_USE_DEFAULTS.inputPolicy`- becomes `autonomous-in-scope`, and `autonomous-in-scope` is available under- every permission mode rather than requiring `accept-edits` or `auto`.--7. **Stop ends the run, not the call.** The indicator's Stop revokes the grant- *and* aborts the turn that holds it, and host-core records the revocation: an- agent-originated `grantCreate` within `AGENT_REGRANT_COOLDOWN` (30s) is- refused with the new `COMPUTER_STOPPED_BY_USER`.--8. **The absolute refusals and the denylist are unchanged, and now matter- more.** PI-Desktop's own windows (by pid, parent pid, and app key) are never- a target, secure input refuses both capture and synthesis, and the built-in- credential-surface denylist cannot be removed.--9. **Capture stays opt-in.** `a11y-only` remains the default capture mode: a- desktop-wide grant that screenshotted by default would put arbitrary windows- into the session transcript.--10. **The audit trail follows the scope.** A grant creation records its scope- and whether the agent or the user minted it; a rebind appends- `computer.grant.rebound` with the application identity it moved to.+`Grant` gains `scope: desktop | window`, where a desktop grant binds to exactly one+unrefused frontmost window and may rebind to any accepted one, while a window grant is+pinned and refuses to move. The agent mints its own grant: on the first call of a session+without a live grant, the `Computer` tool handler in Electron main calls+`computer.grantCreate` with no `targetId`, because enabling the feature is the consent,+and the renderer loses the enumeration and minting channels. Rebinding is a refusal path,+where `computer.inspect` takes an optional `targetId`, re-runs the self-target, denylist,+and elevation checks against a fresh enumeration, and always moves the grant revision so+previous `uid` and `basis` values stop validating, while `computer.act` never binds and an+action aimed at a vanished window is refused with `COMPUTER_STALE_REVISION`. The+observation lists the host enumeration with refused windows and their reason, and the+answer schema gains exactly one kind, `{"kind":"switch","window":"<id>"}`, which spends a+loop step rather than action budget and is re-checked against the host list.+`COMPUTER_USE_DEFAULTS.inputPolicy` becomes `autonomous-in-scope` under every permission+mode, bounded by the action budget, idle expiry, per-action re-validation, and Stop, while+`confirm-each` stays in the contract but unimplemented and its Settings row is removed.+Stop revokes the grant and aborts the turn holding it, and an agent-originated+`grantCreate` within `AGENT_REGRANT_COOLDOWN` is refused with `COMPUTER_STOPPED_BY_USER`+so the next tool call cannot make Stop meaningless, while a user-originated mint clears+the cooldown. PI-Desktop's own windows are never a target, secure input refuses capture+and synthesis, the credential-surface denylist cannot be removed, capture stays opt-in+with `a11y-only` as the default, and the audit trail records grant scope, minter identity,+and `computer.grant.rebound` with the application identity, never window text, typed+values, or pixels.## Consequences-- The product's most dangerous capability no longer has a per-use human decision- in front of it.-- Prompt injection reaches further.-- A user watching one window can be surprised by the agent working in another.-- `confirm-each` is now visibly unbuilt rather than quietly unenforced.-- Stop aborting the turn is a behaviour change beyond computer use: pressing it- stops the agent's current work, not just its screen access.+- The most dangerous capability no longer has a per-use human decision: enabling it means+ the agent may read and operate the user's applications, and the Settings copy says so.+- Prompt injection reaches further, since a hostile window can steer the agent toward+ another application and a user watching one window can be surprised by work in another;+ the step limit, action budget, single-action-per-answer schema, and audit trail bound it.+- Stop aborting the turn stops the agent's current work beyond computer use, and Windows+ and Linux still answer `COMPUTER_PLATFORM_UNSUPPORTED` until the stage 2 backends land.## Alternatives-- **Keep the picker and add a "switch target" request.** The agent would ask,- the user would approve per window.-- **Read the whole desktop, but keep input pinned to one picked window.**- Attractive, because reading is the less dangerous half.-- **Follow the frontmost window automatically, with no switching.** No- enumeration and no window ids reach the model, which is tidier.-- **Implement `confirm-each` and keep it as the default.** This is the right- long-term answer for a desktop-wide scope and remains the plan.+- Keep the picker with a "switch target" request: the friction the owner rejected, and+ approval fatigue would make the dialogs meaningless.+- Read the desktop but pin input to one window: tasks span applications, and the model+ would see buttons it may not press.diff --git a/docs/adr/0345-one-settings-destination-one-subject.md b/docs/adr/0345-one-settings-destination-one-subject.mdindex d8cb3f579..4829e65e0 100644--- a/docs/adr/0345-one-settings-destination-one-subject.md+++ b/docs/adr/0345-one-settings-destination-one-subject.md@@ -11,28 +11,26 @@## Context-The Settings directory grew one destination at a time. D133 shipped five, D166-split out AI and Shortcuts to make seven, and later decisions added-Instructions, the three capability pages, Projects, Voice, Cloud sync and Remote-Hosts.--- **General** carried the Appearance card (theme, language, font, font size,- translucency, startup animation) next to the Sidebar switches, the radial- menu, the outbound proxy, the application data directory and its cold- maintenance, two sleep blockers, the scheduled-tasks master switch, and the- window's close behavior.-- **AI** carried Permissions as a one-row card, then a **Defaults** card that- had reached thirteen rows: the default operating mode, the command shell, the- link open destination, show thinking, auto-fold thinking, transcript display,- auto-fold settled groups, the context ring's leading figure, Enter-to-send,- infinite provider retry, smooth streaming, inline visualizations, and the- large-paste threshold.+The Settings directory grew one destination at a time (D133, D166, then+Instructions, the capability pages, Projects, Voice, Cloud sync, and Remote+Hosts). Two destinations were never given a subject — they took whatever had no+page yet. **General** carried the Appearance card beside the Sidebar switches, the+radial menu, the outbound proxy, the application data directory, two sleep+blockers, the scheduled-tasks switch, and window close behavior: eight cards,+three unrelated subjects. **AI** carried Permissions as a one-row card beside a+**Defaults** card of thirteen rows. "Defaults" is not a subject; it is the absence+of one.-## Decision+This is findability before aesthetics. Since D601 a row's explanation lives behind+a question mark, so a reader who cannot predict which page owns a setting must+hover a whole page to find out, and two pages owning three subjects each turns that+into hovering the product. Search already indexed every row; the gap was that the+rail's structure matched no model a user could hold.-**A settings destination owns exactly one subject.** A subject that belongs to-no destination is a missing destination, not an extra card on an unrelated page.+## Decision+**A settings destination owns exactly one subject.** A subject that belongs to no+destination is a missing destination, not an extra card on an unrelated page.Applied to the two unowned pages, that yields four destinations where there weretwo:@@ -43,46 +41,63 @@ two:| Behavior | What a run starts with and may do | Session defaults · Execution · Computer use || System | This installation | Network · Storage · Power · Close behavior (Windows/Linux) |-1. **Permission mode is not its own card.** It joins the default operating mode- and the command shell in **Session defaults**, because all three answer one- question — what a new conversation starts with.-2. **Scheduled tasks is agent behavior, not chrome.** It withholds scheduled- Agent tools and blocks new runs at the Host; the footer clock is a- consequence, not the subject.-3. **The retired ids stay resolvable.** `general` → Appearance and `ai` →- Behavior, through `resolveSettingsTab`.+The directory is fifteen destinations in the four existing clusters; the order and+glyph per destination are in [04-ux/06-settings-ia](../spec/04-ux/06-settings-ia.md)+§1. Subagents takes the `Sparkles` glyph the retired AI destination released.++Three judgement calls are worth stating:++1. **Permission mode is not its own card.** It joins the default operating mode and+ command shell in **Session defaults**, because all three answer what a new+ conversation starts with; a page made of one-row cards is the pile this ADR+ removes.+2. **Scheduled tasks is agent behavior, not chrome.** It withholds scheduled Agent+ tools and blocks new runs at the Host; the footer clock is a consequence.+3. **The retired ids stay resolvable.** `general` → Appearance and `ai` → Behavior+ through `resolveSettingsTab`, so a persisted selection, native menu item,+ capture scene, or older deep link opens a real page. Neither id appears in the+ directory or in search results.++Two presentation rules accompany the IA:- A destination may declare **one subtitle line** under its title, and each page- repeats its rail glyph at page scale on an accent-tinted fill.-- A card may carry **one visible caption line** under its heading.+ repeats its rail glyph at page scale on an accent-tinted fill; destinations whose+ content already opens with a description declare no subtitle.+- A card may carry **one visible caption line** under its heading, the first+ always-visible explanatory copy since D601: a caption orients a group, a row's+ explanation stays behind its question mark, and a second sentence still belongs+ there.++The selected rail row takes an accent-tinted pill with an accent glyph; both tints+are fills rather than strokes, inside the in-flow surface rule (D297).## Consequences-- **No data or protocol change.** Every `AppSettings` field keeps its name, type- and default; no IPC message, host protocol version or storage schema version- moves.-- **Deep links and search stay correct by construction.** The destination index+- **No data or protocol change.** Every `AppSettings` field keeps its name, type,+ and default, and no IPC message, host protocol version, or storage schema version+ moves; only which page renders which row changes.+- **Deep links and search stay correct by construction**: the destination index(`lib/settings-search.ts`) remains the single source for the rail, the ⌘K- dialog, and the keyword index; new rows are added there, and the retired-id- table lives beside it.-- **The renderer shell becomes a router.** Each destination is a module under+ dialog, and the keyword index, with the retired-id table beside it.+- **The renderer shell becomes a router**: each destination is a module under`features/settings/pages/`, so `SettingsPage.tsx` does not acquire a fifthsubject of its own.-- **Copy that named a destination had to move too.** The proxy and- network-policy messages in all nine catalogs said "Settings → General →- Network"; they now say System.-- **Cost.** Fifteen rail rows instead of twelve, and users who had learned- "General" must learn two names.--## Alternatives considered--- **Reorder the cards inside General and AI.** Cheapest, and it was the first- thing tried on paper.-- **Split the cards but keep the two destination names.** Keeps every deep link- and every piece of copy valid.-- **Collapse the rail into two levels (cluster → destination).** Would hold more- destinations, but the clusters are visual landmarks over a flat searchable- index (§1), and a second interactive level adds a navigation step to every- setting to solve a problem fifteen rows do not have.-- **Make every row's explanation permanently visible.** Addresses the same- findability complaint from the other end.+- **Copy naming a destination moved too**: proxy and network-policy messages in+ every catalog now say System instead of "Settings → General → Network".+- **Cost**: fifteen rail rows instead of twelve, and users who learned "General"+ must learn two new names.+- **Scope**: this does not touch other destinations beyond their order, the+ full-page shell, rail metrics, row primitives, or add a navigation level under a+ cluster heading.++## Alternatives++- Reorder the cards inside General and AI: rejected, ordering changes which card is+ first, not what the page is about, and "Defaults" would still be where undecided+ rows land.+- Split the cards but keep the two names: rejected, "General" and "AI" are the+ names that invited the pile.+- Collapse the rail into two levels: rejected, clusters are visual landmarks over a+ flat searchable index and a second level taxes every setting.+- Make every row's explanation permanently visible: rejected, it reverses D601 and+ makes each page several screens taller.diff --git a/docs/adr/0346-composer-agent-mentions.md b/docs/adr/0346-composer-agent-mentions.mdindex 0c839a971..a759afbc4 100644--- a/docs/adr/0346-composer-agent-mentions.md+++ b/docs/adr/0346-composer-agent-mentions.md@@ -2,47 +2,44 @@- Status: Accepted- Date: 2026-11-06-- Deciders: PI-Desktop core- Related: [ADR 0024](0024-composer-commands-and-file-references.md) ·[ADR 0062](0062-bounded-subagents-behind-a-task-tool.md) ·- [04-ux/08-component-spec §11.8](../spec/04-ux/08-component-spec.md) ·issue #986 · prior design in PR #1101 (@f4ct0r)## Context-A subagent was reachable only when the model decided to call `Task`. Work the-user already knows is separable — "ask the explorer where the retry policy-lives" — had no entry point.+A subagent was reachable only when the model decided to call `Task`, so work the+user already knows is separable had no entry point. Everything downstream of+delegation keys off "this turn contains a `Task` call", so the missing piece is an+entry point rather than a second execution path — the shape `/skill:<id>` already+solved.## Decision-1. **Trigger.** `@` already means "reference an entity", so the `@` menu gains- an **Agents** group above the file rows (each group with its own heading),- listing the same catalog `Task` is built from (`subagentCatalog`).-2. **Resolution at send.** Main resolves `@name` tokens against the launch's- subagent catalog.- - the turn runs in **Agent mode** — the only mode that may execute `Task`- (ADR 0062 §4); Plan and Goal omit the group and leave a hand-typed mention- as literal text;- - it names a catalog subagent; and- - the local workspace root holds **no file or folder of that name** — a- project that really has an `explorer` file keeps the file.-3. **Prompt.** The model receives a short instruction to call `Task` with the- named agents, followed by the unchanged draft (the `@name` tokens stay so- each brief can be written from the part addressed to it).-4. **Persistence.** The user row stores `command` (typed text) and- `agentMentions: [{ start, end, name }]` (UTF-16 offsets) in record meta- beside `skillMentions`.-5. **Transcript.** The typed form renders with each validated mention as a chip- and the surrounding text as text.-6. **Smart stop.** Without a local draft snapshot, Stop restores a row's- `command` instead of its `content`, so the composer never receives the model- instruction.+1. **Trigger.** The `@` menu gains an **Agents** group above the file rows, listing+ the `subagentCatalog` that `Task` is built from; accepting a row inserts the same+ atomic inline chip a file gets, serialized to `@name` only at send time with a+ space on either side when a neighbor is not whitespace.+2. **Resolution at send.** Main resolves `@name` tokens against the launch's subagent+ catalog, and a token is a delegation only in Agent mode (ADR 0062 §4), only for a+ catalog subagent, and only when the workspace root holds no file or folder of that+ name; Plan and Goal omit the group.+3. **Prompt.** The model receives a short instruction to call `Task` with the named+ agents followed by the unchanged draft, Skills load before delegation, and a+ leading template or app command keeps its behavior.+4. **Persistence.** The user row stores `command` and+ `agentMentions: [{ start, end, name }]` (UTF-16 offsets) in record meta beside+ `skillMentions`, with no SQL migration.+5. **Transcript.** The typed form renders each validated mention as a chip, and+ offsets that do not point at an `@token` fall back to plain text.+6. **Smart stop.** Without a local draft snapshot, Stop restores a row's `command`+ instead of its `content`, so the composer never receives the model instruction,+ which also corrects the same gap for templates and Skills.## Consequences-- This is a strong prompt, not an enforced dispatch — the same trade-off- `/skill` accepts.-- The `@` menu reads the delegation catalog with the same short TTL as the file- index; a failed read only empties the Agents group.-- No IPC, Plugin SDK or schema-version change.+- This is a strong prompt, not an enforced dispatch: enforcing it would need a public+ runtime entry point for a private tool, a new RPC, and a synthetic parent row.+- A failed catalog read only empties the Agents group.+- No IPC, Plugin SDK, or schema-version change; one optional field is added to the+ persisted user message.diff --git a/docs/adr/active-turn-steering.md b/docs/adr/active-turn-steering.mdindex da16095d0..aee6664d3 100644--- a/docs/adr/active-turn-steering.md+++ b/docs/adr/active-turn-steering.md@@ -6,22 +6,36 @@## Context-The Composer queues follow-ups, but cannot redirect a running turn. A second+The Composer queues follow-ups but cannot redirect a running turn, and a secondprompt is correctly rejected with `AGENT_BUSY`. pi-agent-core already supplies-`Agent.steer`; Codex's [turn/steer-contract](https://learn.chatgpt.com/docs/app-server#steer-an-active-turn)-provides the expected-turn admission model.+`Agent.steer`, and Codex's turn/steer contract provides the expected-turn+admission model to follow.## Decision-Keep Send/Enter as follow-up. Alt+Enter (Option+Enter on macOS) uses an additive-`agent/steer` channel with `expectedTurnId`.--Steering keeps the active configuration and durable turn. Local foreground shell-and read calls receive cancellation; the runtime waits for their results before-the next request, without the normal Stop grace timeout.--## Consequences and validation--No new provider transport, host protocol version, or storage migration is-required.+Send and Enter stay follow-up; Alt+Enter (Option+Enter on macOS) uses an additive+`agent/steer` channel carrying `expectedTurnId`, with the existing queue slice+submitting optimistic input and restoring rejected drafts, the IPC handler+reusing attachment validation against the running model and workspace, and the+sidecar rechecking the target before calling `Agent.steer`.++Steering keeps the active configuration and durable turn: local foreground shell+and read calls are cancelled and awaited without the normal Stop grace, an+unconfirmed shell failure stays pending until Stop, calls not yet started are+skipped, `TaskWait` yields without cancelling its delegates (issue #1607), and+Stop closes admission while retaining accepted input as history. The event+persistence module journals input through the outbox, `precedingAssistant`+reserves an unfinished reply's position, and the persisted `UiMessage.steering`+marker protects input from Smart Stop across renderer reload, while host+provenance treats steering into a claimed collaboration delivery turn as extra+human input that must target that delivery's session and strips any+client-supplied `session_message` (D597).++## Consequences++- No new provider transport, protocol version, or storage migration is required.+- Streaming reservation updates remain the only exception to append-only message+ persistence.+- Existing regression suites cover surrounding behavior, and+ E2E-AGENT-alt-enter-steers-active-turn stays Draft until rendered E2E+ validation is performed.diff --git a/docs/adr/append-only-review-state.md b/docs/adr/append-only-review-state.mdindex 2e7b09c3f..e0c91f736 100644--- a/docs/adr/append-only-review-state.md+++ b/docs/adr/append-only-review-state.md@@ -7,53 +7,42 @@## ContextRolling back one historical tool card loaded the complete session and called-`replace_messages` to persist `details.review.state`. This rewrote the entire-transcript and rebuilt every SQLite message index row under the Host state lock.+`replace_messages` to persist `details.review.state`, rewriting the whole transcript+and rebuilding every SQLite message index row under the host state lock, although only+one small metadata value changed. Appending a replacement message instead would move+its physical position and break bounded history navigation.## Decision-Append a distinct `tool_review_state` line keyed by message and snapshot IDs.-Keep the original message line and all message-window coordinates unchanged.+Append a distinct `tool_review_state` line keyed by message and snapshot ids, leaving+the original message line and every message-window coordinate unchanged. Full reads,+bounded reads, and tool-parent lookups replay the latest matching state, and those+offsets are indexed separately in layout-cache format 3. Cache reuse requires a+matching file identity and modification stamp, and only a host-owned append from the+proven generation advances an in-memory prefix without a rescan.-Cache reuse requires a matching file identity and modification/change-time-stamp. Only a Host-owned append from the proven generation advances an in-memory-prefix's generation without rescanning.+The owning tool snapshot is validated before appending, duplicate acknowledgements are+avoided, and the existing flush/fsync path provides durability before only the session+timestamp is updated. File order is the order of record, indexed reads sort offsets by+byte position, and the last appended state wins for the same message and snapshot.### Rewrite and archive folding-`truncate_from` first calls `get_session`. Its uncapped read reaches-`read_transcript_with_compactions` / `read_transcript_window`, where-`apply_tool_review_states` overlays the appended records before any cut is-chosen.--`fork_session_through` reads the effective records through `read_transcript`;-`activate_message_revision_with_prefix` combines the effective live prefix and-stored branch before `records_and_texts` serializes them. Coverage includes-`truncate_from_folds_review_state_into_the_retained_prefix` and-`tool_review_state_survives_fork_revision_activation_and_deletion`.--### Ordering--File order is the order of record. Review-state records have no timestamp;-`append_line` writes each complete line and syncs it before returning, while the-calling RPC holds the Host state lock.--`equal_length_state_appends_replay_in_file_order_across_cached_reads` uses JSON-whitespace to make valid `active` and `rolledBack` records exactly equal in-serialized length. Each append must still grow the file, add a distinct state-offset, and preserve last-write-wins state through warm and cold reads.+Existing rewrite, fork, revision, and archive operations consume the effective message+projection, so state is folded into their payloads: the surviving tool's effective+state reaches its canonical message, discarded messages keep theirs in the archived+branch, and fork and revision activation serialize the combined prefix.## Consequences-A review update writes only its IDs and state instead of retained history.--The line type is additive to transcript format 2 and requires no database or RPC-migration.+- A review update writes only its ids and state instead of retained history.+- The first mutation after a restart still runs the storage-integrity verification,+ and ordinary reads also read the small state log.+- The line type is additive to transcript format 2 with no database or RPC migration,+ so older readers skip it and may show stale card state.## Alternatives-- Calling `update_message` still copies all historical bytes for a non-tail- message and therefore leaves the reported review trigger.-- Appending the whole tool message creates a new physical message position.-- A separate metadata file adds another authoritative storage and recovery- lifecycle; the existing transcript append path already provides durability.+- Call `update_message` — rejected: it still copies all historical bytes for a+ non-tail message.+- Append the whole tool message — rejected: it creates a new physical position.diff --git a/docs/adr/asktool-draft-survives-session-switch.md b/docs/adr/asktool-draft-survives-session-switch.mdindex b8a299b70..46e9c5007 100644--- a/docs/adr/asktool-draft-survives-session-switch.md+++ b/docs/adr/asktool-draft-survives-session-switch.md@@ -7,29 +7,29 @@## Context-The card's question index and draft answers were component state. Switching-sessions unmounts the card — `Composer` renders it only while the active session-has a head ask — so returning to the same pending ask remounted a fresh card at-question one with every answer cleared.+The card's question index and draft answers were component state, but `Composer`+renders the card only while the active session has a head ask, so a session+switch unmounted it and returning to the same pending ask remounted a fresh card+at question one with every answer cleared. The spec froze that opposite behavior+by treating drafts as local to the mounted card.## Decision-Draft answers and the open question index live in the app store, keyed by-`requestId` (`askDrafts`). `AskToolCard` reads and writes that entry instead of-owning `useState`, so unmounting and remounting the same request is harmless.--The draft is dropped when the ask is resolved or dismissed, when its tool call-finishes, when the session's asks are cleared, and when a pending-queue-reconcile removes the ask. Drafts remain renderer memory, like `pendingAsks`;-they are not persisted across an application restart and never leak between+Draft answers and the open question index live in the app store keyed by+`requestId` (`askDrafts`), and `AskToolCard` reads and writes that entry instead+of owning `useState`, so unmounting and remounting the same request is harmless+and a missing entry falls back lazily to an empty draft without seeding the store+during render. The draft is dropped when the ask is resolved or dismissed, when+its tool call finishes, when the session's asks are cleared, and when a+pending-queue reconcile removes the ask; drafts stay renderer memory like+`pendingAsks`, are not persisted across a restart, and never leak betweenrequests.## Consequences-- Switching sessions and returning to the same pending ask keeps the selected- options, the custom text, skipped markers, and the open question.-- Resolved, dismissed, and removed asks leave no draft behind.-- `AskToolCard` becomes a controlled view over store state; it keeps no- draft-local `useState`.-- The "Request transitions" section of the asktool card spec is amended: drafts- belong to the request, not to the mounted card instance.+- Returning to the same pending ask keeps the selected options, custom text,+ skipped markers, and open question.+- `AskToolCard` becomes a controlled view over store state with no draft-local+ `useState`, and resolved, dismissed, or removed asks leave no draft behind.+- The "Request transitions" rule is amended: drafts belong to the request, not to+ the mounted card instance.diff --git a/docs/adr/browser-background-lifecycle.md b/docs/adr/browser-background-lifecycle.mdindex b098d694f..0218d4c95 100644--- a/docs/adr/browser-background-lifecycle.md+++ b/docs/adr/browser-background-lifecycle.md@@ -7,40 +7,51 @@## Context-Main already retains one BrowserPane and CDP session per conversation/resource-page. Tool execution nevertheless depended on the shared visible browser chrome,-and the bundled Browser tool called `reveal()` before every action.+Main already retains one BrowserPane and CDP session per conversation or resource+page, but tool execution depended on the shared visible browser chrome and the+bundled Browser tool called `reveal()` before every action, so collapsing the+side panel or switching conversations made a retained page unusable, and a+renderer reload disposed every guest.## Decision-Main owns live pages and their execution. The renderer owns only presentation:-measured bounds, visible page selection and side-panel tabs.+Main owns live pages and their execution; the renderer owns only presentation —+measured bounds, visible page selection, and side-panel tabs.- Every tool API derives its session from the trusted in-flight invocation and- resolves that session's connected page.-- Navigation starts immediately in Main, including in background conversations.-- Background page metadata updates the originating renderer context.-- Unknown/closed targets fail with `UNAVAILABLE`.-- Explicit `reveal()` remains a presentation API with its existing visible-view- acknowledgement.+ resolves that session's connected page, never another conversation's visible+ page; a first navigation or BrowserPreview establishes the connection.+- Navigation starts immediately in Main, including in background conversations,+ and continuing operations never reopen a collapsed panel or steal focus.+- Background metadata updates only its originating renderer context, an unknown+ or closed target fails with `UNAVAILABLE`, and explicit `reveal()` stays a+ presentation API with its visible-view acknowledgement.- Hidden pages are parked in a lazy, invisible sandboxed BrowserWindow owned by- BrowserBackingHost, keeping Chromium's render/input widget connected while the- side-panel container is unmounted.+ BrowserBackingHost, so Chromium keeps its render and input widget while the+ side-panel container is unmounted; showing a page moves that same native view+ back to the measured hole.- Host-only focus emulation and page-relative target coordinates make background- input reliable without native focus or extending the public raw-CDP allowlist.-- Renderer reload hides and detaches presentation, not pages.-- Explicit tab/session closure, plugin disable/unload, window destruction and- app shutdown release the corresponding pages, debugger state and watchers.+ input reliable without extending the public raw-CDP allowlist.+- Renderer reload hides and detaches presentation, not pages: the additive,+ session-filtered `browser/getPages` IPC restores missing tabs without reopening+ the panel or replacing a user-selected resource.+- Explicit tab or session closure, plugin disable, window destruction, and+ shutdown release the corresponding pages, debugger state, and watchers.-The process model, browser plugin contract, URL/file-root gates, permission-checks, raw-CDP allowlist, cookie partition, tool modes and screenshot deadlines-remain unchanged. There is no database migration or restart DOM persistence.+The process model, plugin contract, URL and file-root gates, permissions, cookie+partition, tool modes, and screenshot deadlines are unchanged, with no database+migration or restart DOM persistence.-## Alternatives+## Consequences-Keeping the visibility dependency forces users to babysit a background task.+- Users can collapse the panel, switch conversations, and reload the shell while+ the browser stays usable.+- Memory stays allocated until the page's explicit owner closes it, and restart or+ guest-crash recovery does not promise unsaved DOM.-## Consequences+## Alternatives-Users can collapse the side panel, view another conversation or Settings, and-reload the shell while the original browser remains usable.+- Keep the visibility dependency: rejected; it forces users to babysit a+ background task.+- Address the current visible page globally: rejected; it permits accidental+ cross-session reads and actions.diff --git a/docs/adr/chronological-system-transcript.md b/docs/adr/chronological-system-transcript.mdindex 39e8cf8da..a3532f18b 100644--- a/docs/adr/chronological-system-transcript.md+++ b/docs/adr/chronological-system-transcript.md@@ -10,34 +10,68 @@## ContextMoving new tool declarations to the beginning of a conversation changes its-cached prefix. Rebuilding from visible chat alone also loses the chronology of-instruction and tool changes.+cached prefix, and rebuilding from visible chat loses the chronology of+instruction and tool changes. Pi 0.99.1 already owns tool-state diffing and+request projections, while Desktop owns session persistence and permissions.## Decision-Keep Pi's provider-neutral system messages in chronological order. Use the-existing Host-owned transcript writer and optional versioned `modelSystem`-metadata on hidden system rows, acknowledging writes before dispatch.+Keep Pi's provider-neutral system messages in chronological order, written through+the existing Host-owned transcript writer with optional versioned `modelSystem`+metadata on hidden system rows and acknowledged before dispatch, so anchors+preserve model order when the user row was pre-persisted. Save the effective state+once at explicit compaction and restore it before the summary and retained tail,+while current mode, catalog, and Host permissions stay authoritative for+execution.-Separate Desktop's runtime instructions, skill catalog and contextual guidance-into replaceable sections. The skill-loading header uses `skills`, and each-catalog entry uses `skill:<exact-id>`; a change or removal appends only that-entry's replacement or null tombstone.+Desktop's runtime instructions, skill catalog, and contextual guidance become+separate replaceable sections: the skill-loading header uses `skills` and each+catalog entry uses `skill:<exact-id>`, so a change appends only that entry's+replacement or null tombstone. A legacy aggregate `skills` section is replaced+once at continuation, catalog-only skill changes refresh an idle runtime, body+loading and permission checks stay at the existing Host bridge, and a tool schema+change never reuses an idle runtime on identical names.-## Fixed declarations for the verified Flash route+The published model, API, and endpoint identity is retained before account+overrides, and transcript capability opt-ins are accepted only when that identity+matches the actual request route, letting Pi adapt partial support instead of+persisting a folded projection. models.dev stays authoritative for published+limits, prices, and modalities, while only the five transcript transport flags and+their original binding are copied from Pi's exact published model. Under that+model, the Pi 1.0.0 dependency patch adds the missing mid-conversation system+capability to the `deepseek-flash` catalog entry, verified on the official endpoint+for cache reuse and effective instructions, and stays in the single Pi catalog+rather than a parallel Desktop allowlist.-For the exact official `deepseek-flash` / `openai-completions` binding with-verified chronological system support, declare the complete current tool catalog-in deterministic name order from the first request. ToolSearch changes execution-activation only.+For that exact official binding, declare the complete current tool catalog in+deterministic name order from the first request, with ToolSearch changing only+execution activation and other bindings keeping on-demand schema publication.+DeepSeek caps a request at 128 functions, so a catalog that exceeds it, or whose+prompt and schema cost leaves too little retained tail below the compaction+threshold, falls back to the on-demand path with a logged reason; a catalog is+never truncated.-Keep activation separate from declarations in a versioned `tool_activation`-system section. The section records active deferred names and a SHA-256 identity-of the account, model, API, endpoint, declarations and deferred-name set.+Activation stays separate in a versioned `tool_activation` system section that+records the active deferred names and a SHA-256 identity of the account, model,+API, endpoint, declarations, and deferred-name set. It never turns a declaration+snapshot into execution permission: invalid or mismatched state grants no+activation, temporary prompt replacement preserves the metadata, and any+catalog, schema, mode, account, or route change starts a new declaration epoch.-## Alternatives and consequences+## Consequences-Prepending a reconstructed snapshot was rejected because it changes history on-ordinary continuation.+- Ordinary continuation preserves history and cache prefixes without a new+ persistence store or migration, and unknown old histories establish their first+ baseline at continuation.+- Added records consume transcript storage, and a failed write stops dispatch as a+ local preparation failure that retries with the same row ID.+- The first request is larger, so short conversations may cost more overall; no+ universal savings are promised, and providers may still fold unsupported+ updates and lose cache reuse.-The added records consume transcript storage.+## Alternatives++- Prepend a reconstructed snapshot: rejected; it changes history on ordinary+ continuation.+- Adopt Pi AgentSession or a new persistence store: rejected; it creates another+ session owner.diff --git a/docs/adr/composer-local-file-references.md b/docs/adr/composer-local-file-references.mdindex 93354e7e3..d097d1f89 100644--- a/docs/adr/composer-local-file-references.md+++ b/docs/adr/composer-local-file-references.md@@ -6,21 +6,30 @@## Context-Copying disk-backed clipboard files into session scratch eagerly allocates and-transfers their full contents. The 64 MiB transfer bound prevents attaching a-large file even when the task needs only a bounded read.+Copying disk-backed clipboard files into session scratch eagerly allocates and transfers+their full contents, and the transfer bound prevents attaching a large file even when the+task needs only a bounded read.## Decision-Native clipboard files use the existing sender-bound, one-shot selection token-to register live references in the owning local project. Main creates a UUID-record under `<data_dir>/composer-file-references/` containing only the-canonical path, project path, and originating session id.--Drafts, queued input and messages carry the additive `localReference` id and-byte size. Composer shows the name and human-readable size.+Native clipboard files use the existing sender-bound, one-shot selection token to register+live references in the owning local project: Main creates a UUID record under+`<data_dir>/composer-file-references/` holding only the canonical path, project path, and+originating session id, with no file bytes and no tool access. Drafts, queued input, and+messages carry the additive `localReference` id and byte size shown as name and size, and on+dispatch Main revalidates the record and project, rejects a changed or unavailable target,+and refreshes the size before the agent receives path and size as context to read through+normal tool permissions, requesting referenced images through its Read path. Input history+restores references without reads or snapshots, screenshots and generated payloads keep the+existing scratch materialization, and records without `localReference` are unchanged.## Consequences-The file transfer byte limits still protect actual transfers, while native-references retain the 20-item selection limit.+- Transfer byte limits still protect actual transfers, while native references keep the+ 20-item selection limit and the attachment-root validator.+- A restored reference observes current file contents and can become unavailable after+ deletion, movement, or project relocation; there is no snapshot and no implicit upload.++## Alternatives++- Keep eager scratch materialization: the transfer bound still refuses large files.diff --git a/docs/adr/composer-mcp-invocations.md b/docs/adr/composer-mcp-invocations.mdindex 7fe64c729..26c5dd18e 100644--- a/docs/adr/composer-mcp-invocations.md+++ b/docs/adr/composer-mcp-invocations.md@@ -6,29 +6,36 @@## Context-Explicit MCP selection belongs in the composer alongside Skills and plugin-commands. Tool discovery, argument selection, execution and approval remain-owned by the runtime and Host.+Explicit MCP selection belongs in the composer beside Skills and plugin commands,+while tool discovery, argument selection, execution, and approval stay owned by+the runtime and Host.## Decision-Catalog discovery refreshes enabled user MCP records and uses the runtime's-existing bounded connection path, including before the first session after-restart. The composer exposes ready servers with tools in the current project.--Main revalidates the selection against the session project's current catalog on-prompt or steering submission. It preserves the typed text in `command`, adds a-short model-facing selection instruction, and forwards `mcpServerIds` and-optional `mcpToolNames` through internal RPC.--## Consequences and alternatives--The optional catalog and internal RPC fields reuse the existing execution path-without database, Plugin SDK or Host protocol changes.--Selection makes tools available but does not force execution.--## Unreleased user-facing change--Select a connected MCP server or one of its tools from the composer's `/` menu-and send a task. Existing tool approvals still apply.+Catalog discovery refreshes enabled user MCP records through the runtime's+existing bounded connection path, and the composer exposes ready servers with+tools in the current project as `/mcp:<URI-encoded-server-id>` entries, appending+`:<URI-encoded-tool-name>` for a single tool. Entries carry `kind: "mcp"`,+`mcpServerId`, and an optional `mcpToolName`, existing command aliases keep+precedence, selecting an entry inserts text without connecting or executing, and+credentials and tool schemas stay out of the catalog.++Main revalidates the selection against the session project's catalog on prompt or+steering submission, adds a short model-facing selection instruction, and+forwards `mcpServerIds` and optional `mcpToolNames` through internal RPC. Server+selection activates every mode-allowed tool of that server, tool selection+activates only the requested tools after ownership and mode checks, and neither+removes tools already active; an unavailable selection fails explicitly instead+of becoming prompt text.++## Consequences++- The optional catalog and internal RPC fields reuse the existing execution path+ with no database, Plugin SDK, or Host protocol change.+- Selection makes tools available without forcing execution, and Main rejects a+ selection with no task text or attachment before opening a turn.++## Alternatives++- Have the renderer drive the tool call: rejected; it would duplicate runtime+ argument selection and permission handling.diff --git a/docs/adr/composer-pasted-directory-references.md b/docs/adr/composer-pasted-directory-references.mdindex 362c9b0e2..30910ce50 100644--- a/docs/adr/composer-pasted-directory-references.md+++ b/docs/adr/composer-pasted-directory-references.md@@ -6,21 +6,27 @@## Context-A directory has no regular-file bytes, and Chromium can omit its clipboard File.-Copying its tree into scratch would create an expensive and stale snapshot.+A directory has no regular-file bytes, and Chromium can omit its clipboard `File`,+so copying its tree into scratch would build an expensive, stale snapshot. A pasted+folder still has to reach the model without being snapshotted.## Decision-On an explicit native-file paste, Electron main captures bounded native-clipboard file metadata. Directories become typed draft references and removable-folder cards above the editable text, with a name, localized Folder label and-full-path tooltip.--Directory references serialize as escaped `<dir>absolute/path</dir>` markers-plus one instruction to inspect directory structure and read relevant files as-needed for the current request. They never enter binary attachment transport,-previews, recursive copies or file snapshots.+On an explicit native-file paste, Electron main captures bounded clipboard file+metadata itself, because it reads each platform's native format and accepts no+renderer-supplied paths. Directories become typed draft references rendered as+removable folder cards above the editable text, while mixed regular files register+[live file references](composer-local-file-references.md) through the sender-bound+one-shot selection. Directory references serialize as escaped+`<dir>absolute/path</dir>` markers plus one instruction to inspect the directory+structure and read relevant files, so they never enter binary attachment transport,+previews, or snapshots. They grant no new filesystem access, existing tool+permissions apply, and removing a card removes its prompt hint.## Consequences-Generated image/text paste and the existing directory-drop choice remain.+- Image and text paste and the existing directory-drop choice are unchanged.+- Clipboard metadata is read only for a paste gesture and never enters clipboard+ history; drafts retain paths, not contents.+- The JSON reference shape gains an additive directory kind; host protocol and+ schema versions are unchanged.diff --git a/docs/adr/custom-storage-location.md b/docs/adr/custom-storage-location.mdindex aa4dc7cba..82beb2cd4 100644--- a/docs/adr/custom-storage-location.md+++ b/docs/adr/custom-storage-location.md@@ -6,34 +6,38 @@## Context-Application data and Chromium's browser/plugin state accumulate on the default-system volume. Changing only the host root strands browser state and absolute-internal attachment/plugin references.+Application data and Chromium browser and plugin state accumulate on the default+system volume, and moving only the host root strands browser state and absolute+attachment and plugin references, while copying a live database or profile risks+inconsistent snapshots and late writes.## Decision-Use explicit settings confirmation followed by existing ordered shutdown.-Journal pending work in the original Electron userData directory, which remains-the stable installation identity and single-instance lock.--An empty selected destination owns `data/` and `browser/`. The production Node-filesystem service copies all profile files, preserves links/permissions,-verifies SHA-256 bytes and records ownership for retry.--## Alternatives--- Live relocation: rejected because SQLite, plugin processes, browser- partitions, outbox and logs do not share an atomic live-switch boundary.-- Cache-only relocation: does not satisfy the requested complete storage- migration.-- Move userData and its lock: changes installation identity and admits competing- launches while migrating.-- Rewrite every matching byte/string: would corrupt credentials, user commands,- code, prose, Chromium databases and unknown plugin-owned formats.+Use explicit settings confirmation followed by the existing ordered shutdown,+journal pending work in the original Electron `userData` directory, which stays+the installation identity and single-instance lock, and show cold migration+progress in a sandboxed nonpersistent window before any writer boots. An empty+selected destination owns `data/` and `browser/`: the filesystem service copies+every profile file, preserves links and permissions, verifies bytes, and records+ownership for retry, then Rust alone rewrites known host-owned structured paths+and the copied SQLite index offline without schema upgrades or startup recovery.+The durable pointer is published atomically afterwards, normal startup sets+Chromium `sessionData` before ready, and the selected root reaches every+existing service. Source profiles stay as visible backups behind a separate+confirmed cleanup action.## Consequences-The default profile and Rust ownership remain compatible.+- Migration needs room for one verified copy plus metadata, and source data is+ untouched when copying fails.+- A missing custom volume blocks startup with a recovery message rather than+ creating a misleading empty profile.+- Unknown plugin-private absolute references keep their bytes, and no schema,+ protocol, or plugin SDK change is required.++## Alternatives-Unknown plugin-private absolute references and historical narrative paths retain-their bytes; extension authors own their portability.+- Live relocation: rejected, SQLite, plugin processes, browser partitions, and+ logs share no atomic live-switch boundary.+- Move `userData` and its lock: rejected, it changes installation identity and+ admits competing launches during migration.diff --git a/docs/adr/device-local-project-lists-in-config-sync.md b/docs/adr/device-local-project-lists-in-config-sync.mdindex 8231939d4..48be93fc7 100644--- a/docs/adr/device-local-project-lists-in-config-sync.md+++ b/docs/adr/device-local-project-lists-in-config-sync.md@@ -6,31 +6,33 @@## ContextProject and project-group names, pinning, root lists, and ordering describe a-device's workspace. Synchronizing these records can register unwanted local-workspaces.+device's workspace, so synchronizing them can register unwanted local workspaces,+while project-scoped capabilities still need portable logical bindings and explicit+local folder mappings without synchronizing the workspace list.## Decision-Remove `projects` from the public `ConfigSyncCategory` contract, category UI,-adapter registry, capture, and application. Normalize saved configuration and-draft categories to the supported category set.--Keep local project records and remote revision history intact. Do not publish-project deletions to retire the category.--## Alternatives--- Disable projects by default but retain the category: rejected because it still- permits workspace-list synchronization.-- Remove all project-scoped configuration: rejected because it unnecessarily- removes capability synchronization and local mapping support.-- Delete old project entities from cloud history: rejected because immutable- authenticated revisions remain valid restore points for supported domains.+Remove `projects` from the public `ConfigSyncCategory` contract, category UI, adapter+registry, capture, and application, normalize saved configuration and draft+categories to the supported set, filter retired project entities from local baselines+and pending imports, and validate and authenticate existing remote revisions+completely before ignoring their `projects` entities during sync or restore. Local+project records and remote revision history stay intact, project deletions are not+published, and logical identities and local folder mappings are preserved for+project-scoped MCP, skills, instructions, memory, and automation.## Consequences-New clients no longer capture, preview, activate, or restore workspace-list-metadata.+- New clients no longer capture, preview, activate, or restore workspace-list+ metadata, and consumers of `ConfigSyncCategory` stop requesting `projects`.+- Saved category selections and retired local imports are normalized without user+ action, and other domains in old revisions remain restorable after full validation.+- Older clients can still publish project entities that new clients ignore, which+ neither revokes their behavior nor erases cloud history.++## Alternatives-Older clients can still publish project entities into a shared vault; new-clients ignore them.+- Disable projects by default but keep the category: still permits workspace-list+ synchronization.+- Delete old project entities from cloud history: immutable revisions remain valid+ restore points.diff --git a/docs/adr/floating-annotation-index.md b/docs/adr/floating-annotation-index.mdindex 21ec00e99..99e9f3fa8 100644--- a/docs/adr/floating-annotation-index.md+++ b/docs/adr/floating-annotation-index.md@@ -1,22 +1,28 @@# ADR floating-annotation-index: Floating Annotation Index and Source Locations-> Superseded by ADR 0268.- Status: Superseded by ADR 0268- Date: 2026-09-12-- Amends: ADR response-annotations / D-LOCAL-response-annotations (annotation presentation and duplicate identity)-- Preserves: D209, D301, D261, D-LOCAL-selection-overlay; protocol v11 and schema v15+- Related: D209, D261, D301, D-LOCAL-response-annotations, D-LOCAL-selection-overlay,+ ADR response-annotations## Context-The comment editor solved missing comment entry, but a composer-only attachment-list did not show where selections were made.+A composer-only attachment list did not show where selections were made, and inserting+marker text into Markdown had already broken words, selections, and formulas.## Decision-1. Replace the composer attachment popover with one floating annotation index in- the visible, writable transcript pane, above the composer. It starts- expanded, collapses to its count header, and stays open during reading.+One floating annotation index above the composer in the visible transcript pane listed+numbered excerpts with comments, locate, edit, remove, and clear-all controls in the+same one-based order as source badges and the prompt payload, with each saved resolvable+selection highlighted by a non-interactive overlay outside the answer DOM. A+renderer-only optional anchor stored start and end offsets plus exact answer text,+excluding code chrome, KaTeX's duplicate MathML, and citation markers, relocating a+shifted selection only when its exact text was unique, and deduplication keyed on source+row, excerpt, and offsets so equal words at distinct locations stayed separate. Protocol+v11 and schema v15 were preserved.## Consequences-Superseded (Superseded by ADR 0268). The full record is in git history.+- Selections were locatable from one panel instead of a composer list.+- ADR 0268 retired the surface; the stored anchor fields stay readable.diff --git a/docs/adr/gen-ui-inline-visualization.md b/docs/adr/gen-ui-inline-visualization.mdindex 3d86206cb..2eb87872e 100644--- a/docs/adr/gen-ui-inline-visualization.md+++ b/docs/adr/gen-ui-inline-visualization.md@@ -5,122 +5,90 @@## Context-Models can explain dynamic systems, tunable parameters, and spatial-relationships far better with a small interactive page than with prose, Markdown-tables, or Mermaid. PI-Desktop cannot show such a page in the transcript:-assistant text renders through Markdown only, the transcript has no embedded-frames, and MCP Apps `ui://` resources are not supported.+A model explains dynamic systems, tunable parameters, and spatial relationships+far better with a small interactive page than with prose, tables, or Mermaid,+but the transcript renders Markdown only and supports no embedded frames. This+record adapts the approach Codex and ZCode use — a model-written HTML fragment+in a host-owned per-session directory, validated and framed by the host — and+borrows ZCode's Apache-2.0 visualize kit; interactive state, follow-up messages,+external links, tweak panels, and image export are deferred.## Decision### Reference syntax-The model ends its reply with one standalone line per visualization:--```text-::visualize{"path":"/abs/path/to/chart.html","title":"Optional title"}-```--The renderer parses only completed assistant messages. Fenced and indented code-stays code, except a closing fence containing only one reference is accepted as-the model's reference.+The model ends its reply with a standalone+`::visualize{"path":"/abs/path/to/chart.html","title":"Optional title"}` line+per visualization, the renderer parses only completed assistant messages, and+fenced or indented code stays code except for a closing fence holding one+reference.### Storage root (Rust host-core)-1. Each local session gets `<data_dir>/visualizations/<sessionId>/` as an- additional containment root for `Read`, `Write`, and `Edit`, addressed by- absolute path only, with the same lexical and symlink defenses as the D114- scratch root.-2. Before adding the root, the single optional `scratch_root` parameter that- threads through path resolution is generalized into an ordered list of- contained roots.-3. `Write` and `Edit` into the visualization root accept only `.html` files.-4. Valid contained writes auto-allow under scratch's conditions (local workspace- only; contract and Plan modes still deny), without artifacts or review- snapshots.-5. The directory is created lazily and removed with its session (session delete- and project removal).-6. Forks copy only the fragments their transcript references into- `visualizations/<childId>/` and rewrite those paths, like referenced pasted- files in scratch.+Each local session gets `<data_dir>/visualizations/<sessionId>/` as an+additional containment root for `Read`, `Write`, and `Edit`, addressed by+absolute path only and defended like the D114 scratch root. The single+`scratch_root` parameter becomes an ordered list of contained roots first, so+the new root does not create a parallel path. Writes accept only `.html` while+`Read` is unrestricted inside the root, contained writes auto-allow under+scratch's conditions without artifacts or review snapshots, and the directory+is created lazily and removed with its session, sweeping only sessions that no+longer exist.### Model guidance (agent runtime and Electron Main)-Inline visualizations are opt-in: `AppSettings.inlineVisualizations` is absent-and `false` by default, and only `true` enables them. While the switch is off-the absolute directory path is not advertised in the system prompt, the-`pi-desktop/visualize` skill is withheld from the catalog, the `/` menu, and the-on-demand `Skill` tool, and the renderer hides existing reference lines without-loading a card.+Inline visualizations are opt-in through `AppSettings.inlineVisualizations`,+absent and false by default; while off, the system prompt does not advertise the+directory, the `pi-desktop/visualize` skill is withheld from the catalog, `/`+menu, and `Skill` tool, and the renderer hides existing reference lines.+Remote-host sessions get neither the directory nor the skill, because their+tools write on the remote machine.### Serving (Electron Main)-1. Main registers a `pi-genui:` scheme through the single- `registerSchemesAsPrivileged` call site as `standard` and `secure` only — no- Fetch API support, no CORS, no `Access-Control-Allow-Origin` header.-2. The card URL is `pi-genui://session/<sessionId>/<file>.html`.-3. The handler accepts `GET` only, validates the session ID against- `[A-Za-z0-9_-]` and the file name as a single path component ending in- `.html`, and rejects symlinks, non-regular files, files over 2 MB, and- complete HTML documents (a leading `<!doctype`, `<html`, `<head`, or- `<body`).-4. Main wraps the fragment in a host shell: the kit stylesheet- (`resources/gen-ui/visualize.css`, which defines the agent-facing tokens such- as `--foreground` and `--viz-series-1` from MCP Apps-style `--color-*` host- variables), a small host runtime that reports content height and applies- theme updates, the preloaded chart layer (bundled D3 7.9.0 and the `viz`- helpers in `resources/gen-ui/visualize-helpers.js`, which own container- sizing, resize and theme redraw, axes, and label overlap), the fragment, and- then the kit runtime (tooltips and tabs).-5. The guest CSP is `default-src 'none'`; `script-src` allows `'unsafe-inline'`- and `pi-genui://assets` only, `style-src` `'unsafe-inline'` only; `img-src`,- `font-src`, and `media-src` allow `data:` and `blob:`; `connect-src`,- `frame-src`, `form-action`, and `base-uri` are `'none'`.-6. Permission request and check handlers deny every request from a `pi-genui:`- origin.+Main registers a `pi-genui:` scheme as `standard` and `secure` only, without+Fetch API support, CORS, or an `Access-Control-Allow-Origin` header, and every+response carries `sandbox allow-scripts` in its CSP so the document keeps an+opaque origin even when a caller omits the iframe sandbox. The card URL is+`pi-genui://session/<sessionId>/<file>.html`, derived by the renderer from the+trailing path segment; the handler accepts `GET` only, validates the session id+and single-component file name, rejects symlinks, non-regular files, oversized+files, and complete HTML documents, and reads bytes through the private+`visualizations.readFragment` RPC rather than opening model-written paths.+Fragments are wrapped in a host shell with the kit stylesheet, a height and+theme runtime, a preloaded chart layer with pinned bundled libraries, and the+kit tooltip and tab runtime, and the guest CSP allows only `'unsafe-inline'` and+`pi-genui://assets` with no CDN, no `connect-src`, and no `frame-src`.### Main window-`apps/desktop/index.html` adds exactly `frame-src pi-genui:` to its CSP. The-parent's `frame-src` also governs where the frame may navigate, so a-visualization cannot replace itself with a remote page outside its own CSP.+`apps/desktop/index.html` adds exactly `frame-src pi-genui:` to its CSP, so the+parent also governs where the frame may navigate.### Rendering (renderer)-1. The assistant message bubble splits references out of the message content- before Markdown rendering and renders one card per reference.-2. The card is `<iframe sandbox="allow-scripts" loading="lazy">` without- `allow-same-origin`; the guest has an opaque origin and cannot reach the host- DOM, storage, or preload bridge.-3. The renderer accepts only `{ type: "pi-genui:size", height }` and `{ type:- "pi-genui:wheel", deltaX, deltaY, deltaMode }` messages whose `event.source`- is that card's frame.-4. Expanding opens a modal with a fresh frame for the same URL.-5. A missing, invalid, or remote file renders an "unavailable" card with a- localized reason; the rest of the message renders normally.-6. A shared pool bounds inline and expanded frames to eight across all panes.+The assistant bubble splits references out before Markdown rendering and shows+one card per reference, and with the setting off it still strips the lines while+framing nothing. The card is a `sandbox="allow-scripts"` lazy iframe without+`allow-same-origin`, so the guest cannot reach the host DOM, storage, or preload+bridge; the renderer accepts only size and wheel reports from that frame, clamps+height, replays wheel intent as untrusted input, posts theme and view messages,+and opens a modal with a fresh frame for the expanded view. A shared pool bounds+frames across all panes, and serving errors reach the card as a fixed code.## Consequences-- The transcript can show interactive pages without giving them host- capabilities, network access, or same-origin access.-- host-core gains a small module mirroring the scratch lifecycle and a- behavior-preserving generalization of contained roots.-- Plan mode cannot produce visualizations because it exposes no `Write` or- `Edit` tools.-- Visualizations can use only the bundled libraries; any other library or remote- asset is blocked.-- Data-directory relocation and forks keep working; a fork owns copies of the- fragments it references, so deleting the parent does not break its cards.+- The transcript shows interactive pages without granting host capabilities,+ network access, or same-origin access, at the cost of the bundled-kit weight.+- host-core gains a module mirroring the scratch lifecycle, and forks copy only+ the fragments their transcript references, so relocation and deletion behave+ as they do for pasted files.+- Plan mode cannot produce visualizations, and a guest can still reach the+ network through WebRTC ICE until Chromium enforces `webrtc 'block'`.## Alternatives-- **Store fragments under `scratch/<sessionId>/visualizations/`.** About a third- of the change, but it changes D114's "scratch is temporary" meaning and still- needs a sweep exception.-- **One `<webview>` per card (ZCode).** Process-level isolation, but requires- the webview tag, lifecycle management, and size syncing.-- **Declarative JSON component trees (A2UI).** Safer, but limited to predefined- components, which loses the expressiveness that motivates the feature.-- **MCP Apps `ui://` first.** Standard, but tied to MCP tool results; it can- reuse this sandbox later.+- Fragments under `scratch/<sessionId>/`: rejected, it changes D114's+ "scratch is temporary" meaning for unclear ownership gain.+- Declarative JSON component trees: rejected, predefined components lose the+ expressiveness that motivates the feature.diff --git a/docs/adr/global-sidebar-pins.md b/docs/adr/global-sidebar-pins.mdindex f54c99ffc..4c9fa6782 100644--- a/docs/adr/global-sidebar-pins.md+++ b/docs/adr/global-sidebar-pins.md@@ -2,26 +2,32 @@- Status: Accepted- Date: 2026-09-13-- Related issue: [#306](https://github.com/vastsa/PI-Desktop/issues/306)+- Related: [#306](https://github.com/vastsa/PI-Desktop/issues/306) · E2E-SIDEBAR-global-pinned-conversations- Amends: [ADR 0016](0016-sidebar-organization-and-multi-project-tabs.md)## Context-Conversation sorting puts pinned rows first, but project rendering then places-them in chronological buckets. An older pin can therefore appear below today's-unpinned conversations.+Conversation sorting puts pinned rows first, but project rendering then files them+into chronological buckets, so an older pin can sit below today's unpinned+conversations, and pins vanish when their project tab is collapsed or closed.## Decision-- Render one global Pinned section above standalone Sessions and Projects.-- Apply archive visibility to both the session and its owning project.-- Show project context on each pin and use the existing session sort within the- section without date buckets.-- Remove visible pins from ordinary rows before chronological grouping and the- per-project ten-row limit.-- Reuse ordinary row selection and actions.-- Omit an empty section and bound its scroll area to `min(224px, 30vh)`.+Render one global Pinned section above standalone Sessions and Projects, derived+from existing session summaries and organization metadata rather than a second pin+registry, including sessions whose project tab is not retained. Archive visibility+applies to both the session and its owning project, while closed or collapsed+projects do not hide otherwise visible pins. Each pin shows its project context and+uses the existing session sort without date buckets, and pinned rows leave the+ordinary rows before chronological grouping and the per-project row limit, though+project membership stays intact for activity ordering and archive navigation. Rows+reuse ordinary selection and actions, unpinning returns a session to its normal+history location and restores focus to its relocated overflow control, and an empty+section is omitted.## Consequences-Pins remain discoverable across dates and projects without duplicate rows.+- Pins stay discoverable across dates and projects without duplicate rows.+- Existing persisted pins take effect with no storage migration, IPC change, or+ host ownership change.+- Project context costs row width, so it is ellipsized under the title.diff --git a/docs/adr/host-file-batch-admission.md b/docs/adr/host-file-batch-admission.mdindex b6adec9c9..92120791c 100644--- a/docs/adr/host-file-batch-admission.md+++ b/docs/adr/host-file-batch-admission.md@@ -6,33 +6,67 @@## Context-The first #1982 candidate classified file conflicts using lexical path keys and-a basename fallback. A differently named symbolic link or hard link bypasses-that rule.+The first #1982 candidate classified file conflicts by lexical path keys with a+basename fallback, which a differently named symbolic or hard link bypasses, and+Sidecar PathMutex uses lexical keys too while Host's per-session mutation cap+excludes a second write rather than a concurrent read. Parallel independent-path+access therefore needs trusted resource identity, and source order must survive+because locking on RPC arrival lets a later approved call run before an earlier+pending one. File bodies use `spawn_blocking`, so cancelling the transport waiter is+not proof that disk work stopped, and review snapshots and rollback are filesystem+work, not exceptions to exclusion.## DecisionHost owns resource classification and admission. Runtime registers only logical-calls in pi's ordered prepare phase and seals the batch before dispatch.+calls in pi's ordered prepare phase and seals the batch before dispatch through the+five version-1 methods `tools.fileBatchCapabilities`, `Register`, `Seal`, `Abandon`,+and `Close`. A ticket binds session, optional delegation, batch/ordinal, tool+call/name, and normalized arguments; it is single-use and is not an access+permission. Registration does no file lookup and takes no capacity, unstarted failed+calls are abandoned, turn-end closes metadata, and running work cannot be released+by close or metadata expiry.-Host applies existing permissions before classification. Unknown earlier calls-conservatively block potentially conflicting same-batch successors.+Host applies existing permissions before classification, and unknown earlier calls+conservatively block potentially conflicting same-batch successors. Approved calls+use native object IDs from pinned handles plus resolved path addresses: equal IDs+conflict across roots, because roots are not namespaces for physical IDs. Windows+uses local-disk volume/`FILE_ID_INFO` and supported Unix filesystems dev/ino, while+missing or unknown targets, structural edits, and named registers use a Host-wide+file-domain fence that searches share. Permission and I/O failures keep failing in+their original path, and unknown identity is never evidence of independence.-## Alternatives+`ToolBudget` checks batch predecessors, active resources, conflicting waiters, and+capacity in one synchronous reservation without holding capacity while awaiting a+resource. Source predecessors may bypass a later same-batch RPC-arrival waiter to+avoid a reversed-arrival deadlock, shared requests do not bypass an exclusive+waiter, and global limits with 30-second `HOST_OVERLOADED` behavior are unchanged.++After admission the persisted binding and resource identity are revalidated before+snapshots and again in the blocking body, the blocking task keeps an `Arc` of its+permit even when the RPC future is cancelled, and snapshot, execution, Hashline+updates, and review finalization share one lease. On the negotiated path Host+resources replace sidecar PathMutex, legacy calls keep the sidecar policy, and the+capability is stable per runtime and connection so a live delegate cannot switch+protocol mid-turn. Remote workspaces keep sequential write batches; Bash, plugin/MCP+policy, and persistence formats are unchanged, and coordination covers one Host+process, not arbitrary external writers.-- Realpath/basename only: misses hard links and unknown filesystem identities.-- Return an identity token and keep arrival-order admission: loses source order- when approvals/RPCs arrive in another order; stale identities can also escape.-- Keep every write as a batch-local full barrier: safe fallback, but discards- independent-file read/write overlap even on a capable local Host.-- Reimplement pi execution: duplicates its ordered preparation/result contract.+## Consequences-## Consequences and verification+- This is a cross-runtime/Host protocol amendment, not a TS optimization: it adds+ bounded process-local metadata and registration/sealing overhead that must appear+ in performance measurements.+- Identified local writes with validated tickets may share two session mutation+ slots, still bounded by two global mutations, while uncoordinated calls stay+ single-write and exclude coordinated writes symmetrically; eligibility uses+ immutable request facts, and registry bounds may reject work conservatively.-This is a cross-runtime/Host protocol amendment, not a TS-only optimization.+## Alternatives-Regression evidence must cover actual differently named links in both orders,-reversed RPC/approval arrival, parent/delegate wiring, cross-session aliases,-independent resources, cancellation during blocking work, queue cleanup,-permission denial, argument tampering/replay, review rollback and legacy remote-fallback.+- Realpath/basename only: misses hard links and unknown identities.+- Return an identity token and keep arrival-order admission: loses source order and+ lets stale identities escape.+- Keep every write a batch-local full barrier, or adopt the whole #1908 roadmap: the+ first discards independent-file overlap, the second adds unrelated quota,+ background-job, and MCP changes.diff --git a/docs/adr/image-generation-capability.md b/docs/adr/image-generation-capability.mdindex 865c9804b..f0a0d7d97 100644--- a/docs/adr/image-generation-capability.md+++ b/docs/adr/image-generation-capability.md@@ -2,29 +2,38 @@- Status: Accepted- Date: 2026-09-21-- Related: ADR 0281, ADR 0101, ADR 0172; [image generation spec](../spec/03-runtime/21-image-generation.md)+- Related: ADR 0101, ADR 0172, ADR 0281;+ [image generation spec](../spec/03-runtime/21-image-generation.md)## ContextThe desktop understands image input and previews but has no image production-path. Users need one selectable image model, conversational generation/editing,-and batches without changing their default chat model.+path. Users need one selectable image model, conversational generation and+editing, and batches without changing their default chat model, which a Skill+alone cannot execute and pure image endpoints cannot serve as chat adapters.## DecisionKeep a separate optional settings binding referencing existing provider-credentials. Expose one Agent tool plus a bundled, lazily loaded imagegen skill.--The existing local-tool shortcut does not perform host permission checks. For-this billable tool, the bridge must obtain host-core authorization through-`tools.execute` before invoking the local service.--## Alternatives and consequences--- An independent image workspace would duplicate conversation/history ownership;- use existing chat and previews first.-- A shell/API-only skill would bypass model settings and require scripts to- handle credentials, files and retries.-- A broad multi-protocol framework is unnecessary for the requested single- Images protocol.-- Optional settings preserve existing stored data and conversation defaults.+credentials, exposing one Agent tool plus a bundled, lazily loaded imagegen skill,+with an independent OpenAI Images adapter and batch scheduler in agent-runtime+while the desktop service coordinates host-owned settings, credentials, contained+source files, and saved output. Because the local-tool shortcut performs no host+permission check, this billable tool obtains host-core authorization through+`tools.execute` before invoking the local service, so host-core never performs+the HTTP call, and local tools gain an abort signal for cancellation, timeout, and+process loss.++## Consequences++- Optional settings preserve stored data and conversation defaults, with no+ schema migration, plugin API change, or direct renderer credential access.+- Partial results stay useful and nothing retries automatically, avoiding+ duplicate paid work, and headless hosts without the image runner do nothing.++## Alternatives++- An independent image workspace: rejected; it would duplicate conversation and+ history ownership.+- A shell or API-only skill: rejected; it would bypass model settings and require+ scripts to handle credentials, files, and retries.diff --git a/docs/adr/local-agent-remote-workspace-tools.md b/docs/adr/local-agent-remote-workspace-tools.mdindex 7da1130ea..9a84d7357 100644--- a/docs/adr/local-agent-remote-workspace-tools.md+++ b/docs/adr/local-agent-remote-workspace-tools.md@@ -7,34 +7,44 @@## Context-The remote MVP ran an Agent on the SSH Host and required remote providers and-Host-owned projects. This made project names and model selection differ from-local work.+The remote MVP ran the Agent on the SSH host and required remote providers and+host-owned projects, so project names and model selection diverged from local+work, while the user requires model requests and credentials to stay on Desktop+with the remote machine executing tools only.## DecisionKeep the Agent runtime, provider resolution, credentials, model requests,-transcripts, project names, project-group instructions, project memory and-sessions on Desktop. Root repository instructions are read from the remote-workspace and merged after local global defaults, without remote HOME defaults-or nested traversal.--After the normal local permission and execution-admission gates, host-core-relays supported workspace tools through Electron Main to the paired Host. RACP-transports the execution identity, workspace path and tool arguments only.--## Alternatives--- Automatically copy local providers to the remote Host: rejected because OAuth,- local providers and credentials would still depend on a remote model runtime.-- Add a model gateway through reverse SSH: keeps credentials local but still- leaves session and Agent ownership remote, adding model transport exposure.-- Mirror remote paths into local folders: rejected because tools would act on a- different filesystem and make containment and data consistency ambiguous.+transcripts, project names, group instructions, memory, and sessions on Desktop,+reading root repository instructions from the remote workspace and merging them+after local global defaults. The Rust-owned logical project-group KV boundary+gains a remote workspace binding, where an opaque project identity selects the+group and the remote path is never interpreted as a local path. After the normal+permission and execution-admission gates, host-core relays supported workspace+tools through Electron Main to the paired Host, and RACP carries only the+execution identity, workspace path, and tool arguments — never model+configuration, credentials, or a model request. The Host validates its canonical+browse boundary and executes, and failed, disconnected, cancelled, timed-out, or+unsupported calls fail closed without falling back to local execution or+replaying side effects. New projects use the ordinary name, switcher, sidebar,+archive, and session controls, with remote directory selection in a separate+accessible dialog and no Host project or provider synchronization.## Consequences-The project group's `remote` binding stores `{hostKey, path}` while its primary-root and session `projectPath` use `remote-project:<groupId>`.+- The group's `remote` binding stores `{hostKey, path}` while its primary root+ and session `projectPath` use `remote-project:<groupId>`, and unknown opaque+ identities are rejected before any workspace or session mutation.+- The remote runner admits only Read, Glob, Grep, Write, Edit, and Bash, creates+ no remote project or session records, and preserves workspace containment;+ a lost mutation reply is `REMOTE_MUTATION_OUTCOME_UNKNOWN` and non-retriable.+- Storage stays Rust-owned and backward compatible through additive KV+ metadata, existing remote histories stay readable, and older Hosts report an+ explicit unsupported operation; permission approval stays on Desktop.++## Alternatives-The pure remote runner admits only Read, Glob, Grep, Write, Edit and Bash.+- Copy local providers to the remote Host: rejected, OAuth and local credentials+ would still depend on a remote model runtime.+- Mirror remote paths into local folders: rejected, tools would act on a+ different filesystem and containment would become ambiguous.diff --git a/docs/adr/lossless-tool-image-storage.md b/docs/adr/lossless-tool-image-storage.mdindex b28f9bc24..45fadd14d 100644--- a/docs/adr/lossless-tool-image-storage.md+++ b/docs/adr/lossless-tool-image-storage.md@@ -7,18 +7,25 @@## ContextMCP images are duplicated in structured content/details and exact JSON text-mirrors. A normal long screenshot session can exceed the 64 MiB incoming RPC-frame limit when a Desktop action uploads its retained history.+mirrors, so a long screenshot session can exceed the 64 MiB incoming RPC frame+limit when Desktop uploads its retained history.## Decision-Use reversible storage-private per-record image tables and text templates in-Host-owned self-contained files and the Desktop outbox. Decode before business-consumers see the data.--Use additive ID commands for remaining normal history operations and retain the-existing full-upload APIs. Keep the 64 MiB limit and explicit failure semantics.+Store each image once per record in reversible, storage-private image tables and+text templates inside Host-owned self-contained files and the Desktop outbox, and+decode before business consumers see the data. Public RPC/plugin shapes, legacy+file reads, and the 64 MiB limit with explicit failure semantics stay unchanged;+a backed-up version-only DB migration keeps older binaries from misreading new+records, and legacy files convert only at write through verified temporary files+with atomic replacement. Remaining history operations use additive ID commands+next to the existing full-upload APIs.## Consequences-Images persist once per record without changing visible/plugin/model values.+- Visible, plugin, and model values are unchanged; revisions and forks stay+ self-contained and may each own a copy.+- New code reads legacy data, while older applications cannot open the upgraded+ profile.+- Unique histories beyond 64 MiB stay usable through IDs; arbitrary oversized+ requests still fail.diff --git a/docs/adr/mcp-tool-approval-risk.md b/docs/adr/mcp-tool-approval-risk.mdindex 2ad83c207..928de28af 100644--- a/docs/adr/mcp-tool-approval-risk.md+++ b/docs/adr/mcp-tool-approval-risk.md@@ -7,25 +7,30 @@## ContextUser-configured MCP servers expose tools under the `mcp_<serverId>_<tool>`-namespace (ADR 0056). `PermissionManager` classified every `mcp_` tool as `low`-risk, which auto-allows in every mode, so under `ask` a server's tools could-write files, reach the network or run commands without an approval card.+namespace (ADR 0056), and `PermissionManager` classified every `mcp_` tool as+`low` risk, which auto-allows in every mode, so under `ask` a server's tools could+write files, reach the network, or run commands without an approval card. The user+chose to launch the server, but its tool list comes from the server and can change+between versions, and server-annotated risk is a claim by the party being gated.## Decision-Classify `mcp_` tools as `medium` risk, the same as a plugin tool without a-valid declaration. Under `ask` and `accept-edits` each call shows the approval-card with the reason "MCP server tool requires approval"; allow-once covers one-call and allow-session covers that exact tool name for the session.--Dispatch over `plugins.execute`, read-only-mode handling and the `mcp_`-namespace are unchanged. No host protocol, schema or persistence change.+Classify `mcp_` tools as `medium` risk, the same as a plugin tool without a valid+declaration. Under `ask` and `accept-edits` each call shows the approval card with+the reason "MCP server tool requires approval", where allow-once covers one call+and allow-session covers that exact tool name; `auto` runs without a card,+Plan/Goal keep denying it, and server-declared risk or annotations are ignored.+Dispatch over `plugins.execute`, read-only-mode handling, and the `mcp_` namespace+are unchanged, with no host protocol, schema, or persistence change.## Consequences-Users see an approval card for MCP tool calls in `ask` and `accept-edits` until-they grant the tool for the session.+- Users see an approval card for MCP tool calls in `ask` and `accept-edits` until+ they grant the tool for the session.+- A per-server or per-tool persistent allowlist, if wanted later, is a separate+ decision.## Alternatives-Trusting server annotations would let a server mark itself safe.+- Trust server annotations: a server would be able to mark itself safe.+- Use `high` risk: it adds friction without a different settlement path.diff --git a/docs/adr/message-quotes-and-side-chats.md b/docs/adr/message-quotes-and-side-chats.mdindex 10101f281..e1f27892c 100644--- a/docs/adr/message-quotes-and-side-chats.md+++ b/docs/adr/message-quotes-and-side-chats.md@@ -1,27 +1,39 @@# ADR message-quotes-and-side-chats: Message Quotes and Renderer-Owned Side Chats-> Superseded by ADR 0268.- Status: Superseded by ADR 0268- Date: 2026-09-11-- Deciders: PI-Desktop runtime and desktop UI maintainers- Amends: D209, D301- Preserves: D097, D128, D134, D154-- Related: [04-ux/08-component-spec.md](../spec/04-ux/08-component-spec.md) ·- [04-ux/09-interaction-patterns.md](../spec/04-ux/09-interaction-patterns.md) ·- [04-ux/01-ui-ia.md](../spec/04-ux/01-ui-ia.md) ·- [06-delivery/04-e2e-test-plan.md](../spec/06-delivery/04-e2e-test-plan.md) ·- E2E-CHAT-quote-prefill, E2E-CHAT-side-chat-fork, E2E-CHAT-side-chat-stream, E2E-CHAT-side-chat-add-to-main, E2E-CHAT-side-chat-promote, E2E-CHAT-side-chat-close ·- Amendment: D-LOCAL-selection-overlay, E2E-CHAT-selection-markdown+- Related: [04-ux/09-interaction-patterns.md](../spec/04-ux/09-interaction-patterns.md)## Context-A long conversation carries earlier prompts and answers the user wants to reuse.+Long conversations carry earlier prompts and answers the user wants to reuse, and+the only shipped paths were copying by hand or re-pasting into the composer. The+existing `session.fork` (ADR 0023, D134) already produced an independent durable+child, but every dialog that used it activated the child, which is wrong for a+side question because the fork replaces the visible main conversation.## Decision-1. Every user message and every assistant turn gains a **Quote** action in its- hover action row, beside Copy, Edit, Delete, Fork, and Retry.+Every user message and assistant turn gained a Quote action that prefilled a+Markdown blockquote into the active session's composer draft under the existing+composer-prefill contract, and an Open side chat action that kept a renderer-owned+draft tab until the first Send forked a durable child without activating it. The+feature reused `session.fork`, the existing prompt and abort paths, and the+work-panel surface, with quoted text staying plain draft text under D209's smart+Stop and D301's per-session draft retention.## Consequences-Superseded (Superseded by ADR 0268). The full record is in git history.+- Quote prefill, the selection overlay, and the side-chat panel were removed with+ this record, so the composer again offers no quote entry point.+- A child created by a side chat is an ordinary durable session and remains listed,+ searchable, and openable like any other.+- The `session.fork` capability the panel routed to survives and is used by the+ Fork action.++## Superseded by++[ADR 0268](0268-remove-quotes-annotations-and-side-chats.md) removed quotes,+annotations, and side chats.diff --git a/docs/adr/mode-definitions.md b/docs/adr/mode-definitions.mdindex 30905f3f2..c5011e06f 100644--- a/docs/adr/mode-definitions.md+++ b/docs/adr/mode-definitions.md@@ -2,31 +2,32 @@::: v-pre-- Status: Implemented candidate+- Status: Implemented candidate; supersedes the hard-coded+ `Mode = "plan" | "goal" | "agent"` behavior and contract-mode grouping D198+ (the ADR 0053 Plan approval flow is re-expressed, not removed), and ports the+ durable run engine from PR #1999 / #2140 / #2141 (issue #1995)- Date: 2026-11-07-- Supersedes: hard-coded `Mode = "plan" | "goal" | "agent"` behavior- (contract-mode grouping D198). The Plan approval flow in ADR 0053 is- re-expressed, not removed.-- Credits: the durable run engine (claims, CAS revisions, budgets, pause- closeout, idempotent settlement) is ported from new-Beginner's- PR #1999 / #2140 / #2141 (issue #1995).+- Related: D198, D202, ADR 0053, ADR 0211## Context-Plan, Goal and Agent are closed, hard-coded modes. Their behavior is spread over-the mode prompt table, runtime tool gating, Rust `is_contract_mode` /-`plan_mode_allows`, Plan approval and (in #2141) a Goal-specific loop.+Plan, Goal and Agent are closed, hard-coded modes whose behavior is spread over the+mode prompt table, runtime tool gating, Rust `is_contract_mode` / `plan_mode_allows`,+Plan approval and a Goal-specific loop. Users cannot create a mode, split work into+stages, require an artifact, or act when context is compacted or work completes, while+subagents already use a Markdown definition with frontmatter, a shared parser, and+global-only discovery (D202).## Decision### 1. A mode is one Markdown file-`~/.pi/modes/<name>/mode.md` holds YAML frontmatter and a Markdown body. The-body is the shared system prompt.--Builtins `agent`, `plan` and `goal` use the same format and ship with the app.-The builtin ids are reserved: a user document that uses one is reported in-settings and is not loaded.+`~/.pi/modes/<name>/mode.md` holds YAML frontmatter and a Markdown body that is the+shared system prompt, with optional artifact templates in `templates/`; builtins+`agent`, `plan` and `goal` use the same format, and their reserved ids make a user+document using one reported in settings and not loaded. Discovery is global only, and+settings re-read the directory on each catalog load. A simple mode is a prompt and a+permission level, without stages or a run:```markdown---@@ -38,37 +39,8 @@ permission: contractReview the current changes for defects. Do not modify files.```-```markdown-----name: feature-label: Feature-description: Spec, implement and verify one feature-artifacts:- spec:- path: .pi/runs/{{run.id}}/spec.md- template: templates/spec.md- requiredHeadings: [Goal, Acceptance criteria]-budget: { maxTurns: 30 }-stages:- design:- permission: contract- prompt: Write the spec for {{run.input}}.- exit:- - require: artifact:spec- - ask: user- next: implement- implement:- permission: agent- loop: true- prompt: Implement the approved spec.- on:- compaction: [{ inject: artifact:spec }]- exit:- - run: pnpm test- onFail: { retries: 3 }-----Follow the repository conventions.-```+A staged mode declares stages, artifacts and gates; sending the first message in it+starts a run.### 2. Fields@@ -78,7 +50,7 @@ Follow the repository conventions.| mode | `permission` | `agent` or `contract`, inherited by stages | `agent` || mode | `artifacts` | `id → { path, template?, requiredHeadings? }` | none || mode | `budget` | `{ maxTurns?, maxTokens? }` for one run | `maxTurns: 20`, tokens unlimited |-| mode | `returnTo` | Mode that the session uses after the run ends | `agent` |+| mode | `returnTo` | Mode the session uses after the run ends | `agent` || mode | `stages` | Ordered map; the first stage starts the run | none, which makes a simple mode || stage | `prompt` | System section while the stage is active | none || stage | `permission` | Overrides the mode level | mode value |@@ -87,70 +59,85 @@ Follow the repository conventions.| stage | `exit` | Ordered gates | none || stage | `next` | Next stage; when absent, the stage is final | none |-Variables are `{{run.id}}`, `{{run.input}}` (the message that started the run)-and `{{artifacts.<id>.path}}`. Substitution is text-only.+Template variables are `{{run.id}}`, `{{run.input}}` (the message that started the+run) and `{{artifacts.<id>.path}}`, substituted as text only.### 3. Run semantics-- **Stage brief.** On every turn the Host adds a generated section to the stage- system prompt.-- **Templates.** When a stage is first entered, the Host writes the template of- each missing artifact, with variables substituted.-- **Finishing a stage.** The model calls `CompleteStage { summary, artifacts?,- report? }`.-- **Blocked reports.** Optional structured reports preserve per-criterion `met`- / `unmet` / `unverified` evidence, remaining work and a blocker reason.-- **Completion-channel failure.** The sidecar proxy admits only- `modes.completeStage` and `modes.gateResult`, not user control methods.-- **Gate failure.** The failure goes back to the model as the `CompleteStage`- tool result, for example the missing heading or the command exit code with the- output tail.-- **Transition.** When all gates pass, the run moves to `next` and the Host- starts that stage's first turn.-- **Turns.** A loop stage continues until `CompleteStage` passes, a blocked- report or execution error stops continuation, or the budget is exhausted.-- **Budget.** `maxTurns` and `maxTokens` limit only the turns the Host starts by- itself.-- **Run states.** The states are `running`, `waiting` (for an approval, after- retries are exhausted, or after a non-loop stage stops), `paused`,- `budget_exhausted`, `finished` and `stopped`.-- **Editing a run.** `modes.update` changes an open run's input (the objective)- and its `{ maxTurns, maxTokens }` budget.-- **Remote workspaces.** Staged runs are not available in remote workspaces in- this version.-- **Mode switch.** Selecting another staged mode while a run is active asks the- user to stop the run first.+- **Stage brief and templates.** Each turn the Host adds a generated section to the+ stage prompt with the current stage, declared artifacts and paths, required+ headings, the gates, and how to finish, and on first entry writes the template of+ each missing artifact with variables substituted.+- **Finishing a stage.** The model calls+ `CompleteStage { summary, artifacts?, report? }`; `artifacts` maps an id to Markdown+ and the Host writes it to the artifact path, so a contract stage can produce its+ artifact without Write permission, after which the Host evaluates gates in order. A+ stage with no gates and no `loop` also finishes when its turn ends.+- **Reports and gate failure.** Structured reports keep per-criterion+ `met` / `unmet` / `unverified` evidence, remaining work and a blocker reason: a valid+ `blocked` report moves a live claimed run to `waiting/blocked`, stops autonomous+ continuation and survives restart, a `completed` report requires all outcomes met but+ never bypasses exit gates, and reports are model assertions, not verification. A gate+ failure returns as the `CompleteStage` tool result and the model continues in the same+ turn, with `onFail.retries` (default 2) then waiting for the user and+ `onFail.goto: <stage>` moving the run there instead.+- **Completion channel.** The sidecar proxy admits only `modes.completeStage` and+ `modes.gateResult`, Host ownership, live claim and frozen-input checks still apply,+ and a broken completion RPC or invalid Host outcome fails the current execution turn+ with no blind autonomous retry on transport failures.+- **Transition and turns.** When all gates pass the run moves to `next` and the Host+ starts that stage's first turn; the final stage ends the run and switches the session+ to `returnTo`. A loop stage continues until `CompleteStage` passes, a blocked report+ or execution error stops continuation, or the budget is exhausted; a non-loop stage+ whose turn ends unfinished waits for the user; a user message during a run is input to+ the current stage and runs before any Host-started turn; `maxTurns` / `maxTokens` limit+ only Host-started turns.+- **Run states.** `running`, `waiting` (approval, exhausted retries, non-loop stop),+ `paused`, `budget_exhausted`, `finished`, `stopped`; the status bar shows mode, stage,+ turns or budget, and Pause, Resume, Edit, Remove, Stop. Pause is persisted immediately+ and blocks Host-started turns, a running turn closes out through+ `agent.modeTurnNotice` `closeout`, Stop revokes the claim and interrupts, Remove drops+ the run context (`release`) so the turn finishes as an ordinary turn of `returnTo`,+ and after a restart a run whose turn was in flight is paused, never replayed.+- **Editing, remotes and switching.** `modes.update` changes an open run's input and+ budget from the next claim; the turn holding the claim keeps its input, and its+ `CompleteStage` answers `MODE_INPUT_CHANGED` when no longer current. Staged runs are+ unavailable in remote workspaces in this version. Selecting another staged mode while+ a run is active asks the user to stop it first, and selecting a simple mode leaves the+ run paused.### 4. Actions| Action | Where | Effect | Authority || --- | --- | --- | --- || `require: artifact:<id>` | `exit` | The file exists inside the workspace and contains the required headings | Host |-| `run: <command>` or `run: { command, timeoutMinutes }` | `exit` | Bash in the workspace root through the normal permission prompt (allow-for-session applies); a non-zero exit fails the gate; default timeout 10 min | Host gate |-| `ask: user` | `exit`, must be last | The turn ends and the run waits. Approve continues the transition. Reject keeps the stage, and the user's feedback becomes a normal user message | Host |-| `inject: artifact:<id>` or text | `on` | Adds a system notice with the current file content or the text; never a fake user message. After compaction, the notice follows the summary | Runtime |+| `run: <command>` or `run: { command, timeoutMinutes }` | `exit` | Bash in the workspace root behind the normal permission prompt; a non-zero exit fails the gate; default timeout 10 min | Host gate |+| `ask: user` | `exit`, must be last | The turn ends and the run waits; Approve continues the transition, Reject keeps the stage and the feedback becomes a normal user message | Host |+| `inject: artifact:<id>` or text | `on` | Adds a system notice with the current file content or the text, never a fake user message; after compaction it follows the summary | Runtime |-Completion handling is the final stage's `exit` gates. Compaction handling is+Completion handling is the final stage's `exit` gates; compaction handling is`on.compaction`.### 5. Validation and limits-- The frontmatter must be strict YAML: maps, lists, strings, numbers and- booleans, with no anchors, aliases or tags.-- The parser rejects the whole definition when it finds an unknown key, event,- action or stage reference, a `goto` cycle without a `loop` or `ask` stage, an- `ask` that is not the last gate, or an artifact path outside the workspace.-- Limits: 16 stages, 8 gates per stage, 10 retries, 64 KB per file, 8 KB of- command output returned to the model, and a `run` timeout of at most 60 min.+- Frontmatter must be strict YAML — maps, lists, strings, numbers and booleans, with no+ anchors, aliases or tags.+- The parser rejects the whole definition on an unknown key, event, action or stage+ reference, a `goto` cycle without a `loop` or `ask` stage, an `ask` that is not the+ last gate, or an artifact path outside the workspace; settings show the diagnostic and+ the picker shows the mode as unavailable.+- Limits: 16 stages, 8 gates per stage, 10 retries, 64 KB per file, 8 KB of command+ output returned to the model, `run` timeout at most 60 min.### 6. Permission narrows, never widens-- `contract` keeps today's Plan hard deny: the allowlist plus plan-safe plugin- actions (ADR 0211).-- `Computer` and scheduled-task tools are available only in the builtin `agent`- mode.-- Builtin Goal keeps the session's selected permission on every claimed turn,- including Host continuation.+- `contract` keeps today's Plan hard deny — the allowlist plus plan-safe plugin actions+ (ADR 0211) — while `agent` uses the Agent policy, and Host artifact writes through+ `CompleteStage` are limited to declared paths.+- `Computer` and scheduled-task tools are available only in the builtin `agent` mode.+- Builtin Goal keeps the session's selected permission on every claimed turn, including+ Host continuation, which removes the second-turn Auto-to-Accept-edits downgrade; other+ unattended staged modes keep the `accept-edits` ceiling for `auto`.- No action grants a permission, a session grant or an external path.### 7. Ownership@@ -159,7 +146,7 @@ Completion handling is the final stage's `exit` gates. Compaction handling is| --- | --- || shared | Schema, parser, defaults, limits, variable substitution, wire types (`modeId: string`) || agent-runtime | Discovery, the stage brief, per-stage prompt and tool catalog, the `CompleteStage` tool, `inject` on enter and compaction |-| host-core | Authority: definition snapshot per run, tool policy from that snapshot (never the mode claimed by the runtime), the stage state machine, artifact writes and checks, gate results, the run engine (claim / CAS / budget / pause / settlement from #2141) |+| host-core | Authority: definition snapshot per run, tool policy from that snapshot (never the mode claimed by the runtime), the stage state machine, artifact writes and checks, gate results, and the run engine (claim / CAS / budget / pause / settlement from #2141) || renderer | Mode picker, run status bar, source editor with validation in settings |Only the Host records a gate as passed and moves the run to another stage.@@ -167,51 +154,49 @@ Only the Host records a gate as passed and moves the run to another stage.### 8. PersistenceDesktop attaches the catalog definition to the additive `session.create`-`modeSnapshot` input. The Host validates and stores it in the same transaction-as the session, rather than configuring an already-visible session in a second-RPC.--One migration after the current schema:--- `sessions.mode` keeps its column.-- `mode_snapshots (hash, json)`: an immutable definition per run, so editing a- mode never changes a running run.-- `mode_runs`: generalized from #2141 `session_goals`.-- `mode_gate_results`: run, stage, gate index, action, result, evidence and- timestamp.-- Existing `plan_approvals` rows stay valid.+`modeSnapshot` input, and the Host validates and stores it in the same transaction as+the session, so a failed configuration cannot leave an incomplete session; legacy+callers may omit the snapshot and keep fail-closed policy. One migration follows:+`sessions.mode` keeps its column, with values becoming mode ids and `agent`, `plan`,+`goal` mapping to the builtins, a session whose mode no longer exists falling back to+`agent` and an active run keeping its snapshot. `mode_snapshots (hash, json)` stores an+immutable definition per run, `mode_runs` is generalized from `session_goals` to store+mode, snapshot hash, input, current stage, state, budget, usage, revision, active claim,+retries and rounds completed (schema 30 adds an active elapsed clock `elapsed_ms` /+`active_since_ms` that only Running time accumulates), `mode_gate_results` records run,+stage, gate index, action, result, evidence and timestamp, and existing+`plan_approvals` rows stay valid.### 9. Builtins and compatibility- `agent`: a simple mode.-- `plan`: a simple `contract` mode that keeps the ADR 0053 proposal pipeline- unchanged (EnterPlanMode, SubmitPlan, approval, queued execution).-- `goal`: stage `work` (`agent`, `loop`, artifact `goal` from a template seeded- with `{{run.input}}`, `inject` on compaction, gate `require: artifact:goal`- with headings Objective, Acceptance criteria and Evidence).--The Goal input preference and execution identity are deliberately separate.-Relabeling the executing turn as Agent would lose the snapshot's authority;-keeping the picker on Goal would make ordinary follow-ups ambiguous.-- IPC / RACP `mode` stays a string.+- `plan`: a simple `contract` mode keeping the ADR 0053 proposal pipeline unchanged+ (EnterPlanMode, SubmitPlan, approval, queued execution) with the same behavior, tool+ names and stored approvals; a staged Plan would rewrite a released approval flow.+- `goal`: stage `work` (`agent`, `loop`, artifact `goal` from a template seeded with+ `{{run.input}}`, `inject` on compaction, gate `require: artifact:goal` with headings+ Objective, Acceptance criteria and Evidence), completion staying a model self-report,+ with a new run taking its budget from the valid `goalBudget` setting or else the+ definition. The legacy `EnterGoalMode` / `SubmitGoal` negotiation is no longer offered+ and the Host rejects new proposals with `PLAN_GOAL_ACTIVATION_DISABLED`, while old+ approval rows stay readable; accepted Goal input returns the composer preference to+ Agent without changing the run, its snapshot or its claim.+- IPC / RACP `mode` stays a string, so old clients sending `plan`, `goal` or `agent`+ keep working; builtin labels are localized and user labels are shown as written.## Consequences-- The hard-coded mode-name branches collapse into the registry and the Host- policy table.-- A user creates a simple mode with a prompt, or a staged workflow with- artifacts and checks, in one file.-- One tool (`CompleteStage`) and four actions cover Plan approval, Goal- completion and custom workflows.-- A misconfigured definition can only make a mode stricter or fail to load.-- `run` gates execute commands only when a stage finishes, behind the existing- Bash approval, and the transcript shows them.+- Hard-coded mode-name branches collapse into the registry and the Host policy table,+ and one file expresses either a simple mode or a staged workflow.+- One tool (`CompleteStage`) and four actions cover Plan approval, Goal completion and+ custom workflows, and a misconfigured definition can only make a mode stricter or fail+ to load.## Alternatives-1. Merge #2141 as a third hard-coded mode.-2. A flat list of checkpoints without stages.-3. Evaluating gates after every turn.-4. Project-level definitions.+- Merge #2141 as a third hard-coded mode: every new workflow would repeat the+ cross-layer branching.+- A flat list of checkpoints without stages: cannot express phases, backtracking or+ per-phase permission.:::diff --git a/docs/adr/model-reasoning-effort-override.md b/docs/adr/model-reasoning-effort-override.mdindex 4707a8569..9944c3d21 100644--- a/docs/adr/model-reasoning-effort-override.md+++ b/docs/adr/model-reasoning-effort-override.md@@ -7,26 +7,29 @@## ContextDeepSeek-family Chat Completions compatibility disables `reasoning_effort` for-endpoints that reject that field. Model-name detection also covers custom relays-that do support it, so choosing High can silently omit the parameter.+endpoints that reject the field, but model-name detection also matches custom relays+that support it, so choosing High can silently omit the parameter while changing the+automatic default would regress the endpoints issue #1701 protects.## DecisionAdd optional `supportsReasoningEffort: boolean | null` to the persisted model-binding. Missing/null retains automatic compatibility; true/false explicitly-allows/disallows the parameter.+binding: missing or null keeps automatic compatibility, true and false explicitly+allow or disallow the parameter. Provenance stays separate from catalog+compatibility and applies last, only when building a Chat Completions model, and the+setting neither turns reasoning on nor overrides the selected thinking level. The+per-model settings offer Auto, Send, and Do not send; host normalization and+configuration synchronization preserve the value, and other APIs ignore it.## Update (2026-10-23)-The automatic default for official `deepseek.com` endpoints changed after this-ADR landed: those rows now leave `supportsReasoningEffort` to pi-ai detection,-so the selected level reaches the wire by default (D672, #1821). The explicit-per-model override described here is unchanged and still takes precedence in-both directions.--Expose Auto / Send / Do not send in the existing per-model settings. Host-normalization, configuration copying and synchronization preserve the value.+Official `deepseek.com` endpoints now leave `supportsReasoningEffort` to pi-ai+detection, so the selected level reaches the wire by default (D672, #1821). The+explicit override is unchanged and still wins in both directions.## Consequences-Legacy JSON needs no migration: an absent field retains its prior behavior.+- Legacy JSON needs no migration, and clearing a choice restores automatic+ compatibility.+- A user enabling Send must pick a gateway that accepts the parameter, and provider+ errors stay visible; no retry or silent fallback is added.diff --git a/docs/adr/models-dev-catalog-authority.md b/docs/adr/models-dev-catalog-authority.mdindex 6606b32af..8483516e2 100644--- a/docs/adr/models-dev-catalog-authority.md+++ b/docs/adr/models-dev-catalog-authority.md@@ -1,32 +1,31 @@# ADR: models.dev owns published model metadata-- Status: Accepted for implementation+- Status: Accepted for implementation; supersedes `pi-ai-core-0991-authority.md`- Date: 2026-10-02-- Supersedes: `pi-ai-core-0991-authority.md` for chat model metadata## Context-PI-Desktop's displayed and effective chat limits came from the pinned pi-ai-catalog. Its sibling models can share adapter defaults such as a 272,000-token-context window even when the selected model's published record has a different-limit.+Displayed and effective chat limits came from the pinned pi-ai catalog, where sibling+models share adapter defaults even when the selected model's published record+differs. A reviewed models.dev snapshot and matching logic already exist.## Decision-Use models.dev as the source of published chat model limits, modalities,-reasoning metadata, names and prices. Load the bundled snapshot offline and-refresh it explicitly.--OAuth endpoints remain authoritative for which model IDs an account can use. For-each returned ID, enrich metadata from models.dev; do not copy context, output,-reasoning or prices from a pi-ai sibling.+models.dev is the source of published chat model limits, modalities, reasoning+metadata, names, and prices, and the resolver prefers the selected publisher before a+safe unambiguous match and otherwise keeps the generic shape. OAuth endpoints stay+authoritative for which model IDs an account may use, and each returned ID is enriched+from models.dev instead of copying values from a pi-ai sibling, while explicit+per-account binding overrides are preserved. pi-ai keeps provider discovery and+identity, OAuth and transport, and typed non-chat operations.## Consequences-Published model limits now follow the selected models.dev record across-Settings, context budgeting and runtime launch.+- Published limits follow the models.dev record across Settings, context budgeting,+ and runtime launch; a missing or ambiguous record stays generic.+- No credentials reach models.dev, and no stored data, protocol, or schema changes.## Alternatives-Keeping pi-ai as model metadata authority preserves adapter-adjacent defaults,-but can apply the wrong model's context window to a selected wire model.+- Keep pi-ai as authority: can apply the wrong model's context window.+- Browse models.dev as the model list: exposes models an endpoint does not serve.diff --git a/docs/adr/parallel-read-batches.md b/docs/adr/parallel-read-batches.mdindex 03d734871..4c64141c3 100644--- a/docs/adr/parallel-read-batches.md+++ b/docs/adr/parallel-read-batches.md@@ -1,35 +1,41 @@# ADR: Ordered preparation and parallel file batches-- Status: Proposed+- Status: Proposed (amended 2026-10-30 by #1982; see+ [Host file admission](host-file-batch-admission.md))- Date: 2026-10-12-- Amended: 2026-10-30 by #1982; see [Host file admission](host-file-batch-admission.md)## Context-Independent Read/Glob/Grep calls were serialized. Simply changing execution-flags was unsafe because preflight mutated the prompt in completion order and-Task could start a writable delegate beside a parent read.+Independent Read/Glob/Grep calls were serialized, but changing execution flags alone was+unsafe because preflight mutated the prompt in completion order and Task could start a+writable delegate beside a parent read; the first #1982 attempt at lexical-path claims for+Write/Edit was rejected since differently named files can reference the same object.## Decision-Use pi-agent-core's ordered preparation, concurrent execution and source-order-result submission contract. Native path instruction preparation follows parent-mode/extension checks; children only mutate their own prompt.--Read/Glob/Grep remain parallel candidates. A supported local Host allows-Write/Edit to join; legacy and remote Hosts retain sequential writes.+Use pi-agent-core's ordered preparation, concurrent execution, and source-order result+submission contract: native path instruction preparation follows parent mode and extension+checks, children only mutate their own prompt, prepared argument identity keeps execution+on the same normalized parameters, and direct calls keep preflight, without forking pi or+adding another executor. Read/Glob/Grep remain parallel candidates, and a supported local+Host lets Write/Edit join while legacy and remote Hosts keep sequential writes; Task-only+fan-out is preserved, Task mixed with any file tool keeps the batch sequential, and reads+or searches after a writable Task wait for that delegate. Eligible parallel file calls+register in source order, seal before dispatch, and carry Host tickets, with the Host+owning actual identity, conflicts, capacity, and execution lease lifetime, while outer+executor cleanup covers argument failures, mode denials, cancellation, and calls that+never reach the Host.## Consequences-Independent known-file reads and writes may overlap while aliases keep source-order.--Regression tests must distinguish RPC submission from actual file-body order.+- Independent known-file reads and writes may overlap while aliases keep source order, and+ uncertain paths, namespace changes, and searches coordinate through the Host file+ domain.+- Per-session write capacity remains one, results enter the model in source order, and+ Task and Bash semantics and permissions are unchanged.+- Legacy PathMutex behavior remains only on the legacy path.## Alternatives- Completion-order preflight: sibling calls race to choose prompt instructions.- Sidecar lexical locks: miss aliases and other sessions.-- Write-only Host capacity: does not exclude a read of the same file.-- Waiting/releasing only inside the builtin body: validation/mode errors can- strand registered successors before reaching that body.diff --git a/docs/adr/pi-ai-core-0991-authority.md b/docs/adr/pi-ai-core-0991-authority.mdindex 3d44dc940..778b8a46e 100644--- a/docs/adr/pi-ai-core-0991-authority.md+++ b/docs/adr/pi-ai-core-0991-authority.md@@ -6,31 +6,41 @@## Context-The authorized migration targets pi-ai and pi-agent-core. Pi 0.99.1 exposes-typed Models operations, provider refresh/filter hooks and native thinking-metadata.+The authorized migration targets pi-ai and pi-agent-core, and Pi 0.99.1 exposes+typed Models operations, provider refresh/filter hooks, and native thinking+metadata; a second executable catalog would disagree about limits, entitlement, and+pricing, while accounts and persistence stay Host-owned and plugins keep their SDK+and lifecycle.## Decision-Use Pi Providers/Models as the published model authority. Maintain one Models-collection per account, with Host credential storage and explicit Desktop-binding projection.+Use Pi Providers/Models as the published model authority: one Models collection per+account, Host credential storage, an explicit Desktop binding projection, ambient+auth disabled at catalog startup, OAuth live discovery inside the same+refresh/filter boundary, raw published metadata separate from user overrides, and+images routed through `generateImages`. Non-chat settings keep a display-only+metadata supplement that grants no authentication, dispatch, pricing, or+entitlement, unknown relay matches cannot rewrite wire IDs, and the independent+release-catalog fetch and packaging resource are removed.-Preserve non-chat settings visibility with a display-only metadata supplement;-it must not provide authentication, dispatch, pricing or entitlement. Unknown-relay matches remain conservative and cannot rewrite physical wire IDs.--## Alternatives--Retaining models.dev as executable authority would require duplicating Pi's-operation metadata and refresh semantics.+Usage is attributed to physical operation identities, replayed records aggregate+once, unknown costs stay unknown, and `pi-coding-agent` remains only the compaction+and file compatibility dependency rather than the owner of `AgentSession`, Codemod,+or virtual routing ([design review](../project/pi-coding-agent-design-review.md)).## Consequences-The account adapter reuses Desktop's existing boundaries and preserves saved-data, with a small explicit display-only compatibility gap.+- The adapter reuses Desktop's boundaries and saved data with a small display-only+ gap, catalog changes follow reviewed Pi pins, and the usage ledger needs no+ migration because it reuses the turns usage JSON with optional provenance fields.+- The harness APIs kept during the first migration were later removed: the runtime+ owns transcript projection, estimation, checkpoint preparation, and summary+ generation, host-core stays the durable session owner, and `pi-coding-agent` is+ limited to native Pi session continuation and the trusted-extension shim+ (`02-architecture/06-pi-runtime-dependency-boundary.md`).-### Implementation note (2026-10-03)+## Alternatives-The 0.99.1 migration initially retained pi-coding-agent for compaction and file-compatibility.+- Retaining models.dev as executable authority: duplicates Pi's metadata and refresh+ semantics.+- Adopting ModelRuntime/AgentSession: adds another account and session owner.diff --git a/docs/adr/plan-approval-session-permission.md b/docs/adr/plan-approval-session-permission.mdindex 7e10bf9a6..821e66942 100644--- a/docs/adr/plan-approval-session-permission.md+++ b/docs/adr/plan-approval-session-permission.md@@ -1,30 +1,32 @@# ADR: Plan approval defaults to the owning Session's permission-- Status: Accepted+- Status: Accepted; amends ADR 0053 and ADR 0158- Date: 2026-11-13-- Amends: ADR 0053, ADR 0158+- Related: ADR 0053, ADR 0158## Context-The approval card used a device-wide remembered execution mode, falling back to-Ask independently of the Session. An Auto Session could enter Plan, approve with-the main button, and return to Agent in Ask.+The approval card used a device-wide remembered execution mode falling back to Ask+independently of the Session, so an Auto Session could enter Plan, approve with the main+button, and return to Agent in Ask, while another Session's remembered Auto choice could+replace an Ask Session's policy.## Decision-Initialize Plan and legacy Goal approval from the proposal's owning Session's-effective permission: explicit Session mode, global default for inherit or-unavailable values, then Ask. Refresh the default when the proposal or effective-permission inputs change.+Plan and legacy Goal approval initialize from the owning Session's effective permission —+explicit Session mode, global default for inherit or unavailable values, then Ask —+refreshed when the proposal or the effective permission inputs change, and the legacy+renderer-local `pi.desktop.planApprovalMode` preference is ignored and no longer written.+The explicit Ask / Accept edits / Auto choices remain part of the approval request, while+Host validation, proposal identity, artifact ownership, and the atomic approved-mode write+are unchanged.-Keep the explicit Ask / Accept edits / Auto split-button choices. The displayed-choice remains part of the user approval request.--## Alternatives+## Consequences-Keeping device-wide history as the default would retain cross-Session policy-changes.+- The same Session carries its effective permission through Plan approval, and an explicit+ choice still changes it; already-changed Sessions are not restored.+- No storage migration is needed.-## Consequences+## Alternatives-The same Session now carries its effective permission through Plan approval.+- Keep device-wide history as the default: retains cross-Session policy changes.diff --git a/docs/adr/plan-tool-declarations-and-execution-denials.md b/docs/adr/plan-tool-declarations-and-execution-denials.mdindex 59c6061f3..31155ec0c 100644--- a/docs/adr/plan-tool-declarations-and-execution-denials.md+++ b/docs/adr/plan-tool-declarations-and-execution-denials.md@@ -8,30 +8,33 @@## ContextPlan/Goal removed editing and delegation tools from the provider request while-retaining earlier tool-call history. A model that repeats one of those names can-be rejected by a strict gateway before PI-Desktop receives the call.+retaining earlier tool-call history, so a model repeating one of those names can be+rejected by a strict gateway before PI-Desktop receives the call, leaving the app+unable to produce a tool result with that call's identity.## Decision-Keep Write and Edit declarations in the main session's Plan/Goal requests. When-subagents are configured, retain the Task/TaskWait/TaskList/TaskStop schemas-too.+Keep the Write and Edit declarations in the main session's Plan/Goal requests, and+keep the `Task`/`TaskWait`/`TaskList`/`TaskStop` schemas when subagents are configured,+labelled explicitly unavailable in the contract mode; unknown tools, missing subagent+definitions, on-demand tools, and non-plan-safe plugin tools gain no declaration.-Keep the current mode allowlist authoritative for execution. Block prohibited-calls before extension call hooks or tool handlers run.--## Alternatives--- Delete or rewrite old tool history: changes useful context without proving- that history caused the model's next invalid call.-- Add a user-message correction after a gateway failure: cannot produce a normal- paired tool result and introduces a separate recovery policy.-- Declare every plugin/tool: expands context and capability disclosure beyond- the known mode-restricted tools needed by this failure path.-- Permit editing in Plan/Goal: violates the existing execution boundary.+The mode allowlist stays authoritative for execution: prohibited calls are blocked+before extension hooks or handlers run, the registered handler is wrapped with a fresh+mode check so an object retained across a mode switch cannot execute on stale+authority, and pi's existing error path returns the failure with the original call id+and continues the model loop. The transcript is retained, and no synthetic call,+replacement id, correction prompt, or retry path is added.## Consequences-Declared tools no longer imply permission to execute them.+- A declared tool no longer implies permission to execute it, so the mode prompt and+ each denied description must stay explicit.+- The gateway accepts correctly declared calls, and the normal tool-error channel+ gives the model actionable feedback instead of a request-level 502.+- No database, IPC, plugin permission, or host ownership migration is required.++## Alternatives-No database, IPC, plugin permission or host ownership migration is required.+- Delete or rewrite old tool history — rejected: it changes useful context without+ proving that history caused the invalid call.diff --git a/docs/adr/plugin-fetch-redirect-policy.md b/docs/adr/plugin-fetch-redirect-policy.mdindex 593603c1e..c6987e301 100644--- a/docs/adr/plugin-fetch-redirect-policy.md+++ b/docs/adr/plugin-fetch-redirect-policy.md@@ -5,24 +5,23 @@## Context-Plugins connecting to user-selected endpoints need to refuse or inspect a-redirect before the host contacts its destination. An optional request field-alone is insufficient for old hosts that ignore unknown options.+A plugin connecting to a user-selected endpoint must refuse or inspect a+redirect before the host contacts its destination, which an optional request+field cannot do on old hosts that ignore unknown options, and the injected fetch+service returns a fully materialized response, too late for the host to decide.## Decision-Add follow/error/manual to the existing SDK request and a read-only-`net.getCapabilities` query. Keep omitted mode equivalent to legacy follow.+Add follow/error/manual to the existing SDK request plus a read-only+`net.getCapabilities` query, keeping an omitted mode equivalent to legacy+follow. The hop loop moves into a focused host module whose injection seam is a+single-hop transport receiving manual redirect mode and the shared abort signal,+so the plugin-child RPC and the panel bridge share one policy.## Consequences- Post-response inspection cannot prevent a followed request and is rejected.-- A release-version check alone cannot identify development hosts; capability- detection lets a plugin refuse unsupported hosts before sending anything.-- A same-origin-only mode is optional in the issue and deferred to keep the- additive API small.-- The host must continue testing the injected transport as well as the default- path.--The contract and acceptance live in the plugin API spec and-E2E-PLUGIN-fetch-redirect-policy, not this decision record.+- Capability detection lets a plugin refuse an unsupported host before sending+ anything, which a version check cannot do for development hosts.+- Grants, request rewriting, storage, and sandbox boundaries are unchanged,+ while transports must honor manual redirect and abort semantics.diff --git a/docs/adr/plugin-projects-list.md b/docs/adr/plugin-projects-list.mdindex b0d639e97..8cb93221a 100644--- a/docs/adr/plugin-projects-list.md+++ b/docs/adr/plugin-projects-list.md@@ -8,24 +8,31 @@## Context-Plugins can observe the visible workspace but cannot enumerate durable projects.-A project picker therefore depends on the selected session, and group identities-cannot identify standalone database rows consistently.+Plugins can observe the visible workspace but cannot enumerate durable projects, so+a project picker depends on the selected session and group identities cannot+identify standalone database rows, although the Host owns both the project index+and the logical group metadata.## DecisionAdd `pi.projects.list()` and the equivalent panel bridge channel. Electron main-projects the existing Host `projects.list` response into metadata, enriching a-row from the group whose primary path matches it.+projects the Host `projects.list` response into metadata, enriching a row from the+group whose primary path matches it, with one entry per database row and+secondary rows keeping their own path and identity.-Use the decimal string form of `projects.id`, without a prefix, as `projectId`.-It matches the numeric identity returned by `pi.project.create` and stays stable-for a row's lifetime.+`projectId` is the decimal string form of `projects.id` without a prefix: it matches+the identity `pi.project.create` returns and is stable for the row's lifetime, while+`workspace.get().projectId` still means a logical group id. The API exposes only+ids, names, and registered paths, so it needs no new permission and changes no+workspace, binding, filesystem scope, or creation gate.-## Alternatives+## Consequences-Extending `workspace.get` would conflate selection with enumeration.+Plugins can build project pickers with no selected project; the addition is backward+compatible, needs no migration, and never authorizes reading those paths.-## Consequences+## Alternatives-Plugins can build project pickers while the current session has no project.+- Extending `workspace.get`: conflates selection with enumeration.+- Returning groups alone, or deriving identity from a path: the first omits distinct+ rows and the second changes on rename.diff --git a/docs/adr/plugin-remote-workspace-reads.md b/docs/adr/plugin-remote-workspace-reads.mdindex 0c96900f8..865b160f6 100644--- a/docs/adr/plugin-remote-workspace-reads.md+++ b/docs/adr/plugin-remote-workspace-reads.md@@ -6,23 +6,38 @@ Implemented candidate## Context-Issue #1711 reports a File Manager that keeps loading in an SSH workspace.-Remote projects have an opaque Desktop identity, not a local filesystem root.+Issue #1711 reports a File Manager that keeps loading in an SSH workspace. Remote+projects have an opaque Desktop identity, not a local filesystem root, and the+upstream plugin passes that identity to its own Node filesystem. Existing owner-only+`workspace/files` reads do not enforce a plugin's declared file scope, so forwarding+plugin requests there would widen their access.## Decision-Extend the existing `fs.list` and `fs.readPreview` channels with remote reads.-Desktop admits each call against the plugin permission, scope and current root,-resolves the remote binding from host-owned project records, and sends a closed-`workspace/pluginFiles` request.--The SDK accepts an optional expected workspace identity. All calls, including-legacy calls without this argument, capture their root before asynchronous-admission.+Extend `fs.list` and `fs.readPreview` with remote reads. Desktop admits each call+against the plugin permission, scope, and current root, resolves the remote binding+from host-owned project records, and sends a closed `workspace/pluginFiles` request.+The remote Host advertises this optional capability, accepts it only from paired+owners, and validates canonical containment, protected Host data, the credential+deny-list, and the declared scope before reading; a root must sit under the folder+picker's browse root or match a canonical registered project root, and requested and+canonical file names must both match scope.++The SDK accepts an optional expected workspace identity, and all calls capture their+root before asynchronous admission, so workspace changes, binding replacement, and+plugin unload invalidate late results and remote errors never select a local file of+the same name. Remote workspace metadata adds a display path and a read-only marker+while the opaque identity stays unchanged; this increment covers directories and+classified text/image previews only.## Consequences-Older Hosts remain compatible with existing remote functionality.--The independently maintained File Manager must consume the SDK instead of Node-filesystem calls for remote projects.+- Older Hosts keep working, a missing capability reports an explicit upgrade error,+ and the service carries neither models nor provider credentials.+- The independently maintained File Manager must consume the SDK for remote projects.+ The integration candidate bundles the consumer as Desktop hotfix `0.9.1-pi.1` with+ its checksums in `UPSTREAM.md`, which does not claim the companion proposal was+ accepted or published.+- Remote editing, filesystem search, watching, and application launching stay+ outside this repair, as does exposing the broader owner file service, which would+ not preserve plugin policy.diff --git a/docs/adr/provider-display-order.md b/docs/adr/provider-display-order.mdindex f540c10d6..a7cb36dc6 100644--- a/docs/adr/provider-display-order.md+++ b/docs/adr/provider-display-order.md@@ -5,27 +5,30 @@## Context-Provider rows are listed in creation order. Users need to move frequently used-services ahead of others in settings and model selection menus.+Provider rows list in creation order, but users need frequently used services+ahead of others in settings and model menus, and list placement must survive the+manifest reconciliation that owns provider configuration.## Decision-Rust host-core stores the ordered IDs under the existing `kv` key-`providers.order` and applies them to `providers.list`. The additive-`providers.reorder` RPC moves one ID before or after another under the host-state lock.+Host-core stores ordered IDs under the existing `kv` key `providers.order` and+applies them to `providers.list`, and the additive `providers.reorder` RPC moves+one ID before or after another under the host state lock, so the renderer sends a+move rather than a replacement list and a provider created during a drag stays+present. Cards use pointer dragging with a live slot preview, keyboard moves share+the list-order transformation with model ordering, and a failed save restores the+accepted order.-Provider cards use pointer-driven dragging with a live slot preview and edge-scrolling. Keyboard moves share the list-order transformation with model-ordering.+## Consequences++- No SQL schema or protocol-version migration is needed, and older clients ignore+ the metadata.+- New providers append in creation order and stale saved IDs are ignored, so+ sorting a plugin row grants no permission to edit its fields.## Alternatives-- Renderer-only storage would make order depend on which consumer lists+- Renderer-only storage: rejected; order would depend on which consumer listsproviders.-- A sort field in provider configuration would mix user placement with- plugin-managed fields and require editing multiple provider records per move.--## Consequences--No SQL schema or protocol-version migration is needed.+- A sort field in provider configuration: rejected; it would mix user placement+ with plugin-managed fields.diff --git a/docs/adr/provider-metadata-client-certificate-retry.md b/docs/adr/provider-metadata-client-certificate-retry.mdindex e666d699f..b4130306c 100644--- a/docs/adr/provider-metadata-client-certificate-retry.md+++ b/docs/adr/provider-metadata-client-certificate-retry.md@@ -6,34 +6,38 @@## Context-Electron 43's net module leaves its client certificate responder unimplemented.-A server requesting an optional client certificate therefore aborts model-metadata discovery with `net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED` before HTTP is-sent, even when it accepts an empty client identity.+Electron 43 leaves its client certificate responder unimplemented, so a server+requesting an optional client certificate aborts model metadata discovery with+`net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED` before HTTP is sent, even when it accepts+an empty client identity. Electron 44 (issue Electron #52162) fixes this but+drops macOS 12 support and changes the clipboard API.## Decision-Keep Chromium as the primary transport. Extract the metadata transport from-model discovery and connection probes.--The retry uses the existing authenticated loopback SOCKS relay. Its resolver-consults the default Chromium session, including the active System/PAC, Direct,-custom proxy and bypass configuration.+Keep Chromium as the primary transport but extract the metadata transport from+model discovery and connection probes, and on exactly the+client-auth-certificate error retry that HTTPS GET or OPTIONS once through Node+TLS without a client identity. The retry travels over the existing+authenticated loopback SOCKS relay, whose resolver consults the default Chromium+session including System/PAC, Direct, and custom proxy configuration, with no+direct fallback when proxy routing fails; it keeps the original AbortSignal and+manual redirect mode, uses bundled and OS CA roots per request without changing+process-wide TLS settings, and owns and closes its tunnel, socket, and agent.+Nothing else retries: no global fetch fallback, no agent turns, plugin+requests, ordinary HTTP responses, unrelated TLS failures, or cancelled work.## Consequences-Optional client authentication reaches ordinary HTTP responses; mandatory client-authentication still fails.--A focused Electron E2E reproduces the original failure and exercises actual-model discovery and connection tests through direct and authenticated proxy-routes.+- Optional client authentication reaches ordinary HTTP responses while+ mandatory client authentication still fails.+- There are no persistence, IPC, or plugin contract changes, and the retry+ fails closed where proxy authentication is interactive or OS-integrated.+- The compatibility retry is removed once a validated runtime provides native+ recovery.## Alternatives-- Electron 44: the upstream solution, but requires a separate platform/API+- Electron 44: the upstream solution, but it needs its own platform and APImigration decision.-- Only add an app event handler: Electron 43 never emits it for net requests.-- Replace global fetch with Node: changes unrelated networking, cookies, proxy- authentication and plugin behavior.-- Disable server certificate checks: unrelated to the root cause and unsafe.+- Replace global fetch with Node: rejected, it changes unrelated networking,+ cookies, proxy authentication, and plugin behavior.diff --git a/docs/adr/provider-system-certificates.md b/docs/adr/provider-system-certificates.mdindex 36a2c3e6d..e9c6a90cc 100644--- a/docs/adr/provider-system-certificates.md+++ b/docs/adr/provider-system-certificates.md@@ -2,40 +2,44 @@- Status: Accepted- Date: 2026-09-20-- Related: Issue #714, ADR 0177, ADR 0271+- Related: ADR 0177, ADR 0271, issue #714## Context-HTTPS inspection can present a chain anchored in a locally installed trusted-root. Chromium and the agent sidecar use different TLS implementations; the-sidecar's bundled roots alone can reject a chain trusted by the operating-system.+HTTPS inspection can present a chain anchored in a locally installed trusted root,+but Chromium and the agent sidecar use different TLS implementations, so the+sidecar's bundled roots can reject a chain the operating system trusts. Node's+`--use-system-ca` covers Windows and Linux, yet on macOS that build replaces the+bundled Mozilla roots with an enumerated system set missing public anchors, so a+GlobalSign-anchored chain fails with `UNABLE_TO_GET_ISSUER_CERT` (issue #1187).## DecisionThe desktop launcher passes `--use-system-ca` before the sidecar entry point on-Windows and Linux. On macOS the launcher omits the flag; instead the sidecar-merges its bundled roots, the inherited `NODE_EXTRA_CA_CERTS` set, and the-system-store certificates into the default CA set at startup-(`tls.setDefaultCACertificates`, agent-runtime `system-ca`).--This applies to the desktop sidecar's default Node TLS clients, including the-direct, HTTP proxy and SOCKS provider transports. It is a process-level default,-not a per-provider exception.+Windows and Linux; on macOS it omits the flag and the sidecar merges its bundled+roots, the inherited `NODE_EXTRA_CA_CERTS` set, and the system-store certificates+into the default CA set at startup (`tls.setDefaultCACertificates`, agent-runtime+`system-ca`), deduplicating by content and omitting certificates already expired in+the OS store. Certificate chain, expiration, and hostname validation stay enabled,+the app neither installs roots nor exports a bundle, and the operating system's trust+policy is the authority for local roots. The process-level default covers the+sidecar's default Node TLS clients, including the direct, HTTP proxy, and SOCKS+provider transports, while headless `pi-host` launch policy is unchanged. Explicit+certificate verification codes make `NETWORK_ERROR` non-retriable and exclude it from+transport rebuilding, before setup replay and after the adapter flattens the error,+for both session and built-in delegates.++## Consequences++- Organizations that install trusted inspection roots extend that trust to the+ desktop sidecar, while untrusted chains and hostname mismatches remain rejected.+- No IPC fields, database format, credentials, or proxy settings change, and changing+ roots or the extra-CA environment requires a desktop restart.+- The transcript explains certificate validation failure without asserting that+ security software is the cause.## Alternatives-- Exporting the Windows stores to PEM adds platform-specific subprocesses,- filesystem lifecycle, and duplicate trust-policy maintenance.-- A new custom-CA setting introduces persistence and restart semantics.-- Disabling certificate or hostname verification is unacceptable.-- Suppressing every `tls` category is too broad: that category also includes- protocol errors, not just certificate validation failures.--## Consequences and validation--Organizations that install trusted inspection roots now extend that trust to the-desktop sidecar.--`scripts/e2e-provider-certificates.mjs` exercises the real desktop launcher,-bundled sidecar, pi-ai and a loopback HTTPS provider.+- Export Windows stores to PEM: adds platform-specific subprocesses and duplicate+ trust-policy maintenance.+- Add a custom-CA setting: `NODE_EXTRA_CA_CERTS` already covers it.diff --git a/docs/adr/registry-header-variable-spelling.md b/docs/adr/registry-header-variable-spelling.mdindex e7cb794a7..36fd9dfb6 100644--- a/docs/adr/registry-header-variable-spelling.md+++ b/docs/adr/registry-header-variable-spelling.md@@ -2,31 +2,38 @@- Status: Proposed- Date: 2026-09-20-- Deciders: Pending maintainer review- Related: ADR 0245, E2E-MCP-MARKET-SEMANTICS## Context-The official MCP registry spells a remote header variable `{name}` and declares-the name in the header's `variables` map. Its schema describes `variables` as-the values that replace "keys in the input `value` that are wrapped in-`{curly_braces}`".+The official MCP registry spells a remote header variable `{name}` and declares the+name in the header's `variables` map, with lower-case names such as `api_key` allowed,+while builtin catalog and stdio templates spell `${NAME}` in upper case and the registry+adapter knew only that spelling, so a record kept `Authorization: Bearer {api_key}` with+no `requiredEnv` entry and left an unresolved template at the parser boundary.## Decision-1. The registry adapter resolves `{name}` only when that same header declares it- in `variables`; undeclared braces remain literal.-2. Add optional `headerBindings` to the shared catalog template.-3. Header templates accept both spellings and consume the `$`, so a `${NAME}`- header resolves without a stray dollar.-4. stdio templates keep the `${NAME}` spelling and the upper-case name rule.-5. `requiredEnv` names are validated against the transport: variable names for- `http`, environment-variable names for `stdio`.+The registry adapter resolves `{name}` only when that same header declares it in+`variables`, keeping undeclared braces literal and legacy `${NAME}` tokens working+without a variables map, and each header owns its definitions. The shared catalog+template gains optional `headerBindings`, mapping exact tokens per header to an editable+`requiredEnv` input or a fixed literal, where its presence — even empty — selects+explicit binding mode so `{name}` and `${NAME}` stay literal regardless of global+`requiredEnv` names, and only catalogs without it use the legacy global input scope,+with collision-safe names for same-named inputs in separate headers. Header templates+accept both spellings and consume the `$`, while URL templates keep the upper-case+`${NAME}` rule so a header declaration never makes bare `{name}` in a URL editable, and+`collectCatalogPlaceholders` and `resolveCatalogEntry` select the same pattern per+field. stdio templates keep `${NAME}` unchanged, bindings never enter the host+`McpServerInput` or persisted config, and `requiredEnv` names are validated against the+transport: variable names for `http`, environment-variable names for `stdio`.## Consequences-- Declared editable header variables yield prompts and resolve according to- their own defaults and requiredness.-- Builtin catalog entries and stdio packages behave exactly as before.-- The catalog can express a header variable that is not an environment variable- name, which is what the registry publishes.+- Declared editable header variables prompt and resolve by their own defaults, while+ fixed variables and unbound brace text prompt for nothing and header-local bindings+ prevent cross-header leakage.+- Bare URL tokens stay literal through mapping, resolution, and host persistence.+- Builtin catalog entries and stdio packages behave as before, and the catalog can+ express a header variable that is not an environment-variable name.diff --git a/docs/adr/remote-project-home-workflow.md b/docs/adr/remote-project-home-workflow.mdindex 6fc2ed08e..ffb5b05d3 100644--- a/docs/adr/remote-project-home-workflow.md+++ b/docs/adr/remote-project-home-workflow.md@@ -2,41 +2,41 @@- Status: Superseded for new projects by [Local Agent remote workspace tools](local-agent-remote-workspace-tools.md)- Date: 2026-10-11-- Related: ADR 0286, ADR 0292,- [remote Agent Control](../spec/02-architecture/05-remote-agent-control.md)+- Related: ADR 0286, ADR 0292, [remote Agent Control](../spec/02-architecture/05-remote-agent-control.md)## Context-The experimental remote client already registers Host directories and routes-session operations over RACP. Its project creation entry point lived in-Settings, and opening a remote chat replaced the regular chat surface with a-separate text-only conversation UI.+The remote client registered Host directories and routed session operations over+RACP, but project creation lived in Settings and opening a remote chat replaced+the chat surface with a separate text-only UI, so users could neither create a+remote project from home nor switch projects through the usual controls. Remote+paths must also never be reused as local workspace paths.## Decision-Use the existing Create project dialog and shared ChatSurface, Composer, and-retained transcript panes for remote projects. The dialog selects a connected-Host, an existing remote project, or a directory on that Host.--Electron main validates the host/path input and directory response. The Host-retains its canonical directory containment and browse-root policy.--## Alternatives--- Add another home shortcut to the Settings workbench: simpler, but leaves- different creation, project switching, and conversation workflows.-- Treat remote paths as local project paths: rejected because identity- collisions and workspace activation would cross the machine and security- boundary.-- Enable all local controls for remote chats: rejected because the current Host- capability profile does not implement those operations or desktop-tool relay.+Remote projects use the existing Create project dialog and the shared+ChatSurface, Composer, and transcript panes, with an additive Desktop-only+`remoteHostBrowseProjects` IPC channel exposing the Host's `project/browse`+operation and no new RACP method or protocol version. Electron main validates+host and path input, and the Host keeps its canonical containment and+browse-root policy. A remote project is identified by `(hostKey, projectId)`:+home and sidebar selection create remote sessions directly and never place a+remote path in local project state, new chat reuses only an empty idle chat in+that identity, and retained panes authorize against their own session. Composer+and transcript actions follow session capabilities, so text, tools, permissions,+and input cards work while local attachment staging, commands, plugins, file+resolution, previews, rollback, and unsupported configuration stay unavailable.## Consequences-No persisted database, Plugin SDK, Host wire protocol, provider ownership, or-process architecture changes.+- No persisted database, Plugin SDK, Host wire protocol, or process architecture+ change, and local projects and concurrent local work are unaffected.+- Remote chats keep unsupported features disabled; this is not full R2 feature+ acceptance.++## Alternatives-Validation covers real dialog/Composer/project-switching interactions with-isolated IPC fixtures, retained-pane action guards, opaque history cursors, and-a packaged Host directory-selection-to-agent-turn path with a local model-fixture.+- Treat remote paths as local project paths: rejected, identity collisions would+ cross the machine and security boundary.+- Enable all local controls for remote chats: rejected, the Host capability+ profile does not implement them.diff --git a/docs/adr/remote-provider-import.md b/docs/adr/remote-provider-import.mdindex 934047d23..45db07d71 100644--- a/docs/adr/remote-provider-import.md+++ b/docs/adr/remote-provider-import.md@@ -5,27 +5,32 @@## Context-A fresh SSH Host cannot chat until it has a usable provider/model. RACP must not-become a credential relay, and starting a second host-core to import+A fresh SSH Host cannot chat until it has a usable provider and model, RACP must+not become a credential relay, and starting a second host-core to importconfiguration would violate the single-writer lifecycle.## Decision-Keep the existing ownership model. The user selects eligible providers and-confirms credential copying in Settings.+The user selects eligible providers and confirms credential copying in Settings;+Main reads only those secrets, validates a versioned bounded payload, and writes+it to an explicit SSH command's stdin. `pi-host provider-import` forwards the+payload to the running Host over an owner-only Unix socket that accepts only+provider import and uses the Host's existing Rust RPC connection instead of being+a general-purpose tunnel. Permissions, a process ownership lock, connection and+request limits, and deadlines bound the channel, and a private digest receipt+journal makes identical retries idempotent without storing raw credentials.-Directory/socket permissions, a process ownership lock, connection/request-limits and deadlines bound the new local channel. A private digest receipt-journal makes identical retries additive and idempotent without storing raw-credentials.--## Alternatives+## Consequences-- Sending secrets through RACP would expand the network credential boundary.-- A standalone database importer would introduce a second writer and bypass- existing provider validation and secret storage.-- Automatic bulk copying would make consent and minimum disclosure unclear.+- No database schema, AgentEvent, or RACP operation changes, and existing remote+ rows are never overwritten.+- Import requires a running same-version Host and a Unix SSH target, and OAuth,+ local CLI providers, and local-only endpoints are not portable.+- Uncertain creation is reported for operator diagnosis rather than retried+ silently.-## Consequences+## Alternatives-No database schema, AgentEvent or RACP operation changes.+- Sending secrets through RACP: rejected; it expands the network credential+ boundary.+- A standalone database importer: rejected; it introduces a second writer.diff --git a/docs/adr/response-annotations.md b/docs/adr/response-annotations.mdindex c70719907..1bc0c6e19 100644--- a/docs/adr/response-annotations.md+++ b/docs/adr/response-annotations.md@@ -3,39 +3,35 @@- Status: Superseded by ADR 0268- Date: 2026-09-11-- Deciders: PI-Desktop runtime and desktop UI maintainers- Amends: D-LOCAL-message-quotes decision 3 (for assistant turns)- Preserves: D209, D301, D097, D128-- Related: [04-ux/08-component-spec.md](../spec/04-ux/08-component-spec.md) ·- [04-ux/09-interaction-patterns.md](../spec/04-ux/09-interaction-patterns.md) ·- [03-runtime/11-provider-model-system.md](../spec/03-runtime/11-provider-model-system.md) ·- ADR message-quotes-and-side-chats · E2E-CHAT-annotation-attachments, E2E-CHAT-annotation-session-state · Amendment: 2026-09-12 (comment editor)+- Related: ADR message-quotes-and-side-chats, E2E-CHAT-annotation-attachments,+ E2E-CHAT-annotation-session-state · Amendment: 2026-09-12 (comment editor)## Context-ADR message-quotes-and-side-chats (D-LOCAL-message-quotes) made quoting a-**draft edit**: the excerpt becomes `> `-prefixed Markdown text inside the-composer, attributed with `chat.quoteSource`.--```text-# Response annotations:-Each item contains text selected from an earlier Codex response and may include a user comment. …-<response-annotations>-[{"text":"…","annotation":"…","source":{…}}]-</response-annotations>--## My request:-…the user's own prompt…-```+Quoting as a draft edit copied the model's words into the draft the user was+writing, so "refer to this pass" became indistinguishable from "write this text+myself" and several references collapsed into one unaddressable block.## Decision-1. Selecting text inside an **assistant turn** and activating the selection- overlay's **Add to chat** creates one annotation instead of editing the- draft. An annotation carries an id, the anchored turn (`messageId`), the- excerpt (Markdown, capped at 2000 characters with a trailing ellipsis), an- empty `annotation` comment field, and a creation time.+Selecting text in an assistant turn attached a numbered annotation instead of+editing the draft: annotations were renderer-owned session state in capture+order, each with its own comment, sent as a `<response-annotations>` block+ahead of the user's request while the visible draft stayed the user's own words.+The answer body was never decorated by the app — only a model-written+`:codex-annotation{index="N"}` citation rendered as a marker — and a later+amendment replaced the silent attach with a comment editor and an annotation+list disclosure in the composer. No host protocol, storage schema, IPC channel,+or permission changed.## Consequences-Superseded (Superseded by ADR 0268). The full record is in git history.+- The model received each annotated pass as a numbered data item while the+ user's prompt stayed exactly what the user typed.+- Annotations were lost on relaunch and after the send that carried them.+- The draft quote from D-LOCAL-message-quotes survived for user messages and+ side-chat handoff.++Superseded by [ADR 0268](0268-remove-quotes-annotations-and-side-chats.md).diff --git a/docs/adr/retained-browser-pages-per-tab.md b/docs/adr/retained-browser-pages-per-tab.mdindex e95a1763e..90712cc31 100644--- a/docs/adr/retained-browser-pages-per-tab.md+++ b/docs/adr/retained-browser-pages-per-tab.md@@ -6,24 +6,31 @@## Context-Browser resource tabs initially retained addresses but shared one guest.-Switching reloaded pages and discarded form/scroll/JavaScript state.+Browser resource tabs retained addresses but shared one guest, so switching reloaded+pages and discarded form, scroll, and JavaScript state, while mixing session-only+navigation with tab addresses let `BrowserPreview` overwrite the active tab and+exposed old state in empty tabs.## Decision-Electron Main's BrowserHost owns pages keyed by session id and tab id. Each page-owns its BrowserPane, CDP state, navigation generation, and current browser-state.--BrowserPreview validates the request and asks BrowserHost to create and load a-new resource page before its renderer tab mounts. Background browser.navigate-runs immediately in its session's connected page.--## Alternatives--Keeping one guest and saving only URLs cannot preserve live page state.+Electron Main's `BrowserHost` owns pages keyed by session id and tab id. Each page+owns its `BrowserPane`, CDP state, navigation generation, and browser state; only+the selected page attaches to the measured browser hole, and hidden pages keep+their `WebContents` under background throttling. The browser partition and existing+URL, permission, file-root, and CDP allowlists stay intact. `BrowserPreview` asks+`BrowserHost` to create and load a resource page before its renderer tab mounts, and+background `browser.navigate` runs in its session's connected page, so presentation+and the tool connection are independent (see+[background lifecycle](browser-background-lifecycle.md)). Bundled chrome tags+requests with the owning session and tab, so a delayed reply cannot repaint another+tab. Closing a tab releases its page and CDP state, as do session deletion, plugin+disposal, and shutdown; a renderer reload only detaches presentation while Main+keeps the pages for restoring side-panel tabs.## Consequences-Normal tab switching preserves forms, scroll position and per-tab navigation-history without issuing another load.+- Tab switching preserves forms, scroll position, and per-tab history without+ another load, and stale work cannot change another tab.+- Memory grows with open pages and is released by closing tabs.+- Restart persists no arbitrary DOM and a crash does not promise unsaved-form+ recovery; no schema or plugin permission is added.diff --git a/docs/adr/s3-only-configuration-backup-sync.md b/docs/adr/s3-only-configuration-backup-sync.mdindex ecf646ca0..55097ef57 100644--- a/docs/adr/s3-only-configuration-backup-sync.md+++ b/docs/adr/s3-only-configuration-backup-sync.md@@ -6,35 +6,42 @@## ContextA configuration vault must preserve encryption, domain allowlists, device-local-mappings, credential opt-in, approvals, and concurrent-edit safety. The existing-WebDAV compatibility mode required per-device heads and listing/ancestry logic-while still lacking atomic initialization and reliable shared publication.+mappings, credential opt-in, approvals, and concurrent-edit safety. The WebDAV+compatibility mode needed per-device heads and listing ancestry while still+lacking atomic initialization and reliable shared publication, and the approved+direction is direct private S3 storage without a custom cloud service, database+upload, or WebDAV fallback. Users also need a local-snapshot backup mode that+applies no remote changes.## Decision-Keep persistence, encryption, merge, scheduling and import ownership in Rust-Host Core. Replace WebDAV with a bounded AWS Signature V4 S3 transport using-maintained cryptographic primitives.--Use separate authenticated `head` and `backup-head` objects. Sync performs-three-way merge and applies remote changes; backup publishes only local-snapshots.--## Alternatives--- Keep WebDAV alongside S3: rejected by the approved S3-only scope and because- it preserves a second publication and compatibility path.-- Accept ignored conditional headers: rejected because concurrent publication- can silently lose configuration changes.-- Store SQLite or the entire data directory: rejected because it includes device- state, credentials and unrelated data rather than portable entities.-- Delete everything outside the 30-entry history index: rejected because- resource sharing, in-flight publication and offline devices are not proven- safe by one device's index.+Rust Host Core keeps persistence, encryption, merge, scheduling, and import+ownership and replaces WebDAV with a bounded AWS Signature V4 S3 transport on+maintained cryptographic primitives, supporting path-style and virtual-hosted+addressing and session tokens, with a mandatory successful conditional-write+probe and no append-only or unconditional fallback. Separate authenticated+`head` and `backup-head` objects drive three-way merge: sync applies remote+changes, backup publishes only local snapshots, and each head indexes the latest+revisions while immutable objects stay indefinitely. Only the new S3 data format+is supported, with no legacy detection or migration and no deletion of unrelated+old data, under a new `configSyncS3` key namespace with a fresh local state+identity on connection or mode changes and credential reuse bound to the whole+connection identity. Sync restore publishes a new shared revision with explicit+propagation acknowledgment, backup restore applies locally, both save a local+recovery point, and password changes rewrap the same vault key.## Consequences-The implementation has one cloud transport and publication model, no server-component, and unchanged process ownership.+- One cloud transport, one publication model, no server component, and unchanged+ process ownership; existing WebDAV users must configure S3 explicitly and+ their old backups stay untouched but cannot be restored through S3.+- Storage can grow indefinitely, and a bucket lifecycle policy that expires+ referenced objects can break synchronization or restore.+- Providers must honor strong ETags and conditional writes, and encryption+ protects contents but not bucket identity, timing, sizes, or traffic patterns.++## Alternatives-Storage can grow indefinitely.+- Keep WebDAV alongside S3: rejected, it preserves a second publication path.+- Accept ignored conditional headers: rejected, concurrent publication can+ silently lose configuration changes.diff --git a/docs/adr/scheduled-desktop-automations.md b/docs/adr/scheduled-desktop-automations.mdindex 5d6f17fa7..9f4a702a2 100644--- a/docs/adr/scheduled-desktop-automations.md+++ b/docs/adr/scheduled-desktop-automations.md@@ -5,43 +5,53 @@## Context-The shipped Scheduled page stores a cadence but never dispatches work when that-cadence becomes due. The pinned pi-ai, pi-agent-core and pi-coding-agent 0.87.1-packages supply agent execution, not a persistent desktop wall-clock scheduler.+The Scheduled page stored a cadence but never dispatched work when it became due.+The pinned pi packages supply agent execution, not a persistent desktop wall-clock+scheduler, and the host-owned task and run tables already provide the right storage+boundary.## Decision-Keep schedule calculation, persistence, duplicate admission and restart recovery-in Rust host-core. A small Electron lifecycle service polls every 30 seconds-while the app runs and dispatches admitted work through the existing agentPrompt-handler.--Use the existing config_json extension boundary for a validated schedule {hour,-minute, weekday, weekdays?}, nextRunAt in epoch milliseconds and workspacePath.-The workspace is captured when a schedule is first configured.+Schedule calculation, persistence, duplicate admission, and restart recovery stay in+Rust host-core. A small Electron lifecycle service polls while the app runs and+dispatches admitted work through the existing `agentPrompt` handler, never asking the+renderer to execute a background task, and the existing turn finalizer closes the+run. The existing `config_json` extension boundary carries a validated+`{hour, minute, weekday, weekdays?}` schedule, `nextRunAt` in epoch milliseconds,+and the `workspacePath` captured when the schedule is first configured, so no new+tables, columns, or migration are needed; old cadence-only records stay unarmed until+configured. `scheduled.run` keeps its prepare-only response, `scheduledExecute`+dispatches a turn, and `scheduledListRuns` exposes the run ledger. Automatic runs use+the task's saved permission mode, default to Ask when the field is absent, keep Plan+and Goal denied, and reuse a saved provider and model or resolve the app defaults at+execution time, while the task's project survives a foreground workspace change.+Scheduled is reachable from a footer clock action and global search.++### Calendar provenance++The optional `calendarConfigured` key records explicit Daily or Weekly intent+separately from Hourly's internal placeholder. Legacy Daily and Weekly rows infer+intent from their cadence, while legacy Hourly rows keep their fields but require an+explicit schedule on conversion, because their origin cannot be recovered.++### Conversation management++Project-scoped CRUD is exposed as on-demand Agent tools through the existing+`tools.execute` permission and audit pipeline. A thin host adapter reuses the+scheduled RPC handlers with the calling session's project, so a background+conversation cannot retarget tasks, and list stays read-only.## Consequences-The app must remain running.--## Calendar provenance compatibility--The optional `calendarConfigured` configuration key records explicit Daily or-Weekly calendar intent separately from Hourly's required internal placeholder.-Legacy Daily/Weekly rows infer intent from their saved cadence.+- The app must keep running: a due occurrence more than ninety seconds late is+ skipped rather than replayed in a burst, and an active run suppresses an+ overlapping occurrence.+- Daily and weekly times follow the host timezone and weekly schedules need a+ nonempty unique weekday selection, while hourly tasks wait one elapsed hour after+ saving, enabling, startup, or the previous admission.+- No cloud execution, OS service, arbitrary cron, or sub-hourly interval is added.## Alternatives-A plugin would duplicate lifecycle/storage ownership and make baseline-automation depend on extension availability.--## Conversation management--Expose project-scoped CRUD as on-demand Agent tools using the existing-`tools.execute` permission and audit pipeline. A thin Host adapter reuses the-scheduled RPC handlers with the calling session's project, so background-conversations cannot retarget tasks when the foreground workspace changes.--The UI offers four time periods (09:00, 14:00, 19:00, 22:00) to keep setup-simple. AI tools retain precise local time configuration, and the form preserves-those custom times.+- A plugin: duplicates lifecycle and storage ownership.+- A second agent loop: bypasses existing admission, persistence, and permissions.diff --git a/docs/adr/session-content-search.md b/docs/adr/session-content-search.mdindex 4b53483d5..14f3a7de9 100644--- a/docs/adr/session-content-search.md+++ b/docs/adr/session-content-search.md@@ -2,28 +2,73 @@- Status: Accepted- Date: 2026-09-13-- Issue: https://github.com/vastsa/PI-Desktop/issues/270+- Related: issue #270## Context-Global search originally filtered the renderer's session titles and project-labels, even though host-core already indexed message text. A remembered error-or sentence could not recover its conversation.+Global search filtered the renderer's session titles and project labels even though+host-core already indexed message text, so a remembered error or sentence could not+recover its conversation, and a separate historical reader duplicated the transcript+behind an extra Back to conversation action. Search results should identify and open+the original conversation.## Decision-Add `search.sessions` and `search.context` host RPCs with allowlisted desktop-`session/search` and `session/searchContext` IPC channels. Keep the legacy-`search.query`, `session.get`, protocol version, and storage schema compatible.+Add the `search.sessions` and `search.context` host RPCs behind allowlisted+`session/search` and `session/searchContext` IPC channels, keeping `search.query`,+`session.get`, the protocol version, and the storage schema compatible. Rust stays+the sole SQLite owner, Electron forwards requests, and the renderer owns presentation+and transient query state.-`search.sessions` searches all non-deleted sessions, combining title/project-metadata with indexed user/assistant text. Trigram FTS supplies candidates for-queries of at least three Unicode characters.+`search.sessions` searches all non-deleted sessions, combining title and project+metadata with indexed user and assistant text. Trigram FTS supplies candidates for+queries of at least three Unicode characters, and a host-owned Unicode literal+predicate verifies them and handles shorter or non-ASCII-cased queries, so quotes,+`%`, `_`, and backslashes never become operators. The whole query is a literal+substring, not split into words or read as FTS syntax. Results are paged by updated+time and id with full matching-message counts and at most two recent excerpts per+session, and offset paging continues the current query.-## Consequences and validation+Previews use the sentence or line containing the first match, with Chinese and+English punctuation and line breaks as bounds and a bounded match-centered excerpt+for very long sentences. Archive preferences stay renderer-owned: empty-query recents+hide archived sessions while an explicit search keeps the existing archived+discovery behavior, and tools, thinking, attachments, and discarded revisions stay+outside the searchable body.-There is no migration or new index to maintain.+Selecting a message preview closes search, selects the original conversation, and+scrolls the existing transcript to that message's matching rendered text, using a+stable message id for mouse and keyboard alike. Each assistant fragment exposes its+own anchor even when fragments share one assistant-turn row, literal ranges are+highlighted without rewriting the React-owned Markdown tree, and parser-owned source+offsets map hidden Markdown destinations to the visible link, image, code block, or+file chip so a source-only match highlights that element.-Rust regression tests cover pagination beyond 50 sessions and 100 messages,-literal CJK/symbol queries, complete counts, soft deletion, physical positions,-and target text beyond the display cap.+The additive `session.get({ messageAround, messageLimit, contentLimit })` form+resolves a stable id against physical JSONL positions and returns the original+`UiMessage` projection centered on it. It requires a positive limit, is mutually+exclusive with `messageBefore`, and returns no session for a missing target instead+of an unrelated tail. Only the selected message's text is complete, including a+match beyond the usual display cap, and bounded responses add exclusive `messageEnd`+and `hasMoreAfter` so forward paging uses physical positions. For a nested answer,+optional `navigationParent` carries the owning Task projection and the subagent dock+locates it, while a missing parent reports failure instead of an invisible hit.++The renderer store owns one reading view per retained session for both ordinary+paging and search navigation, as defined in+[ADR transcript-reading-ownership](/adr/transcript-reading-ownership), so no second+historical reader is needed. Ordinary history merges authoritative live output, an+explicit search keeps its snapshot until the user returns to latest or starts a+turn, and neither mode writes live or model caches. Reads are owned by the pending+view's identity, so newer navigation, pane eviction, edits, or a return to latest+invalidate stale completions.++## Consequences++- There is no migration and no new index to maintain, though short and+ non-ASCII-cased queries still need a literal scan.+- Search previews stay bounded, and a search read cannot rewrite conversation data+ or disturb an active turn.+- `search.context` and `session/searchContext` stay compatible for existing callers+ even though global search no longer uses them. The documented scenario is+ `E2E-SESSION-content-search-and-message-navigation`.diff --git a/docs/adr/sidebar-layout-recovery.md b/docs/adr/sidebar-layout-recovery.mdindex d9a5c4cad..f0d52607e 100644--- a/docs/adr/sidebar-layout-recovery.md+++ b/docs/adr/sidebar-layout-recovery.md@@ -2,24 +2,25 @@- Status: Accepted- Date: 2026-11-07-- Amends: ADR 0016 and the renderer sidebar preference contract in data storage.+- Related: ADR 0016## Context-Sidebar presentation state previously existed only in renderer localStorage. A-fresh Chromium profile could therefore hide every retained Project except the-Host-selected one while the Project archive and Sessions remained intact.+Sidebar presentation state lived only in renderer localStorage, so a fresh Chromium+profile could hide every retained project except the host-selected one.## Decision-Keep an atomic, private `sidebar-preferences.json` copy in the selected app data-root. Only the trusted Main top frame can read or replace it through dedicated-IPC.--Restore before bootstrap persists its selected Project. An existing backup wins-over the cache; without a backup, migrate a valid legacy cache, including an-explicitly empty retained-tab list.+Main keeps an atomic, private `sidebar-preferences.json` copy in the selected app data+root that only the trusted Main top frame reads or replaces over dedicated IPC, while+Rust keeps owning projects, sessions, and the active workspace. Restore runs before+bootstrap persists its selected project: an existing backup wins over the cache, a valid+legacy cache is migrated otherwise, and only when both are absent or invalid may the+renderer recover projects from the host. An unreadable backup is never overwritten by an+empty startup snapshot.## Consequences-Writes are bounded to 2 MiB, flushed and atomically renamed.+- A wiped profile no longer loses the sidebar; only an absent and invalid pair falls back+ to host recovery.+- Writes stay atomic and bounded, with no schema or API change.diff --git a/docs/adr/steering-local-tool-interruption.md b/docs/adr/steering-local-tool-interruption.mdindex daccff9c9..d33d48e8d 100644--- a/docs/adr/steering-local-tool-interruption.md+++ b/docs/adr/steering-local-tool-interruption.md@@ -1,25 +1,26 @@# ADR: Steering waits for confirmed tool settlement-- Status: Accepted+- Status: Accepted (supersedes the started-tool behavior in ADR active-turn-steering)- Date: 2026-11-06-- Supersedes: started-tool behavior in ADR active-turn-steering-- Issue: https://github.com/vastsa/PI-Desktop/issues/2131+- Related: active-turn-steering, issue #2131## Context-An indefinitely running tool prevents accepted steering from reaching the model.-Continuing before a mutating operation stops can cause conflicting side effects.+An indefinitely running tool prevents accepted steering from reaching the model, while+continuing before a mutating operation stops can cause conflicting side effects.## Decision-Accepted steering requests cancellation of local foreground Bash and read-operations owned by the current turn. The model receives the input only after-the operations settle; steering does not use Stop's bounded grace period.--Remote workspace calls cannot acknowledge remote settlement through their-existing abort path, so steering does not cancel them. Other started operations-settle normally.+Accepted steering cancels local foreground Bash and read operations owned by the current+turn and reaches the model only after they settle, without Stop's bounded grace period;+unstarted calls are skipped, TaskWait yields while delegates continue, and background+commands are retained. Remote workspace calls cannot acknowledge settlement through their+abort path, so steering does not cancel them, and a shell lifecycle failure, remote failure,+or uncertain external timeout waits for explicit Stop while the UI reports the pending+operation.## Consequences-A hung or unreachable Host may still require Stop.+A hung or unreachable Host may still require Stop; steering keeps the same turn, model,+workspace, and permissions, and leaves the Host's cancellation and process ownership+authoritative.diff --git a/docs/adr/subagent-model-fallback.md b/docs/adr/subagent-model-fallback.mdindex b0b4429f6..40b950819 100644--- a/docs/adr/subagent-model-fallback.md+++ b/docs/adr/subagent-model-fallback.md@@ -6,24 +6,44 @@## Context-A subagent can select only one model. Its existing bounded provider retries-cannot recover when that model remains unavailable.+A subagent can select only one model, and its bounded provider retries cannot+recover when that model stays unavailable, while restarting the delegated task on+another agent could repeat tools that already changed files.## Decision-Add optional `fallbackModels` to a definition, the user-subagent record/input,-and the existing internal launch definition. It is an ordered list of-`provider/model` strings in managed Markdown and host RPC, parsed into model-pins in Shared.--Electron resolves alternatives through the same credential, provider-count, and-model-capability boundaries as primary pins. These bindings are scoped to their-owning definition, even when Task explicitly overrides its primary.--## Settings example--The Advanced section keeps one primary model and lists fallback models in-priority order. Each fallback can be moved up/down or removed.--+A definition, the user-subagent record and input, and the internal launch definition+accept an optional `fallbackModels` ordered list of `provider/model` strings —+managed Markdown and host RPC, parsed into model pins in Shared — alongside the+unchanged primary `model` and Task override priority; a missing list keeps+single-model behavior, an omitted update preserves the list, and `[]` clears it,+with no database or protocol version change. Electron resolves alternatives through+the same credential, provider-count, and model-capability boundaries as primary+pins, scoped to their owning definition, and a primary pin that cannot resolve still+fails before launch while an unresolved alternative is reported when reached and+skipped. After the current model's retries are exhausted, or on a non-retryable+provider error, the runtime tries the next alternative, each resolved+provider-id/model-id pair at most once per delegation: the same agent keeps its+system prompt, original task, successful assistant and tool history, tool scope,+counters, and usage, only the failed assistant request leaves model context before+`continue()` while staying in the visible transcript, and no task or completed tool+is replayed. The model, adapter, credentials, headers, output cap, and thinking+level change together, with thinking re-clamped per model from the definition or+original parent selection; the original abort signal owns the whole chain, and+host/tool failures, missing reports, thrown errors, and cancellation do not initiate+fallback.++## Consequences++- Failed attempts stay visible in child transcript diagnostics and the bounded+ parent report, and lifecycle snapshots keep the final effective model, thinking,+ and additive `modelFailures` diagnostics.+- Exhausting the chain returns `failed` with the final provider error; it never+ selects an unlisted model or silently inherits the parent as recovery.+- Settings lists fallback models in priority order under Advanced, each movable and+ removable.++## Alternatives++- Restart the delegated task on another agent: could repeat tools that already+ changed files.diff --git a/docs/adr/subagent-model-opt-in.md b/docs/adr/subagent-model-opt-in.mdindex f87db128a..b257d6cd2 100644--- a/docs/adr/subagent-model-opt-in.md+++ b/docs/adr/subagent-model-opt-in.md@@ -6,26 +6,41 @@## Context-Electron resolves definition pins and automatically selectable models into one-credential-bearing `subagentProviders` map. Treating every map key as a-`Task.model` selection both advertises private pins and bypasses main's-`availableForSubagents` check on the on-demand path.+Electron resolved definition pins and automatically selectable models into one+credential-bearing `subagentProviders` map, and treating every map key as a+`Task.model` selection both advertised private pins and bypassed main's+`availableForSubagents` check. A definition pin expresses one delegate's default, not+permission to select that model for any delegate.## Decision-Add an optional `subagentModelKeys: string[]` field to the internal Electron-to--sidecar launch payload, runtime options, and reuse comparison. Main includes-only successfully resolved bindings independently marked `availableForSubagents`-on enabled providers.--The runtime uses the separate keys for its model summary. Missing keys mean no-cached override authorization.+Add an optional `subagentModelKeys: string[]` to the Electron-to-sidecar launch+payload, runtime options, and reuse comparison, filled only from resolved bindings+independently marked `availableForSubagents`, while `subagentProviders` keeps carrying+all bindings so definition defaults still work. Reusing a resolved pin does not skip+that opt-in decision, and when an opted-in row's alias collides with another row's+binding, main uses that row's exact provider id, so one account's opt-in cannot+authorize another account's pinned credentials.++The runtime uses those keys for its model summary, and missing keys mean no cached+override authorization. Other keys still pass `provider.resolveSubagentModel`, whose+response may fill a separate override cache that never takes part in launch reuse+matching; on-demand matching uses the same unique id, vendor, and name rule and fails+closed on ambiguous aliases, a changed launch list retires an idle runtime on the next+prompt, and on-demand grants expire at every new parent prompt or approved plan/goal+execution.++The opt-in governs every entry point through which the AI picks a model for delegated+work, including `session/collaboration/spawn` (ADR 0237), whose `modelKey` is refused+with `PERMISSION_DENIED` before a worker exists. `models.list` keeps reporting every+ready model with its `availableForSubagents` flag, which is advice to the caller and+authority only in main (#386), and D278's priority `Task.model` → definition pin →+session model is unchanged.## Consequences-- No provider credential leaves its existing process boundary.-- Older callers that omit the additive field retain definition defaults and- session inheritance.-- Runtime, model transport, and launch wiring regression coverage prove the- boundary.-- Reversing model-selection priority is a product decision outside this fix.+- No provider credential leaves its process boundary, and no host RPC, setting,+ schema, or Plugin SDK change is required.+- Callers omitting the field keep definition defaults and session inheritance, while+ explicit overrides require on-demand authorization and fail closed without it.+- Reversing model-selection priority stays a product decision outside this fix.diff --git a/docs/adr/tool-abort-abandons-host-call.md b/docs/adr/tool-abort-abandons-host-call.mdindex f6ef4fd79..a8f158956 100644--- a/docs/adr/tool-abort-abandons-host-call.md+++ b/docs/adr/tool-abort-abandons-host-call.md@@ -1,51 +1,50 @@# ADR: A user stop preserves tool side-effect boundaries-- Status: Accepted for implementation-- Date: 2026-10-20 (amended 2026-10-23)-- Issues: #1767-- Amends: spec 03-runtime/03-tools-and-permissions.md §3+- Status: Accepted for implementation (amended 2026-10-23; amends+ `03-runtime/03-tools-and-permissions.md` §3)+- Date: 2026-10-20+- Related: issue #1767## ContextThe runtime registered an abort listener for every tool call but returned-immediately unless the tool was `Bash` or `GenerateImages`. For every other tool-— `Grep`, `Read`, `Glob`, `WebFetch`, plugin tools — the listener was inert, and-`tools.execute` was awaited with no deadline and no race against the signal.--1. Host cancellation can close a pending permission and remote calls.-2. Bash process aborts retain their short-lived early-arrival tombstones.-3. `TOOL_ABORTED` already means "the tool was cancelled by a user stop or a turn- abort before it finished" (spec 03-runtime/08-error-codes.md), so the runtime- may report that outcome without host cooperation.+immediately unless the tool was `Bash` or `GenerateImages`, so for `Grep`, `Read`,+`Glob`, `WebFetch`, and plugin tools the listener was inert and `tools.execute` was+awaited with no deadline or race against the signal, letting one long call hold the+turn and session hostage. Local file writes and desktop-dispatched MCP/plugin calls+cannot be safely abandoned once started, but `TOOL_ABORTED` already means "cancelled+by a user stop or turn abort before it finished"+(`03-runtime/08-error-codes.md`), so the runtime may report that outcome without host+cooperation.## Decision-The runtime sends typed `tools.abort` requests for in-flight tools. Host-core-registers cancellation before permission evaluation, so stopping a pending-approval or queued tool prevents it from starting.--For `Bash` and `GenerateImages`, the runtime waits a bounded 10s grace window-for the host to return output collected before process termination. For-mutating, MCP, and plugin calls, the runtime waits for the host result after-requesting cancellation.+The runtime sends typed `tools.abort` requests for in-flight tools, and Host-core+registers cancellation before permission evaluation, so stopping a pending approval+or queued tool prevents it from starting. Local `Read`, `Glob`, and `Grep` calls end+the runtime's wait immediately because they are read-only, with the host observing+cancellation and discarding their result. `Bash` and `GenerateImages` get a bounded+10s grace window for output collected before process termination, while mutating,+MCP, and plugin calls wait for the host result after cancellation: a pending+permission is cancelled, and an operation that already started is not reported as+stopped until its result arrives. Abort records are keyed by session, call id, and+tool name so a delayed abort cannot affect a different tool that reuses the call id,+and `abort()` itself walks the in-flight calls and runs the same handler instead of+relying on the signal alone.## Consequences- A long-running read-only tool no longer holds the turn open after Stop, whilepending permission prompts and admission waits are cancelled at the host.-- Local filesystem workers and already-started extension operations may still- consume resources until they return.-- A new turn uses distinct tool call ids.-- Progress output for an abandoned call stops at the moment of the stop.+- Local filesystem workers and already-started extension operations may consume+ resources until they return, and progress output for an abandoned call stops at the+ stop.+- A new turn uses distinct call ids, and typed abort records keep one tool name's+ abort from being inherited by another.## Alternatives-- **Locally abandon every tool.** Could report a stopped turn while a pending- `Write` approval is later accepted or an already-started plugin/MCP action- continues.-- **Only arm a grace timer on abort (no race for cancellable tools).** Simpler,- but leaves every non-cancellable tool waiting the full window and still keeps- the turn blocked for that window.-- **Wait for host-core to grow cancellation for every tool.** Correct durable- fix, tracked separately; it cannot ship as a bug fix for a turn that is stuck- today.+- Locally abandon every tool: could report a stopped turn while a pending `Write`+ approval is later accepted.+- Only arm a grace timer on abort: leaves every non-cancellable tool waiting the full+ window.diff --git a/docs/adr/transcript-reading-ownership.md b/docs/adr/transcript-reading-ownership.mdindex f16ffd31f..ac4d8e4f0 100644--- a/docs/adr/transcript-reading-ownership.md+++ b/docs/adr/transcript-reading-ownership.md@@ -6,23 +6,38 @@## Context-Search navigation added a pane-local controller alongside ordinary history-paging, a global target handoff, and live/model caches. These independent paths-needed separate cancellation and rewrite handling.+Search navigation added a pane-local controller beside ordinary history paging,+a global target handoff, and live and model caches, so independent paths needed+separate cancellation and rewrite handling, nested assistant answers had no+top-level transcript row, and Markdown could hide the source characters that+matched a query.## Decision-The renderer store owns one transient `TranscriptView` per retained session.-Ordinary paging and search use the same read actions and physical cursors;-MainChat and the subagent dock use the same projection.--Reading views never populate runtime/model caches. A message action hydrates-canonical input when history is partial or display-limited, then rechecks the-session, run, navigation, and message-snapshot ownership before publishing it.+The renderer store owns one transient `TranscriptView` per retained session:+ordinary paging and search share the same read actions and physical cursors,+MainChat and the subagent dock share the same projection, the pending view's+identity owns an asynchronous read, and replacement, eviction, return to latest,+canonical edits, and new turns invalidate stale completions. Ordinary history+always uses the current canonical value for overlapping rows while an explicit+search keeps its selected historical snapshot until the user leaves it or starts+a turn, and reading views never populate runtime or model caches. The additive+`SessionDetail.navigationParent` field carries a nested target's latest owning+Task as capped display context without widening the physical page, and+parser-owned source offsets map hidden Markdown syntax and destinations to+visible elements.## Consequences-This removes the global target transfer, pane-local navigation controller, and-separate ordinary-history load lock.+- The global target transfer, pane-local navigation controller, and separate+ ordinary-history load lock are gone, while cache ownership, transcript+ storage, IPC allowlisting, and the protocol version are unchanged.+- Navigation never loads a whole transcript into the renderer, but stable-ID and+ parent lookup still scan canonical physical identities.+- The optional parent projection stays backward compatible for existing+ session readers.++## Alternatives-Navigation does not load an entire transcript into the renderer.+No alternative kept the single read path: a pane-local controller duplicates+cancellation and rewrite handling, which is the problem this record removes.diff --git a/docs/adr/tray-session-shortcuts.md b/docs/adr/tray-session-shortcuts.mdindex 8fa9090b5..85b8b55d0 100644--- a/docs/adr/tray-session-shortcuts.md+++ b/docs/adr/tray-session-shortcuts.md@@ -6,32 +6,40 @@## Context-The resident tray exposes only Open and Quit. Session pins and archives are-renderer-owned presentation metadata; Host owns session records and the durable-notification inbox.+The resident tray exposed only Open and Quit. Session pins and archives are+renderer-owned presentation metadata while the Host owns session records and the+durable notification inbox, and background turns continue after the window is+hidden, so a renderer-only snapshot would go stale.## Decision-1. Extend the existing native menu with Running, Unread, and Pinned groups in- that order.-2. Renderer mirrors its session pin/archive/order metadata, archived project- paths, and effective session sort through the main-window-only- `tray/setSessionPreferences` IPC.-3. A Main-owned tray service reads `session.list` and `notification.list` (the- existing 200-record inbox), consumes root agent lifecycle/status events, and- refreshes after session/inbox mutations.-4. A session click restores/focuses the main window and sends- `tray/event/sessionActivated { sessionId }` (`null` means View more) only- after the renderer finishes bootstrap and acknowledges menu readiness.-5. Opening the macOS tray menu does not restore the window or mark results read.+1. The native menu gains Running, Unread, and Pinned groups in that order, each+ session assigned to its highest-priority group, with every non-empty group+ keeping a minimum share and leftover rows redistributed to groups that still+ overflow up to a fixed total. Empty groups are hidden, groups follow the+ session sort preference, and unread results use newest-first inbox order with+ the sidebar's latest-result and read rule.+2. The renderer mirrors pin/archive/order metadata, archived project paths, and+ the effective sort through the main-window-only `tray/setSessionPreferences`+ IPC, which Main validates and keeps only ephemerally while localStorage stays+ the owner of organization preferences.+3. A Main-owned tray service reads `session.list` and `notification.list`,+ consumes root agent lifecycle events, refreshes after session and inbox+ mutations, coalesces pending reads, rejects obsolete host generations, and+ clears shortcuts when a refresh fails, with no renderer attached.+4. A session click restores and focuses the window and sends+ `tray/event/sessionActivated { sessionId }` (`null` for View more) only after+ the renderer finishes bootstrap and acknowledges menu readiness, rechecking+ existence and archive state after waits.+5. Opening the macOS menu does not restore the window or mark results read, and+ each overflowing group offers View more, which restores the window and+ expands the sidebar.## Consequences-- Two additive allowlisted desktop IPC channels; the preferences setter is- excluded from local MCP control and rejected for non-main-window senders.-- No database migration, host protocol version change, persisted preference- format change, Plugin SDK change, new timers, or renderer persistence owner.-- Tray reuses existing organization sorting and latest-result helpers without- changing their renderer behavior.-- Native menu rendering and cross-platform activation require the documented E2E- scenario; unit/build results alone do not prove OS menu behavior.+- Two additive allowlisted desktop IPC channels, with the preference setter+ excluded from local MCP control and from non-main-window senders.+- No database migration, host protocol version change, or persisted format+ change.+- Native menu behavior is proven by the documented E2E scenario, not by unit or+ build results alone.diff --git a/docs/adr/trusted-extension-operation-ownership.md b/docs/adr/trusted-extension-operation-ownership.mdindex c7357c1c9..012e2a9e5 100644--- a/docs/adr/trusted-extension-operation-ownership.md+++ b/docs/adr/trusted-extension-operation-ownership.md@@ -5,25 +5,27 @@## Context-Retiring a hook wait alone leaves SDK subprocesses and UI requests alive.-Commands and tools can resume after Stop and publish work into the next turn.+Retiring a hook wait alone leaves SDK subprocesses and UI requests alive, so+commands and tools can resume after Stop and publish work into the next turn,+and because trusted modules run in-process a deadline cannot terminate+arbitrary JavaScript.## Decision-Give each factory, event handler, command and tool execution an invocation scope-propagated through async context. Retire the scope on completion, timeout,-cancellation and disposal.--Preserve the 30-second event/load budget, but do not impose it on commands or-tools: legitimate long tasks continue until explicitly stopped. Calls already-admitted to Host persistence are not transactions that can be undone by-cancelling a JavaScript wait.--## Alternatives--A fixed 30-second limit for all tools would break legitimate long jobs.+Give each factory, event handler, command, and tool execution an invocation+scope propagated through async context and retired on completion, timeout,+cancellation, and disposal, then guard SDK calls against that original scope.+Contexts and tools receive a cooperative signal, SDK subprocess groups are owned+and terminated, and UI cancellation is addressed by session, extension, and+request ID. The event and load budget is preserved but not imposed on commands+or tools, and calls already admitted to Host persistence survive a cancelled+JavaScript wait.## Consequences-SDK work detached from a completed callback must move into an awaited command or-tool.+- SDK work detached from a completed callback must move into an awaited command+ or tool, and a cancelled command stops instead of continuing through+ dismissed prompts.+- Direct Node operations, escaped process groups, and synchronous JavaScript+ stay outside the cancellation guarantee, while the UI wire contract gains+ optional request identity and prompt retirement.diff --git a/docs/adr/turn-process-and-thinking-display.md b/docs/adr/turn-process-and-thinking-display.mdindex 4fc015343..661e68a81 100644--- a/docs/adr/turn-process-and-thinking-display.md+++ b/docs/adr/turn-process-and-thinking-display.md@@ -8,41 +8,132 @@## Context-A model can alternate reasoning, tool calls and progress text many times before-answering one user request. Separate activity groups leave those progress-messages at the same visual level as the answer, while one flat process-container still leaves long tool/search sequences difficult to scan.+A model can alternate reasoning, tool calls, and progress text many times before+answering. Separate activity groups put progress text on the same visual level as+the answer, one flat process container makes long tool sequences hard to scan, and+some readers want a thinking indicator without rapidly changing reasoning text.## Decision-One unified turn-process presentation applies to every loaded assistant-turn-entry: it projects the entry into one collapsible process disclosure plus its-trailing answer. Thinking, tools, intermediate assistant text and the turn's-`Bash` run rows keep their original order inside that disclosure.+Every loaded assistant turn is projected into one collapsible process disclosure+plus its trailing answer. Thinking, tools, intermediate text, and the turn's+`Bash` run rows keep their order inside it. Trailing text stays visible while+streaming and moves into the process if later activity follows, without changing+the stored message. `UiMessage` has no final-answer marker, so the renderer never+guesses intent from wording; user/system messages and compaction dividers keep+their turn boundaries.-One turn renders exactly one process disclosure. Every row the turn produced-before its answer lives inside it — the activity groups and the `Bash` run rows-alike — so a long turn collapses in one gesture instead of leaving a column of-sibling disclosures above the answer.+One turn renders exactly one disclosure holding every row produced before the+answer, so a long turn collapses in one gesture. An untouched process closes when+the turn completes; without final text the header and its error or pending-action+surfaces stay visible.-- In `fully-folded`, contiguous activity forms ordinary activity groups: one- contiguous tool/search/thinking/Bash segment between ordinary assistant- progress paragraphs.-- In `command-first`, ordinary activity groups still render, but every- `Bash`/run alias is lifted out as a standalone row beside them: adjacent calls- stay separate and a row's detail stays closed until the user opens it.-- In `flat`, no nested activity groups render at all.+`AppSettings.transcriptDisplayMode` decides grouping inside the disclosure:+`flat`, `command-first`, or `fully-folded`, with absent or unknown values+resolving to `fully-folded` (the v0.20.0 layout).++- `fully-folded`: contiguous activity forms ordinary groups — one contiguous+ tool/search/thinking/Bash segment between progress paragraphs. A run row stays+ inside its group, and Task topology remains its segment's container.+- `command-first`: groups still render, but every `Bash`/run alias becomes a+ standalone row beside them, closed until opened; a progress message and a+ command both end the current group.+- `flat`: no nested groups; the disclosure lists tools, commands, thinking, and+ progress in transcript order with tool details collapsed.++In the first two modes a group appears only with at least two visible items under+the current thinking preference; a singleton uses its item disclosure. Deprecated+`keepCommandsExpanded` still loads from persisted settings, is hidden from+Settings, is not read for rendering, and new writes store+`transcriptDisplayMode`.++The 2026-11-04 amendment (#2094) replaced the earlier settled defaults (small+groups and Thinking rows stayed open). A settled turn now folds both levels: its+activity groups and every non-streaming Thinking row start closed, so expanding a+finished turn reads as a list of headings. Two opt-outs carry the choice.+`autoCollapseSettledGroups` (`Auto-fold finished groups`) folds settled groups+whatever their size; when off, every settled group stays open — the four-item tier+is retired, because a switch labelled auto-collapse must not still collapse+something. `autoCollapseThinking` (`Auto-fold finished thinking`) folds completed+reasoning; when off, rendered reasoning rows stay open. Each is a sub-row of the+setting that gates it (`Show thinking`, and a non-flat `Transcript display`), and+hiding a sub-row never writes a value, so the stored choice survives toggling the+parent. The group no longer inherits open state from contained reasoning: closing+hides expanded reasoning, reopening restores each row's own answer. Live work never+folds — a running turn, or a group owning a running tool or delegation, stays open.+A folded group is one line whose header states its composition: contained actions+joined with the locale's list wording, capped at three plus "and more", then the+call count as a separate token that ellipsizes last (`搜索并读取文件 · 12 次操作`).+Reasoning is named but is not an operation, and a reasoning-only group counts steps.+The group header renders no issue counter, because the failed row reports itself.++The disclosure header states the outcome with only bounded metadata: status,+recorded duration, and direct tool/search count. It never echoes the item being+worked on, since a command or query can be arbitrarily long. It reads `failed`,+`stopped`, `running`, or finished, in that precedence: a recorded failure outranks+a stop, because the turn produced no answer. A stop comes from an aborted message,+the only signal the runtime records; aborted activity rows record a stop while a+step is in flight, and delegated child rows never decide the parent's outcome.+While running, compaction and recovery name themselves, a live reasoning step reads+`Thinking`, and momentary stages read as running. Missing timing drops the duration+instead of showing zero. The header is a full-width row on a hairline, with status,+duration, tool count, and caret as one left-aligned run; hover changes ink only.++The disclosure and group headers share one left edge. A nested group keeps the+v0.20.1 hierarchy: children indent 12px, with the group's collapse rail in that+gutter — invisible at rest, a 2px bar on hover or focus. The outer fold adds no+hierarchy, and a review-backed Write/Edit stays a single tool-level row under its+file header.++Thinking is the boolean `showThinking`. When on, visible Thinking rows expand by+default in all modes and can be collapsed per row: expanded shows full reasoning+markdown, collapsed shows only the indicator with no summary. When off, no+completed reasoning row renders; a live whole-run `TextShimmer` `Thinking`+indicator remains while reasoning streams — a 1.2s linear sweep with a 220ms fade,+no spinner or per-character animation, static under reduced motion. Stored+reasoning is retained, so re-enabling restores the rows, and hidden thinking never+creates an empty group wrapper.++Apart from those Thinking defaults, item payloads never open themselves: a+tool-call, hosted-search, or plan row stays a header row until the user opens it.+Each header toggles only its own level: closing a parent preserves descendant+choices, siblings do not form an accordion, and an explicit choice never pins an+ancestor. Reading protection is transient — while focus or a selection is inside a+level, automatic close is deferred for it and its ancestors. Manual choices survive+streaming, completion, preference changes, reparenting, and row remounts while the+retained pane lives; pane eviction, session deletion, or restart releases this+pane-owned presentation state, which is never stored in messages or host settings.++Search/navigation reveals the ancestor path its target needs — the turn process+and any owning group. Replaying a request never overrides a later manual close,+reasoning hidden by the preference stays hidden until `showThinking` is on, and+errors, stopped partial answers, and pending permission/question/plan/goal+decisions stay outside hidden process content and reachable without expanding it.++Settings → AI → Defaults exposes `Show thinking` (optional `showThinking`) and+`Transcript display` (`Flat`, `Commands first`, `Fully folded`, optional+`transcriptDisplayMode`); absent or invalid mode values resolve to `fully-folded`+in both the renderer and the main-process normalizers. Absent or non-boolean+`showThinking` falls back to legacy `thinkingDisplayMode`: `compact` hides+reasoning, while `detailed`, unknown, or absent shows it. Legacy fields stay only+for persisted-settings compatibility. These preferences change presentation only —+never provider thinking levels, context, stored reasoning, export, permissions,+execution, or copy payloads — and the thinking preference does not control+folding. Headers use recorded timing, direct counts, and running state, never+double-count delegate work, and never treat a failed child as a failed turn.## Consequences-- One disclosure per turn keeps the final answer and actionable interruptions- reachable, and makes a long turn collapsible in a single gesture.-- Group folding defaults are unified across display modes: active work stays- visible, small completed ordinary groups and Task topology groups stay open,- and larger ordinary groups start closed.-- With `showThinking` off, no completed reasoning row renders; only the live- whole-run TextShimmer `Thinking` indicator remains while reasoning streams.-- `transcriptDisplayMode` keeps the three layouts available and defaults to the- released `fully-folded` layout.-- With `showThinking` on, Thinking rows default expanded in `flat`,- `command-first`, and `fully-folded`.+- One disclosure per turn keeps the answer and actionable interruptions reachable+ and makes a long turn collapsible in one gesture.+- Fold defaults are uniform across modes, explicit choices survive the thinking+ preference, and reopening a turn restores group defaults and explicit choices.+- With `showThinking` off only the live whole-run shimmer remains; stored reasoning+ reappears when it is re-enabled.+- `transcriptDisplayMode` keeps three layouts with the released `fully-folded`+ default, and reading the mode while rendering repaints immediately.+- The header answers "how did this turn end up" in one line; echoing the current+ command was removed because it pushed the counts off the row.+- Disclosure memory is pane-owned presentation state with stable identities, not a+ persisted transcript contract, and grouping covers loaded entries only — it never+ reconstructs unloaded history or joins turns across compaction boundaries.diff --git a/docs/adr/windows-native-snap-without-frame-insets.md b/docs/adr/windows-native-snap-without-frame-insets.mdindex a100e8598..020a47074 100644--- a/docs/adr/windows-native-snap-without-frame-insets.md+++ b/docs/adr/windows-native-snap-without-frame-insets.md@@ -2,28 +2,49 @@- Status: Accepted- Date: 2026-11-13-- Related: issue #2330, ADR 0317, ADR 0325, E2E-167+- Related: ADR 0317, ADR 0325, issue #2330## Context-Pinned Electron 43.6.0 removes `WS_THICKFRAME` and `WS_CAPTION` when the main-window uses `thickFrame: false`, excluding it from native keyboard and titlebar-drag snapping. Enabling Electron's thick frame restores its left/right/bottom-client-area insets and would regress the borderless surface fixed by ADR 0317.+The pinned Electron drops `WS_THICKFRAME` and `WS_CAPTION` for a `thickFrame:+false` window, excluding it from native keyboard and titlebar-drag snapping, while+enabling Electron's thick frame would restore client-area insets and regress the+borderless surface fixed by ADR 0317.## Decision-Keep `frame: false` and `thickFrame: false`. Private Main-to-Host RPC-`window.enableNativeSnap` restores only the HWND's `WS_THICKFRAME | WS_CAPTION`-bits, preserving other styles and bounds.--The RPC accepts a decimal HWND and owner PID, never an arbitrary style mask.-Host checks the requested PID against Main's injected PID and verifies the live-HWND owner before mutation.+Keep `frame: false` and `thickFrame: false` and let a private Main-to-Host RPC,+`window.enableNativeSnap`, restore only the HWND's `WS_THICKFRAME | WS_CAPTION`+bits while preserving other styles and bounds, so Electron keeps its inset-free+client layout; `WS_CAPTION` also avoids the maximized DWM overshoot seen with+`WS_THICKFRAME` alone, and Windows 11's `DWMWA_BORDER_COLOR` is set to+`DWMWA_COLOR_NONE` so DWM cannot paint an outline over client edges, with Windows+10's unsupported-attribute `E_INVALIDARG` handled explicitly and other native+failures left as errors.++The RPC accepts a decimal HWND and owner PID, never an arbitrary style mask: Host+checks the PID against Main's injected PID and verifies the live HWND owner before+mutating, sharing that validation with the corner RPC, and exposes no raw handle or+new channel to renderer, preload, plugins, or remote clients. Main awaits initial+application before showing the window and reapplies after show, focus and blur,+restore, maximize and unmaximize, leaving fullscreen, activation changes, and+returning from fullscreen, cancelling queued work on close and logging errors+without blocking startup. Existing minimum sizes, persistence, resizing, corners,+fullscreen interlocks, and maximize/work-area correction are unchanged.## Consequences-`test:e2e:window-snap` exercises the production Main service and compiled Host-in an isolated profile.+- Keyboard and titlebar-drag snapping work on the borderless window, with the+ client and the DWM-visible maximized frame matching the work area.+- Renderer, plugin, and remote surfaces gain no window-handle capability.+- The custom maximize button still needs separate `HTMAXBUTTON` integration for+ hover Snap Layouts, and native layout and pixels must be requalified on Electron+ upgrades. The isolated replay is described in+ [independent replay](../project/windows-native-snap-replay.md).++## Alternatives-`--baseline` omits service installation and must fail the keyboard-snap check.+- Enable Electron's thick frame: rejected because its client-area insets regress+ the borderless surface.+- Intercept keys or implement snapping in the renderer: rejected because native+ window behavior stays outside the renderer.diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 4347b57ff..5f2a64f39 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -6,9 +6,9 @@This log freezes previously open questions into concrete decisions.-Entries backed by an ADR keep a one-sentence summary; the ADR holds the-context, rationale, and consequences. Entries without an ADR keep their full-text here. Earlier full-text revisions remain in git history.+Entries backed by an ADR carry a one-sentence decision and point at the ADR,+which holds the context and rationale. Entries without an ADR keep their full+text here.## A. High-priority architecture decisions@@ -18,46 +18,46 @@ text here. Earlier full-text revisions remain in git history.| D002 | SQLite ownership | **Rust host-core owns SQLite exclusively** | Single writer, clearer privilege boundary || D003 | Default mode | **Agent** | Product is an agent desktop, not pure chat || D004 | Former restricted profile | *(superseded by D189)* **The former Chat read-only profile is removed; persisted Chat values migrate to Plan.** | The product now has one Agent with a planning state and a separate approval boundary |-| D005 | Permission timeout *(amended by D636 / ADR 0310)* | **Historical: 120s → deny. Local permission approvals now have no automatic deadline; explicit decision or cancellation is required.** | D636 preserves explicit cancellation and tool execution budgets without turning an unattended card into an automatic decision |+| D005 | Permission timeout *(amended by D636 / ADR 0310)* | **Local permission approvals have no automatic deadline; explicit decision or cancellation is required.** | D636 keeps explicit cancellation and tool budgets. See ADR 0310. || D006 | `allow-session` scope | **By `toolName`** | Simple UX; workspace sandbox still enforces path safety || D007 | `~/.pi` compatibility | **No auto-import in MVP** | Keep config ownership clean in `~/.pi-desktop` || D008 | Node runtime packaging | **Dev uses system Node; release runs the bundled sidecar on the Electron binary via `ELECTRON_RUN_AS_NODE=1` (no separate Node shipped)** | Unblock M1–M4; resolved at M5, see 03-runtime/07-process-model §6 || D009 | Plugin runtime isolation | **Target = separate process; M4 may use host-managed sandboxed runtime** | Ship plugin foundation pragmatically without weakening API gateway || D010 | First release platform | **macOS arm64 only** | Focus acceptance and packaging |-| D373 | Remote Agent Control host boundary | *(amended by D374 and D375)* **Remote control (post-MVP) runs through a logical Agent Host that owns Sessions, Turns, event cursors, approvals, attachments, workspace policy, and crash recovery; a production Gateway owns identity, routing, rate limits, revocation, and audit, and the Agent Host connects outbound.** | See ADR 0205. |-| D374 | Remote Agent Control v1 target amendments | **Amend D373 / ADR 0205: `RACP-WS` is the only normative v1 binding (`RACP-HTTP` is the browser profile, `RACP-GRPC` is reserved); typebox in `packages/shared` is the single contract source; the headless `packages/agent-host` module is the first deliverable and is shared by desktop IPC, local MCP, and RACP; cursors are `{ epoch, sequence }` with ephemeral deltas …** | See ADR 0205. |-| D447 | Headless runtime boundary | **Amend ADR 0205 rollout R2 prerequisites (ADR 0284): the Electron-independent runtime layer under the Agent Host module lives in `packages/host-runtime` — the host-core and sidecar stdio transports, the restart supervisor (process-model §4 policy), the durable turn lifecycle (`RuntimeService` as the module's `RuntimePort`: `session.beginTurn` → user row → prompt …** | See ADR 0205, ADR 0284. |-| D448 | RACP-WS transport and device pairing | **Amend ADR 0205 rollout R2 (ADR 0285): `packages/racp` holds both ends of the normative `RACP-WS` binding.** | See ADR 0205, ADR 0285. |-| D451 | Review opens only on explicit user action | **A tool result never opens, activates, or resizes the work panel.** | See ADR 0043. |-| D452 | Plan and goal artifacts open in the bundled file view | **The contract approval card's artifact opener hands the immutable `.pi/plan/*.md` or `.pi/goal/*.md` path to the bundled `pi.file-manager` view whenever that view is launchable, and to the host file tab otherwise — the same preference and fallback a chat file reference already uses (ADR 0241).** | See ADR 0241, ADR 0043. |-| D459 | Restore resizable sidebar width with collapse-below-threshold | **Amend D408 / ADR 0238 and restore ADR 0141 (ADR 0290): the expanded sidebar is again a renderer-owned `240px..520px` column (default `275px`) with a right-edge handle that previews on pointer-down, persists on release, and supports ArrowLeft/ArrowRight (16px), Home, and End.** | See ADR 0238, ADR 0141, ADR 0290. |-| D457 | Signed macOS DMG is a two-icon install | *(amended by D634)* **Amend D406 / ADR 0232 / ADR 0204: official and local DMGs contain only PI-Desktop.app and the Applications link on a branded 720×440 plate.** | See ADR 0232, ADR 0204, ADR 0296, ADR 0309. |-| D634 | Remove bundled macOS first-launch guidance | **Amend D457 / ADR 0296 and the macOS distribution provisions of ADR 0232 / ADR 0204: neither macOS DMG nor ZIP ships `PI-Desktop-macOS-open.command`, `PI-Desktop-macOS-opening-help.txt`, or another bundled quarantine-clearing helper or opening note.** | See ADR 0296, ADR 0232, ADR 0204, ADR 0309. |-| D635 | Work-area-capped 800×560 window minimum | **Supersede the 1040×700 window minimum in D156 / D447 (and the matching clauses of ADR 0029 / ADR 0238) and the `1040..10000` `window/setWorkPanelChatWidth` range (ADR 0146): Electron enforces an 800×560 minimum, capped per dimension to the current display work area by `clampMinimumSizeToWorkArea`.** | See ADR 0029, ADR 0238, ADR 0146. |-| D636 | Local permission approvals have no automatic deadline | **Amend D005 / ADR 0011 and supersede the local tool-permission timeout clauses in the runtime and UX specs: a permission-gated `tools.execute` request remains pending in host-core, the renderer, and the transport until the user chooses Allow once, Allow for session, or Deny, or the request is cancelled / the process shuts down.** | See ADR 0011, ADR 0310. |-| D637 | Remove the Windows frameless resize rim | **Disable the Windows main window's thick frame while retaining Electron 43.6 native frameless edge and corner resizing.** | See ADR 0317, ADR 0325. |-| D638 | Publish native Linux arm64 artifacts | **Amend D126 / D285 / D603 / ADR 0022: tag releases publish native Linux arm64 AppImage, deb, and rpm packages, built on GitHub's native `ubuntu-22.04-arm` runner and carrying an arm64 `pi-desktop-host-core`.** | See ADR 0022, ADR 0318. |+| D373 | Remote Agent Control host boundary | *(amended by D374 and D375)* **Remote control runs through a logical Agent Host owning sessions, turns, cursors, approvals, and a Gateway owning identity and routing.** | Remote needs its own boundary, not IPC. See ADR 0205. |+| D374 | Remote Agent Control v1 target amendments | **Amend D373: `RACP-WS` is the only normative binding, and typebox in `packages/shared` is the single contract source.** | Draft review found narrower vocabulary and per-token deltas. See ADR 0205. |+| D447 | Headless runtime boundary | **Amend ADR 0205 (ADR 0284): the Electron-free runtime layer lives in `packages/host-runtime` with transports, supervisor, turn lifecycle, and D299 persistence.** | `pi-host` must run the desktop's lifecycle invariants. See ADR 0205, ADR 0284. |+| D448 | RACP-WS transport and device pairing | **Amend ADR 0205 (ADR 0285): `packages/racp` holds both `RACP-WS` ends, header-profile device and pairing tokens, and the extended contract.** | Needs a bindable server and a desktop client. See ADR 0205, ADR 0285. |+| D451 | Review opens only on explicit user action | **A tool result never opens, activates, or resizes the work panel; Review needs explicit user action.** | Silent side panels compete with the user's reading. See ADR 0043. |+| D452 | Plan and goal artifacts open in the bundled file view | **The approval card's artifact opener uses the bundled `pi.file-manager` view, falling back to a host file tab.** | Plans landed where users do not browse files. See ADR 0043, ADR 0241. |+| D459 | Restore resizable sidebar width with collapse-below-threshold | **Amend D408 and restore ADR 0141: the sidebar is again a resizable `240px..520px` column defaulting to `275px`.** | Long labels need reclaimable width. See ADR 0238, ADR 0290. |+| D457 | Signed macOS DMG is a two-icon install | *(amended by D634)* **Amend D406: DMGs ship only `PI-Desktop.app` and the Applications link; ZIPs ship only the app.** | Signed DMGs no longer need first-launch guidance. See ADR 0232, ADR 0296, ADR 0309. |+| D634 | Remove bundled macOS first-launch guidance | **Amend D457: no macOS DMG or ZIP ships a quarantine-clearing helper, opening note, or first-launch script.** | Signed releases removed the need for the workaround. See ADR 0296, ADR 0309. |+| D635 | Work-area-capped 800×560 window minimum | **Supersede the 1040×700 minimum in D156: Electron enforces an 800×560 minimum capped to the work area.** | A fixed minimum exceeded 150%-scaled Windows work areas. See ADR 0029, ADR 0238. |+| D636 | Local permission approvals have no automatic deadline | **Amend D005: a local permission-gated `tools.execute` stays pending until the user decides, cancels, or the process exits.** | Missed requests must not become automatic denials. See ADR 0011, ADR 0310. |+| D637 | Remove the Windows frameless resize rim | **Disable the Windows thick frame while keeping native frameless edge resizing and the D635 minimum contract.** | The thick frame paints an unwanted rim. See ADR 0317, ADR 0325. |+| D638 | Publish native Linux arm64 artifacts | **Amend D126, D285, and D603: releases publish native Linux arm64 AppImage, deb, and rpm packages.** | arm64 devices could not run the x64 artifact. See ADR 0022, ADR 0318. || D639 | models.dev owns published chat-model metadata | **Supersede D136 / D266 and ADR `pi-ai-core-0991-authority` for chat metadata: the bundled and explicitly refreshed models.dev catalog supplies published chat-model limits, modalities, reasoning metadata, names, and prices. Prefer the selected official publisher; when it has no record, accept another publisher only for a safe, unambiguous match, otherwise keep generic metadata. The checked-in preset identities are the priority set; do not assert an unsupported fixed count of 39. Live endpoint/OAuth discovery still owns selectable IDs. Pi remains responsible for OAuth, wire identity, transport and typed non-chat operations, but never supplies sibling chat limits, reasoning or prices. Explicit user binding overrides remain authoritative. No credentials are sent to models.dev; no host schema/protocol or persistence change. See ADR `models-dev-catalog-authority` and E2E-162 / E2E-MODEL-catalog-window-correction-reaches-saved-bindings.** | A Pi sibling default assigned a 272,000-token window to GPT models whose selected models.dev records publish 1,050,000 tokens, changing the Settings display and runtime context budget. || D640 | User MCP tools keep the normal approval path | **`mcp_<serverId>_<tool>` calls are `medium` risk in host-core: under `ask` and `accept-edits` each call shows the approval card ("MCP server tool requires approval"), allow-once and allow-session keep their usual scope (one call / that exact tool name in that session), `auto` runs without a card, and Plan/Goal still deny. Annotations or risk values the MCP server declares about its own tools are ignored and never lower the path. Dispatch, read-only-mode handling and the `mcp_` namespace are unchanged; no host protocol or persistence change. See ADR `mcp-tool-approval-risk` and E2E-MCP-tool-requires-approval.** | MCP tools were auto-allowed as `low` risk, so a configured server could write files, call networks or run commands without any prompt under `ask`. Configuring a server is consent to launch it, not to every action its opaque tools take. || D641 | Custom endpoint API style precedence | **A custom endpoint uses the saved provider-row `apiStyle` ahead of a model catalog's adapter API. Named and OAuth providers can continue to use a model-level wire API pin where their published configuration requires a different transport. This keeps a user's explicit endpoint choice stable without removing model-specific routing such as OpenCode Go Responses models. No persisted format or protocol change. See E2E-005E and issue #1313.** | A publisher's adapter default must not silently redirect a custom gateway whose user-selected API format is different. || D642 | Cloud sync is a public Experimental destination *(amended by D643)* | **Remove the developer-mode and packaged-build gates from the Settings `sync` destination: its rail row, page, and settings-search hits exist for every user in every build, and a saved `sync` tab no longer falls back to General. Remote Hosts keeps both gates and its own badge. The destination keeps its Experimental badge on the rail row and page title; sync behavior, protocol, host schema, and persisted data are unchanged. See `04-ux/06-settings-ia.md` and E2E-CONFIG-SYNC-webdav-portable-configuration.** | Encrypted WebDAV backup is the app's only multi-device configuration path, and a developer-mode gate left it undiscoverable for the users who need it. || D643 | Cloud sync ships without an Experimental badge *(amended by D649 and D655)* | **Amend D642: the Settings `sync` destination drops `experimentalBadgeKey`, and `settings.configSync.experimental` is removed from every bundled locale. Cloud sync stays available to every user in every build. Remote Hosts keeps its own badge and both gates. Sync behavior, protocol, host schema, and persisted data are unchanged. See `04-ux/06-settings-ia.md` and E2E-CONFIG-SYNC-webdav-portable-configuration.** | Cloud sync is the app's shipped multi-device path, so an Experimental label no longer described it and only made the destination look unfinished. || D644 | Portable instruction files have no size cap | **Remove the 32 KiB per-file cap Host enforced on portable instruction files. Global and project instruction content is bounded only by the same portable-entity payload bound every other domain already has, checked when a revision is uploaded and when a remote one is validated. UTF-8 validation, symlink rejection, scope selection, mapping, and approval rules are unchanged. See `03-runtime/22-config-sync.md` §2.** | A 33 KiB project `AGENTS.md` failed the entire capture with `CONFIG_SYNC_LIMIT_EXCEEDED: instruction file is too large`, which the Settings page could only show as a generic backup-size error. |-| D450 | Signed macOS GitHub Releases | **Amend D078 / ADR 0022: GitHub tag releases Developer ID-sign, notarize (`notarytool` via electron-builder 26), staple, and Gatekeeper-verify macOS DMG/ZIP before upload, using identity `Developer ID Application: XingYu Liu (DUV63RKYTW)` / team `DUV63RKYTW` from Actions secrets (`CSC_LINK`, `CSC_KEY_PASSWORD`, `APPLE_ID`, `APPLE_APP_SPECIFIC_PASSWORD`, `APPLE_TEAM_ID`).** | See ADR 0022, ADR 0278, ADR 0289. |+| D450 | Signed macOS GitHub Releases | **Amend D078: tag releases Developer ID-sign, notarize, staple, and verify macOS DMG and ZIP before upload.** | Production DMGs must open without a Gatekeeper warning. See ADR 0022, ADR 0289. |-| D648 | Skill Market pins an acceptable address for mixed direct DNS answers | **Amend ADR 0272: on a direct route, when DNS includes both rejected and acceptable answers, Skill Market selects and pins one acceptable address instead of letting Chromium choose among them.** | See ADR 0272, ADR 0321. |+| D648 | Skill Market pins an acceptable address for mixed direct DNS answers | **Amend ADR 0272: on direct routes Skill Market pins one acceptable DNS answer instead of letting Chromium choose.** | Rejected answers must never be dialed. See ADR 0272, ADR 0321. || D649 | Cloud backup stays closed to users *(amended by D655)* | **Amend D642 / D643: the Settings `sync` destination carries `developmentOnly: true` again, so a packaged build omits its rail row, page, and settings-search hits and falls back to General, while development builds keep it. Developer mode stays irrelevant to the destination and it still carries no Experimental badge. Sync behavior, protocol, host schema, and persisted data are unchanged; dropping the flag reopens it for packaged builds. See `04-ux/06-settings-ia.md` and E2E-CONFIG-SYNC-webdav-portable-configuration.** | The encrypted WebDAV backup is not ready to be offered to packaged-build users yet, so it stays implemented but out of the way until it opens. |-| D650 | Plugin providers appear in Add Service | **Amend ADR 0259: optional `category` groups manifest-owned provider rows; optional localized `description` supplies one-sentence hover/focus copy.** | See ADR 0259, ADR 0322. |+| D650 | Plugin providers appear in Add Service | **Amend ADR 0259: plugin `provider.register` rows appear in Add Service with an optional category and description.** | Community providers were undiscoverable through Add Service. See ADR 0259, ADR 0322. || D651 | Transcript tool rows never auto-open | **Amend the leaf auto-open provision of the turn-process / thinking-display decisions and ADR `turn-process-and-thinking-display`: a tool-call, hosted-search or plan row keeps its payload collapsed in both display modes and only an explicit user action opens it, including the literal final item of the last activity group. Whole-process and ordinary-group defaults, failed/denied behavior, retained per-item choices, and the thinking row's own leaf default are unchanged. Renderer-only; no host protocol, persistence, permission or plugin contract change. See `04-ux/08-component-spec.md` §9.1/§9.2/§9.5/§9.6, `04-ux/09-interaction-patterns.md` §4.2, and E2E-040.** | A payload that opened itself under the newest call pulled attention away from the answer the user was waiting for and made one turn look different depending on how it ended; leaving every payload to the user keeps one predictable row. |-| D652 | Make session title generation a standalone plugin *(amended by D654)* | **Supersede ADR 0186: remove the built-in title completion and keep only the deterministic local fallback restored by D654; new sessions otherwise keep their localized default title until a user or plugin changes it.** | See ADR 0186, ADR 0323. |-| D653 | Make Composer prompt enhancement an optional plugin | **Supersede ADR 0121: remove host-owned prompt-enhancement UI, settings, direct completion IPC, and MCP action.** | See ADR 0121, ADR 0324. |-| D654 | Keep the deterministic first-prompt session title in the core | **Amend D652 / ADR 0323: a session whose stored title is still a recognized placeholder derives a whitespace-collapsed 48-character fallback from the first prompt, written through the host RPC and IPC `session/deriveTitle`.** | See ADR 0323. |+| D652 | Make session title generation a standalone plugin *(amended by D654)* | **Supersede ADR 0186: remove built-in title completion, keep the D654 fallback, and add the `session.autoTitle` plugin capability.** | Title generation belongs to an optional plugin. See ADR 0323. |+| D653 | Make Composer prompt enhancement an optional plugin | **Supersede ADR 0121: remove host-owned prompt enhancement and add the permission-gated `composer.transform` plugin contribution.** | Enhancement belongs to a separately installed plugin. See ADR 0324. |+| D654 | Keep the deterministic first-prompt session title in the core | **Amend D652: a still-placeholder title derives a 48-character fallback from the first prompt through `session/deriveTitle`.** | Untouched sessions kept showing a placeholder. See ADR 0323. || D655 | Cloud sync opens in packaged builds as Experimental | **Amend D649: remove the packaged-build visibility gate from Settings `sync` and restore its `Experimental` badge on the rail row and page title. Cloud sync and Remote Hosts are both available in packaged and development builds with Experimental badges. The S3 sync behavior, protocol, Host schema, and persisted data are unchanged. See `04-ux/06-settings-ia.md`, `03-runtime/22-config-sync.md`, and E2E-CONFIG-SYNC-s3-portable-configuration.** | The existing encrypted backup is useful to packaged-build users; the Experimental badge communicates its current maturity without keeping the feature hidden. |-| D656 | Quarantine appends the host keeps refusing instead of stalling the outbox | **Amend ADR 0041 / D318 / D444 / D597: an append whose `session.appendMessage` or `session.recordUsage` call fails with an error the outbox cannot classify as a duplicate message id, a `PERMISSION_DENIED:` poison row, or a foreign-key orphan is retried on a bounded backoff (5s, doubling to a 60s cap) instead of ending the flush.** | See ADR 0041. |-| D657 | Let the embedded Browser open local files outside the workspace | **Amend ADR 0170: an explicit absolute path or `file:` URL may load any existing regular local file, and a local-file page may navigate to other existing local files.** | See ADR 0170, ADR 0328. |-| D659 | Reopen archived projects in the sidebar | **Amend D093 / D455: successful explicit project activation clears the normalized path's renderer-local archived flag and persists it, so Open from Project archive, reopening the same folder through Add project, and opening a project session reveal the project in the home sidebar.** | See ADR 0294. |+| D656 | Quarantine appends the host keeps refusing instead of stalling the outbox | **Amend ADR 0041: an unclassifiable append is quarantined to a bounded dead-letter file and the flush continues.** | One refused append blocked every session's writes. See ADR 0041. |+| D657 | Let the embedded Browser open local files outside the workspace | **Amend ADR 0170: the embedded Browser may load any existing local file given an absolute path or `file:` URL.** | Users inspect local HTML outside a project. See ADR 0170, ADR 0328. |+| D659 | Reopen archived projects in the sidebar | **Amend D093: successful explicit project activation clears and persists the renderer-local archived flag.** | Reopening hid the project behind its archived flag. See ADR 0294. || D661 | Segmented turn process and independent thinking preference *(amended by D668)* | **Supersede the `Detailed` / `Compact` display-mode behavior and the single whole-process disclosure recorded by D633 / D651 and the `turn-process-and-thinking-display` ADR: a turn renders as chronological collapsible process segments, Bash and run aliases stay outside every folded container (the turn-level process disclosure and any ordinary activity group) and remain visible even when every group is collapsed, and process/group folding defaults are independent of the thinking preference. The preference is the optional boolean `AppSettings.showThinking`; absent or non-boolean values fall back to the legacy `thinkingDisplayMode` field (`compact` hides, `detailed`/unknown/absent shows), which is retained only for persisted-settings compatibility. `showThinking` joins the portable application fields so it synchronizes like the legacy field; no other host protocol, persistence schema, permission, or plugin contract change. See the amended ADR, `04-ux/06-settings-ia.md`, `04-ux/08-component-spec.md`, `04-ux/09-interaction-patterns.md`, and E2E-CHAT-turn-process-and-thinking-display.** | One flat container left long tool/search runs hard to scan and forced reasoning visibility and process folding into the same two-valued switch; an independent boolean plus always-visible Bash rows keeps shell-heavy turns readable without hiding the answer. |-| D662 | Open scoped HTML files in the work-panel Browser from plugins | **Add `pi.fs.openInBrowser(pathFromRoot)` under `fs.read`.** | See ADR 0330. |+| D662 | Open scoped HTML files in the work-panel Browser from plugins | **Add `pi.fs.openInBrowser(pathFromRoot)` under `fs.read`, opening validated scoped HTML files in the work-panel Browser.** | File Manager needs preview without `browser.cdp`. See ADR 0330. |## B. Secondary implementation defaults@@ -77,17 +77,18 @@ text here. Earlier full-text revisions remain in git history.| D022 | Local telemetry | **Local logs only in MVP (no remote telemetry)** || D664 | Sidebar running activity defaults | **When unset, the master and Count badge resolve on while Activity rail resolves off. Explicit saved values remain authoritative. The master continues gating both affordances; turning it off does not rewrite either child preference. No schema or migration change.** |+## C. Provider & model coverage decisions (0.3.4)| ID | Topic | Decision | Rationale ||---|---|---|---|| D023 | Provider coverage goal | **Universal market coverage** (not a tiny fixed vendor list) | Globalization + real coding workflows || D024 | Coverage strategy | **pi-ai native providers + first-class OpenAI-compatible + custom providers** | Maximum reach without rewriting every SDK |-| D308 | Zhipu / Z.AI named endpoint presets | **Amend D024 / ADR 0116: the add-provider Service select offers four OpenAI-compatible Zhipu endpoints — China and international standard API plus GLM Coding Plan — with locked published URLs and models.dev `vendorKey`s (`zhipuai`, `zhipuai-coding-plan`, `zai`, `zai-coding-plan`).** | See ADR 0116, ADR 0155. |+| D308 | Zhipu / Z.AI named endpoint presets | **Amend D024: the add-provider Service select offers four named OpenAI-compatible Zhipu and Z.AI endpoints with locked URLs.** | Named presets avoid wrong URL and vendor mismatches. See ADR 0116, ADR 0155. || D389 | DeepSeek reasoning_content replay on aggregators | **Amend D024: Completions requests for DeepSeek-family models set `requiresReasoningContentOnAssistantMessages: true` (and, off `deepseek.com`, `supportsReasoningEffort: false`; amended by D672) when the row `vendorKey`, base URL, model id, or catalog `family` identifies DeepSeek. Do not change `thinkingFormat` for that match. pi-ai still auto-detects official `deepseek.com` URLs.** | DeepSeek thinking mode 400s if any replayed assistant message omits `reasoning_content` or if a relay receives the unsupported generic `reasoning_effort` field. PI-Desktop stores a UUID as `model.provider`, so SiliconFlow, Volcengine, and custom gateways never match pi-ai's `provider === "deepseek"` check. See E2E-005E. |-| D424 | DeepSeek reasoning across compaction | **Amend D389 / ADR 0136: restore thinkingSignature on history rebuild; store recent thinking in checkpoint `details.retainedReasoning` and replay after the summary; non-official DeepSeek Completions rows set `requiresNonEmptyReasoningReplay` so the pi-ai patch uses a documented placeholder instead of `""`.** | See ADR 0136. |-| D309 | Add-provider common path is Service + key | **Amend D308 / ADR 0116 / ADR 0155: a new add-provider dialog starts with only Service.** | See ADR 0116, ADR 0155, ADR 0156. |-| D310 | Custom API format stays beside the key; Service lists top models.dev vendors | **Amend D309 / ADR 0155 / ADR 0156: Custom endpoint shows Name + Base URL, then API key beside API format on the common path.** | See ADR 0155, ADR 0156. |+| D424 | DeepSeek reasoning across compaction | **Amend D389: restore thinkingSignature on history rebuild, retain recent reasoning in the checkpoint, and replay a placeholder for third-party DeepSeek.** | Empty reasoning echoes 400 after compaction. See ADR 0136. |+| D309 | Add-provider common path is Service + key | **Amend D308: add-provider starts with Service only, then the key; Name and API format stay in Advanced.** | Known services should not look like generic gateways. See ADR 0116, ADR 0155, ADR 0156. |+| D310 | Custom API format stays beside the key; Service lists top models.dev vendors | **Amend D309: Custom endpoint shows API format beside the key, and Service lists published models.dev vendor endpoints.** | Gateways need the format beside the key. See ADR 0155, ADR 0156. || D311 | Service picker is searchable; discovery waits for a stable choice | **Amend D310: the add-provider Service control is a searchable anchored menu (same pattern as the default-model picker), not a native select. Filtering is client-side over localized name, vendor key, aliases, and host. Named add-path discovery does not start until an API key is present (editing still reuses the stored secret). Custom endpoints still probe a valid URL without a key. The discovery hook does not mark loading until the debounce fires, and an endpoint change clears the previous list immediately.** | Native selects with optgroups are sluggish in the overlay, and changing Service or typing a key used to refetch/re-render on every change. Search matches how models are filtered. See E2E-005 / E2E-005D. || D312 | Service list is a flat vendor catalog; add Xiaomi | **Amend D310 / D311: named Service options are one vendor list, not International / China groups. Add Xiaomi (`vendorKey: "xiaomi"`, `https://api.xiaomimimo.com/v1`, Chat Completions). Custom stays first. Search still matches localized name, vendor key, alias, and host.** | Region headings split the same vendors users already search by name. Xiaomi's first-party MiMo API is a models.dev vendor. See E2E-005. || D025 | Model allowlist | **No closed product allowlist** | Models churn; power users need free-form IDs |@@ -101,55 +102,56 @@ text here. Earlier full-text revisions remain in git history.| D033 | Tool result limits | **256KB/4000 lines defaults with explicit truncation markers** *(amended by D194, D306)* | Protect context & UI || D306 | Search/read truncation is a cut, not a window | **Amend D033 / D194: Read/Glob/Grep `truncated` is true only when the host cut content the caller asked for (byte budget, per-line clip, Grep/Glob match cap). A Read that returned the requested or default window of a longer file is complete for that window; `totalLines`/`offset`/`lineCount` and a next-offset `notice` describe the remainder. Default Read window is 2000 lines (max 4000). `BUDGET_SEARCH` is 128KB / 4000 lines. Per-line clip is 16,384 characters. The UI truncated chip follows this flag.** | The 48KB / 500-line window marked almost every source and spec file truncated, including successful paged reads, which hid real cuts and forced the agent to re-search what it already had. || D307 | Revision payloads follow the live branch | **Amend D109: a regenerate branch keeps growing after its archive (later prompts, error-ended turns that never reach `agent_end`), so every operation that discards the live branch first writes it back over the variant it belongs to. `session.activateRevision` re-archives the live branch of the family from the durable transcript before switching and takes the prefix from there; the regenerate path refreshes the stamped variant via `session.saveRevision { revisionIndex }`; `session.saveActiveRevision` refreshes an already-archived index instead of skipping it. The variant refreshed is the one the live root's `activeRevision` stamp names; a stamped variant with no index row yet is stored as its own variant, never over a previous one. Switching also carries each surviving message's owning `turn_id` and keeps checkpoints whose anchors survive.** | The archive was written once and reused forever: paging away from a branch that had grown since its agent_end archive, then back, restored the stale copy and silently deleted every later turn from the transcript and its JSONL. |-| D390 | Host-owned regenerate truncate | **Amend D199 / D258 / D307: `agent/prompt` truncates through `session.truncateFrom` under the host lock (identity-first cut, abort leftover running turn, archive discarded tail, rewrite prefix).** | See ADR 0216. |-| D391 | Host stdout sender must not outlive serve | **Amend D390 / ADR 0216: the Windows Alt+Space hook retains only a weak clone of the stdout sender.** | See ADR 0216, ADR 0217. |-| D392 | Effective image-input overrides across Composer and transport | **Amend D243 / ADR 0101: image capability starts with the published model record, then an exact binding's `supportsImages` value wins when it is `true` or `false`; absent or `null` follows the published value.** | See ADR 0101, ADR 0218. |-| D393 | User-invoked Skills in the composer | **Amend D123 / D174 / ADR 0024 / ADR 0039: active built-in, plugin, and user Skills appear in a separate `Skills` group at the end of the composer slash menu.** | See ADR 0024, ADR 0039, ADR 0219. |-| D394 | Windows work-panel chrome keeps one resource action cluster | **Amend D154 / D357 / ADR 0195: the open work-panel header keeps one compact resource switcher; resource close is owned by the existing keyboard-operable context-menu rows, the viewport-fixed toggle remains the only panel collapse control, and subagent detail returns with a back chevron.** | See ADR 0195, ADR 0220. |+| D390 | Host-owned regenerate truncate | **Amend D199, D258, and D307: `agent/prompt` truncates through `session.truncateFrom` under the host lock, so the kept transcript never crosses JSON-RPC.** | Large sessions timed out and killed host stdin. See ADR 0216. |+| D391 | Host stdout sender must not outlive serve | **Amend D390: the Alt+Space hook keeps only a weak stdout sender, so host-core exits after stdin EOF.** | A strong sender kept host-core a zombie. See ADR 0216, ADR 0217. |+| D392 | Effective image-input overrides across Composer and transport | **Amend D243: a binding's explicit `supportsImages` override wins over the published record for Composer and transport alike.** | Badges and transport disagreed on one endpoint. See ADR 0101, ADR 0218. |+| D393 | User-invoked Skills in the composer | **Amend D123: active Skills appear in a composer `Skills` group as `/skill:<id>` while the Skill tool keeps body loading.** | Known workflows become discoverable without moving bodies. See ADR 0024, ADR 0219. |+| D394 | Windows work-panel chrome keeps one resource action cluster | **Amend D154: the work-panel header keeps one compact resource switcher; the viewport-fixed toggle remains the only collapse control.** | Duplicate close affordances crowded narrow panels. See ADR 0195, ADR 0220. || D396 | Renderer and plugin-panel scrollbars share one compact contract | **Amend D300: every renderer scroll container uses one 6px, trackless, transparent-at-rest scrollbar with the same hover, focus-within, scroll-reveal, and dragged-thumb states. Remove the sidebar-specific width and opacity override. The plugin-panel preload applies the same contract and 300ms reveal mark to docked and detached plugin documents, including the bundled Files view. External pages loaded inside the Browser guest remain page-owned. Presentation-only; no protocol, storage, host runtime, or external-page behavior change. See E2E-157.** | Windows' classic scrollbar made the right-side work-panel Files view visibly heavier than the conversation, while the sidebar retained a second scrollbar treatment. |-| D-LOCAL-message-quotes | Message quotes and renderer-owned side chats | *(retired by ADR 0268 on 2026-09-16)* **Amend D209 / D301: every user message and assistant turn gains a Quote action that inserts a `> `-prefixed Markdown blockquote plus a `chat.quoteSource` attribution into the active session's composer draft and focuses it, using the live selection inside that message row when one exists and the message's own text otherwise; it never sends and adds no chip kind …** | See ADR 0268, ADR message-quotes-and-side-chats. |-| D-LOCAL-response-annotations | Response annotations as prompt attachments | *(retired by ADR 0268 on 2026-09-16)* **Amend D-LOCAL-message-quotes (decision 3) for assistant turns: selecting text in a response and choosing Add to chat attaches a numbered annotation to that turn instead of editing the composer draft — the answer body is not decorated (only a citation the model writes renders, as a numbered reference), the composer shows one annotation attachment chip whose tooltip …** | See ADR 0268, ADR response-annotations. |-| D398 | Context usage display preference | **Amend D347 / ADR 0184: the context usage inspector's leading figure — the trigger ring arc, percentage, token label, popover heading, tooltip, and `aria-label` — is configurable via `AppSettings.contextUsageDisplay` (`"remaining"` or `"used"`).** | See ADR 0184, ADR 0222. |+| D-LOCAL-message-quotes | Message quotes and renderer-owned side chats | *(retired by ADR 0268 on 2026-09-16)* **Amend D209 and D301: messages gain a Quote action that prefills a quoted draft, and side chats fork without activating.** *(amended by D-LOCAL-selection-overlay)* | Reuse needs no change to the visible conversation. See ADR message-quotes-and-side-chats, ADR 0268. |+| D-LOCAL-response-annotations | Response annotations as prompt attachments | *(retired by ADR 0268 on 2026-09-16)* **Amend D-LOCAL-message-quotes: assistant selections attach as numbered prompt annotations instead of editing the composer draft.** | Quoting copied model words into the user's prompt. See ADR response-annotations, ADR 0268. |+| D398 | Context usage display preference | **Amend D347: `AppSettings.contextUsageDisplay` selects remaining or used for the inspector's leading figure, defaulting to remaining.** | Users reason either way; colours stay on remaining. See ADR 0184, ADR 0222. || D399 | Project group manual ordering | *(amended by D402)* **Amend D093: retained project groups expose a visible-on-hover/focus grip. Native drag/drop and ArrowUp/ArrowDown on that grip write contiguous normalized-path `order` values and set `projectSort` to `manual` in renderer-local sidebar preferences. Archived and pinned priority remains ahead of manual order; project activation, host workspace identity, session ordering, and on-disk directories are unchanged.** | Users with several active repositories need a stable working order independent of recent activity or alphabetical names, while the existing path-keyed and host-owned project model remains untouched. |-| D400 | Restore deferred tools from effective session context | **Amend D185 / ADR 0048: before each new prompt and after a mode switch, clear the in-memory deferred activation set, then restore names from successful `ToolSearch` results (`addedToolNames`) and successful deferred-tool results in the effective `buildSessionContext` projection.** | See ADR 0048, ADR 0225. |-| D402 | Long-press project title to reorder | *(amended by D403)* **Amend D399 / D093 / ADR 0227: retained project groups have no visible reorder grip.** | See ADR 0227, ADR 0228. |-| D403 | Press-and-move project title reorder | **Amend D402 / D093 / ADR 0228: mouse and pen reorder by pressing the project title and moving 8px; a click with no qualifying movement still selects and toggles collapse.** | See ADR 0228, ADR 0229. |-| D404 | Skill ships with the Agent core tool set | **Amend D174 / D185 / ADR 0048 / ADR 0219: `Skill` joins the Agent-mode core tool set, so its schema is present on the first provider request whenever the skill catalog is non-empty.** | See ADR 0048, ADR 0219, ADR 0230. |-| D405 | Ideographic comma opens the slash menu | **Amend D123 / D139 / ADR 0024: a `、` (U+3001) committed as the first character of an empty composer draft is rewritten to `/` before trigger detection, so a Chinese IME reaches the ordinary slash menu without switching input methods.** | See ADR 0024, ADR 0231. |-| D406 | Keep macOS DMG opening guidance text-only | *(amended by D457 and D634)* **Amend D371 / ADR 0204: macOS DMGs no longer expose the opening-help note or executable helper, and macOS ZIP packages no longer retain them.** | See ADR 0204, ADR 0232, ADR 0296, ADR 0309. |-| D407 | Restore archived projects after session import | **Additive renderer behavior for issue #250: when a core or plugin import adds a new project-bound session, the import-triggered session refresh normalizes its project path and clears the renderer's archived presentation state for that project.** | See ADR 0236. |-| D408 | Prioritize MainChat in the three-column shell | **Amend ADR 0226 / ADR 0151 / ADR 0033 for issue #267: MainChat keeps a hard 450px minimum, the work panel is capped by the live budget (`client width - 450px - expanded sidebar`, with no fixed maximum), and the expanded sidebar yields at that threshold — including while `sidebar-out` still occupies flex space.** | See ADR 0226, ADR 0151, ADR 0033, ADR 0238. |-| D409 | Host-owned session collaboration messages | *(amended by D446)* **Amend ADR 0237 / ADR 0165 / ADR 0213: Rust host-core owns a durable session-collaboration ledger keyed by message id and real source/target Session IDs.** | See ADR 0237, ADR 0165, ADR 0213, ADR 0239. |-| D410 | Independent session discovery and navigable collaboration projections | **Amend ADR 0239: add the reviewed read operation `session/collaboration/list`, bounded to 100 non-deleted Agent sessions and redacted to Session IDs, titles, status, updated time, readable provider/model labels, and bounded creation links.** | See ADR 0239, ADR 0240. |-| D446 | Silent completion notices | **Amend D409 / ADR 0239 and the D193 silent-turn contract for issue #504: the first settled assistant reply to a current Host-resolved completion notice may end with no visible text and no tool call without silent-turn recovery or `EMPTY_MODEL_RESPONSE`.** | See ADR 0239. |+| D400 | Restore deferred tools from effective session context | **Amend D185: deferred activations are rebuilt from effective successful `ToolSearch` and deferred-tool results before each prompt.** | Activations outlived their absence from the provider schema. See ADR 0048, ADR 0225. |+| D402 | Long-press project title to reorder | *(amended by D403)* **Amend D399: a 400ms still press on the project title arms pointer reorder; ArrowUp/ArrowDown is the keyboard path.** | A grip cost a column beside the title. See ADR 0227, ADR 0228. |+| D403 | Press-and-move project title reorder | **Amend D402: mouse and pen reorder by pressing the title and moving 8px; touch never starts a reorder.** | A long press is slower than desktop lists. See ADR 0228, ADR 0229. |+| D404 | Skill ships with the Agent core tool set | **Amend D174: `Skill` joins the Agent-mode core tool set, leaving the deferred catalog and on-demand list.** | Deferral cost a round trip before any call. See ADR 0048, ADR 0230. |+| D405 | Ideographic comma opens the slash menu | **Amend D123: a `、` committed first in an empty draft is rewritten to `/` before trigger detection.** | Chinese IME users needed no input-method switch. See ADR 0024, ADR 0231. |+| D406 | Keep macOS DMG opening guidance text-only | *(amended by D457 and D634)* **Amend D371: macOS DMG and ZIP packages ship no opening-help note or executable helper.** | Signed builds do not need the Terminal fallback. See ADR 0204, ADR 0232, ADR 0296. |+| D407 | Restore archived projects after session import | **An import that adds a project-bound session clears that project's renderer archived presentation state.** | Imports materialized sessions the sidebar still hid. See ADR 0236. |+| D408 | Prioritize MainChat in the three-column shell | **MainChat keeps a hard 450px minimum; the work panel is capped by the live budget and the sidebar yields.** | Preview reserves traffic lights per D433. See ADR 0033, ADR 0238. |+| D409 | Host-owned session collaboration messages | *(amended by D446)* **Amend ADR 0237: host-core owns a durable session-collaboration ledger keyed by message and Session ids.** | Polling hid durable outcomes and sender identity. See ADR 0237, ADR 0239. |+| D410 | Independent session discovery and navigable collaboration projections | **Amend ADR 0239: add bounded `session/collaboration/list` discovery and navigable creator and created-session projection links.** | Valid targets stayed undiscoverable outside plugin-created sessions. See ADR 0239, ADR 0240. |+| D446 | Silent completion notices | **Amend D409 and D193: one Host-ledger completion notice may settle silently, spent once and revoked by user steering.** | Retrying a verified silence reported failure for success. See ADR 0239. || D447 | Stage Manager bounds watchdog is macOS-only | **The permanent 1.5s `boundsWatchdog` in `bootstrap/window.ts` runs on macOS alone; every other platform clears the interval on its first tick. Its two inputs are macOS-only (the `/tmp/pi-window-bounds` CG helper, and a "window smaller than 500x400" test the 1040x700 minimum window size makes unreachable), so elsewhere it could never recover anything and only called `window.setAlwaysOnTop(false)` forever. On Linux/X11 that repeats a `_NET_WM_STATE` removal, and Mutter answers it by raising the window (`meta_window_unmake_above` calls `meta_window_raise` unconditionally), so the app yanked itself back to the top of the stack about 1.5s after the user focused another window even though `_NET_WM_STATE` never carried `_NET_WM_STATE_ABOVE`. macOS Stage Manager recovery is unchanged. See D039, D053, D083 and US-UI-19.** | A window that re-raises itself over whatever the user just focused is not usable, and the interval had no purpose off macOS; the fix removes the message instead of teaching each platform to tolerate it. |-| D413 | Skill market public-HTTPS catalog fetch | **Additive: Settings → Skills Market discovers SKILL.md catalogs in Electron main under a shared public-HTTPS policy (syntactic public host + DNS classification + per-hop redirect re-validation).** | See ADR 0243. |-| D421 | Native Pi session continuation | **Amend baseline D007: discover Pi v3 sessions as source-discriminated projections and continue them through coding-agent `AgentSession`/`SessionManager` against their canonical JSONL.** | See ADR 0254, ADR 0268. |-| D412 | Delta-only coalesced streaming updates | **Amend the local `message_update` contract: append-only streaming frames carry `stream: delta` plus `deltaText`/`deltaThinking` (and reset flags) without growing `content`/`thinking`.** | See ADR 0242. |-| D416 | Git clone accepts only syntactically public hosts | **Amend home git clone: `parseGitCloneUrl` reuses `isPublicHostname` so loopback, private, CGNAT, link-local, ULA, and `.local`/`.localhost` remotes are rejected before `git clone` runs.** | See ADR 0247. |-| D417 | Plugin runtime theme APIs + sidebar image token | **Add `pi.app.setTheme` and `pi.themes.upsert`/`remove`/`list` under `ui.theme` (ADR 0260 / issue #352).** | See ADR 0260. |-| D420 | Structured, bounded, and redacted process logs | **Amend ADR 0046 / ADR 0212: every app/host/agent NDJSON record has a stable event and top-level correlation fields.** | See ADR 0046, ADR 0212. |-| D422 | Host turn-end event for plugins | **`session:turnEnded` is a host event with payload `{ sessionId, turnId, reason }` (`completed` / `aborted` / `error`), broadcast once per turn actually started by `session.beginTurn` at the end of turn teardown, after the durable `session.endTurn` attempt.** | See ADR 0252. |-| D423 | Remove the subagent turn limit | **Amend D328 / ADR 0062 / ADR 0063 / ADR 0119 / ADR 0126 / ADR 0166 / ADR 0210: `maxTurns` and `MAX_SUBAGENT_MAX_TURNS` leave the definition type, the frontmatter parser and its clamp/invalid warnings, `UserSubagentRecord` / `UserSubagentInput`, the host-core registry (record, input, frontmatter parse, document render, `MAX_TURNS_CEILING`), the five built-in documents …** | See ADR 0062, ADR 0063, ADR 0119, ADR 0126, ADR 0166, ADR 0210, ADR 0189, ADR 0253. |--| D244 | Compact context usage summary | **Amend D103 / D184 / ADR 0047: keep the context inspector's remaining-capacity trigger, used/window counts, turn total, completed-turn speed, exact provider values, aggregate tool types/calls/tokens, and checkpoint summary, but render them as a short summary.** | See ADR 0047, ADR 0103. |-| D347 | Composer-docked context usage inspector | **Amend D103 / D184 / D244 / ADR 0047 / ADR 0103: the compact context inspector lives in the composer right toolbar, immediately left of the model × reasoning chip, and always mirrors the newest assistant turn that reported usage.** | See ADR 0047, ADR 0103, ADR 0184. |-| D355 | Last-request occupancy in the context inspector | **Amend D103 / D184 / D244 / D347 / ADR 0047 / ADR 0103 / ADR 0184: remaining capacity, used/window counts, turn total, and provider input/output/cache/reasoning/hit-rate are the newest usage-bearing assistant message (the last model request).** | See ADR 0047, ADR 0103, ADR 0184, ADR 0193. |-| D356 | Optional subagent thinking override | **Amend ADR 0062 / ADR 0144: subagent frontmatter accepts `thinkingLevel: omit` in addition to inherit and the seven canonical levels.** | See ADR 0062, ADR 0144, ADR 0194. |+| D413 | Skill market public-HTTPS catalog fetch | **Skill Market discovers SKILL.md catalogs in Electron main under a shared public-HTTPS policy; the renderer never fetches.** | Discovery needs main-process egress without a host allowlist. See ADR 0243. |+| D421 | Native Pi session continuation | **Amend D007: Pi v3 sessions are discovered as projections and continued natively against canonical JSONL while SQLite stays authoritative.** | A flattened copy loses the tree and visibility. See ADR 0254. |+| D412 | Delta-only coalesced streaming updates | **Amend the local `message_update` contract: streaming frames carry deltas coalesced every 16ms, while start and end stay full snapshots.** | Per-token snapshots cost O(n²) bytes per turn. See ADR 0242. |+| D416 | Git clone accepts only syntactically public hosts | **`parseGitCloneUrl` reuses `isPublicHostname`, rejecting loopback, private, CGNAT, link-local, ULA, and `.local` remotes before clone.** | Clone accepted literals the market fetchers already reject. See ADR 0247. |+| D417 | Plugin runtime theme APIs + sidebar image token | **Add `pi.app.setTheme` and `pi.themes.upsert`/`remove`/`list` under `ui.theme`, splitting the sidebar paint token.** | Plugins could not apply or live-edit themes. See ADR 0260. |+| D420 | Structured, bounded, and redacted process logs | **Amend ADR 0046: logs get stable events and correlation fields, one record per tool call, redacted and capped at 8KiB.** | Rows were redundant and free-form details leaked. See ADR 0046, ADR 0212. |+| D422 | Host turn-end event for plugins | **`session:turnEnded` broadcasts once per started turn with `{ sessionId, turnId, reason }` after durable teardown, without ack or replay.** | Idle timers fire mid-turn; identity settles it once. See ADR 0252. |+| D423 | Remove the subagent turn limit | **Amend D328: `maxTurns` leaves every surface; a delegate ends only on completion, `TaskStop`, user Stop, or parent failure.** | The parent cannot see work it would cap. See ADR 0253. |+++| D244 | Compact context usage summary | **Amend D103 and D184: the context inspector keeps its aggregate signal as a short summary, dropping per-tool rows and meters.** *(amended by D347)* | Drill-down chrome made a routine check tall. See ADR 0047, ADR 0103. |+| D347 | Composer-docked context usage inspector | **Amend D103 and D244: the compact inspector moves into the composer toolbar and mirrors the newest usage-bearing assistant turn.** | The inspector scrolled out of reach under answers. See ADR 0103, ADR 0184. |+| D355 | Last-request occupancy in the context inspector | **Amend D244 and D347: capacity figures come from the newest usage-bearing message, not the tool-loop sum.** | Tool-loop sums inflated cache reads beside small windows. See ADR 0193. |+| D356 | Optional subagent thinking override | **Amend ADR 0062: subagent frontmatter accepts `thinkingLevel: omit`, keeping bookkeeping `off` while synthesizing no thinking override.** | Users needed inherit, off, and provider default. See ADR 0144, ADR 0194. || D348 | macOS sidebar source-list vibrancy | **Amend D304: the main window uses Electron `vibrancy: "sidebar"` instead of `under-window`. `nativeTheme.themeSource` follows the app theme (`system` / `light` / `dark` / plugin base) process-wide. Vibrancy re-applies only when `themeSource` changes; a missing plugin theme falls back to `system`.** | macOS 26 Liquid Glass made `under-window` a light plate that the 40% tint could not keep dark, including when app and OS appearances were both dark. See `04-ux/08-component-spec.md` §1.7 and US-UI-74 / E2E-076. |-| D243 | Model-aware image attachment transport | **Amend D197 / ADR 0059: Composer file references retain structured kind/name/MIME metadata.** | See ADR 0059, ADR 0101, ADR 0218. |-| D245 | OpenCode-style bounded provider 429 retry | **Amend D186 / D233 / ADR 0091: `PROVIDER_RATE_LIMITED` gets five silent, abortable retries after the initial attempt, with one counter shared across request setup and mid-stream recovery.** | See ADR 0091. |-| D237 | Vendor-account (OAuth) login for providers | **A provider row may be authenticated by a vendor subscription instead of an API key. pi-ai's seven OAuth flows are registered statically at startup (`registerBunOAuthFlows()`); Electron main owns login/logout orchestration and implements pi-ai's `CredentialStore` over host-core's encrypted secret store under the new ref `secret:provider:<id>:oauth`, serializing …** | See ADR 0095. |+| D243 | Model-aware image attachment transport | **Amend D197: Electron main resolves vision from the model record or binding override and sends eligible images as transient blocks.** | A path replaced image content for vision models. See ADR 0059, ADR 0101. |+| D245 | OpenCode-style bounded provider 429 retry | **Amend D186 and D233: `PROVIDER_RATE_LIMITED` gets five silent abortable retries sharing one counter across setup and stream.** | One retry exposed transient 429s too early. See ADR 0091. |+| D237 | Vendor-account (OAuth) login for providers | **A provider row may authenticate with a vendor subscription; Electron main owns OAuth login and resolves short-lived tokens per request.** | Subscribers needed no separate API credit. See ADR 0095. |-| D238 | Flat Settings directory and marketplace context ownership | **Settings renders one flat searchable directory in the exact order Basics / AI / Shortcuts / Instructions / Model configuration / Import / Project archive / Info.** | See ADR 0096. |+| D238 | Flat Settings directory and marketplace context ownership | **Settings renders one flat searchable directory in the fixed order, and the marketplace source selector moves into Extensions.** | The rail repeated navigation and duplicated a label. See ADR 0096. |-| D239 | Place global defaults under AI | **The eight-destination Settings directory remains unchanged.** | See ADR 0097. |-| D240 | Independent vendor OAuth accounts and settings ownership | **Amend D237 / ADR 0095: every OAuth login creates a fresh provider row and row-scoped `CredentialStore`, even when `vendorKey` matches an existing account.** | See ADR 0095, ADR 0098. |-| D339 | Per-provider User-Agent override | **Superseded by D341. Each AI-service and OAuth provider row may store optional `config_json.userAgent`.** | See ADR 0176. |-| D341 | Per-provider custom HTTP headers | **Amend D339 / ADR 0176: each AI-service and OAuth row stores optional `config_json.headers`.** | See ADR 0176, ADR 0178. |-| D242 | Builtin subagents inherit the parent permission mode | **Builtin subagents use the default `permission: inherit` behavior.** | See ADR 0100. |+| D239 | Place global defaults under AI | **Global behavior defaults — operating mode, command shell, Enter-to-send — move under AI, leaving eight Settings destinations unchanged.** | They change agent behavior, not appearance. See ADR 0097. |+| D240 | Independent vendor OAuth accounts and settings ownership | **Amend D237: every OAuth login creates a fresh row-scoped account, and vendor bindings resolve by exact `providerId` or fail closed.** | One vendor-global row let accounts overwrite each other. See ADR 0095, ADR 0098. |+| D339 | Per-provider User-Agent override | *(superseded by D341)* **Each provider row could store an optional `config_json.userAgent` applied to outbound HTTP, max 256 bytes.** | Gateways and subscriptions inspect the User-Agent header. See ADR 0176. |+| D341 | Per-provider custom HTTP headers | **Amend D339: each provider row stores optional `config_json.headers` as last-writer headers on outbound HTTP, migrating `userAgent`.** | Users needed arbitrary non-secret headers, not only User-Agent. See ADR 0176, ADR 0178. |+| D242 | Builtin subagents inherit the parent permission mode | **Builtin subagents keep `permission: inherit`; only definitions with explicit non-inherit scopes override the parent session.** | `fixer` overrode an `auto` parent with `accept-edits`. See ADR 0100. || D241 | Titled Settings navigation clusters | **Keep the eight-destination Settings directory flat and searchable, but render four non-interactive localized group headings — Personal / 个人 (Basics, AI, Shortcuts), Agent / 智能体 (Instructions, Model configuration), Workspace / 工作区 (Import, Project archive), and About / 关于 (Info). Headings use whitespace for separation and no divider lines. Empty groups disappear with filtered search. This supersedes only D238's prohibition on group headings; destination order, IDs, search ownership, and marketplace placement remain unchanged.** | The flat rows became visually dense without scan landmarks. Muted headings restore grouping while preserving one-level navigation and the existing destination ownership. |-| D442 | Marketplace download requests carry a device identifier | **Amend D238: the official plugin channel resolves every install and update through `POST /api/v1/download/resolve` and sends a stable `deviceId` — the SHA-256 digest of a platform machine identifier, or a locally persisted random id when none is readable.** | See ADR 0276. |+| D442 | Marketplace download requests carry a device identifier | **Amend D238: the official channel resolves installs and updates through `POST /api/v1/download/resolve` with a stable `deviceId`.** | Counting and rate limits need one stable identity. See ADR 0276. |## D. Codex visual parity decisions (0.3.5+)@@ -201,15 +203,15 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.| D133 | Project index moves to Settings archive | *(five-destination count/order superseded by D166; flat-list presentation superseded by D168)* **The home sidebar no longer has a standalone Projects destination. Settings adds Project archive (zh-CN: 项目归档) after Import and before Info, bringing the compact directory to Basics / Model configuration / Import / Project archive / Info. The archive reuses the durable Projects index and always includes archived records, with search, add, activate, task expansion, pin, archive/restore, and close actions. Project and session groups remain in the home sidebar for active work. Global search exposes the archive as a Settings result, not a standalone page. This supersedes the standalone-destination clauses of D042/D066 and D090's four-destination limit without changing project storage or activation semantics.** | Active project work already lives in retained sidebar groups; moving historical project management into Settings reduces primary navigation while keeping recovery and archive controls discoverable. || D168 | Project archive presentation redesign | *(band layout and per-section panels superseded by D267)* **Project archive renders three stacked bands: an overview banner (intent sentence, primary Add project, and four derived counters for projects, open, archived, sessions), a toolbar (search with clear affordance and live match count, plus a Recent/Name sort segmented control), and a grouped index whose always-visible sections run Pinned / All projects / Archived with per-section counts, one settings panel per section, and hairline row separators. Rows carry a disclosure control, glyph, name with Active/Open/pinned/Archived tags, one meta line (shortened monospace path, branch, session count), relative last-active time, and hover/focus-revealed New task plus row menu; the menu groups create/edit above pin, archive/restore, and destructive Close, and dismisses on Escape or outside press. Archived rows are grouped and softened, never hidden or filtered, so D133's no-visibility-toggle rule still holds. This supersedes D133's flat-list presentation without changing project storage, search matching, session batching, or activation semantics.** | The flat single-list archive gave equal weight to pinned, working, and archived records and hid its disclosure and row actions behind hover, so scanning a long durable index meant reading every row. Grouping with derived counters and an explicit sort makes state legible at a glance while keeping archived history permanently reachable. || D267 | Project archive is one workbench, not three bands | *(row anatomy and inline expansion superseded by D455)* **Revise D168's band layout: Settings → Project archive renders the D257 one-workbench composition — a quiet intro line carrying only the page description, one toolbar (Recent/Name sort on the shared `settings-segment` primitive, search with clear affordance and live match count, primary Add project), and one settings panel whose always-visible Pinned / All projects / Archived groups are non-interactive in-panel header strips with per-section counts instead of one panel per section. The decorative gradient hero band is removed together with the four page-level overview counters it carried, retiring the `project.statProjects`, `project.statOpen`, `project.statArchived`, and `project.statSessions` keys; the per-group counts on the panel's header strips are now the only totals. The external uppercase section labels are removed as well; row geometry matches the capability rows (32px controls, 14px list gap, 28px row glyph). Beyond dropping the four retired counter keys this is presentation only: D168's row anatomy, row menu grouping, search matching, session batching, activation semantics, and accessibility semantics are unchanged, and no ADR is required.** | D168's overview banner used a decorative gradient and `--text-xl` counter tiles, which the design system forbids, and its per-section panels repeated the same elevated frame three times. Demoting the counters to an inline run kept the clutter without earning it: every total they showed is already legible from the per-group strip counts, so restating them above the toolbar duplicated numbers and gave the destination a header no sibling page has. Dropping them leaves the durable index looking and behaving like the agent capability pages. |-| D455 | Project archive is a list + inspector | *(row anatomy superseded by the same-day "Project archive reads as an inset grouped card list" entry)* **Revise D267's expanding rows: Settings → Project archive keeps the quiet intro and toolbar, then a one-column workbench.** | See ADR 0294. |-| D456 | Session thinking-parameter omission | **Amend ADR 0194 / ADR 0144 / ADR 0221: session `thinkingLevel` accepts `omit` in addition to the seven canonical levels.** | See ADR 0194, ADR 0144, ADR 0221, ADR 0295. |+| D455 | Project archive is a list + inspector | **Revise D267: Project archive is a one-column list plus inspector; a click selects and double-click or Enter activates.** | Inline expansion made a long index unscannable. See ADR 0294. |+| D456 | Session thinking-parameter omission | **Amend ADR 0194: session `thinkingLevel` accepts `omit` in addition to the seven canonical levels, widening the schema v19 CHECK.** | `off` still sends a disable; `omit` sends nothing. See ADR 0144, ADR 0295. || D458 | Composer reasoning slider on the menu root | **Amend the combined model × reasoning menu: when more than one level is listed, a native range slider with one labeled stop per level sits under the Reasoning level entry. Slider and tick commits persist the last pending level through `configureActiveSession` without leaving the root; the entry still opens the classic radio list. Tick labels are not tab stops. The slider shows a rail with one track dot per stop and a visible label under each stop; the dots row and labels row are full-width n-column grids and the range input overlays the rail inset by half a column minus the thumb radius, so the dot, thumb and label share one column center for every stop count. The selected stop uses the accent token, the rest muted. Renderer only. See issue #417, `04-ux/08-component-spec.md`, and E2E-050.** | Switching a level required a submenu trip; a Codex-style slider keeps the radio list while making quick adjustments one drag. |## E. M5 hardening decisions (0.4.0)| ID | Topic | Decision | Rationale ||---|---|---|---|-| D078 | macOS signing lanes | *(amended by D450 / ADR 0289)* **Static configuration does not embed a certificate identity, so local builds without a configured certificate remain unsigned.** | See ADR 0289. |+| D078 | macOS signing lanes | *(amended by D450 / ADR 0289)* **Static configuration embeds no certificate identity; official releases require Developer ID signing and notarization from Actions secrets.** | Contributors package unsigned; published artifacts must satisfy Gatekeeper. See ADR 0022, ADR 0289. || D079 | App icon / brand mark v1 | *(renderer asset path refined by D221)* **`build/icon_1024.png` is the canonical PI-Desktop logo; `scripts/make-icon.py` derives `build/icon.icns` without overwriting the PNG; packaged macOS builds, `pnpm dev`, and renderer chrome reuse those assets** | Keep one visual identity across development, renderer, and packaged lanes while preventing the derivation script from restoring the obsolete generated mark || D080 | Backend supervision | **Child exit rejects in-flight RPCs immediately; backoff restarts (0.5s→4s, max 3 per 2min); `hostStatus` events drive renderer degradation UI** | Crash recovery without hangs; fail visible, not silent || D081 | Renderer sandbox | **`sandbox: true` with fully bundled CJS preload; production CSP drops `unsafe-eval` and localhost connect-src** | Electron security baseline; verified by `test:e2e:boot` |@@ -271,14 +273,14 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.| D157 | One visual assistant turn per user turn | **Provider-level assistant messages separated by thinking/tool activity remain distinct canonical transcript records, but ChatTranscript composes all records after one user message and before the next into one `role=article` assistant turn. Ordered markdown fragments and activity disclosures remain visible; only the composed turn owns the trailing aggregate model/usage row and Copy/Fork/Retry toolbar. Copy joins all contentful fragments with paragraph breaks; Fork and Retry use the last contentful assistant record as their durable boundary.** | Tool-capable providers close and reopen assistant messages around every tool call. Rendering those transport boundaries as separate responses duplicated action toolbars and made one agent run look like many AI replies. || D162 | Latest-wins cached session switching | **The renderer marks the newest selected row immediately, coalesces session-detail prefetch/load work, retains an LRU-style five-transcript memory cache, and starts the newest transcript read without waiting for superseded reads. Workspace alignment may overlap transcript IO; navigation generations gate the atomic visible commit. ChatSurface keeps the previous complete view non-interactive while React defers a changed session tree, then paints the destination at its final record. Cached snapshots are always revalidated.** | The former global selection promise queue made every click wait behind obsolete full-transcript JSONL reads, while one synchronous long Markdown commit delayed visible feedback. Latest-wins IO plus a stable deferred frame matches Codex-style navigation without weakening session/workspace isolation. || D156 | Independent native-window and work-panel resize ownership | *(responsive-clamp and no-native-reservation clauses superseded by D163)* **Electron Main exclusively owns BrowserWindow bounds at a 1040x700 minimum, while the renderer owns a persisted preferred work-panel width. The divider uses anchored, frame-coalesced preview and commit-on-release; Escape, pointer cancellation, and lost capture roll back. Native window-edge resize never rewrites the panel preference. This supersedes D083's restore minimum and removes the `window/resizeBy` delta channel and resize-attribution heuristic.** | Circular ownership made divider release resize the OS window a second time, introduced async races and platform differences, moved windows near display edges, and rewrote a panel preference during unrelated native resize. |-| D163 | Native width reservation for the fixed work panel | *(width range superseded by D167)* **An open docked panel keeps one committed fixed width in `364..720`; native window/sidebar changes never clamp it.** | See ADR 0029, ADR 0032. |-| D167 | Slimmer default work-panel width | **The docked work panel opens at a 280px committed default (one third narrower than D163's 420px) and clamps to `244..720px`; the renderer constant, the Electron reservation validator, and the `.work-panel` CSS floor share those bounds.** | See ADR 0122. |-| D255 | Restore native reservation while the work panel is visible | **Keep the work panel as an in-flow fixed-width renderer column, but request its committed width through `window/setWorkPanelReservation` before presenting it.** | See ADR 0033. |-| D256 | Native taskbar minimize for Windows/Linux window controls | **Amend D216 / D252 and ADR 0078 / ADR 0117: Windows/Linux renderer and native-menu `minimize` actions call Electron's native minimize transition, and their `minimize` event is not converted to `hide()`, so the taskbar entry remains available. macOS native minimize remains tray-resident.** | See ADR 0078, ADR 0117, ADR 0090. |-| D258 | Transcript layout index, one window coordinate space, and identity truncation | **Refine ADR 0120: host-core keeps a per-session transcript layout (byte offset of every message and compaction line plus the `file_len` those offsets were recorded against) and serves a bounded window by seeking to its first selected line, so opening a session costs the window instead of the whole history.** | See ADR 0120, ADR 0127. |-| D259 | Bounded shared budget for transient provider failures | **Amend D186 / D245 and ADR 0050 / ADR 0091: non-429 transient provider failures share one bounded logical-turn budget of four retries after the initial attempt, for five provider attempts total, shared across request setup and stream delivery.** | See ADR 0050, ADR 0091. |-| D164 | Dual-locale in-app product changelog | **Product "what's new" text for app updates is maintained as a dual EN/zh-CN catalog in `packages/shared` (`CHANGELOG`).** | See ADR 0022. |-| D357 | Viewport-fixed work panel toggle | **Amend D128 / D207 / D221 and ADR 0068 / ADR 0085: AppShell owns one viewport-fixed toggle at the top-right of every non-Settings route.** | See ADR 0068, ADR 0085, ADR 0195. |+| D163 | Native width reservation for the fixed work panel | *(width range superseded by D167)* **Open panel keeps one committed `364..720` width through idempotent `window/setWorkPanelReservation`, superseding the D156 clamping clauses.** | A docked tool should not take chat width. See ADR 0029, ADR 0032. |+| D167 | Slimmer default work-panel width | **Amend D163: the docked panel opens at 280px, clamps to `244..720px`, and double-click restores 280px.** | The panel opened wider than review content needs. See ADR 0122. |+| D255 | Restore native reservation while the work panel is visible | **Keep the panel in flow, but request its committed width natively before showing it and zero it before unmounting.** | Collapsing left the window wider than chat needed. See ADR 0033, ADR 0122. |+| D256 | Native taskbar minimize for Windows/Linux window controls | **Amend D216 and D252: minimize uses the native taskbar transition; close keeps D230's hide-or-exit.** | Minimize was using the close-to-tray hide. See ADR 0078, ADR 0090, ADR 0117. |+| D258 | Transcript layout index, one window coordinate space, and identity truncation | **Refine ADR 0120: host-core keeps a transcript layout, serving a window by seeking and classifying lines with one depth-aware scan.** | Full scans made long sessions open slowly. See ADR 0120, ADR 0127. |+| D259 | Bounded shared budget for transient provider failures | **Amend D245: non-429 transient provider failures share one bounded budget of four retries covering network, timeout, stream, and retryable errors.** | A gateway 502 became a terminal error card. See ADR 0050, ADR 0091. |+| D164 | Dual-locale in-app product changelog | **Amend D120: product what's-new notes are a dual EN/zh-CN catalog attached to the existing update IPC as plain text.** | Bilingual highlights need no second network surface. See ADR 0022. |+| D357 | Viewport-fixed work panel toggle | **Amend D128: AppShell owns one viewport-fixed toggle on every non-Settings route as the sole panel-level collapse control.** | The shortcut-only entry left the panel undiscoverable. See ADR 0068, ADR 0195. |## L. Transcript presentation decisions@@ -297,57 +299,58 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.| D113 | WorkBuddy-inspired local profile footer | **The expanded sidebar ends in a transparent 58px footer. Its 44px profile trigger contains a 30px circular local-user glyph, two-line `Custom` + `Local profile` / `本地配置` identity, and a chevron; a separate 32px Help shortcut opens Settings → Info. The 280px profile menu opens 8px above the footer with a repeated identity header, divider, and Settings / Logs / Theme actions, preserving Escape, outside-click, arrow-key, and focus-restore behavior. This supersedes D041; no cloud account, notification, share, or update capability is implied.** | Adapt WorkBuddy's avatar-and-actions footer grammar to PI-Desktop's truthful local-only capabilities while improving identity hierarchy and eliminating the stale cloud stand-in || D137 | Glyph-only message toolbars; edit means edit-the-prompt | **Message toolbars carry icons only: the label lives in a CSS hover/focus tooltip (`data-tip`) plus `aria-label`, never as a visible chip caption (worded buttons stay only on error surfaces). Edit moves off the assistant answer onto the user turn: it opens the prompt in an inline textarea (slash turns seed the typed `command` form so the resend re-expands the template) and saving replays the D105/D109 regenerate path with the new text in the same session — the replaced prompt and its whole answer tail are archived as a revision, so the existing `current / total` pager walks back to the original. Editing the assistant's own text and its fork-into-a-child-session variant (D134) are dropped; Fork stays as the explicit divergence action.** | Four worded chips under every answer read as a sentence and crowded the transcript; and the useful correction is almost always "I asked it wrong", which users expect to re-run in place with history intact (ChatGPT semantics) rather than to hand-edit the model's words in a new session || D165 | Safe lazy Mermaid diagrams in assistant answers | **A completed `mermaid` fence in assistant answer prose renders as a theme-aware SVG after entering the near-viewport band. Partial stream fences and all thinking prose stay source code. The renderer dynamically loads official Mermaid, serializes its global theme renders, caps source at 20,000 characters and edges at 500, locks strict/no-HTML/no-link configuration, and applies a second SVG-profile sanitizer. Invalid or oversized diagrams fall back to visible copyable source; the diagram toolbar toggles source and copies it.** | Diagrams improve architecture and flow explanations, but parsing partial streams or every offscreen historical fence would undermine direct-stream and fast-session-switch behavior. Strict bounded local rendering adds the capability without a new protocol, network, or Electron privilege boundary. |-| D261 | The mounted transcript is a window, not the loaded history | **Refine ADR 0120 / D258 in the renderer: the mounted history is a trailing window over the loaded history — 15 rows in the first commit after a session switch, a 60-row steady state, grown 40 rows at a time.** | See ADR 0120. |-| D317 | Live/durable transcript merge keeps chronological order | **Amend ADR 0120 / D261 / ADR 0137 in the renderer: `mergeLiveSessionMessages` stitches a bounded durable `session.get` page onto the live snapshot in chronological order.** | See ADR 0120, ADR 0137. |-| D324 | Idle session switch keeps a not-yet-flushed completed tail | **Amend D317 / ADR 0137 in the renderer: `selectSession` stitches the bounded durable page onto the live snapshot whenever the session is running or still has live provenance (`liveSessionTranscripts`).** | See ADR 0137. |-| D327 | Completed replies survive process restart | **Amend D299 / ADR 0153 / ADR 0041: the finished `message_end` snapshot is checkpointed before the outbox append; `completed`/`error` `session.endTurn` deletes `.inflight.json` only when that id is already indexed; boot recovery skips completed leftovers so the outbox can append first; handshake awaits that drain then `session.recoverInflightMessages` promotes …** | See ADR 0153, ADR 0041. |-| D444 | Cross-session message id collision remaps; outbox UNIQUE is not a pause | **Amend ADR 0041 / D327: `session.appendMessage` still treats an id already indexed in the same session as a no-op (or a terminal-assistant replacement of a streaming row).** | See ADR 0041. |-| D597 | Drain poison outbox entries; accept steering into a delivery turn | **Amend ADR 0041 / ADR 0239 / ADR active-turn-steering / D444: Electron's persistence outbox treats a host append whose message carries a `PERMISSION_DENIED:` prefix as a permanent rejection, drops that row, and keeps draining.** | See ADR 0041, ADR 0239, ADR active-turn-steering. |-| D328 | Parent-judged subagent lifetime | **Amend ADR 0089 / ADR 0119 / ADR 0129: idle and duration watchdogs are not armed; parent `agent_end` does not abort running delegates; the runtime keeps the durable turn open and prompts the parent with reports when they finish.** | See ADR 0089, ADR 0119, ADR 0129. |-| D352 | Parent fatal error aborts leftover delegates | **Amend D328 / ADR 0166: parent idle still keeps the durable turn open and does not abort running delegates.** | See ADR 0166, ADR 0189. |-| D354 | Label both macOS release architectures | **Amend D353 / ADR 0145: both native macOS release lanes pass target-specific electron-builder patterns.** | See ADR 0145. |-| D353 | Disambiguate Intel macOS release artifacts | **Amend D285 / ADR 0145: the native macOS x64 release lane passes target-specific electron-builder patterns so its public assets are `PI-Desktop-<version>-Intel.dmg` and `PI-Desktop-<version>-Intel-mac.zip`.** | See ADR 0145. |-| D329 | Agent-chosen Bash timeout | **Amend D190 / D273 / ADR 0054: Bash still defaults to 60 seconds.** | See ADR 0054. |+| D261 | The mounted transcript is a window, not the loaded history | **Refine D258: the mounted transcript is a trailing window of 15 rows, then 60, grown 40 at a time.** | Every paged row stayed mounted and memory grew. See ADR 0120, ADR 0137. |+| D317 | Live/durable transcript merge keeps chronological order | **Amend D261: `mergeLiveSessionMessages` stitches the durable page chronologically, keeping older live rows before it and the tail after.** *(amended by D324)* | The page-prefix merge hid the just-sent prompt. See ADR 0120, ADR 0137. |+| D324 | Idle session switch keeps a not-yet-flushed completed tail | **Amend D317: idle session switch keeps a completed tail the durable page lacks until every live id is present.** | Idle revalidation dropped replies already on screen. See ADR 0137. |+| D327 | Completed replies survive process restart | **Amend D299: the finished `message_end` snapshot is checkpointed before the outbox append, and recovery skips completed leftovers.** | Replies sat in the outbox across a quit. See ADR 0041, ADR 0153. |+| D444 | Cross-session message id collision remaps; outbox UNIQUE is not a pause | **Amend ADR 0041 and D327: a cross-session id remaps to `{sessionId}:{id}`, and an outbox UNIQUE conflict acks idempotently.** | Tool call ids are not globally unique. See ADR 0041. |+| D597 | Drain poison outbox entries; accept steering into a delivery turn | **Amend D444: a `PERMISSION_DENIED:` append is dropped while draining, and steering enters a matching delivery turn.** | A poison head stalled the outbox at 1024. See ADR 0041, ADR 0239. |+| D328 | Parent-judged subagent lifetime | **Amend ADR 0089: no idle watchdogs; only `TaskStop` or user Stop aborts a delegate, and `maxTurns` stays.** | Parents treated wait expiry as permission to finish. See ADR 0119, ADR 0166. |+| D352 | Parent fatal error aborts leftover delegates | **Amend D328: a terminal parent error aborts leftover delegates, emits `agent_end`, and leaves `isRunning` free for Continue.** | A delegate kept the sidecar busy after failure. See ADR 0166, ADR 0189. |+| D354 | Label both macOS release architectures | **Amend D353: both macOS lanes use target-specific patterns, publishing arm64 and x64 DMG and ZIP asset names.** | arm64 assets did not name their architecture. See ADR 0145. |+| D353 | Disambiguate Intel macOS release artifacts | **Amend D285: the macOS x64 lane publishes `-Intel` asset names, leaving the arm64 lane's generic names.** | Users could not tell the Intel download apart. See ADR 0145. |+| D329 | Agent-chosen Bash timeout | **Amend D190: Bash defaults to 60 seconds and accepts `timeout` to 21,600, reading larger values as milliseconds.** | A 300-second ceiling killed legitimate builds. See ADR 0054. || D331 | Host-owned completed-turn token history | **Amend D103: parent `message.usage` stays pi-ai Usage for that assistant message. Subagent spend accumulates on the durable turn only. Electron sums parent `message_end` usages plus `turn_end.subagentUsage` into `session.endTurn.usage`. `stats.getTokenUsageHistory` rolls up completed turns over a bounded local-calendar window with filled `day` / ISO `week` / `month` buckets. Additive IPC/RPC and `idx_turns_ended_at`; no protocol or schema version bump. No currency pricing. The user-facing dashboard is plugin `pi.token-insights` (D335).** | The turns table was already the usage rollup, but Electron never sent `usage`, and merging subagent tokens into message chips would lie to the context inspector. |-| D335 | Plugin-owned token usage dashboard | **Amend D331 / ADR 0171: Settings has no Usage destination.** | See ADR 0171, ADR 0173. |-| D326 | Withdraw A2A and Peer coordination | **Remove the Agent2Agent broker, `a2a.*` RPC domain, leftover `SubagentMailbox` / `Peer` tool, and parent/delegate `A2A` tools.** | See ADR 0165. |-| D318 | Restore a missing sessions row from its transcript / outbox | **Amend ADR 0041 / D119 in host-core and Electron main: a live `sessions/<id>.jsonl` whose SQLite sessions row is gone is restored at host boot (`recover_orphaned_sessions`) and on `session.appendMessage`.** | See ADR 0041. |-| D262 | Spill large composer text pastes into session scratch | **Text-only composer pastes at or below the persisted `largePasteThreshold` remain native textarea input; the default is 600 characters and valid values are integers from 1 through 1,000,000.** | See ADR 0131. |-| D265 | One delegation reads as a card, like a fan-out | **Amends D201 / ADR 0062 in the renderer: every `Task` call in an activity group renders as a full-width delegation card — main-agent root, connector, one node per delegate — a lone delegation included, instead of falling back to a compact tool row.** | See ADR 0062. |-| D319 | A delegation card is only the Task fan-out | **Amends D201 / D265 / ADR 0062 in the renderer: consecutive `Task` starts form their own activity group and are the only rows inside the delegation card.** | See ADR 0062. |-| D320 | Sent file references stay chips and open on click | **Amend D209 / ADR 0070 in the renderer and Electron main: a sent user turn parses serialized `@path` / `@"quoted path"` tokens and paints each as a composer-matching leaf-name chip (icon, ellipsized name, canonical path in tooltip/name).** | See ADR 0070, ADR 0163. |+| D335 | Plugin-owned token usage dashboard | **Amend D331: Settings has no Usage destination; token history belongs to the `pi.token-insights` marketplace plugin over host data.** | Settings duplicated a weaker plugin heatmap. See ADR 0171, ADR 0173. |+| D326 | Withdraw A2A and Peer coordination | **Withdraw A2A: broker, `a2a.*` RPC, mailbox and Peer tools, and A2A tables go; delegates coordinate only through parent `Task*` reports.** | The channels had no product need beside `Task*`. See ADR 0165. |+| D318 | Restore a missing sessions row from its transcript / outbox | **Amend ADR 0041 and D119: a transcript without its sessions row is restored at boot and append.** | A lost row stalled a long session's outbox. See ADR 0041. |+| D262 | Spill large composer text pastes into session scratch | **Composer pastes above `largePasteThreshold` go through the session paste bridge into session scratch as a generated `@` token.** | Huge native pastes overwhelm and resist editing. See ADR 0131. |+| D265 | One delegation reads as a card, like a fan-out | **Amend D201: every `Task` call renders as a full-width delegation card, including a lone delegation, with singular-aware headers.** *(amended by D319)* | The common single case lost outcome and runtime. See ADR 0062. |+| D319 | A delegation card is only the Task fan-out | **Amend D265: only consecutive `Task` starts form the card; parent thinking, tools, and lifecycle rows stay outside it.** | Parent work painted itself onto the subagent tile. See ADR 0062. |+| D320 | Sent file references stay chips and open on click | **Amend D209: sent `@path` tokens stay chips, opening workspace HTML in the panel browser and other files natively.** | Serialized paths undid the compact composer node. See ADR 0070, ADR 0163. || D322 | Relative transcript paths preview and open | **Amend the chat/markdown file-link resolver: unprefixed relative paths stay workspace-rooted; `./` and `../` resolve against the workspace root in chat and against the viewed file's directory when previewing a markdown document. `.` / `..` normalize in place; a walk that leaves the workspace stays inert. Assistant markdown linkifies bare file tokens (known extension) in addition to inline code, links, and images. The linkify pass is a unified attacher that returns a transformer; it is never the transformer itself, so freeze does not invoke it with a missing tree. No host-protocol, IPC, or storage schema change.** | Agents write workspace-relative paths in prose and markdown files use `./` / `../` links; those were either not clickable or resolved as if they lived at the workspace root, so preview/open failed. Passing the transformer to `remarkPlugins` made unified call it at freeze with `tree === undefined`, crashing session open on `tree.type`. || D323 | Live parent turns stay transparent | **Amends D101 / D297 in the renderer: a streaming assistant turn does not sit on a `--ds-tile` and does not reserve a 14px inset or left rail. Thinking, workspace tools, and answer fragments stay on the page background like a completed turn. The tile remains only on the delegation card (D319) and the nested `.subagent-run`. Renderer only: no IPC, storage, host-protocol, or runtime change.** | D297 replaced the streaming rail with a whole-turn tile so the tint would not reflow. That boxed ordinary answers the same way as a subagent card. D101 already required transparent assistant prose; D319 already assigned the tile to the Task group. |-| D268 | A lifecycle row is a subagent row | **Refines D201 / D265 / ADR 0062 and ADR 0089 in the renderer: the delegation lifecycle rows (`TaskWait`/`TaskList`/`TaskStop`) stay compact tool rows and stay out of the topology counts, but are presented as subagent rows.** | See ADR 0062, ADR 0089. |-| D263 | A cross-display drag is user intent, not an OS adjustment | **Amend D255 / ADR 0122 in Main: the work-panel reservation reconcile no longer treats every display change alike.** | See ADR 0122, ADR 0132. |-| D269 | History continuation keeps the conversation outline reachable | **Amend D108 / D261 / ADR 0130 in the renderer: when loaded rows are withheld above the mounted window or the host reports an older page, the conversation outline remains present with one dotted earlier-history continuation even if the mounted tail has fewer than two markers or does not overflow.** | See ADR 0130. |+| D268 | A lifecycle row is a subagent row | **Refine D265: lifecycle rows stay compact tool rows outside counts but read as subagent rows summarized from the returned roster.** | They rendered as bare UUID tool calls. See ADR 0062, ADR 0089. |+| D263 | A cross-display drag is user intent, not an OS adjustment | **Amend D255: `os-adjusted` keeps ADR 0122, while a `user-moved` cross-display drag takes the new position as base bounds.** | Windows jumped on release and stale bounds persisted. See ADR 0122, ADR 0132. |+| D269 | History continuation keeps the conversation outline reachable | **Amend D108: the conversation outline keeps a dotted earlier-history continuation and advances while the top boundary stays visible.** | Scroll-only triggers stranded history behind short tails. See ADR 0130. || D270 | One model picker for both credential kinds | **Refines D237 / D240 in the renderer: the model picker is one shared renderer component rendered by both the AI service dialog and the vendor account dialog. A vendor account therefore gets the same discovered model list, the same `ModelBinding` shape, the same per-model context-window and max-output editing, the same thinking-level controls, and the same explicit binding persistence. Only the left pane heading differs between the two dialogs. The thinking-level catalog-gating clauses are superseded by D283. Renderer only: no IPC, storage, host-protocol, or provider-config schema change is implied, and no ADR is required.** | The two surfaces were copies of one picker, and the copy silently lost the advanced controls, so a vendor-account binding could not edit the same model settings as an AI service. One component makes the guarantee structural instead of a convention two files had to remember. |-| D271 | An expanded delegate run scrolls in place | **Refines D201 / D268 / ADR 0062 in the renderer: a delegate's nested rows render in a bounded `.subagent-run-rows` scroll area of `min(420px, 48dvh)` with `overscroll-behavior-y: contain`, placed on that inner wrapper rather than on `.subagent-run` so the absolutely positioned collapse rail is not clipped.** | See ADR 0062. |+| D271 | An expanded delegate run scrolls in place | **Refine D201: a delegate's nested rows scroll in a bounded `min(420px, 48dvh)` area, and `fields` tables cap at 260px.** | Expanding one delegation moved the reading position. See ADR 0062. || D302 | An expanded delegate run follows its latest output | **Refines D271 / D071 in the renderer: the bounded `.subagent-run-rows` scroller uses the parent transcript's pinned-follow contract independently. Expanding pins to the newest row; content growth follows the bottom while pinned; the first real upward gesture (wheel / trackpad / touch / scrollbar / keyboard) pauses follow and shows a nested jump-to-latest control; layout clamps and programmatic `scrollTo` never release follow. Native overflow anchoring is disabled on the nested scroller. The jump control overlays a relative wrapper around `.subagent-run-rows`, never on `.subagent-run`, so the collapse rail stays unclipped. Presentation only: no IPC, storage, host-protocol, or runtime change, and no ADR is required.** | D271 capped the nested run so it would not grow the transcript, but left that scroller without stick-to-bottom. A live delegate's new thinking, tool, and answer rows therefore appended below the viewport of an expanded card, and the user had to scroll by hand to see progress (issue #37). || D272 | Quitting stops plugins as a shutdown, not as a crash | **Refines spec 07 §3.1 in the main process: `before-quit` calls `PluginRuntime.disposeAll()` instead of `disposeWatchers()`. It marks every loaded plugin as disposing and cancels its pending restarts before anything else, disposes watchers, then stops services and runs `onUnload` in parallel — 1.5s per plugin, 3s for the whole sequence, after which the children are killed. `onPluginCrash` no longer sends its own toast, since the runtime already raised one on that path. Main process only: no IPC, storage, host-protocol, or manifest change, and no ADR is required.** | Quit left the plugin children to be killed by the process teardown, and an unmarked exit is indistinguishable from a crash: `handleChildExit`'s `disposing` guard never applied, so every quit logged `PLUGIN_CRASHED` per plugin at `exitCode: 0`, toasted "stopped unexpectedly" twice, and scheduled restarts into a closing app. 613 of 633 crash reports in one local log were this, which is what made the real crashes hard to see. || D273 | A model's habitual argument name is accepted, not corrected | **Refines spec 03 §4 in the agent runtime: `Read`/`Write`/`Edit`/`BrowserPreview` accept `file_path` beside `path`, and `Glob`/`Grep` accept `query` beside `pattern`. Both spellings are optional in the schema so either validates; the runtime folds the alias onto the canonical name before the write lock, the host call, and the transcript, requires exactly one of the pair, and lets the canonical name win when both arrive. `Bash.timeout` widens its schema maximum to 3600000 so a millisecond value validates, and the runtime reads a value of at least 1000 as milliseconds, clamped to the honoured 300-second ceiling, while 301 to 999 stays an out-of-range seconds value. Runtime only: no IPC, storage, or host-protocol change, and host-core's schemas are unchanged.** | Argument names are pretraining habits, not instructions a schema can correct. 852 of 1679 failed tool calls in one local month were a parameter-name miss, 724 of them `Read` sent with `file_path`, which alone was 87% of `Read`'s failures and put its error rate at 11%. Another 69 were a `timeout` in milliseconds. Each cost a turn on an error the model could not see itself making. || D274 | Retry an unchanged edited prompt | **Amends D137 in the renderer: confirming a valid user-prompt edit always dispatches the existing edit-resend/Regenerate path, even when the trimmed text matches the original. The inline controls are localized Retry and Cancel actions; Retry retains the existing revision archive, identity-based truncation, slash-command expansion, and attachment behavior. Renderer and i18n only: no IPC, storage, host-protocol, or runtime contract change.** | Treating an unchanged confirmation as a no-op made the “Edit and resend” action appear broken (issue #23), while the old Send label suggested a new ordinary prompt rather than replaying the selected turn. |-| D275 | Preserve the active task boundary across context compaction | **Amends D203 / ADR 0064 in the agent runtime: checkpoints record opaque `details.retainedTailMode`.** | See ADR 0064. |+| D275 | Preserve the active task boundary across context compaction | **Amend D203: checkpoints record `details.retainedTailMode`, retaining the latest user message only inside an active turn.** | Retained prompts made a new task look continued. See ADR 0064. || D278 | Subagent model selection | **Task.model overrides definition pin; only models with `availableForSubagents` appear in the delegation catalog; on-demand RPC resolves models not pre-resolved at launch** | The parent agent needs per-task model choice without exposing the full provider configuration. An opt-in flag keeps the delegation catalog bounded and intentional, and on-demand resolution avoids stale bindings for models added after sidecar launch. See §3/02 §5f, §3/11 §7, and E2E-166. |-| D365 | Named quiet intervals on the live activity row | **Amend D338 / ADR 0175: `AgentActivity` adds `preparing`, `compacting`, and `recovering`; `starting` shows its own label; `waiting-subagents` carries a live running snapshot (`name`, `lastPhase`, `lastToolName`) that updates on child tool/thinking changes, not on every token.** | See ADR 0175, ADR 0198. |-| D599 | A development build is its own installation | **Narrow D236 / amend ADR 0094: a development build (unpackaged, or `PI_DESKTOP_DEV=1`) takes `PI-Desktop Dev` as its Electron `userData` — and with it the single-instance lock, renderer `localStorage`, the plugin panel partitions, and browser pane cookies — and reads `~/.pi-desktop-dev`.** | See ADR 0094. |+| D365 | Named quiet intervals on the live activity row | **Amend D338: `AgentActivity` adds `preparing`, `compacting`, and `recovering`, and `waiting-subagents` carries a live running snapshot.** | Quiet intervals looked like a stuck generic wait. See ADR 0175, ADR 0198. |+| D599 | A development build is its own installation | **Narrow D236: a development build uses `PI-Desktop Dev` userData and `~/.pi-desktop-dev`, leaving packaged installs where they are.** | `pnpm dev` quit on a locked packaged profile. See ADR 0094. || D602 | Crash dumps stay in the data directory | **Electron's Crashpad reporter starts local-only (`uploadToServer: false`) before `ready`. Dumps live under `<data_dir>/crash-dumps`, not the default Electron `userData` crashDumps path, so a `PI_DESKTOP_DATA_DIR` profile does not share dumps. The next lock-holding launch writes one `diagnostics` line for dumps newer than `crash-dumps.json`, classified by Crashpad `ptype`: `error` if any new dump is the browser/main process, `warn` for recovered renderer/GPU/utility crashes. Host-core and sidecar crashes stay on the supervisor path. No upload, no IPC, no schema change.** | A crash left a minidump nobody read. Crashpad also records recovered renderer crashes, so a next-launch `error` that said the previous run died was a lie; and dumps outside the data directory escaped `PI_DESKTOP_DATA_DIR` isolation. |-| D619 | A copied formula is its TeX source | **Renderer only: a copy whose selection covers rendered math writes `text/plain` from the MathML `annotation` — `$…$` inline, `$$…$$` on its own lines, the delimiters `lib/latex-math.ts` normalizes `\(…\)` and `\[…\]` to, each run widened past any run inside the formula as a code span's fence is — instead of the two trees KaTeX paints.** | See ADR 0268. |-| D620 | pi-ai built-in API-key services are named presets | **Add fifteen named endpoint presets — Ant Ling, Baseten, Cerebras, Hugging Face, Meta (`responses`), MiniMax (International), Moonshot AI (International), NVIDIA, OpenCode Zen, Vercel AI Gateway, Qwen Token Plan (`alibaba-token-plan`), Qwen Token Plan (China), Xiaomi Token Plan (China / Europe / Singapore) — to `NAMED_ENDPOINT_PRESETS`, each at its published host …** | See ADR 0307. |+| D619 | A copied formula is its TeX source | **A copy covering rendered math writes `text/plain` TeX from the MathML annotation, in the delimiters `lib/latex-math.ts` normalizes.** | Formulas pasted as glyphs could not be reused. See ADR 0268. |+| D620 | pi-ai built-in API-key services are named presets | **Fifteen pi-ai API-key services become named endpoint presets at published hosts; eight built-ins stay recorded exceptions.** | A hand-maintained catalog drifted from pi-ai's provider list. See ADR 0307. || D668 | One process disclosure per turn, with three transcript display modes | **Amend D661 / the `turn-process-and-thinking-display` ADR. A turn renders exactly one top-level process disclosure holding every pre-answer row; the answer stays outside it. `AppSettings.transcriptDisplayMode` selects the layout: `flat` renders no nested activity groups, `command-first` renders `Bash`/run rows as standalone rows beside activity groups, and `fully-folded` (the default for absent or invalid values) keeps commands inside their groups and lets only ordinary assistant progress text split them. The mode is read while rendering, so switching repaints immediately - the projection cache is keyed by messages and compactions only. The disclosure header reports failed / stopped / running / finished with precedence in that order and never echoes the current item, and the disclosure shares one left edge with the levels it reveals. `transcriptDisplayMode` joins the portable application fields; `keepCommandsExpanded` is deprecated, retained only for persisted-settings compatibility, and no longer exposed or read for rendering. No host protocol, persistence schema, permission, or plugin contract change. See the amended ADR, `04-ux/06-settings-ia.md`, `04-ux/08-component-spec.md`, `04-ux/09-interaction-patterns.md`, and E2E-CHAT-turn-process-and-thinking-display.** | Chronological segmentation split one turn into several sibling disclosures above the answer, and the boolean command-folding preference could only express two layouts; a three-mode setting covers flat, command-first, and the released grouped view without changing what a tool received or stored. || D669 | `@` queries search past a truncated file index | **Amend D124: while the 8000-entry `fs/index` snapshot is truncated, a non-empty `@` query is also searched over the root's full listing through the read-only Electron channel `pi-desktop/fs/search` once typing pauses, and its best 50 rows merge with the local matches. A complete index never searches. Remote sessions keep their snapshot. No host RPC, storage, or schema change.** | The shallowest-8000-entry index left a script several folders down matching no query at all, even though the truncation note invited the reader to refine it (issue #1781). |-| D671 | Inline generative UI visualizations | **Amend D114: local sessions get a second host-owned contained root `<data_dir>/visualizations/<sessionId>/` for `.html` fragments only (Read/Write/Edit, auto-allowed like scratch, never in remote or contract sessions).** | See ADR gen-ui-inline-visualization. |+| D671 | Inline generative UI visualizations | **Amend D114: local sessions get a host-owned `visualizations/<sessionId>/` root for HTML fragments rendered inline through a sandboxed `pi-genui://` iframe.** | Interactive explanations need an embedded page. See ADR gen-ui-inline-visualization. || D674 | Per-turn changed-files summary under a finished reply | **A completed reply whose turn recorded workspace review changes renders one read-only `TurnChangesCard` below its answer and above `entryExtra`, built only from that turn's message-owned `details.review` records (no new capture, IPC, or persistence). The card starts collapsed, keeping its counts visible in a full-width disclosure button; click or Enter/Space reveals or hides its file list and Review link. Choices remain turn-scoped in the existing transcript disclosure state. Rows merge edits per path (`D` if the turn ends by deleting, else `A` if any edit created the file, else `M`; counts summed; rolled-back files stay listed and struck through). When expanded, up to four files use relaxed rows, more use dense rows, and rows past 12 fold into `+N more`. Clicking a row opens Review on that file's recorded changes; the per-call review rows and the Review tab are unchanged.** | Issue #1891, design 10 (adaptive density): the per-call review rows answer "what did this call change", and Review answers it for the whole session, but nothing answered "what did this turn change" without counting rows. || D675 | Inline images are admitted by pixel size as well as bytes | **Amend D361: an image whose PNG/JPEG/GIF/WebP header reports a longest edge above `MAX_INLINE_IMAGE_EDGE_PX` (8000) is never inlined. Host Read refuses it with `TOOL_FAILED`; prompt attachments and restored history take the existing `@path` fallback; and the runtime's last provider view replaces any such image block (user or tool result) with a text notice naming its size. The probe reads headers only (no decoder); unknown dimensions keep the byte-only rule. No protocol, schema, or persisted-format change.** | Issue #1913: a 1.89 MB, 780 x 14182 full-page screenshot passed every byte check, the provider rejected it with a non-retriable 400, and replay made every later request in that session fail. Dropping is deterministic for the same bytes, so the request prefix and prompt caching stay stable; resampling would need an image decoder and is deferred. || D676 | A completed turn the reader followed ends at its prompt | **Amend the stream-completion rule: when a turn completes while the transcript is visible and still following the stream, the renderer scrolls that turn's newest user message to 16px below the titlebar band the transcript reserves at its top (smooth unless reduced motion), releases follow mode, and shows jump-to-latest. Nothing moves when the prompt is already in view, the reply failed or was aborted, the pane is hidden or in a reading window, a disclosure position is held, or a new run starts before the move. Renderer only; no setting, IPC, or persistence change.** | Issue #1889: after a long reply the reader sat at its last line and had to scroll back up to find where it began. |-| D677 | DeepSeek reasoning replay uses one field per row and never covers real reasoning | **Amend ADR 0256 decision 3: the pi-ai fill pass takes the reasoning field from the newest assistant row that has real reasoning, normalizes every assistant row to that single field (moving real reasoning from another field name, deleting the others), and fills the placeholder only on rows with no reasoning.** | See ADR 0256. |+| D677 | DeepSeek reasoning replay uses one field per row and never covers real reasoning | **Amend ADR 0256: the fill pass uses one reasoning field from the newest real reasoning row, filling only empty rows.** | The placeholder overwrote a live row's real reasoning. See ADR 0256. || D678 | Radial context menu rebuilt and moved to General | **The opt-in transcript radial menu gets at-rest icon-and-label sectors (the hover-only hub label is gone), one filled highlight for the active sector with no focus rectangle, a recessed hub carrying the click-point dot, a 248 px disc with hairline separators and the composer shadow, and shared motion tokens for hover and reveal. A right-press started while the ring is open runs the sector it is released on; releasing in the hub dismisses without running; the release trailing the opening right-click is inert. The settings card moves from the AI tab to General after Sidebar and the settings-search index follows. Action vocabulary, per-direction defaults, `AppSettings.radialMenu`, persistence, and IPC are unchanged.** | The icon-only ring could not be read without hovering every sector, the sector fill and button background painted two highlights over one target, and the ring's switch sat in the AI tab although the surface is a transcript-interaction preference. |+## M0. Model catalog decisions| ID | Topic | Decision | Rationale ||---|---|---|---|-| D266 | Use models.dev as the primary model catalog | **Historical decision, superseded for chat metadata by D639 / ADR `models-dev-catalog-authority`.** Previous text: Electron main loads `https://models.dev/api.json` as the primary provider/model metadata source, with the pinned `pi-ai` catalog as local fallback. Provider endpoint discovery and explicit model IDs remain available for custom/account-specific models; no provider credential is sent to models.dev, and no host schema/protocol change is introduced. | A bounded, main-process models.dev fetch was first introduced to give Settings and Composer broader catalog coverage. D639 removes Pi sibling metadata as the chat fallback after it assigned wrong context limits. |+| D266 | Use models.dev as the primary model catalog | **Historical: Electron main owned a models.dev catalog fetch with the pinned `pi-ai` catalog as fallback, superseded for chat metadata by D639 / ADR `models-dev-catalog-authority`.** | Broader catalog coverage from the main process. See ADR models-dev-catalog-authority. |## M. Agent runtime decisions@@ -358,22 +361,22 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.| D132 | Composer permission menu shows effective modes only | **The agent-mode composer chip and menu expose only `ask`, `accept-edits`, and `auto`, with the effective mode selected directly and no global-default/inherit entry or provenance label. Choosing an item stores that explicit session override. Existing `inherit` persistence and resolution from D115 remain unchanged until the user chooses a mode. This supersedes only D115's composer-presentation clause.** | The inherited entry repeated a selectable mode and exposed storage provenance instead of the permission posture the user is choosing; presenting the three effective modes makes the control direct without changing host enforcement || D116 | Provider failures as assistant messages | **Every provider/model turn failure is attached to a durable `role=assistant`, `status=error` transcript message through optional `UiMessage.error`. The message shows a localized summary and stable code, keeps redacted provider detail behind an accessible disclosure, and offers context-appropriate Retry or Settings actions. Message-bound failures never use toast/global banner presentation and never re-enter later model context.** | Errors belong to the failed turn; preserving them in the transcript makes the response diagnosable after session switches/restarts without contaminating the next model request or exposing credentials || D127 | Context-preserving reseed + transport retry | **Reseeding a recreated pi runtime from the persisted transcript restores tool call/result pairs (from tool rows' `toolCallId`/`toolArgs`/`toolResult`) in addition to user/assistant text and thinking. Interrupted tool rows restore as errored results; orphaned tool rows get a synthesized call-only assistant carrier so pairs stay adjacent and well-formed. Failed assistant turns stay transcript-only. Separately, request setup uses one bounded pi-ai retry for transient transport/provider failures; post-response stream recovery is defined by D186.** | Text-only reseed collapsed a session's context after any runtime recreation (regenerate/edit, config change, restart): the model lost every tool result it had gathered and — seeing its own history answer without visible tool use — stopped calling tools, degrading agent sessions into bare chat. The incident trigger was a single un-retried provider timeout that forced the user into regenerate. D127 corrects the initially duplicated D120 identifier; D120 remains the earlier application-update decision frozen by baseline 0.4.6. |-| D136 | pi-ai owns known-model metadata | **Historical decision, superseded for chat metadata by D639 / ADR `models-dev-catalog-authority`.** Previous text: resolved Pi records governed published metadata; unknown IDs used generic metadata. **This supersedes D102 and the provider-override clauses of D096/D107.** | A second desktop-owned model matrix had previously discarded Pi metadata. The later D639 root-cause evidence showed that Pi sibling defaults could misstate the selected model's context window. |-| D183 | Segmented tool and model latency logs *(superseded by D385 / ADR 0212; UI clause superseded by D184)* | **Every `tools.execute` call is timed in segments instead of one opaque duration: host-core emits a `tool timing` line on the `host` channel and persists `prompted`, `permissionWaitMs`, `overheadMs`, and `totalMs` next to the existing `durationMs` on `tool_execute` / `tool_denied` audit rows; the sidecar writes greppable `[timing] kind=tool …` (`hostRttMs`) and `[timing] kind=model …` (`providerWaitMs`, `streamMs`, including failed/aborted turns) lines to the `agent` channel, suppressible with `PI_DESKTOP_TIMING=0`. The original no-UI clause is superseded by D184; logging remains unchanged.** | "Executing a command is slow" was undiagnosable from the logs: approval waiting, the tool body, and the provider round trip were indistinguishable, so a 45s gap between two audit rows with 0ms durations gave no clue whether it was the user, the model, or the host. Splitting the stages makes the answer readable without reproducing the run. |-| D158 | Turn-boundary context checkpoint compaction *(soft-boundary, model-tool, and visibility clauses superseded by D200; the model tool and visibility restored in Codex's shape by D203)* | **PI-Desktop owns context estimation, session-context projection, compaction preparation, and summary generation; pi-agent-core supplies the agent loop and stable types.** | See ADR 0030. |-| D185 | Lazy per-turn tool activation *(the always-active `CompactContext` clause is void under D200, and holds again for `new_context` under D203; activation restoration amended by D400 / ADR 0225)* | **The sidecar keeps a complete local tool registry but sends only the mode core set and local `ToolSearch` on each new prompt. `BrowserPreview`, plugin tools, `Skill`, and plugin-development helpers appear as bounded compact catalog entries and are activated by exact-name or capability search; the next turn receives their schemas, native pi-ai deferred search is used when supported, and the in-memory set resets before the next user prompt, then restores only successful activation evidence still present in the effective context and allowed by the current catalog and mode. Host permissions, containment, timeouts, and audits are unchanged.** | Full tool schemas made simple first requests disproportionately large and repeated optional capability cost across turns. A pi-style active set preserves core coding ergonomics while making ancillary tools pay-as-you-go and provider-independent; restoring successful context evidence prevents the model from seeing a capability marker without receiving the corresponding schema. |-| D200 | Imperceptible background context compaction *(background pre-computation, incremental trigger, silence, and no-model-tool clauses superseded by D203)* | **Compaction becomes a host-owned background activity with no user-visible surface.** | See ADR 0049, ADR 0061. |-| D201 | Bounded subagents behind a `Task` tool | **Agent mode exposes `Task` when the catalog contains one of the four inline builtins or an enabled global document under `~/.agents/subagents/*.md`.** | See ADR 0062, ADR 0112. |-| D202 | Managed global subagent definitions | *(Page-shape clause superseded by D257 / ADR 0126; the global-only data boundary stands)* **host-core scans global Markdown documents under `~/.agents/subagents`, stores enabled state in `<data>/agent-capabilities/subagents.json`, and exposes them through the Settings > Agent > Subagents page.** | See ADR 0126, ADR 0063, ADR 0112. |-| D203 | Codex-parity context compaction | **Compaction is rebuilt to match Codex's mechanism, reversing four D200 clauses and keeping the rest.** | See ADR 0064. |-| D186 | Bounded provider stream recovery and diagnostics *(429 budget amended by D245)* | **Provider request setup uses one bounded retry for non-rate-limit transient failures.** | See ADR 0050, ADR 0091. |--| D187 | Resource-isolated host RPC stdio | **host-core reads stdin and serializes stdout through one dedicated named OS thread per direction, never through Tokio's dynamic blocking pool.** | See ADR 0051. |-| D191 | Agent-only mode; Chat renamed to read-only | *(superseded by D188/D189: the mode selector returned as `Agent | Plan`, and `chat` migrates to `plan`)* **`agent` is the only session mode the product exposes.** | See ADR 0055. |-| D369 | Effective subagent thinking metadata | *(amended by D395)* **The immediate `Task` result, `SubagentRunResult`, and lifecycle snapshots carry the effective `modelId` and `thinkingLevel` passed to each child run; the topology node and side-dock header show the raw canonical non-`off` level after the model name, while `off`, `omit`, and unsupported reasoning stay model-only.** | See ADR 0202, ADR 0221. |--| D395 | Canonical thinking-level values in the UI | **Amend D369 / ADR 0202: Composer, model configuration, and delegation surfaces render `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max` directly instead of translating them.** | See ADR 0202, ADR 0221. |-| D445 | Compaction summary retries and is right-sized before retained-tail recovery | **Amend ADR 0049 decision 1 / D203: the automatic summary request carries a bounded pi-ai `RetryPolicy` (3 retries, 2s/4s/8s backoff, abort-aware; pi-ai classifies what is transient).** | See ADR 0049, ADR 0282. |+| D136 | pi-ai owns known-model metadata | **Historical: `pi-ai` supplied known-model metadata, superseding D102 and D096/D107's provider overrides, then D639 / ADR `models-dev-catalog-authority` replaced it for chat metadata.** | Pi sibling defaults misstated model context windows. See ADR models-dev-catalog-authority. |+| D183 | Segmented tool and model latency logs *(superseded by D385 / ADR 0212; UI clause superseded by D184)* | **Tool and model latency is logged in segments through host `tool timing` lines, per-stage audit fields, and greppable `[timing]` sidecar lines.** | Stage timing makes slow runs diagnosable without reproduction. See ADR 0212. |+| D158 | Turn-boundary context checkpoint compaction *(soft-boundary, model-tool, and visibility clauses superseded by D200; the model tool and visibility restored in Codex's shape by D203)* | **PI-Desktop owns context estimation: after every `turn_end` it enforces model-aware budgets, writes durable checkpoints beside the untouched visible transcript, and retries once after a provider overflow.** | End-of-run-only protection cannot guard long tool loops. See ADR 0030. |+| D185 | Lazy per-turn tool activation *(the always-active `CompactContext` clause is void under D200, and holds again for `new_context` under D203; activation restoration amended by D400 / ADR 0225)* | **Each new prompt sends only the mode core tools and `ToolSearch`; catalog tools activate by name or capability and the active set resets per turn.** | Full schemas made first requests disproportionately large. See ADR 0225. |+| D200 | Imperceptible background context compaction *(background pre-computation, incremental trigger, silence, and no-model-tool clauses superseded by D203)* | **Compaction becomes silent host-owned background work: a graded trigger pre-computes a checkpoint while the provider is idle and installs it at the next boundary if valid.** | Compaction was correct but intrusive. See ADR 0061, ADR 0049. |+| D201 | Bounded subagents behind a `Task` tool | **Agent mode exposes `Task` for bounded delegation over at most 16 global subagent definitions, keeping delegate reports out of the parent context.** | Bounded delegation preserves parent ownership of context. See ADR 0062, ADR 0112. |+| D202 | Managed global subagent definitions | *(Page-shape clause superseded by D257 / ADR 0126; the global-only data boundary stands)* **host-core scans global Markdown subagents under `~/.agents/subagents`, stores enablement in app state, and exposes them only through Settings > Agent > Subagents.** | Global-only scanning avoids a second project precedence model. See ADR 0063, ADR 0112. |+| D203 | Codex-parity context compaction | **Compaction now follows Codex: synchronous at the hard limit or on `new_context`, keeping recent user messages, with a transcript divider row and a toast.** | Earlier work cited Codex while doing the opposite. See ADR 0064. |+| D186 | Bounded provider stream recovery and diagnostics *(429 budget amended by D245)* | **Provider setup gets one bounded retry, a transient stream failure replays once with the failed assistant removed, and `Edit` mismatches get one fresh read.** | Unbounded recovery burned context and turns. See ADR 0050, ADR 0091. |++| D187 | Resource-isolated host RPC stdio | **host-core serves stdin and stdout on dedicated named OS threads instead of Tokio's blocking pool, preserving NDJSON framing and bounded admission.** | Thread exhaustion turned resource pressure into host crashes. See ADR 0051. |+| D191 | Agent-only mode; Chat renamed to read-only | *(superseded by D188/D189: the mode selector returned as `Agent | Plan`, and `chat` migrates to `plan`)* **`agent` is the only exposed session mode; the former `chat` profile becomes a host-enforced read-only surface with no UI, and legacy rows migrate.** | An unreachable mode switch is a footgun. See ADR 0055. |+| D369 | Effective subagent thinking metadata | *(amended by D395)* **Subagent results and lifecycle snapshots carry the effective `modelId` and `thinkingLevel`, and delegation surfaces show the raw canonical non-`off` level.** | Cards need the level actually sent. See ADR 0202, ADR 0221. |++| D395 | Canonical thinking-level values in the UI | **Amend D369 / ADR 0202: composer, model configuration, and delegation surfaces render canonical thinking-level values directly instead of translating them, and the locale entries are removed.** | Levels are protocol values, not locale strings. See ADR 0221, ADR 0202. |+| D445 | Compaction summary retries and is right-sized before retained-tail recovery | **Amend ADR 0049 / D203: the summary request retries a bounded policy, is sized by the serialized prompt, and tries one reduced input before falling back.** | Six of ten checkpoints were a 112-token notice. See ADR 0282, ADR 0049. |## N. Notification decisions@@ -386,65 +389,66 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.| ID | Topic | Decision | Rationale ||---|---|---|---|| D118 | Platform application menu and window chrome | **macOS installs a conventional system application menu and keeps hidden-inset traffic lights. Windows/Linux use the shared 46px frameless shell with localized File/Edit/View/Window/Help menus and renderer-drawn minimize/maximize-or-restore/close controls. Both menu surfaces route renderer-owned actions through a fixed `AppMenuCommand` allowlist; renderer menus route native editing/window actions through a separate fixed allowlist. Target packaging builds the local release host before Electron packaging. This adds platform-ready shell behavior but does not reverse D010: Windows/Linux release qualification remains post-MVP.** | A default Electron menu leaves macOS shell commands incomplete, while a frameless Windows/Linux window otherwise loses both application menus and window controls. Shared allowlists keep behavior consistent without exposing an arbitrary privileged command bridge. |-| D120 | Application update delivery | *(amended by D364 / D603 / D628)* **Electron Main exclusively owns a fixed GitHub Releases feed, update polling, typed state, and install lifecycle.** | See ADR 0022. |-| D628 | User-selectable application update behavior | **Amend D120 / D603 / ADR 0022: persist a per-install `AppSettings.updatePreference` (`automatic` or `manual`).** | See ADR 0022. |-| D313 | Main-owned GitHub issue feedback | **GitHub issue forms are the only intake path.** | See ADR 0157. |-| D330 | Main-owned `openExternal` protocol allowlist | **Every `shell.openExternal` call parses the URL first.** | See ADR 0109, ADR 0168. |-| D332 | Classified plugin file preview and live workspace events | **Amend ADR 0104 / 0105 / 0109 / 0111: add `fs.readPreview` under `fs.read` (text / image data URL / binary / tooLarge, same caps as the host Files tab).** | See ADR 0104, ADR 0105, ADR 0109, ADR 0111. |-| D334 | Contained in-chat image display | **Amend the desktop `fs/read` workspace-only clause: `fs/read`, `fs/reveal`, and `fs/open` share `resolveOpenablePath` (workspace, `<data_dir>/scratch/`, `<data_dir>/attachments/`, plus `attachments/<sha256>` blobs).** | See ADR 0172. |-| D336 | Host-owned plugin completions and session context | **Amend D019: plugins may read the in-flight tool session's model-facing transcript through `pi.session.getLlmContext()` when `session.read` is granted, and may run a one-shot completion through `pi.agent.complete()` when `agent.complete` is granted.** | See ADR 0174. |-| D340 | User-configurable outbound proxy | **Settings → General → Network exposes Proxy as System / Direct / Custom.** | See ADR 0177. |-| D342 | Import model configuration from local agent stores | **Amend D007: Settings → Import still never auto-imports `~/.pi` (or any other tool).** | See ADR 0188, ADR 0179, ADR 0319. |-| D351 | Preserve distinct credentials during model configuration import | **Amend D342 / ADR 0179: an imported provider is equivalent only when normalized endpoint, API style, and credential all match.** | See ADR 0179, ADR 0188. |-| D344 | Main-owned picker capabilities | **Amend D197 / D334: composer native file and image pickers keep selected absolute paths in Electron main behind a short-lived, sender-bound, one-shot token.** | See ADR 0181. |-| D314 | Shipped locale registry and language picker | **Amend D073: UI locales are listed in `@pi-desktop/i18n` (`en`, `zh-CN`, `zh-TW`, `tr`).** | See ADR 0160, ADR 0182. |--| D345 | Traditional Chinese shell locale | **Amend D314 / ADR 0160: ship `zh-TW` as an independent full shell catalog with native name 繁體中文.** | See ADR 0160. |-| D346 | P0 international shell locales | **Amend D314 / ADR 0160 / ADR 0182: ship complete `de`, `es`, and `fr` shell catalogs with native names Deutsch, Español, and Français.** | See ADR 0160, ADR 0182. |-| D349 | Korean shell locale | **Amend D314 / ADR 0160 / ADR 0183: ship a complete `ko` shell catalog with native name 한국어 and English name Korean.** | See ADR 0160, ADR 0183. |-| D605 | Brazilian Portuguese (pt-BR) shell locale | **Amend D314 / ADR 0160 / ADR 0183 / ADR 0185: ship a complete `pt-BR` shell catalog with native name Português (Brasil) and English name Portuguese (Brazil).** | See ADR 0160, ADR 0183, ADR 0185, ADR 0306. |-| D350 | Focus-aware native task notifications | **Amend D117 / ADR 0107: `notification/showNative` carries `kind` as `task` or `interactive`.** | See ADR 0107, ADR 0187. |-| D358 | Show provider retry causes in the active-turn status | **Amend ADR 0175: `AgentActivity.retrying` may carry bounded, already-redacted error details.** | See ADR 0175, ADR 0196. |+| D120 | Application update delivery | *(amended by D364 / D603 / D628)* **Electron Main owns the fixed GitHub Releases feed, polling, typed update state, and install lifecycle, downloading in-app only where the platform supports installation.** | Installation stays outside the sandboxed renderer. See ADR 0022. |+| D628 | User-selectable application update behavior | **Amend D120: a persisted per-install `updatePreference` selects automatic in-app updates or manual notify-only, defaulting by installer format.** | Control with safe no-install defaults. See ADR 0022. |+| D313 | Main-owned GitHub issue feedback | **GitHub issue forms are the only intake path; Settings → Info opens a Main-built prefilled bug report, and the renderer cannot supply the URL.** | Reports without version or steps cannot be triaged. See ADR 0157. |+| D330 | Main-owned `openExternal` protocol allowlist | **Every `shell.openExternal` call parses its URL and admits only `http`, `https`, and `mailto` hrefs, throwing `DISALLOWED_EXTERNAL_URL` otherwise.** | Unvalidated links can launch OS protocol handlers. See ADR 0109, ADR 0168. |+| D332 | Classified plugin file preview and live workspace events | **Amend ADR 0104 / 0105 / 0109 / 0111: add `fs.readPreview`, broadcast panel events to docked views, and deliver workspace changes to panels and plugins.** | `fs.readText` cannot preview images or cap binaries. See ADR 0104. |+| D334 | Contained in-chat image display | **`fs/read`, `fs/reveal`, and `fs/open` share one contained resolver, and a renderer-only `fs/readImageDataUrl` returns bounded image data or a failure tag.** | History attachments are unreadable extension-less data-root blobs. See ADR 0172. |+| D336 | Host-owned plugin completions and session context | **Amend D019: granted plugins may read the in-flight tool session's model-facing transcript and run one-shot completions through host-owned APIs that never expose credentials.** | Second opinions need models and context, not secrets. See ADR 0174. |+| D340 | User-configurable outbound proxy | **Settings → General → Network offers System, Direct, or Custom proxy, applied to Chromium, the agent sidecar, and marketplace fetches from one persisted setting.** | Node fetch ignored the OS proxy. See ADR 0177. |+| D342 | Import model configuration from local agent stores | **Amend D007: Settings never auto-imports, but an explicit Model configuration card scans five local agent stores and copies chosen provider drafts.** *(amended by D645 / ADR 0319: model import moved to Models and Settings has no session-import UI)* | Users retyped endpoints and keys they already had. See ADR 0179, ADR 0188, ADR 0319. |+| D351 | Preserve distinct credentials during model configuration import | **Amend D342 / ADR 0179: an imported provider matches only when normalized endpoint, API style, and credential all agree, so same-endpoint accounts stay separate rows.** | Endpoint-only idempotence dropped all but one account. See ADR 0188. |+| D344 | Main-owned picker capabilities | **Amend D197 / D334: native file and image pickers hand back a short-lived sender-bound token, never absolute paths, and the directory option is removed.** | Renderer-supplied paths were a file exfiltration primitive. See ADR 0181. |+| D314 | Shipped locale registry and language picker | **Amend D073: `@pi-desktop/i18n` owns the shipped locale registry, and Settings → General language becomes a searchable picker that includes Auto.** | Preview cards cannot scale past two languages. See ADR 0160, ADR 0182. |++| D345 | Traditional Chinese shell locale | **Amend D314 / ADR 0160: ship a complete `zh-TW` shell and changelog catalog, resolved by `zh-Hant`, `zh-HK`, and `zh-MO` as well.** | Traditional users need their own terminology and notes. See ADR 0182. |+| D346 | P0 international shell locales | **Amend D314: ship complete `de`, `es`, and `fr` shell catalogs with native names, resolving each regional variant to its base locale.** | Highest-value missing P0 coverage; the registry already scales. See ADR 0160, ADR 0183. |+| D349 | Korean shell locale | **Amend D314: ship a complete `ko` shell and changelog catalog with native name 한국어, resolving `ko` and `ko-*` to it.** | Korean needs a distinct complete shell language. See ADR 0183, ADR 0185. |+| D605 | Brazilian Portuguese (pt-BR) shell locale | **Amend D314: ship a complete `pt-BR` shell and changelog catalog named Português (Brasil), resolving `pt_BR` and regional `pt-*` to it.** | Brazilian users need a matching complete shell language. See ADR 0306, ADR 0160. |+| D350 | Focus-aware native task notifications | **Amend D117 / ADR 0107: `notification/showNative` carries `kind` as `task` or `interactive`, and task banners stay suppressed while the main window is focused.** | Two notification kinds need different focus rules. See ADR 0187. |+| D358 | Show provider retry causes in the active-turn status | **Amend ADR 0175: `AgentActivity.retrying` may carry bounded redacted error details, revealed on hover or focus without creating transcript error rows.** | Users need the retry cause in place. See ADR 0196. || D359 | Summarize first-turn session titles with a main-owned one-shot *(superseded by D652)* | **Historical: the core once applied a first-prompt fallback, then ran `session/summarizeTitle` from Electron after `agent_end`. D652 removes both automatic title paths and moves optional generation to a standalone plugin.** | A truncated first prompt was a poor sidebar label, but title generation must not block the turn or expose credentials to the renderer. |-| D361 | Inline image transport uses a 10 MB app-side bound | **Amend ADR 0101 / D197: `MAX_INLINE_IMAGE_BYTES` is 10,000,000.** | See ADR 0101. |-| D316 | Searchable theme picker | **Amend ADR 0160: Settings → General theme is a searchable picker row (same anchored-menu pattern as Language), not three preview cards.** | See ADR 0160, ADR 0161. |+| D361 | Inline image transport uses a 10 MB app-side bound | **Amend ADR 0101 / D197: `MAX_INLINE_IMAGE_BYTES` is 10,000,000, shared by Electron main and the sidecar, and larger images fall back to `@path`.** | MiniMax accepts at most 10 MB per image. See ADR 0101. |+| D316 | Searchable theme picker | **Amend ADR 0160: the theme setting becomes a searchable picker pinning System, Light, and Dark above plugin themes, replacing the card grid.** | Plugin themes outgrew the card grid. See ADR 0161, ADR 0160. || D121 | Branded macOS development host | **`pnpm dev` on macOS launches electron-vite through a fingerprinted, ad-hoc-signed PI-Desktop copy of the installed Electron host bundle under `.cache/electron-dev/`. The generated bundle changes only development host metadata, executable name, bundle identifier, and the ICNS resource; it never mutates `node_modules`. Windows/Linux keep the stock development executable, while packaged lanes remain electron-builder-owned.** | AppKit ignores runtime app-name/menu overrides for the top-level application identity and takes the native menu name and About icon from the host bundle; a branded development host is required for parity with packaged PI-Desktop. |-| D129 | Menu-free Windows/Linux window chrome | **The application menu is a macOS system-menu surface only.** | See ADR 0021. |+| D129 | Menu-free Windows/Linux window chrome | **The application menu is macOS-only; Windows and Linux keep the frameless 46px titlebar with renderer-drawn controls and no in-window menu bar.** | An in-window menu duplicates macOS chrome needlessly. See ADR 0021. || D130 | Sidebar-footer notification entry | **The durable notification Bell moves from the main titlebar to the separate `32px` action at the right of the expanded sidebar footer, replacing D113's Help shortcut. Its unread badge and complete D117 inbox behavior remain unchanged; the popover opens above and to the right of the footer, and no duplicate Bell remains in the main titlebar. This supersedes only the entry-location clauses of D113 and D117.** | Notification history belongs with the persistent local profile controls and the footer position keeps the main titlebar quiet while preserving a compact, familiar status entry. || D141 | Canonical Windows native application identity | *(amended by D443)* **Electron Main sets the product name before readiness and registers `com.pi-desktop.app` as the Windows process AppUserModelID before creating any window. That ID is the existing electron-builder/NSIS application ID; Windows packaging explicitly retains `PI-Desktop` for the executable and Start menu shortcut. Native notification attribution, notification settings, taskbar grouping, installed shortcuts, and packaged executable identity must expose `PI-Desktop`, not the stock Electron host. D121 remains unchanged: Windows development may use the stock Electron executable while its OS-facing runtime identity uses the canonical AUMID.** | `app.setName` changes Electron's internal name but not the Windows identity used by notifications and shell integration. One stable ID across runtime and packaging prevents both the observed notification-source leak and adjacent shell-brand drift without changing the published NSIS upgrade identity. |-| D204 | Empty home task-entry surface | *(supersedes D111's non-docked home-composer clause and its contextual quick-action clauses; starter-grid amendment in D205 is superseded by D206)* **The empty chat home keeps the restrained hero and optional first-run checklist in the scrollable content region.** | See ADR 0066. |+| D204 | Empty home task-entry surface | *(supersedes D111's non-docked home-composer clause and its contextual quick-action clauses; starter-grid amendment in D205 is superseded by D206)* **The empty chat home keeps the hero and optional first-run checklist in the scroller, with the composer as a bottom-reserved sibling that never covers content.** | The direct composer stays the primary action. See ADR 0066. || D205 | ChatGPT-inspired empty-home guidance | *(superseded by D206)* **The empty chat home adds a compact four-card developer starter grid between the hero and optional checklist: Explore a codebase, Build a feature, Fix a bug, and Review a change. Each localized card only prefills and focuses the bottom composer; it never sends a prompt or creates a turn. The bottom-reserved composer and single scrollable home flow from D204 remain unchanged.** | The previous hero-only middle left too much unused space and offered no starting cues. ChatGPT's clear empty-state hierarchy improves first-task discoverability while developer-specific prompts keep the surface purposeful rather than promotional. || D206 | Remove empty-home developer starter cards | **The empty chat home does not render developer starter cards, starter glyphs, or a contextual quick-action row. It keeps the restrained hero, short supporting line, optional onboarding checklist, and D204's bottom-reserved composer; task entry starts directly in the composer. This supersedes D205 without changing D204's scroll and bottom-reservation layout.** | Review confirmed that the direct composer is the preferred task-entry surface and that the cards add an unnecessary decision layer to the empty home. |-| D208 | Recoverable native-tool path contracts | **Keep D185's deferred Glob/Grep boundary, but make every prompt and schema explicit that Read accepts an existing regular file, Glob accepts a directory, and Grep accepts a file or directory.** | See ADR 0069. |-| D216 | Cross-platform tray-resident minimize | *(Windows taskbar clause amended by D252 / ADR 0117; explicit Windows/Linux action clauses amended by D256 / ADR 0123)* **Electron Main creates one packaged-resource tray icon on macOS, Windows, and Linux.** | See ADR 0117, ADR 0123. |-| D218 | Host-owned cross-platform plugin panel chrome | **Plugin panel windows adopt the main window's 46px platform chrome: macOS uses `hiddenInset` with traffic lights at `{x:16,y:16}`, while Windows/Linux are frameless with a 112px custom minimize/maximize-or-restore/close band.** | See ADR 0081. |-| D234 | Plugin-owned panel surface with a host window-control capsule | **Plugin panels use frameless windows on macOS, Windows, and Linux.** | See ADR 0081, ADR 0082. |-| D235 | Strict 46px plugin drag band with a minimal capsule | **Plugin panels reserve exactly 46px for a transparent host drag band on every platform.** | See ADR 0092. |-| D343 | Custom global UI type scale | **Settings → General → Appearance gains a Font size row under Font.** | See ADR 0180. |-| D232 | Custom global UI font | *(amended by D598)* **Settings → Basics → Appearance gains a searchable Font picker (trigger previews the current family).** | See ADR 0083. |-| D598 | The app ships no fonts | **Amend D232 / ADR 0083: every bundled family is removed.** | See ADR 0083, ADR 0298. |-| D230 | User-configurable close behavior with close-to-tray | **Windows/Linux close behavior is a persisted preference stored by Electron main in `<data>/close-behavior.json`.** | See ADR 0078, ADR 0090. |+| D208 | Recoverable native-tool path contracts | **Keep the deferred Glob/Grep boundary but make contracts explicit: Read refuses directories, Grep accepts one file or a directory, and path errors carry structured recovery arguments.** | Sessions showed repeated path mistakes and false failures. See ADR 0069. |+| D216 | Cross-platform tray-resident minimize | *(Windows taskbar clause amended by D252 / ADR 0117; explicit Windows/Linux action clauses amended by D256 / ADR 0123)* **Electron Main owns one tray icon everywhere; explicit minimize hides the window while background work continues and native Windows taskbar minimize stays ordinary.** | Background work must survive a hidden window. See ADR 0078, ADR 0117, ADR 0123. |+| D218 | Host-owned cross-platform plugin panel chrome | **Plugin panels adopt the main window's 46px platform chrome, rendered by the sandboxed preload in a closed Shadow DOM through a private sender-validated control channel.** | Default frames looked detached and varied by platform. See ADR 0081. |+| D234 | Plugin-owned panel surface with a host window-control capsule | **Plugin panels are frameless everywhere, and the preload renders only a transparent 46px band with one three-button window-control capsule while the plugin owns the rest.** | The host titlebar consumed the plugin's visual hierarchy. See ADR 0092, ADR 0081, ADR 0082. |+| D235 | Strict 46px plugin drag band with a minimal capsule | **Plugin panels reserve exactly 46px as a transparent host drag band on every platform, holding one minimal page-adaptive capsule and no host title.** | Frameless panels need a drag band, not chrome. See ADR 0092. |+| D343 | Custom global UI type scale | **Appearance adds cup presets and a percentage slider persisted as `AppSettings.fontScale`, scaling every `--text-*` token and shared icon through one root multiplier.** | One multiplier scales the whole frozen type ramp. See ADR 0180. |+| D232 | Custom global UI font | *(amended by D598)* **Appearance gains a searchable font picker over bundled and installed families, persisted as `AppSettings.fontFamily` and applied by overriding `--font-sans` without a reload.** | Renderer preferences should not widen host RPC. See ADR 0083. |+| D598 | The app ships no fonts | **Amend D232 / ADR 0083: remove every bundled family and its licensing surface, keeping the picker on installed system families plus a system CJK fallback tier.** | Bundled faces duplicated OS coverage at 15.7 MiB. See ADR 0298. |+| D230 | User-configurable close behavior with close-to-tray | **Windows and Linux close behavior is asked once and persisted as tray or quit, with a Settings toggle that cannot restore prompting.** | Close quit outright where minimize had hidden. See ADR 0090, ADR 0078. || D363 | Explicit quit confirms before shutdown | **Amend D230 / D216: Cmd+Q, the application-menu Quit item, and the tray Quit item show one themed in-app confirmation (Cancel / Quit), restoring a tray-hidden main window first and using a native fallback when the renderer is unavailable. Cancel leaves the app running and allows a later quit to prompt again. Confirm runs the ordered `before-quit` shutdown. A window-close path that already chose Quit in the D230 dialog sets `quitConfirmed` and does not ask again. Boot, supervision, and capture probes skip the dialog, and so does the quit an in-app update performs: `autoUpdater.quitAndInstall()` spawns the platform installer before `app.quit()`, and that installer aborts once the app outlives its wait window, so the update restart must reach the ordered shutdown without a prompt. Additive lifecycle-dialog IPC only; no storage or host-protocol change. See E2E-204.** | An explicit quit tears down host-core, the sidecar, and in-flight work; a one-step confirm prevents an accidental Cmd+Q or tray Quit from doing that, without re-prompting a user who already chose Quit on the close-behavior dialog. |-| D252 | Windows taskbar preserves native minimize/restore | *(Explicit renderer/menu minimize clauses superseded by D256 / ADR 0123)* **Amend D216 / ADR 0078: when the focused Windows main window is toggled from its taskbar button, Electron lets the native `minimize` transition complete instead of hiding the window.** | See ADR 0123, ADR 0078. |-| D236 | One desktop instance per data directory | **Electron main takes `app.requestSingleInstanceLock()` during module evaluation — after `app.setName`, because the lock lives under the name-derived `userData` path, and before the logger, the persistence outbox, or any other data-directory access.** | See ADR 0094. |-| D367 | Host-owned plugin session import and ownership API | **`pi.session` gains `import`, `importBatch`, `list`, `get`, `listMessages`, `rename`, and `delete`; `contributes.sessionSources` is required for every source; host-core generates ids and scopes every operation to `(pluginId, source, externalId)` ownership; imports never activate project/provider/model bindings.** | See ADR 0200. |-| D368 | Explicit plugin project ids and host-owned session refresh | **Permission-gated `pi.project.create({ path })` creates or reuses a project and returns its host-generated id without activating the workspace; import items may bind an existing `projectId`, omitted ids stay unbound, and historical origin paths never become tool roots.** | See ADR 0201. |-| D680 | Plugin session scope: `.all` grants and message-level writes | **`pi.session` gains `session.read.all`, `session.update.all`, and `session.delete.all`, which carry `list`/`get`/`listMessages`, `rename`, and `delete` over every live session instead of only the calling plugin's imports.** | See ADR 0200, ADR 0323, ADR 0333, ADR 0340. |-| D370 | Local MCP control plane for desktop operations | *(amended by D372)* **An opt-in Streamable HTTP MCP server inside Electron Main binds to `127.0.0.1`, authenticates with a persistent random bearer token, validates supplied Origins against loopback hostnames, writes a mode-restricted connection manifest, and delegates to the same registered IPC handlers the renderer uses.** | See ADR 0203. |-| D372 | Tightened local MCP control-plane boundary | **Amend D370 / ADR 0203: the first-version catalog is the project/session/Agent/workspace flow plus reviewed reads; secret-shaped arguments are stripped; `session/configure` is dangerous; listen addresses are asserted loopback; protocol versions are negotiated rather than echoed; results including `structuredContent` are bounded; renderer session refresh is mutation-only.** | See ADR 0203. |-| D377 | Plugin desktop control requires native user consent | **A `dangerous` desktop operation invoked through `pi.desktop.invoke` needs the plugin's `confirm: true` and then the user's answer to a host-owned native dialog that shows only the catalog operation id, description, and a bounded argument preview; dismissal, Deny, and a host without a dialog service fail with `PERMISSION_DENIED`.** | See ADR 0208. |+| D252 | Windows taskbar preserves native minimize/restore | *(Explicit renderer/menu minimize clauses superseded by D256 / ADR 0123)* **Amend D216 / ADR 0078: a taskbar toggle on Windows completes the native minimize instead of hiding, while explicit minimize actions still hide to the tray.** | Hiding on taskbar toggle removed the taskbar entry. See ADR 0117, ADR 0123. |+| D236 | One desktop instance per data directory | **Electron main takes the single-instance lock at startup for default data directories; a second launch quits, and the running instance restores its window instead.** | Two shells shared one single-writer database (D002). See ADR 0094. |+| D367 | Host-owned plugin session import and ownership API | **`pi.session` gains import, list, read, rename, and delete over host-generated ids scoped to `(pluginId, source, externalId)`, backed by new schema columns.** | Plugins need durable session ownership boundaries. See ADR 0200. |+| D368 | Explicit plugin project ids and host-owned session refresh | **Plugins create or reuse projects by path without activating the workspace, and Electron main emits a session-changed event after plugin imports, renames, or deletes.** | Plugin writes need a host-owned renderer refresh path. See ADR 0201. |+| D680 | Plugin session scope: `.all` grants and message-level writes | **`pi.session` gains `session.read.all`, `session.update.all`, and `session.delete.all` grants plus message-level writes, enforced per scope with audits.** | Ownership-only scope could not express reading user sessions. See ADR 0340, ADR 0200. |+| D370 | Local MCP control plane for desktop operations | *(amended by D372)* **An opt-in loopback MCP server inside Electron Main authenticates with a bearer token and delegates to the same registered IPC handlers, requiring confirmation for dangerous operations.** | External agents need control without duplicating permission logic. See ADR 0203. |+| D372 | Tightened local MCP control-plane boundary | **Amend D370 / ADR 0203: the first catalog is the project, session, Agent, and workspace flow plus reviewed reads, with stripped secrets, asserted loopback, and bounded results.** | The first catalog exposed secret writes without confirmation. See ADR 0203. |+| D377 | Plugin desktop control requires native user consent | **A `dangerous` `pi.desktop.invoke` operation needs the plugin's `confirm` flag and the user's answer to a host-owned native dialog showing a bounded preview.** | Caller-set confirmation let plugins act with no human. See ADR 0208. |## P. Transcript storage decisions| ID | Topic | Decision | Rationale ||---|---|---|---|| D119 | Transcript file store; SQLite index-only | **Schema v7: message content moves out of SQLite into per-session JSONL files under `~/.pi-desktop/sessions/` — `<id>.jsonl` (a session-header line, then one canonical block-array message line per message, RFC3339 stamps) plus an append-only `<id>.revisions.jsonl` for regenerate branches. `messages` drops `content_json`/`meta_json` and becomes a pure index (ordering, promoted filter columns, extracted `text` feeding FTS); `message_revisions` swaps `messages_json` for `message_count`, with `is_active` tracked in the DB only. Writes are file-first then index transaction; reads skip unknown/torn lines and dedupe repeated message ids keep-last; full rewrites are temp-file + atomic rename; session files are deleted only with their session and never age/orphan-swept. Opening a pre-v7 database archives it as `pi.sqlite.v6.bak` and bootstraps fresh — an explicit breaking reset, with all v1–v6 migration code removed. RPC wire format is unchanged, so Electron/renderer/importers need no changes.** | The database grew without bound carrying tool args/results and thinking payloads; codex/claude-code-style per-session files keep transcripts human-readable, greppable, and portable while SQLite stays a small, fast index (list, search, badges). A dev-phase breaking reset was chosen over migration machinery. |-| D122 | Independent conversation session fork | **Protocol v5 adds host-owned `session.fork`: an idle source's complete active canonical transcript is copied into a new independent session with remapped message/tool-call ids and inherited project/provider/model/mode/thinking/permission configuration.** | See ADR 0023. |+| D122 | Independent conversation session fork | **Protocol v5 adds host-owned `session.fork`, copying the active transcript into a new independent session with remapped ids and inherited configuration, without runtime or lineage state.** | Host-owned snapshot keeps persistence consistent across forks. See ADR 0023. || D134 | Assistant response fork and reversible edit | *(edit clause superseded by D137)* **The completed-assistant toolbar exposes Copy, Fork, Edit, and Regenerate but no Delete. Fork calls the existing host-owned `session.fork` with optional `throughMessageId`, producing an independent session whose canonical transcript ends at that response. Edit uses the same isolated child, replaces only the selected assistant text there, and stores original/edited tails as a two-entry D109 revision family so the existing pager can restore either. Both require an idle source, remap message/tool-call ids, and never share the source session id, runtime, transcript, revisions, or provider cache state.** | Response-level divergence and correction should remain reversible without mutating the source or letting an edited history reuse cached runtime state built from different assistant content. |-| D199 | Regenerate branch archived under the host RPC lock | **`session.saveActiveRevision` performs the read, the branch archive, and the `revisionCount` / `activeRevision` stamp in one host call under the state lock, replacing Electron main's `session.get` + `session.replaceMessages` read-modify-write.** | See ADR 0060, ADR 0041. |+| D199 | Regenerate branch archived under the host RPC lock | **`session.saveActiveRevision` reads, archives the branch, and stamps revision counters in one host call under the state lock, after draining the outbox.** | Async index writes lost the turn's final message. See ADR 0060, ADR 0041. |## Q. Still deferred+1. Exact marketplace domain / provider IDs2. Private marketplace auth mechanism3. Signature key distribution operational details@@ -460,7 +464,7 @@ section mirrors only marketplace/catalog items still blocking nothing.|---|---|---|---|| D143 | Settings directory rail icons | **The five settings destinations use fixed Lucide glyphs: Basics=`SlidersHorizontal`, Model configuration=`Bot`, Import=`Download`, Project archive=`Archive`, Info=`Info`. Refresh/rotate glyphs are not used on this rail.** | Prior mapping reused Settings/RefreshCcw/RotateCw, which read as generic gear/reload rather than the destination semantics; monochrome Lucide keeps the compact directory scannable. || D166 | Settings directory split into AI and Shortcuts destinations | **The Settings rail grows from five to seven destinations in order: Basics (`SlidersHorizontal`), 全局 AI/AI (`Sparkles`, new), Shortcuts (`Keyboard`, new), Model configuration (`Bot`), Import (`Download`), Project archive (`Archive`), Info (`Info`). Permissions and Context management move from Basics to the new AI destination; Keyboard shortcuts moves from Basics to the new Shortcuts destination; Developer moves from Basics to Info. Basics keeps only Appearance and Defaults. This supersedes the five-destination count/order of D133 and the five-icon set of D143 (adding `Sparkles` and `Keyboard`) without changing any setting's semantics, the full-page shell, or rail metrics.** | Basics accumulated six unrelated cards, burying global AI behavior (permission mode, context compaction) and shortcut configuration alongside look-and-feel; splitting them gives each concern a scannable home while keeping provider/connection config separate in Model configuration. |-| D684 | One settings destination owns one subject | **Amend D143 / D166 / D678 and see ADR 0345: the Settings directory is fifteen destinations in order — Appearance (`Palette`), Conversation (`MessageSquare`), Shortcuts (`Keyboard`), Voice (`Mic`), Behavior (`SlidersHorizontal`), Models (`Bot`), Instructions (`FileText`), Skills (`BookOpen`), MCP (`Server`), Subagents (`Sparkles`), Projects (`Archive`), System …** | See ADR 0345. |+| D684 | One settings destination owns one subject | **Amend D143 / D166 / D678: the Settings rail is fifteen single-subject destinations in four clusters, retiring `general` and `ai` into Appearance, Conversation, Behavior, and System.** | Two destinations had become mixed landing places. See ADR 0345. || D685 | Composer model picker: text rail and segmented reasoning | **Amend D458: the reasoning control in the combined Composer model menu is a segmented track with a raised pill under the selected level, placed in the menu footer, instead of a rail with track dots. The native range input, its column geometry, latest-wins commits and keyboard ownership are unchanged. The model list uses a text-only source rail with one sliding marker; Escape clears a typed search before closing the menu. Renderer only. See `04-ux/08-component-spec.md` and E2E-050.** | The dot rail and colored source tiles read heavy next to compact model rows; a segmented pill and a text rail match the rest of the menu chrome. |## R. Decision rules going forward@@ -473,21 +477,21 @@ section mirrors only marketplace/catalog items still blocking nothing.| ID | Topic | Decision | Rationale ||---|---|---|---|-| D123 | Composer slash commands, three sources | **Typing `/` at position 0 of the composer opens an inline command menu merging (a) pi prompt templates from `<workspace>/.pi/prompts/*.md` and `~/.pi/agent/prompts/*.md` (project overrides user-global on name conflict; frontmatter `description`/`argument-hint`), (b) builtin palette commands through slash aliases defined in one registry shared with palette search …** | See ADR 0024. |-| D124 | `@` file references are plain-text light references | **`@` at a token boundary opens a fuzzy file menu over a workspace index served by the new Electron-only channel `pi-desktop/fs/index` (files+dirs, `git ls-files -co --exclude-standard` fast path with ignore-set walk fallback, 8000-entry cap with truncation flag, short TTL cache, workspace-rooted, fails soft without a workspace).** | See ADR 0019. |+| D123 | Composer slash commands, three sources | **Typing `/` opens one command menu for pi prompt templates, builtin palette commands, and plugin commands, expanding templates in Electron main before persistence.** | Keeps pi argument semantics and template assets. See ADR 0024. |+| D124 | `@` file references are plain-text light references | **`@` opens a fuzzy workspace file menu and inserts a canonical `@rel/path` plain-text reference that the model follows with Read.** | Matches pi CLI semantics without context inflation. See ADR 0019. || D125 | Composer autocomplete interaction and IME contract | **One menu component anchored above the composer, full composer width, focus always stays in the textarea. Keys while open: ↑/↓ cycle with wraparound, Enter/Tab accept, Escape closes only the menu (takes precedence over the composer's clear/blur Escape), typing filters live; Enter never sends while an item is highlighted, and an empty result list counts as closed. The menu closes on outside mousedown, blur, deleting past the trigger character, or session switch. All key handling and trigger detection sit behind the IME guard (`isComposing || keyCode === 229` plus composition start/end tracking): during composition nothing triggers, updates, or intercepts, and state is re-evaluated on compositionend.** | First explicit IME rule in the spec — zh-CN Enter-to-send plus candidate confirmation must never fight the menu; uniform insert-then-dispatch keeps two-Enter flows fast and predictable. || D632 | Composer input history recall with ArrowUp/ArrowDown | **Amend D125 / D209 / D301: the accepted submissions of one conversation — a normal or steering prompt and a dispatched slash, extension, or mode command — are recorded newest-first in renderer-local `localStorage` (`pi.desktop.composerInputHistory`, one bounded bucket per conversation held newest-written-first, 100 entries per conversation, 20 conversations, consecutive duplicates collapsed) with the draft text and its file-reference snapshot, and recalling shows only that conversation's prompts. With the autocomplete menu closed and the draft empty (no text and no references), ArrowUp loads the newest entry and further ArrowUp walks older entries to the oldest; ArrowDown walks newer entries and past the newest returns to the empty draft. While browsing, both keys keep driving history even for a multi-line entry; any user input event, a submission, or a draft-key (session) change ends browsing, after which arrows are native again. IME composition and an open autocomplete menu keep priority over history. Because an entry is always recalled in the conversation that sent it, its file and image references are restored with its text, and no cross-conversation notice or i18n string exists. The caret moves to the end of the recalled text; the empty home composer (no conversation) recalls nothing, and a prompt sent from home is recorded in the conversation that submission materialized. Storage is best-effort: a missing, blocked, or corrupted store reads as empty and never breaks sending. No protocol, host, storage-schema, permission, theme, or packaging change. See `04-ux/09-interaction-patterns.md` and E2E-COMPOSER-input-history-recall.** | Retyping or re-copying a previous instruction is the most repeated composer action, and the app already keeps renderer-local MRU history for the plugin launcher (D219). Scoping the history to the conversation keeps a recalled draft's context intact and makes attachment restoration unconditional, because attachments live in that conversation's own scratch directory. |-| D633 | Completed turn-process disclosures fold by default | **Amend ADR turn-process-and-thinking-display: Detailed opens the whole-process disclosure while a turn is active; on settlement, untouched process details start closed and explicit user choices remain authoritative.** | See ADR turn-process-and-thinking-display. |+| D633 | Completed turn-process disclosures fold by default | **Amend ADR turn-process-and-thinking-display: Detailed opens the whole process while a turn runs, and untouched details start folded once it settles.** | The completed process stayed open by default. See ADR turn-process-and-thinking-display. || D197 | Composer clipboard files become session-scratch references | **When the composer clipboard contains one or more OS files/images, the renderer intercepts the file paste, transfers bounded bytes plus name/MIME metadata through the Electron-only `pi-desktop/composer/pasteFiles` channel, and includes the durable session id. Electron main verifies the session, sanitizes names, and writes unique files below `<data_dir>/scratch/<sessionId>/pasted/`; D209 amends the draft presentation while preserving each returned absolute path as the quoted-or-unquoted `@` reference sent to the agent. Text-only paste remains native. A home composer creates or reuses a durable session first. Clipboard bytes never enter the prompt, workspace, or artifact store, and session deletion removes the pasted files with the scratch root.** | Fixes the broken file/image paste path without dirtying the project or inventing provider-specific binary prompt plumbing; it reuses the existing scratch containment and lifecycle contract. |-| D209 | Composer file references separate compact display from canonical prompt paths | **Completed workspace-file selections and materialized clipboard files become renderer-owned, session-scoped reference chips.** | See ADR 0070. |+| D209 | Composer file references separate compact display from canonical prompt paths | **Completed file and pasted references become session-scoped chips showing only the leaf name, serialized to canonical paths just before submit, with unanswered-send undo intact.** *(amended by D362: chips are inline sentinel-backed elements in the contenteditable draft)* | Chips keep the prompt readable; paths stay exact. See ADR 0070. || D362 | Accepted `@` files insert the same inline chip as paste | **Amend D209 / D125 in the renderer: accepting a completed workspace file from the `@` menu (Enter, Tab, or click) replaces the trigger token with one private-use sentinel in the draft and stores that token on the reference, the same path clipboard paste already uses. The chip paints at the caret; that confirmation never sends. Directories still insert `@dir/` as text. Token-less references are not a visible draft surface. Workspace-relative chips still drop on project switch; absolute scratch/paste paths stay. No IPC, storage, host-protocol, or schema change.** | After chips moved inline, file accept still stripped `@query` and stored a token-less reference that no longer painted, so Enter made the file vanish. |-| D333 | Work-panel browser is the bundled `pi.browser` plugin | **The work-panel Browser launcher, chrome, and agent CDP ship as bundled plugin `pi.browser` (enabled by default, disableable, not uninstallable).** | See ADR 0170. |-| D211 | Global plugin launcher | **A customizable `openPluginLauncher` shortcut defaults to Option+Space on macOS and Alt+Space on Windows/Linux.** | See ADR 0072, ADR 0076, ADR 0080. |-| D212 | Running composers stage next-turn configuration and stopped turns preserve throughput | **During an active turn, draft text and mode/thinking/permission selectors remain editable.** | See ADR 0073. |-| D215 | Windows-reserved global shortcut fallback | **On Windows, host-core installs a narrow `WH_KEYBOARD_LL` hook for the effective `Alt+Space` default binding because the shell may reserve it from Electron's `globalShortcut`.** | See ADR 0076. |-| D217 | Early plugin launcher warm-up | **As soon as Electron is ready, before backend/plugin boot completes, Electron starts creating and loading the retained plugin launcher while it remains hidden.** | See ADR 0080. |+| D333 | Work-panel browser is the bundled `pi.browser` plugin | **The work-panel Browser and agent CDP ship as the bundled `pi.browser` plugin, while the guest view and debugger stay host-owned behind gated APIs and an allowlist.** | The browser should be optional like Files. See ADR 0170. |+| D211 | Global plugin launcher | **A customizable global shortcut opens one prewarmed frameless launcher listing enabled panel plugins, with pinyin-aware matching and a Windows low-level hook fallback.** | Panel plugins need a keyboard-first entry while unfocused. See ADR 0072, ADR 0076, ADR 0080. |+| D212 | Running composers stage next-turn configuration and stopped turns preserve throughput | **During a running turn the composer queues the next prompt while the in-flight runtime stays pinned, and stopped answers record measured or estimated throughput.** | Staging must not mutate running configuration. See ADR 0073. |+| D215 | Windows-reserved global shortcut fallback | **On Windows, host-core installs a narrow low-level hook for the reserved `Alt+Space` default and emits only that binding's event.** | The shell reserved the shipped launcher chord. See ADR 0076. |+| D217 | Early plugin launcher warm-up | **Electron begins building the retained launcher window as soon as it is ready, sharing one in-flight promise so early shortcuts join that load.** | Overlapping startup removes first-invocation stutter. See ADR 0080. || D219 | Plugin launcher most-recently-used history | **The launcher renderer records each successfully opened plugin id with a timestamp in renderer-local `localStorage` (key `pi.desktop.pluginLaunchHistory`, capped at 24) and presents an empty query in most-recently-used order. A typed query ranks search relevance first and uses recency only as a tiebreaker, so unused plugins sort after the recent ones by name. Corrupted or unavailable storage degrades to the existing name order without breaking launching. This refines D211's presentation without changing IPC, host RPC, permissions, protocol v9, or storage schema v11.** | Keyboard-first launcher users reopen the same plugins repeatedly; remembering the last-used order keeps the most frequent target one Enter away while relevance stays authoritative once the user types. |-| D221 | Renderer output size controls | *(bundled CJK clause superseded by D598)* **The renderer build sets `minify: "esbuild"` explicitly because `electron-vite` hard-defaults its renderer preset to `minify: false`.** | See ADR 0083. |+| D221 | Renderer output size controls | *(bundled CJK clause superseded by D598)* **The renderer build minifies explicitly, drops legacy font sources, and imports 192px brand marks refining D079/D094, with tests asserting all three.** | Output fell from 31 MiB to 24 MiB. See ADR 0083. || D198 | Goal mode is the second contract mode | **Goal is a third durable operating mode (`agent` / `plan` / `goal`) that reuses the Plan approval pipeline end to end. `EnterGoalMode` switches an active Agent turn into the Goal contract state; `SubmitGoal(title, markdown, question)` writes an immutable host-owned `.pi/goal/<unique-name>.md` artifact and inserts one pending `plan_approvals` row. The single approval table gains a `kind` column (`plan` or `goal`, defaulting to `plan`) in schema v11; the kind — not the projected planning state — selects the prompt, artifact directory, submit tool, and i18n namespace, so one approval bar and one execution queue serve both. Plan and Goal are together the contract modes: they share one tool allowlist (Read/Glob/Grep/BrowserPreview/Bash plus their own submit tool), one host hard deny for Write/Edit/plugin/unknown tools evaluated against the durable mode, the shared `*_IN_PLAN` error codes, and the `PLAN_REQUIRES_INTERACTIVE_SESSION` rejection of unattended runs. An approved Goal executes autonomously in Agent: it chooses its own approach and keeps working until every acceptance criterion is verified or a boundary blocks it, then reports criterion by criterion. The wire `kind` is optional and absent means `plan`, so this is additive inside protocol v9.** | Plan answers "carry out these steps"; users also need "reach this outcome, decide the steps yourself" (Claude Code's plan mode and Codex's goal-shaped runs). Making the goal statement, acceptance criteria, and boundaries an approved contract keeps autonomy auditable, and discriminating one pipeline by kind avoids a parallel table, approval surface, and permission boundary that would inevitably drift. || D144 | Sidebar primary chrome at 14px | **Expanded sidebar primary chrome (New task, Plugins, session titles, footer identity name, profile menu actions) uses `--text-base` (14px). Project/group titles and empty-state copy use `--text-md` (13px). Section labels use `--text-sm` (12px). Primary sidebar content must not use the micro `--text-xs` band.** | 13px sidebar body felt undersized next to the 14px chat surface; bumping only primary chrome keeps density while restoring visual balance without a global type-scale change. || D145 | Disable browser text correction on editable fields | **Every text `input` and `textarea` in the desktop renderer disables browser text correction: `spellCheck={false}`, `autoCorrect="off"`, and `autoCapitalize="off"`. Shared `Input`/`Textarea` primitives default these values; raw fields (composer, message edit, command palette, global search, settings/plugins/projects search, model search, browser URL bar, provider model combo) set them explicitly. Checkboxes and non-text controls are unchanged.** | Coding prompts, paths, model ids, and URLs must not be red-underlined or auto-mutated by Chromium/OS text correction; the shell is an application, not a document editor. |@@ -501,25 +505,26 @@ section mirrors only marketplace/catalog items still blocking nothing.| D264 | Composer typing avoids full sorts and redundant DOM writes | **The `@` file menu picks its visible rows with a bounded top-K selection over the match list instead of sorting every match; the selection returns exactly the row set and order a full sort produced, and the small, kind-grouped command list keeps its full sort. Composer auto-resize and `--composer-dock-height` publication are idempotent: an unchanged height performs no DOM write and no document-wide style invalidation, and the `height: auto` measurement probe is taken only when the box may need to shrink. Growth through seven rows, internal scrolling past the seventh, and contraction on delete or submit are unchanged. Draft file-reference state and the cursor keep their identity and value when a keystroke changes neither, so the draft-cache serialization effect and autocomplete trigger detection stop re-running per keystroke. No IPC, storage, host-protocol, or schema change.** | With a large workspace and the `@` menu open, every keystroke paid a full sort over the whole 8000-entry file index to show 50 rows, plus a forced synchronous reflow from the measurement probe, while a fresh `fileReferences` array identity per keystroke re-ran the draft-cache serialization effect. The cost was typing latency, not correctness; ordering equivalence with the full sort is covered by unit tests. || D660 | Composer file menu rows always show the full relative path | **Amend the `@` file-completion row presentation of D124 (specs `04-ux/08-component-spec.md` §11.8, `04-ux/09-interaction-patterns.md` §8a.1, E2E-102a): every row renders the leaf name — directories keep the trailing `/` — followed by the entry's complete workspace-relative path in a de-emphasized mono span that carries the raw `entry.path` without a trailing slash. The span takes the row's remaining width and ellipsizes before the leaf name can, and no row overflows the menu. The tooltip keeps the complete relative path and the accessible name becomes the path alone, because the visible row already includes the leaf name. D209/D362 chip rendering, completion, insertion, and serialization are unchanged; no earlier decision owned the old leaf-only row wording, so no entry is marked amended.** | Duplicate leaf names in different directories were indistinguishable until hover, and the relative location — often the actual intent of an `@` reference — was invisible in the persistent row. |+## T. Release delivery decisions| ID | Topic | Decision | Rationale ||---|---|---|---|| D126 | Three-platform release delivery (lifts D010) | *(amended by D364 / D603)* **Tag builds publish every artifact the matrix produces to the GitHub Release: macOS dmg/zip (arm64), Windows NSIS x64, Linux AppImage + deb (x64), each with blockmaps and the platform's `latest*.yml` electron-updater feed. Publishing the feeds activates D120's in-app update lanes for Windows NSIS and Linux AppImage; macOS stays in notify-and-link mode until a signed channel is qualified. The NSIS artifact name is pinned space-free (`PI-Desktop-Setup-${version}.${ext}`) because GitHub asset URLs mangle spaces. D010's macOS-only scope is lifted per the baseline-bump rule (baseline `0.4.7`); the release pipeline itself was qualified end-to-end on v0.1.1-rc.1/v0.1.1.** | The pipeline builds and validates all three platforms on every tag anyway; keeping installers as expiring Actions artifacts (90-day retention) withheld them from users without adding safety. Publishing the update feeds is the point of shipping: platforms with in-app lanes update silently, and future platform regressions surface through real installs instead of unused artifacts. |-| D364 | Windows portable exe without installer | *(superseded by D603)* **Amend D120 / D126 / ADR 0022: tag builds publish a Windows x64 portable exe `PI-Desktop-Portable-${version}.exe` alongside the NSIS installer `PI-Desktop-Setup-${version}.exe`.** | See ADR 0022, ADR 0197. |-| D603 | Windows portable delivery uses a normal ZIP | *(amended by D628)* **Amend D364 / ADR 0022 / ADR 0197: tag builds publish a Windows x64 portable ZIP `PI-Desktop-Portable-${version}.zip` alongside the NSIS installer `PI-Desktop-Setup-${version}.exe`.** | See ADR 0022, ADR 0197. |+| D364 | Windows portable exe without installer | *(superseded by D603)* **Amend D120 / D126 / ADR 0022: tag builds also publish a Windows portable executable that keeps notify-and-link updates and the existing data directory.** | Some environments whitelist only a single executable. See ADR 0197. |+| D603 | Windows portable delivery uses a normal ZIP | *(amended by D628)* **Amend D364 / ADR 0197: the portable target becomes a user-extracted ZIP kept out of `latest.yml`, launched directly as `PI-Desktop.exe` with notify-and-link updates.** | The self-extracting wrapper triggered administrator prompts. See ADR 0197. || D260 | Release documentation is a version surface | **A stable version bump must update every version-bearing surface before the tag: the shipped-locale in-app changelog and its test list, every workspace `package.json` including `docs/package.json` (a third workspace root `scripts/release.mjs` previously skipped), the Cargo workspace version and `host-core` lockfile entry, `APP_VERSION`, and the `<major>.<minor>.x` release line stated in `README.md` and `README.zh-CN.md`. `scripts/check-release-docs.mjs` verifies all of them; `scripts/release.mjs` runs it after bumping and refuses to commit or tag while any surface disagrees, with `--skip-docs-check` reserved for deliberate non-release bumps. Extends D164.** | The in-app changelog gate alone left published documentation behind: the READMEs still advertised the `0.5.x` line at `0.10.8`, and `docs/package.json` sat at `0.5.8`. A tag is irreversible, so the check runs before the tag exists rather than as review etiquette. |-| D371 | Explicit unsigned macOS first-launch helper | *(amended by D406, D443, and D634)* **Every macOS distribution used to ship an executable `PI-Desktop-macOS-open.command`; that helper is no longer distributed.** | See ADR 0204, ADR 0309. |-| D443 | Canonical application ID and macOS codesign identifier | **Amend D141 / D371 / ADR 0204: the application ID is `net.aiuo.pi-desktop` (`APP_ID`, electron-builder `appId`, macOS `CFBundleIdentifier`, Windows AppUserModelID).** | See ADR 0204, ADR 0278. |+| D371 | Explicit unsigned macOS first-launch helper | *(amended by D406, D443, and D634)* **Every macOS distribution no longer ships the executable `PI-Desktop-macOS-open.command` helper, so quarantine guidance lives only in the documentation.** | Quarantine blocked unsigned builds with misleading errors. See ADR 0204, ADR 0309. |+| D443 | Canonical application ID and macOS codesign identifier | **Amend D141 / D371 / ADR 0204: the application ID is `net.aiuo.pi-desktop`, with a `.dev` variant for development, and no adhoc signing of the unsigned pack.** | The owner domain binds the application identity. See ADR 0278, ADR 0204. |## V. Extension activation decisions| ID | Topic | Decision | Rationale ||---|---|---|---|-| D192 | Activation scope shared by every extension kind | **Plugins, user MCP servers and user skills each carry `enabled: boolean` plus `scope: { mode: "global" \| "projects"; projects: string[] }`.** | See ADR 0056. |-| D193 | User-owned MCP servers need no plugin | **host-core stores one JSON configuration file per MCP id under `~/.agents/servers` or `<project>/.agents/servers`; enablement and project overrides live only in `<data>/agent-capabilities/mcp.json`.** | See ADR 0112. |-| D194 | User-owned skills are Markdown documents in `.agents` roots | **host-core scans `~/.agents/skills` and `<project>/.agents/skills`, accepts direct Markdown files and `<skill>/SKILL.md`, and exposes frontmatter `name`/`description` through level-aware `skills.list` and `skills.active`.** | See ADR 0112. |-| D257 | Capability pages are one workbench that can author | **Refine D193 / D194 and supersede D202's page shape: Settings > Agent > Skills / MCP / Subagents each render one toolbar (level filter as a segmented control with live counts, one search field, project picker, primary actions) above one elevated panel whose rows are divided by level group headers and carry their own level badge.** | See ADR 0126. |+| D192 | Activation scope shared by every extension kind | **Plugins, MCP servers, and skills each carry `enabled` plus a global or project scope, matched case-insensitively and enforced at catalog assembly and dispatch.** | One boolean made every extension global. See ADR 0056. |+| D193 | User-owned MCP servers need no plugin | **MCP servers live as one JSON file per id under `.agents` roots, with enablement and project overrides kept in app-local state.** | Servers are configuration, not plugin packages. See ADR 0112. |+| D194 | User-owned skills are Markdown documents in `.agents` roots | **host-core scans `.agents/skills` roots for Markdown documents or `<skill>/SKILL.md`, exposing them through level-aware list calls with enablement kept outside the file.** | Skills stay portable documents; activation stays app-local. See ADR 0112. |+| D257 | Capability pages are one workbench that can author | **Refine D193 / D194 and supersede D202's shape: Skills, MCP, and Subagents render one toolbar over one panel and can create, edit, and delete.** | Pages listed capabilities without managing them. See ADR 0126. |## 2026-07-28 — Plugin marketplace, panels, and high-risk APIs@@ -667,7 +672,14 @@ section mirrors only marketplace/catalog items still blocking nothing.## 2026-07-28 — Independent window and work-panel resizing-Native window edges now resize only the Electron shell; work-panel open, collapse, close, and divider commits leave outer bounds unchanged. Related decisions: D156. See ADR 0029.+- Native window edges resize only the Electron shell, so work-panel open,+ collapse, close, and divider commits leave the outer bounds untouched.+- The divider uses anchored pointer deltas, a frame-coalesced preview,+ cancellation rollback, and a wider hit area; responsive clamping no longer+ overwrites the persisted preferred width.+- The renderer-to-Main `window/resizeBy` channel, programmatic resize+ attribution, and panel-specific window-state offset are removed.+- Decision D156. See ADR 0029.## 2026-07-28 — Single assistant toolbar per user turn@@ -681,7 +693,15 @@ Native window edges now resize only the Electron shell; work-panel open, collaps## 2026-07-28 — Turn-boundary context checkpoint compaction-PI-Desktop now evaluates context after every `turn_end`, before the next provider request, with a transient soft reminder and a deterministic hard checkpoint guard. Related decisions: D158. See ADR 0030.+- PI-Desktop evaluates context after every `turn_end`, before the next provider+ request, with a transient soft reminder and a deterministic hard checkpoint+ guard.+- Durable checkpoint records rebuild model context without deleting or hiding+ visible transcript messages, and an exact provider overflow receives one+ compacted retry.+- pi-agent-core primitives are reused; OpenCode DCP stays an AGPL-3.0+ behavioral reference only, neither linked nor copied.+- Decision D158. See ADR 0030.## 2026-07-28 — Sidebar typography aligned with the global body scale@@ -694,7 +714,12 @@ PI-Desktop now evaluates context after every `turn_end`, before the next provide## 2026-07-28 — Icon-free composer prompt row-Home and thread-docked composer prompt rows render no leading brand icon; draft text and placeholder ink align directly with the input gutter. Related decisions: D160. See ADR 0031.+- Home and thread-docked composer prompt rows render no leading brand icon, so+ draft text and placeholder ink align with the input gutter.+- The canonical logo stays in the home hero, sidebar, native application+ identity, startup splash, and About surfaces, while session-creation controls+ keep their message-plus icon.+- Decision D160. See ADR 0031.## 2026-07-28 — Smooth latest-wins session switching@@ -719,11 +744,28 @@ Home and thread-docked composer prompt rows render no leading brand icon; draft## 2026-07-29 — Native width reservation for the fixed work panel-The docked panel now keeps its committed `364..720px` width while open; native edges resize MainChat only. Related decisions: D163, D156. See ADR 0032, ADR 0033, ADR 0029.+- The docked panel keeps its committed `364..720px` width while open, and+ native edges resize MainChat only.+- Open, collapse, final close, and divider commit set one idempotent+ native-width target; chat stays stable when the work area reserves the full+ width and absorbs only the unavoidable shortfall otherwise.+- Maximized and fullscreen geometry waits for normal state, persisted base+ bounds exclude the reservation width and x shift, and background artifacts+ cannot change the visible target.+- Decision D163; ADR 0033 later superseded its window-expansion portion and+ the contrary parts of D156 and ADR 0029.++See ADR 0032 and ADR 0033.## 2026-07-29 — Dual-locale in-app product changelog-Ship EN + zh-CN product highlights in `packages/shared` and attach them to `UpdateState.releaseNotes` from Electron Main when an update is discovered. Related decisions: D164, D120. See ADR 0022.+- EN and zh-CN product highlights ship in `packages/shared` and attach to+ `UpdateState.releaseNotes` from Electron Main when an update is discovered.+- The update banner and Settings → Info surface a compact What's new list in+ the active product locale, with no new feed or IPC domain.+- Release tagging requires both locale catalogs to be updated before the tag+ build.+- Decision D164; extends D120. See ADR 0022.## 2026-07-29 — Release process: mandatory dual-locale changelog gate@@ -737,7 +779,15 @@ Ship EN + zh-CN product highlights in `packages/shared` and attach them to `Upda## 2026-07-29 — Bounded atomic tool batches in context checkpoints-Automatic compaction now bounds an oversized final parallel tool-result batch inside the checkpoint copy instead of repeatedly failing at the same transcript boundary. Related decisions: D158. See ADR 0030.+- Automatic compaction now bounds an oversized final parallel tool-result+ batch inside the checkpoint copy instead of failing repeatedly at the same+ transcript boundary.+- The retained copy keeps every call and result envelope, distributes text+ budget fairly with explicit head and tail truncation markers, omits duplicate+ provider-irrelevant details, and leaves original transcript rows complete.+- Decision D158; it amends ADR 0030's blocking policy for an indivisible batch.++See ADR 0030.## 2026-07-29 — Safe lazy Mermaid diagrams in assistant answers@@ -753,7 +803,17 @@ Automatic compaction now bounds an oversized final parallel tool-result batch in## 2026-07-31 — Slimmer default work-panel width-The docked work panel now opens at 280px instead of 420px, a third narrower, and its fixed clamp becomes `244..720px`. Related decisions: D154, D167, D163. See ADR 0033.+- The docked work panel opens at 280px instead of 420px, and its fixed clamp+ becomes `244..720px`.+- `WORK_PANEL_DEFAULT_WIDTH`, `WORK_PANEL_MIN_WIDTH` (renderer and Electron+ Main), and the `.work-panel` CSS floor stay in sync, and divider double-click+ restores the new default.+- D154's 364px floor was sized for a 44px activity rail beside 320px of content;+ the rail became a header switcher, so the floor scales with the default.+ Persisted wider widths remain valid and the 720px maximum is unchanged.+- Decision D167, superseding the D154/D163 width clamp and ADR 0033 §4.++See ADR 0033.## 2026-07-31 — Project archive presentation redesign (bands superseded by D267)@@ -823,17 +883,74 @@ The docked work panel now opens at 280px instead of 420px, a third narrower, and- Decision D170; the single-file layout assumed by `04-ux/07-ui-design-system.md`§Typography and `04-ux/08-component-spec.md` no longer holds.+## 2026-07-31 — Plugin skills activation and the plugin devkit-`contributes.skills` is activated. `PluginRuntime.getSkills()` reads each declared skill file at prompt time, only for plugins granted `agent.prompt.inject`, and only through the containment guard the gated `fs` APIs use. Related decisions: D171, D174. See ADR 0037, ADR 0039.+- `contributes.skills` is activated: the runtime reads each declared skill file+ at prompt time for plugins granted `agent.prompt.inject`, through the gated+ `fs` containment guard, and renders a `# Plugin skills` section capped at+ 16 KiB total and 8 KiB per skill, with its own budget rather than ADR 0037's+ 32 KiB instruction chain, ordered after built-in skills and before project+ instructions. Runtime reuse keys on a skills digest, so enabling, revoking, or+ editing retires the idle runtime. Closes roadmap gap R2.+- Plugin authoring ships as `@pi-desktop/plugin-devkit`, owning `scaffold` /+ `check` / `pack` over one implementation shared by the `pi-plugin` CLI, the+ `PluginScaffold` / `PluginCheck` / `PluginPack` agent tools, and the plugins+ page's New plugin from template action; `pack` writes store-only (method 0)+ `.piplug` entries because `extract_zip_bytes` accepts nothing else. Closes+ roadmap gap R3's template and `check`/`pack` items.+- A bundled plugin was rejected as the delivery vehicle because a plugin cannot+ produce a `.piplug` and scaffolding would need high-risk `fs.write.workspace`.+ The built-in `plugin-development` skill activates only for plugin workspaces,+ and development plugins hot reload on a debounced save, capped at 16, with a+ reload never allowed to widen the approved permission set. Closes roadmap gap+ R3's hot-reload item.+- Decision D171; D174 later replaced the prompt-injection half with a skills+ catalog plus a `Skill` tool, leaving the devkit, hot-reload, and+ workspace-gate clauses standing. See ADR 0039.## 2026-07-31 — Creating a plugin from a template opens the folder-Creating a plugin from a template now also opens the chosen folder as the active project (`workspace.set`, which registers the project and switches to chat), not just as a loaded development plugin. Related decisions: D172. See ADR 0039.-+- Creating a plugin from a template also opens the chosen folder as the active+ project (`workspace.set`), not just as a loaded development plugin, because+ development needs the sources inside the workspace the agent, the file panel,+ and the built-in `plugin-development` skill all read.+- Activation runs in the renderer through the existing `activateProject` action+ rather than the template IPC handler, so project state, the sidebar project+ list, and the navigation intent guard keep their single owner.+- The success toast distinguishes the two outcomes, and Load local plugin+ deliberately keeps its behavior because running someone else's plugin is not a+ reason to switch the user's project.+- Decision D172; no ADR — this completes the flow ADR 0039 describes.++See ADR 0039.## 2026-07-31 — Work panel header menu: tools first, no duplicated entries-The unified header menu lists the four tools (Review, Terminal, Browser, Files) first, in a fixed order, and only then — after a divider, and only when they exist — the resources the transcript opened. Related decisions: D173. See ADR 0033.+- The unified header menu lists the four tools (Review, Terminal, Browser,+ Files) first, in a fixed order, and only then — after a divider, and only when+ they exist — the resources the transcript opened. The previous layout listed+ every open tool twice: once in the resource switcher and again in the+ create-new section, which made "open" and "switch to" indistinguishable.+ Each tool row now carries its own open state and its own close control, so a+ single row is the whole affordance for that tool.+- Activating a tool that is already open activates its existing tab instead of+ replacing it with a fresh singleton, so the Browser keeps its URL. The header+ action cluster is pinned right (`margin-left: auto`) so the close/collapse+ controls no longer slide with the label length, and the trailing close slot in+ each row is always reserved so labels and open dots never shift.+- Menu rows own real DOM focus (WAI-ARIA menu pattern) rather than a roving+ highlight: the trigger's ArrowDown/ArrowUp opens on the active or last row,+ Arrow/Home/End walk rows only, Delete/Backspace closes the focused row while+ the menu stays open with focus on its neighbor, and Escape/Tab/selection+ return focus to the trigger. Only a session switch dismisses the menu+ implicitly — selecting a row closes it explicitly, so the previous+ active-tab-keyed auto-dismiss (which fired whenever a background artifact+ changed the active tab) is gone.+- Missing `panel.tabs.file` was the reason a bare Files tab showed a literal+ `file` label; the catalogs now carry it plus `panel.tools`, and the obsolete+ `panel.openTool` is removed.+- Decision D173; no ADR — presentation and input handling only, inside the+ existing work-panel architecture (ADR 0033).## 2026-07-31 — Plugin skills are model-invoked@@ -857,15 +974,23 @@ The unified header menu lists the four tools (Review, Terminal, Browser, Files)## 2026-09-11 — User-invoked Skills in the composer (D393)-D174's model-invoked catalog remains the Skill body-loading and security contract, but its rejection of a user-facing slash entry made active Skills difficult to discover for users who already knew the workflow they wanted. Related decisions: D174. See ADR 0219.+- Decision D393 / ADR 0219 adds active built-in, plugin, and user Skills as the final group of the composer `/` menu; selection inserts `/skill:<id>` while keeping the original id for send-time resolution.+- Electron main revalidates the current project scope and asks the model to call the local `Skill` tool, while D174's model-invoked catalog and body-loading security contract stand.+- The typed command remains the transcript chip, and no host protocol or durable schema changes.+See ADR 0219.## 2026-09-11 — Windows work-panel chrome keeps one resource action cluster (D394)-The open work-panel header now keeps one compact resource switcher. Related decisions: D154, D357. See ADR 0195.+- Decision D394 amends D154 / D357 / ADR 0195: the open work-panel header keeps one compact resource switcher, and resource close stays on the existing unified context-menu rows so a second `X` does not sit beside the Windows native close control.+- The viewport-fixed panel toggle remains the sole panel-level collapse control, subagent detail uses a back chevron, and Windows/Linux native controls stay fixed at the window edge.+- Renderer-only: no panel state, window geometry, IPC, protocol, or storage change.+See ADR 0220.## 2026-09-11 — Canonical thinking-level values in the UI (D395)-Thinking levels are stable protocol values, but translating them made the same provider/runtime setting vary with the application locale. Related decisions: D369. See ADR 0221, ADR 0202.+- Decision D395 / ADR 0221 amends D369 / ADR 0202: Composer, model configuration, and delegation surfaces render `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max` directly, because translating them made one provider setting vary with the application locale.+- Those values leave every locale catalog, while effective metadata, clamping, provider requests, protocol, and storage are unchanged.+See ADR 0221.## 2026-09-11 — Renderer and plugin-panel scrollbars share one compact contract (D396)@@ -884,15 +1009,26 @@ Thinking levels are stable protocol values, but translating them made the same p`04-ux/08-component-spec.md`, and E2E-157.## 2026-09-11 — Composer accepts native file and folder drops (D397)-Native file-system drops into the Composer now prevent the browser default and use one accent outline around the complete shell without changing its layout. See ADR 0101, ADR 0222.+- Native file-system drops into the Composer prevent the browser default, use one accent outline around the complete shell without changing its layout, and turn regular files into removable leaf-name chips through the bounded session-scratch paste bridge.+- The preload resolves each dropped `File` with Electron's `webUtils.getPathForFile`, and a folder's complete native path enters the caret as literal `@<path>/` text with mixed item order, surrounding draft, focus, and caret preserved; folders are never read, traversed, or copied.+- Decision D397 amends ADR 0101's previous drag/drop scope, and no host RPC, protocol, workspace, or durable-schema change is added.+See ADR 0222.## 2026-09-11 — Message quotes and renderer-owned side chats (D-LOCAL-message-quotes)-*(Retired by ADR 0268 on 2026-09-16: the feature and its surfaces were removed, and these IDs stay retired and must not be reused. See ADR 0268, ADR message-quotes-and-side-chats.+*(Retired by ADR 0268 on 2026-09-16: the feature and its surfaces were removed, and these IDs stay retired and must not be reused. The record is kept for history.)*++- Every user message and assistant turn gains a Quote action that inserts a `> `-prefixed Markdown blockquote plus a `chat.quoteSource` attribution line into the active session's composer draft, using the live selection when it lies inside the clicked row and the message's own text otherwise, capped at 2000 characters, and never sending.+- Open side chat forks the anchored message through the existing `session.fork` without activating the child, registers it as a renderer-owned side chat of the parent, and opens one `sidechat` tab streaming through the shared background-transcript reducer with Add to main chat, Open as a conversation, Send/Stop, and the permission card.+- Closing that tab or promoting the child to a conversation removes the registration and its projection; the durable child stays an ordinary session, and no protocol, storage-schema, IPC channel, or permission changes.+See ADR message-quotes-and-side-chats.## 2026-09-11 — Context usage display preference (D398)-The context usage inspector's leading figure — the trigger ring arc (`strokeDashoffset`), percentage, token label, popover heading, tooltip, and `aria-label` — is configurable via `AppSettings.contextUsageDisplay` (`"remaining"` or `"used"`). Related decisions: D347. See ADR 0184, ADR 0223.+- Decision D398 amends D347 / ADR 0184: `AppSettings.contextUsageDisplay` (`"remaining"` or `"used"`, defaulting to and falling back on `"remaining"`) selects whether the trigger ring arc, percentage, token label, popover heading, tooltip, and `aria-label` lead with remaining or used capacity.+- `"used"` fills the ring by `usedRatio` and shows the used-capacity pair, while the warning and critical thresholds stay computed from remaining capacity.+- Settings → AI → Defaults gains the Remaining / Used segmented control after Link open destination and before Enter-to-send.+See ADR 0223.## 2026-09-11 — Project groups can be manually reordered (D399)@@ -909,7 +1045,10 @@ The context usage inspector's leading figure — the trigger ring arc (`strokeDa## 2026-09-11 — Restore deferred tools from effective session context (D400)-A new prompt or mode switch clears the in-memory deferred activation set, then restores successful activation evidence from the effective session context. Related decisions: D185. See ADR 0048, ADR 0225.+- Decision D400 amends D185 / ADR 0048: a new prompt or mode switch clears the in-memory deferred activation set, then restores successful activation evidence from the effective session context, with `ToolSearch` rows contributing `addedToolNames` and successful deferred-tool rows their own tool name.+- Restoration keeps only names still in the current mode's deferred catalog; failed, interrupted, and missing-result placeholder rows are ignored, and assistant or user prose is never read as activation evidence.+- Host permissions, workspace containment, and audit behavior are unchanged.+See ADR 0225.## 2026-07-31 — Plugin themes ship CSS files@@ -932,43 +1071,77 @@ A new prompt or mode switch clears the in-memory deferred activation set, then r## 2026-07-31 — Plugin MCP servers over stdio and remote HTTP-`contributes.mcpServers` declares `{ id, label?, transport }` plus exactly one transport's fields: `stdio` takes `command` / `args` / `env`, `http` takes `url` / `headers`. Related decisions: D018, D176. See ADR 0038.+- `contributes.mcpServers` declares `{ id, label?, transport }` with exactly one transport's fields — `stdio` taking `command` / `args` / `env` under `mcp.server.local`, `http` taking `url` / `headers` under `mcp.server.remote` — and the main process speaks protocol `2025-06-18` as NDJSON over stdio or streamable HTTP/SSE with lazy connect and teardown on unload.+- Discovered tools register as `plugin_<pluginIdSafe>_<serverId>_<toolName>` in the existing plugin tool map, inheriting the audit trail, timeout, and disable switch, and they stay `risk: "medium"` because a third party's schema cannot be trusted to declare its own risk.+- `env` and `headers` resolve only from plugin settings via `{ "setting": "<key>" }`, the host environment is never passed through (D018), and `url` must be `https` unless the host is loopback.+- Decision D176 ships both transports, because a hosted endpoint is common enough that stdio-only would push plugins into a worse local shim.+See ADR 0038.## 2026-07-31 — Resident plugin services and their restart policy-`contributes.services` declares `{ id, label?, autoRestart? }` behind `background.service`, at most 4 per plugin. Related decisions: D177. See ADR 0040.+- Decision D177: `contributes.services` declares up to four `{ id, label?, autoRestart? }` entries behind `background.service`; the broker runs `start` after `onLoad` and `stop` before `onUnload` inside the plugin's own `utilityProcess`, so a service never outlives its plugin.+- A crash takes the service down with the process and the supervisor restarts the whole plugin with 1s/2s/4s/8s/16s backoff capped at 30s, five attempts, and a 60s healthy reset, while `autoRestart: false` opts out and the last attempt leaves the plugin visibly `failed`.+- Per-service state and restart count are read over `plugin/services`, rendered as chips, and audited as `plugin.service.*`; manual enable or disable outranks the supervisor by cancelling the timer and clearing the counter.+See ADR 0040.## 2026-07-31 — Inter-plugin message bus routes declared topics only-`pi.bus.publish` / `subscribe` require `bus.publish` / `bus.subscribe` and a matching entry in `contributes.bus`: publishers list concrete topics, subscribers list patterns. Related decisions: D178. See ADR 0040.+- Decision D178: `pi.bus.publish` / `subscribe` require both the permission and a matching `contributes.bus` entry, so a granted permission alone routes nothing and the manifest stays a complete description of what a plugin says and hears.+- Topics are dot-separated segments with `*` for one segment and trailing-only `**`; the broker excludes the publisher, delivers fire-and-forget over a one-way `{ t: "event" }` frame that also makes `pi.events.on` / `off` real, and caps payloads at 64KB, 16 subscriptions, and 100 publishes per rolling 10s.+- A payload conveys data and never capability, so a topic is public within the app.+See ADR 0040.## 2026-08-02 — Bash tool inherits the user's login-shell PATH-On Unix, the first Bash call probes the user's login shell for its PATH — `$SHELL` (fallback `/bin/zsh` → `/bin/bash` → `/bin/sh`) with `-lic 'printf %s "$PATH"'` — so `-l` sources login files and `-i` sources the interactive rc, matching a fresh terminal. Related decisions: D181. See ADR 0045.+- Decision D181: on Unix the first Bash call probes `$SHELL` (fallback `/bin/zsh` → `/bin/bash` → `/bin/sh`) with `-lic 'printf %s "$PATH"'`, bounded to 5s, cached per process, discarding stderr and keeping only the last stdout line, then injects that PATH into every Bash child.+- `bash -lc` still re-runs the bash profile at startup; agent commands remain POSIX bash, the resolved binary is unchanged, and Windows keeps `bash -c` with the host environment.+- This fixes Finder and Dock launches that could not see nvm, pnpm, or Homebrew tooling initialized in `~/.zshrc` / `~/.zprofile`.+See ADR 0045.## 2026-08-02 — Route process logs into category files-The `app`, `host`, and `agent` channels remain local NDJSON files, but each channel is now a directory containing focused `<category>.log` files. Related decisions: D182. See ADR 0046.+- Decision D182: the `app`, `host`, and `agent` channels stay local NDJSON but each becomes a directory of focused `<category>.log` files, and every record carries a `category`.+- Host and agent stderr is classified into the same categories with timing lines isolated in `timing.log`, buffered by line, decoded as UTF-8, and stripped of ANSI before persistence; unknown child output goes to `runtime.log`.+- Rotation stays 5 MB with two rotated files per category file, byte lengths count UTF-8, rotation and disk failures stay best effort, and existing flat log files are not deleted during migration.+See ADR 0046.## 2026-08-02 — Context usage inspector-Replace the oversized context ring with a compact Codex-style trigger that combines a remaining-capacity ring, `Context` label, and percentage. Related decisions: D225, D184. See ADR 0047.+- Replace the oversized context ring with a compact Codex-style trigger combining a remaining-capacity ring, `Context` label, and percentage, opening a non-modal panel *(superseded by D225: the trigger is click-toggled)* with the context window, exact provider input/output/cache/reasoning usage, aggregate generation speed in `tokens/s`, and each unique tool type in first-seen order.+- Tool rows aggregate repeated calls with call count, argument and result tokens, estimated footprint, share bar, and known duration, using pi-agent-core's four-characters-per-token heuristic while provider-reported usage stays authoritative and the rows stay labelled as estimates.+- The panel renders at document body level as a fixed, collision-aware viewport overlay that follows scroll and resize, and its window total comes from the same `pi-ai` model record the agent sidecar receives, with provider metadata and the 128K default as fallbacks.+- `UiMessage.responseDurationMs`, `UiMessage.toolUsage`, and the optional `toolUsage` field on `tool_end` are additive, so older persisted messages and peers remain readable.+See ADR 0047.## 2026-08-02 — Lazy per-turn tool activation-The sidecar keeps a complete local registry but sends only the mode's core tools and local `ToolSearch` on a new prompt. Related decisions: D200, D203, D185. See ADR 0048.+- The sidecar keeps a complete local registry but sends only the mode's core tools and local `ToolSearch` on a new prompt (`CompactContext` was always active here until D200 removed it, and D203 restored it as `new_context`).+- Agent follows pi's coding-agent core (`Read`/`Bash`/`Edit`/`Write`) while Chat keeps (`Read`/`Glob`/`Grep`); Agent-mode `Glob`/`Grep`, `BrowserPreview`, plugin tools, `Skill`, and plugin-development helpers ship as bounded catalog entries instead of full parameter schemas.+- An exact-name or capability search activates at most four matches for the next turn, `addedToolNames` lets providers with native deferred search serialize those definitions at the load point, and activation resets before the next prompt.+- Host permissions, workspace and scratch containment, timeouts, and audit behavior are unchanged, and persisted results keep their activation markers.+See ADR 0048.## 2026-08-04 — Bound provider stream recovery and diagnostics-Provider request setup now has one bounded pi-ai retry. Related decisions: D186. See ADR 0050.+- Provider request setup has one bounded pi-ai retry: a transient stream, network, or timeout failure after streaming begins gets one same-turn retry with a short abortable backoff, the failed assistant leaves model context, and the visible assistant id is reused.+- `terminated` and equivalent incomplete stream messages map to `STREAM_FAILED`, while a second failure stays terminal and carries bounded phase, timing, provider status/code, and retry-attempt diagnostics.+- Mutation recovery is finite: one unique local `Edit`, else a `Write` rewrite, then one fresh read or regeneration after a mismatch, with a second same-path `Edit` failure or a failed shell patch emitting the terminating hint.+See ADR 0050.## 2026-08-04 — Recover automatic compaction failures with a retained tail-Automatic threshold and provider-overflow compaction failures now attempt a deterministic, aggressively bounded retained-tail checkpoint before ending the turn. Related decisions: D158. See ADR 0030, ADR 0049.+- Automatic threshold and provider-overflow compaction failures now attempt a deterministic, aggressively bounded retained-tail checkpoint before the turn ends, keeping the previous summary when available and the visible transcript untouched, with host persistence and the hard-budget recheck still mandatory.+- The summary input is preflighted against the model window so an obviously oversized request goes straight to the bounded path instead of a provider rejection or timeout.+- The lifecycle event marks the recovery `fallback: "retained_tail"` so the renderer keeps the run active with a warning, while manual `/compact` stays fail-fast.+- Decision D158 amends ADR 0030 and adds ADR 0049.+See ADR 0049.## 2026-08-04 — Resource-isolated host RPC stdio-Host-core no longer uses Tokio's stdio adapters for its NDJSON control pipe. Related decisions: D187. See ADR 0051.+- Decision D187: host-core no longer uses Tokio's stdio adapters for its NDJSON control pipe: one named OS thread reads stdin and one named thread serializes stdout, keeping per-message framing and retrying interrupted or transient `EAGAIN`/`EWOULDBLOCK` errors.+- That closes the process-exit path where Tokio's blocking pool panicked after the OS refused another worker thread (errno 35 on macOS); a control thread that cannot start is a startup error rather than an unhandled panic.+- The login-shell PATH probe also uses `thread::Builder` and falls back to the inherited PATH.+See ADR 0051.## Plan checkpoint and shell decisions (0.4.14)@@ -984,11 +1157,14 @@ D193, and D194.| D188 | Replace Chat profile with Plan state | *(superseded by D189)* **PI-Desktop has one pi Agent and one product selector: `Agent | Plan`. Plan is that Agent after entering planning state, never a second Agent, planner model, planner service, or permission mode. Agent remains the default. Persisted sessions, app defaults, and scheduled values stored as `chat` migrate to `plan`; the internal `page = "chat"` route may remain as a conversation-surface detail. Plan exposes `Read`, `Glob`, `Grep`, `BrowserPreview`, `Bash`, `CompactContext`, and `ExitPlanMode`; it denies `Write`, `Edit`, plugin tools, and unknown tools. Plan retains permission-mode selection: Bash prompts under `ask` and `accept-edits`, and runs without confirmation under `auto`, so Plan is planning intent rather than a strict read-only security profile.** | Historical pre-checkpoint Plan contract; retained to explain the supersession chain || D189 | Plan checkpoint artifact, approval, and execution epoch | **The same pi Agent uses `Agent | Plan`, with Agent default. Plan calls `SubmitPlan(title, markdown, question)` as the only tool in its assistant batch. Rust host-core writes the submitted Markdown bytes unchanged to a new immutable unique file under `<workspaceRoot>/.pi/plan/*.md`; it stores the relative artifact path, SHA-256, and byte size together with structured title/question fields in the existing `plan_approvals` row. No title/question wrapper is added and no prior artifact is replaced. The approval surface displays title, question, an artifact opener, absolute expiry, and status, and offers only Approve or Reject. Approve requires an explicit `ask`, `accept-edits`, or `auto` permission mode, with Ask selected by default; Reject carries no mode. The approval expires at one absolute 30-minute deadline and uses `PLAN_APPROVAL_TIMEOUT`. The same `plan_approvals` row carries `execution_id` and `execution_state` through `queued → running → completed|interrupted`. A startup transaction marks prior pending approvals and queued/running execution states interrupted before serving RPC; no work is replayed. Pending interruption/rejection/expiry leaves the session Plan; an already-approved queued/running interruption leaves the session Agent. One active turn, idle-only configuration, and one pending approval/queued-or-running execution per session are enforced. Scheduled Plan is rejected before provider, artifact, or queue work with `PLAN_REQUIRES_INTERACTIVE_SESSION`. Protocol v9 and storage schema v10 carry the contract without a serialized process-epoch field.** | Immutable host artifacts preserve the submitted checkpoint while one approval/execution row and a startup process fence prevent restart replay without losing the already-approved Agent state || D190 | Selectable command shell catalog and execution identity | **Host-core exposes stable platform-aware catalog IDs: `windows-powershell`, `cmd`, `git-bash`, and `bash`; the platform catalog contains only IDs supported by that platform. `defaultCommandShell` persists in host settings, and settings writes reject unavailable or wrong-platform IDs. If a persisted choice later becomes unavailable, the effective shell intentionally falls back to the first available platform shell. The `Bash` tool and `tools.execute` protocol name remain unchanged; each turn pins the effective shell ID and dialect, and host rejects a stale ID/dialect before spawn with `COMMAND_SHELL_CHANGED`. Shell identity is the catalog selection, not an executable path hash. Bash streams stdout and stderr separately, uses a mandatory 60-second default timeout with a 1–300 second override, and cancellation/timeout shuts down the complete process tree.** | Users can choose the command language without multiplying protocol tools, while platform validation, explicit fallback, and turn-pinned catalog identity keep execution predictable |-| D604 | Trust the network endpoints the user enters themselves | **Amend ADR 0243 / 0245 / 0247 for user-supplied URLs; follow ADR 0142 / 0257 / 0300.** | See ADR 0243, ADR 0245, ADR 0247, ADR 0142, ADR 0257, ADR 0300, ADR 0304. |+| D604 | Trust the network endpoints the user enters themselves | **Amend ADR 0243 / 0245 / 0247: user-typed URLs reach private, link-local, and `.local` hosts over plain `http` under one `networkPolicy.mode` (`relaxed` by default); third-party content stays public-only.** | Typed endpoints were a user decision. See ADR 0304. |## 2026-08-05 — Agent-only mode-`agent` is the only session mode. The former `chat` profile is renamed `read-only`; host-core still hard-denies Write/Edit/Bash for it, but nothing in the UI can select, display, or command it. Related decisions: D191, D189, D188. See ADR 0055, ADR 0052, ADR 0053.+- `agent` is the only session mode: the former `chat` profile becomes `read-only`, still hard-denying Write/Edit/Bash in host-core but no longer selectable, displayable, or commandable in the UI.+- The gate is negative everywhere (`mode != "agent"` → read-only surface), `chat` normalizes to `read-only` on every host write path, `*_DISABLED_IN_CHAT` becomes `*_DISABLED_IN_READ_ONLY`, and database open rewrites stored `chat` values inside schema v7.+- Decision D191 is superseded by D189; the mode concept it removed returned as Plan (D188/D189, ADR 0052/0053), and the entry stays because the `read-only` normalization and the `chat` fix-up shipped.+See ADR 0055.## 2026-08-05 — Structured tool-result presentation in the transcript@@ -1068,29 +1244,33 @@ D193, and D194.## 2026-08-05 — MCP servers and skills the user owns, scoped per project-Plugins, user MCP servers and user skills now share one activation shape: `enabled` plus `{ mode: "global" | "projects", projects: [] }`. Related decisions: D174, D192, D193, D194. See ADR 0053.+- Plugins, user MCP servers, and user skills share one activation shape — `enabled` plus `{ mode: "global" | "projects", projects: [] }` — so switching something off keeps the narrowed project list and the `off` / `projects` / `global` control is derived rather than stored.+- Matching is case- and trailing-separator-insensitive, a scoped path covers its subdirectories, and scope is checked when the per-turn catalog is built and again at dispatch, because a visible tool is one the model will try to call; themes stay unscoped.+- Adding an MCP server is a paste through `parseMcpImport`, a failed handshake stays failed until the user edits it or presses Test, and a user skill is one `SKILL.md` under D174's untouched contract with the description above the body.+- Four tabs rather than one merged list, because plugin rows, MCP rows, and skill rows need a connection light, a byte counter, and a permissions matrix that one list would hide.+See ADR 0053.## 2026-08-05 — Permission-gated external paths and portable native search-Explicit `path` arguments for `Read`, `Glob`, `Grep`, `Write`, and `Edit` are classified against the durable session workspace and scratch roots before the normal risk matrix. Related decisions: D195. See ADR 0057.+- Explicit `path` arguments for `Read`, `Glob`, `Grep`, `Write`, and `Edit` are classified against the durable workspace and scratch roots before the risk matrix: `ask` and `accept-edits` emit the permission card with the path preview, `auto` executes, and denial, timeout, or cancellation return `TOOL_DENIED` without touching the path.+- The approved resolver re-canonicalizes the deepest existing ancestor at execution time so `..` and symlink escapes cannot skip the boundary, and the outside location is never promoted to a workspace root.+- The sidecar exposes the host's bounded search controls with the canonical `filesWithMatches` spelling and normalizes provider aliases, preferring native tools and portable workspace-relative paths over shell search.+- Decision D195 changes the host/runtime boundary.+See ADR 0057.## 2026-08-05 — Extensions page density and theme-readable actions-- The Extensions destination no longer renders the four-card numeric overview- band. Installed, MCP, Skills, and Marketplace remain separate tabs; tab- counts, installed state-group counts, and the pending-update alert retain- actionable state without duplicating it in a static summary row.-- Shared primary and secondary buttons use semantic accent, surface, text, and- border tokens. Primary actions invert the current theme surface; secondary- actions keep an opaque elevated surface and visible border in both themes.-- Decision D196 amends the presentation portion of D169 without changing- plugin, MCP, skill, marketplace, permission, or runtime contracts. See ADR- 0058, `04-ux/01-ui-ia.md`, `04-ux/07-ui-design-system.md`,- `07-plugins/07-plugin-marketplace.md`, and E2E-024N/E2E-060b.+- The Extensions destination drops the four-card numeric overview band while Installed, MCP, Skills, and Marketplace stay separate tabs, with tab counts, installed state-group counts, and the pending-update alert carrying the actionable state.+- Shared primary and secondary buttons use semantic accent, surface, text, and border tokens: primary actions invert the theme surface, and secondary actions keep an opaque elevated surface and a visible border in both themes.+- Decision D196 amends the presentation portion of D169 without touching plugin, MCP, skill, marketplace, permission, or runtime contracts.+See ADR 0058.## 2026-08-05 — Clipboard files become session-scratch references-The composer now distinguishes native text paste from a clipboard payload containing files or images. Related decisions: D197. See ADR 0059.+- The composer distinguishes native text paste from a clipboard payload carrying files or images, sending bytes to Electron main only once the renderer holds a durable session id and creating or reusing one on a home composer.+- Main validates the session and writes bounded, uniquely named files under `<data_dir>/scratch/<sessionId>/pasted/`, and the draft receives ordinary `@absolute/path` references with quoting for whitespace.+- Decision D197 and ADR 0059 define the new renderer/main boundary, keeping pasted material out of binary prompt content and off the project.+See ADR 0059.## 2026-08-06 — Goal mode joins Plan as a contract mode@@ -1122,23 +1302,41 @@ The composer now distinguishes native text paste from a clipboard payload contai## 2026-08-06 — The regenerate branch is archived under the host RPC lock-Turn completion used to archive the finished regenerate branch with a read-modify-write from Electron main: `session.get`, then `session.replaceMessages` to stamp `revisionCount` / `activeRevision` on the user root. Related decisions: D199. See ADR 0041, ADR 0060.+- Turn completion used to archive the regenerate branch from Electron main with `session.get` plus `session.replaceMessages`, so a snapshot could predate the turn's final message — assistant and tool rows reach SQLite through the persistence outbox (ADR 0041) — and the rewrite then deleted it along with every row's `turn_id`.+- `session.saveActiveRevision` now performs the read, the archive, and the user-root stamp in one host call under the state lock, re-reading the transcript at write time so a line appended meanwhile survives; main drains the outbox first and skips the archive with a warning otherwise.+- Decision D199 and ADR 0060 define this: `session.replaceMessages` carries each surviving message's `turn_id` across a rewrite and is documented as safe only for a caller that owns the whole transcript for the duration.+See ADR 0060.## 2026-08-06 — Context compaction becomes imperceptible-Compaction is host-driven and silent. The `CompactContext` tool, the `<context_management>` soft-boundary nudge, and the host no-confirmation allowlist entry are gone, so a long session never spends a model turn asking to be compacted and never grows a transcript row for it. Related decisions: D158, D200. See ADR 0049, ADR 0061, ADR 0030.+- Compaction is host-driven and silent: the `CompactContext` tool, the `<context_management>` soft-boundary nudge, and the host no-confirmation allowlist entry are gone, so a long session never spends a model turn asking to be compacted and never grows a transcript row.+- `contextBudget()` keeps D158's hard limit and headroom, derives the retained-tail target from the model window instead of settings, and adds a 70% background limit that also requires growth since the newest checkpoint's baseline.+- Generation and installation are separate: a checkpoint builds only in provider-idle windows and installs at the next turn boundary when its base, anchor, and budget still hold, and a failed background build is discarded with no event, no persistence, and no ADR 0049 fallback.+- `compaction_start`/`compaction_end` gain optional `phase` and `status { generation, summaryTokens }` inside protocol v9, a successful automatic compaction notifies nobody, and Settings exposes no compaction controls.+See ADR 0061.## 2026-08-06 — Context compaction is rebuilt to match Codex-The previous round cited Codex and then implemented its opposite on four counts. Related decisions: D200, D203, D158. See ADR 0064, ADR 0061, ADR 0030.+- Compaction is inline again: background pre-computation, its 70% limit, the increment-scoped trigger, and the three idle call sites are deleted, and `prepareNextTurn()` compacts when the context crosses `hardLimit` or the model called `new_context`, matching Codex's `should_roll_over`.+- A checkpoint carries the summary plus recent user messages, unfiltered so no message leaves model context uncovered, retained newest-first to 20,000 tokens with the crossing message truncated rather than dropped and assistant messages taking their tool calls so no orphaned call reaches a provider.+- Both Codex families ship — the summary path and a `fresh_window` rollover with a fixed marker — behind an internal switch (`PI_DESKTOP_COMPACTION_STRATEGY`) absent from settings and i18n, because no user can judge that trade-off from a settings row.+- `new_context` is parameterless, sits on the no-confirmation allowlist, and is never assignable to a subagent; two budget reminders ride the turn's system prompt, `compaction_end` carries `mark`, and every successful compaction raises one warning toast, while decision D203 / ADR 0064 amend D200 / ADR 0061 and restore D158 / ADR 0030's visibility property.+See ADR 0064.## 2026-08-06 — Bounded subagents behind a `Task` tool-A session can delegate one self-contained piece of work to a subagent and get back a single written report. Related decisions: D201. See ADR 0062.+- A session delegates one self-contained piece of work to a subagent and receives a single written report: four inline builtins (`explorer`, `code-reviewer`, `test-runner`, `fixer`) plus enabled global documents under `~/.agents/subagents/*.md`, re-read on every launch, capped at 16, with malformed documents degraded to launch diagnostics.+- A definition declares its own `tools` from a fixed list and is read-only when it declares none; a delegate never inherits mutation rights, cannot reach plugin, skill, mode, or meta tools, has no `Task` tool of its own, and may pin `model: <provider>/<model>` resolved once per launch, with an unresolvable pin failing the call instead of falling back.+- `Task` is offered in Agent mode only: an all-`Task` batch runs concurrently, capped at 4 slots with each delegate at its own `maxTurns` (default 24, maximum 80), and same-path `Write`/`Edit` calls serialize through a `PathMutex`.+- The parent gains only the bounded 12k-character report, while delegate rows persist with `parentToolCallId` / `agentName`, nest one level inside their `Task` row, stay out of the turn stream and minimap, and share one per-session permission queue.+See ADR 0062.## 2026-08-07 — Empty home uses direct bottom task entry-Empty chat home uses a direct bottom composer and keeps the hero and optional onboarding content in one scrollable region. Related decisions: D204. See ADR 0066.+- Empty chat home uses a direct bottom composer and keeps the hero and optional onboarding content in one scrollable region.+- The composer is a bottom-reserved sibling of that region, so it stays visible while checklist content scrolls independently on short windows.+- Decision D204 and ADR 0066 define the layout.+See ADR 0066.## 2026-08-07 — Empty home gains developer starter guidance (superseded)@@ -1163,48 +1361,75 @@ Empty chat home uses a direct bottom composer and keeps the hero and optional on## 2026-08-07 — Work panel gains a direct keyboard entry point-`Cmd/Ctrl + J` is a customizable renderer shortcut named `openWorkPanel`. Related decisions: D221, D207, D128, D142. See ADR 0068.+- `Cmd/Ctrl + J` is a customizable renderer shortcut named `openWorkPanel` that reveals the active session's retained work-panel context at the committed width without creating a resource tab. *(Open-only clause amended by D221: the shortcut also collapses the visible panel.)*+- No active session and the Settings page are no-op contexts, and the context menu remains the place to create Review, Terminal, Browser, or Files.+- Decision D207 supersedes D128's no-global-shortcut clause and amends D142's no-launcher presentation; artifact-driven resource creation, session ownership, background-event isolation, collapse behavior, and width persistence are unchanged.+See ADR 0068.## 2026-08-10 — Native path mistakes recover without false turn failure-- Read is file-only, Glob is directory-only, and Grep accepts a file or- directory; directory Read errors include structured Glob recovery args.-- Recovered tool errors remain visible on their own rows but no longer turn the- containing processing group into a terminal failure surface.-- D185's deferred Agent search tools remain unchanged. Decision D208 and ADR- 0069 define the compatible tool and transcript contracts.+- Read is file-only, Glob is directory-only, and Grep accepts a file or directory, with directory Read errors carrying structured Glob recovery args.+- Recovered tool errors stay visible on their own rows but no longer turn the containing processing group into a terminal failure surface.+- D185's deferred Agent search tools are unchanged; decision D208 and ADR 0069 define the compatible tool and transcript contracts.+See ADR 0069.## 2026-08-10 — Composer file references use compact draft chips-Completed workspace-file selections and pasted session-scratch files now live as renderer-owned, session-scoped references instead of exposing their canonical paths in the textarea. Related decisions: D209, D124, D197. See ADR 0070, ADR 0059.+- Completed workspace-file selections and pasted session-scratch files become renderer-owned, session-scoped references, and the composer shows only removable leaf-name chips with full paths available to tooltips and assistive technology.+- Immediately before the existing submit dispatcher, references serialize after the visible text with the unchanged quoted-or-unquoted `@path` grammar; reference-only sends, slash templates, and mode aliases keep their behavior, and a failed send retains text and references.+- An accepted send keeps only an in-memory, session/turn-scoped copy of its pre-serialization draft for unanswered smart Stop to restore; once reply content begins, abort preserves the partial transcript and restores nothing.+- Decision D209 and ADR 0070 amend the draft-presentation clauses of D124 / ADR 0024 and D197 / ADR 0059, leaving clipboard bytes, scratch containment, cleanup, host RPC, storage, and provider payloads unchanged.+See ADR 0070.## 2026-08-11 — Global corners use an Apple-inspired shape hierarchy-Fixed radii use a regular 4/6/8/10/12/14/16/18/20/24px ladder. Related decisions: D210, D072. See ADR 0071.+- Fixed radii follow a regular 4/6/8/10/12/14/16/18/20/24px ladder, with rounded rectangles for compact and medium desktop controls and pill or circle tokens reserved for semantic capsules, equal-width icon controls, switches, tracks, avatars, and dots.+- Nested surfaces use Apple's concentricity rule when their corners align — outer radius equals inner radius plus the inset between edges — and structural full-width shell panels stay square.+- The composer keeps its 20px visible radius through the shared scale, while experimental `corner-shape` waits because Electron 37's Chromium 138 does not support it.+- Decision D210 amends D072's pixel-preserving ladder without changing its token-only enforcement.+See ADR 0071.## 2026-08-11 — Global plugin launcher and uninterrupted next-turn preparation-Option+Space on macOS and Alt+Space on Windows/Linux opens a centered, frameless plugin launcher. Related decisions: D211, D212. See ADR 0072, ADR 0073.+- Option+Space on macOS and Alt+Space on Windows/Linux opens a centered, frameless plugin launcher that searches launchable panels by Chinese name, full pinyin, pinyin initials, normalized name/id, and description, then opens the highlighted result through the existing panel host.+- During an active answer the draft and the mode, thinking, and permission choices stay editable for the next turn while Send stays disabled, and the renderer flushes only the newest full choice once the host reports idle.+- A user-stopped partial response keeps its elapsed duration and exact provider output when present, falling back to a visibly approximate output count so throughput survives persistence and reload.+- Decisions D211/D212 and ADRs 0072/0073 define the native-window, IPC, in-flight configuration, and transcript metadata contracts.+See ADR 0072 and ADR 0073.## 2026-08-12 — Plugins can request and send native notifications-`pi.ui.notify` remains an in-app Toast for compatibility. Related decisions: D213, D117. See ADR 0074.+- `pi.ui.notify` stays an in-app toast, and plugins with the existing `notify` permission gain `getNotificationPermission`, `requestNotificationPermission`, and `showNativeNotification`.+- Native notification objects stay owned by Electron main, which returns a best-effort `granted` / `denied` / `unknown` / `unsupported` state because Electron has no cross-platform read-only query, and native plugin notifications create no durable inbox rows or session activation events.+- Decision D213 and ADR 0074 define the public API and its separation from D117's application-owned task notification contract.+See ADR 0074.## 2026-08-12 — Development plugins get an explicit permission-ceiling reload-Automatic development-plugin reloads continue to reject manifest permission additions, preserving the no-silent-widening boundary. Related decisions: D214. See ADR 0075.+- Automatic development-plugin reloads still reject manifest permission additions, preserving the no-silent-widening boundary.+- The Plugins page offers Reload for `source: "dev"` rows: `plugin/reload` resolves the registered folder, reloads it through the existing Electron runtime, and re-arms the watcher with the current declared permissions as the new ceiling.+- Decision D214 and ADR 0075 define this additive renderer/main IPC surface, with host RPC and storage schema versions unchanged.+See ADR 0075.## 2026-08-12 — Windows reserves the plugin launcher chord-Windows' `Alt+Space` system-menu reservation can cause Electron's global shortcut registration to fail while the application is unfocused. Related decisions: D215. See ADR 0076.+- Windows' `Alt+Space` system-menu reservation can make Electron's global shortcut registration fail while the application is unfocused, so host-core owns a narrow low-level keyboard hook for the default binding, consumes the chord, and emits `keyboard.shortcut`.+- Electron toggles the existing launcher window, custom bindings keep the normal Electron global shortcut path, and protocol version 9 and storage schema 11 stay unchanged.+See ADR 0076.## 2026-08-13 — Plugin launcher renderer warms during startup-Electron starts creating and loading the retained plugin launcher as soon as Electron is ready, before backend/plugin boot completes, while keeping the window hidden. Related decisions: D217, D211. See ADR 0080, ADR 0072.+- Electron starts creating and loading the retained plugin launcher as soon as it is ready, before backend and plugin boot complete, while keeping the window hidden.+- Shortcut delivery during warm-up joins the same in-flight creation promise, a failed warm-up stays retryable, each visible invocation still refreshes the plugin catalog, and macOS reveals the panel through one normal activation path without a focus steal.+- Decision D217 and ADR 0080 supersede only D211 / ADR 0072's first-use lazy creation clause, leaving IPC, host RPC, protocol v9, and storage schema v11 unchanged.+See ADR 0080.## 2026-08-12 — Approval cards focus on the artifact and remember the mode-Plan/Goal approval cards now show only the title, host-created artifact opener/path, Reject, and Approve. Related decisions: D215, D189. See ADR 0076, ADR 0053.+- Plan/Goal approval cards show only the title, the host-created artifact opener and path, Reject, and Approve, dropping the submitted question, status, deadline, and inline warnings.+- The selected Ask / Accept edits / Auto mode is remembered in renderer-local device preferences as the next default with Ask as the fallback, and title-derived artifact filenames preserve Unicode alphanumerics so localized titles stay recognizable.+- Decision D215 and ADR 0076 amend D189 / ADR 0053; the host's internal deadline remains a fail-closed boundary without being exposed, and protocol and storage versions are unchanged.+See ADR 0076.## 2026-08-14 — Plugin launcher remembers recently opened plugins@@ -1237,11 +1462,18 @@ Plan/Goal approval cards now show only the title, host-created artifact opener/p## 2026-08-21 — New Task creates an immediate durable empty slot-New Task now resolves the current project or Temporary group by its most recent non-archived session. Related decisions: D252, D220. See ADR 0084, ADR 0113.+- New Task resolves the current project or Temporary group by its most recent non-archived session, reusing an empty latest session or creating, refreshing, and selecting one before the first prompt.+- The renderer serializes same-group New Task requests so rapid clicks cannot race multiple empty inserts, and an older empty row is deliberately left alone when a newer non-empty session is the latest.+- `SessionSummary.messageCount`, derived by host-core from `sessions.last_seq`, replaces title heuristics as the empty predicate, so empty rows stay visible and title localization stays presentation.+- Decision D252 supersedes D220 and ADR 0084: the startup home stays an unpersisted renderer draft while explicit New Task is eager and durable, with `messageCount` additive inside protocol v9 and storage schema v11 unchanged.+See ADR 0113.## 2026-08-14 — The work panel shortcut toggles instead of only opening-`Cmd/Ctrl + J` (`openWorkPanel`) now collapses the visible work panel as well as revealing a closed one, going through the same store action as the header collapse control. Related decisions: D221, D207, D128, D142. See ADR 0068, ADR 0085.+- `Cmd/Ctrl + J` (`openWorkPanel`) now collapses the visible work panel as well as revealing a closed one, through the same store action as the header collapse control, retaining tabs, active resource, Browser resource, and committed width.+- The shortcut id stays `openWorkPanel` so existing keybinding overrides keep working, and only the Settings → Shortcuts label changes to describe toggling.+- Decision D221 amends D207 and reverses ADR 0068's rejected toggle alternative while D128's and D142's remaining clauses stand; protocol v9, host RPC, IPC channels, and storage schema v11 are unchanged.+See ADR 0085.## 2026-08-14 — A recorded change is a list row, not a card@@ -1270,7 +1502,11 @@ New Task now resolves the current project or Temporary group by its most recent## 2026-08-14 — PI-Desktop stays a regular macOS application-The plugin launcher window asked Electron for `visibleOnFullScreen` without `skipTransformProcessType`, so Electron ran `TransformProcessType(kProcessTransformToUIElementApplication)` on the whole process and PI-Desktop vanished from the Dock and Cmd+Tab. Related decisions: D216, D223. See ADR 0080, ADR 0078, ADR 0072, ADR 0086.+- The launcher asked Electron for `visibleOnFullScreen` without `skipTransformProcessType`, so Electron transformed the whole process into a UI element and PI-Desktop vanished from the Dock and Cmd+Tab — ADR 0080's warm-up made it happen on every launch; the launcher now passes `skipTransformProcessType: true`, and `app.dock.hide()` / `app.setActivationPolicy` stay forbidden in Main.+- The launcher keeps `canJoinAllSpaces` and `FullScreenAuxiliary` but gives up overlaying another application's fullscreen Space, which macOS reserves for accessory apps, so invoking it from there activates PI-Desktop.+- macOS activation also restores the shell from `did-become-active` for a booted, non-quitting app with no visible window, so Cmd+Tab and App Exposé resurface a tray-hidden window (D216 / ADR 0078) while launcher and plugin-panel activations leave the main window alone.+- Decision D223 constrains ADR 0072's launcher window and completes D216's restore paths, with ADR 0080's warm-up and latency budget intact.+See ADR 0086.## 2026-08-14 — Revealed work panel with no resource lists its four tools@@ -1301,7 +1537,11 @@ The plugin launcher window asked Electron for `visibleOnFullScreen` without `ski## 2026-08-14 — Context usage inspector opens on click-The inspector trigger no longer opens on `pointerenter` or focus. Related decisions: D225, D184. See ADR 0047.+- The inspector trigger no longer opens on `pointerenter` or focus: a click or `Enter`/`Space` toggles the panel, and the 140ms hover-grace close timer is deleted, so reading, scrolling, and selecting text outlast a wandering pointer.+- Dismissal is explicit — a second activation, a capture-phase pointerdown outside trigger and panel, or `Escape` returning focus — and scrolling the trigger out of view still closes it, as does the body-level collision-aware placement from ADR 0047 §6.+- The panel becomes `role="dialog"` with the localized `Context` label and `aria-haspopup="dialog"` on the trigger, so keyboard users keep a stable panel instead of one that vanished on blur.+- Decision D225 amends D184 / ADR 0047 and is renderer-only.+See ADR 0047.## 2026-08-14 — A run row's command lives in its head, not in its body@@ -1367,129 +1607,190 @@ The inspector trigger no longer opens on `pointerenter` or focus. Related decisi> Superseded by D245 on 2026-08-19; the one-retry behavior below is retained as> the historical decision and is no longer the active provider policy.-- A mid-stream HTTP 429 is now classified as retryable `PROVIDER_RATE_LIMITED`- and joins `STREAM_FAILED`, `NETWORK_ERROR`, and `TIMEOUT` in the runtime's- same-turn bounded replay path: one 750 ms abortable backoff, the failed- assistant is removed from model context, and the turn is replayed once with- the same visible assistant bubble.-- The retry budget is unchanged — one same-turn retry per prompt. A second 429- remains terminal and emits the normal assistant error plus lifecycle `error`- event with `retryAttempt: 1` and `providerStatus: 429` in the details, so the- transcript keeps its manual retry action.-- Request-setup 429s were already covered by pi-ai's one bounded retry that- honors `Retry-After` up to the 8-second cap; this closes the post-stream gap- where that wrapper can no longer act.-- Decision D233 refines D186 and is runtime-only. Protocol, host RPC, IPC- channels, and storage schema are unchanged. See- `03-runtime/02-agent-runtime.md` §5d, `03-runtime/08-error-codes.md`, ADR- 0091, and E2E-149.+- A mid-stream HTTP 429 becomes retryable `PROVIDER_RATE_LIMITED` and joins `STREAM_FAILED`, `NETWORK_ERROR`, and `TIMEOUT` in the runtime's same-turn bounded replay path: one 750 ms abortable backoff, the failed assistant removed from model context, and one replay in the same visible bubble.+- The budget stays one same-turn retry per prompt, so a second 429 is terminal with the normal assistant error and lifecycle `error` event carrying `retryAttempt: 1` and `providerStatus: 429`.+- Request-setup 429s were already covered by pi-ai's bounded retry that honors `Retry-After` up to 8 seconds, so this closes the post-stream gap where that wrapper cannot act.+- Decision D233 refines D186 and is runtime-only.+See ADR 0091.## 2026-08-15 — A stopped mutation loop says so-D186's repeat guard counted every same-path `Edit` failure alike, so the two failures it allows could both be spent on errors that already told the model what to do next. Related decisions: D186, D228. See ADR 0089.+- D186's repeat guard counted every same-path `Edit` failure alike, so `EDIT_TAG_MISMATCH`, `EDIT_TAG_UNKNOWN`, and `EDIT_LINES_UNSEEN` — each of which already hands back the live tag or the withheld content — now get one free attempt per path, every other code counts on its first occurrence, and a landed write clears that path's history.+- The guard still stops the loop by terminating the tool batch, which pi-agent-core reads as "no more work"; the runtime now finalizes the assistant row with retriable `MUTATION_RETRY_BUDGET_EXHAUSTED` and emits the matching error event, recording the turn as `error` rather than `completed`.+- Decision D228 refines D186 and is runtime-only.+See ADR 0089.## 2026-08-15 — A file permission carries a range, and a delete is recoverable-The three fs permissions were workspace-wide switches: `fs.read.workspace` reached `.env`, and `recursive: false` bounded one `fs.remove` call while a `glob` plus a loop reached the whole tree. Related decisions: D229, D009. See ADR 0008, ADR 0088.+- A permission now says whether a plugin may touch files at all while `manifest.fs` says which ones per mode with globs relative to the mode's root: `fs.read` may ask for the whole tree, but `fs.write` and `fs.delete` are refused a whole-tree pattern at validation time.+- Every `pi.fs.*` call passes four gates in a fixed order — declared ∩ granted, `realpath` containment on both sides, the credential deny-list plus the host's data directory, then the declared scope — with native deny/allow-once/allow-session consent outside it, and a host with no consent service refuses.+- Deletion is bounded rather than scoped alone: `own: true` removes what the plugin wrote itself through a path+mtime ledger invalidated by a user edit, anything else needs a declared scope, and removal goes through `shell.trashItem`, stays non-recursive, and is braked at 50 per rolling minute.+- `root: "userSelected"` trades standing power for reach through a memory-only directory handle, pre-scope names still install but are downgraded on load with the marketplace preflight and `pi-plugin check` naming the downgrade, and decision D229 continues ADR 0008 D009 by adding the manifest `fs` section and the `pi.fs.remove` / `pi.fs.requestDirectory` APIs.+See ADR 0088.## 2026-08-16 — Proactive background subagent delegation-`Task` stops blocking: it starts a delegate in the background and returns a `delegationId` immediately. Related decisions: D231, D201. See ADR 0062, ADR 0089.+- `Task` stops blocking: it starts a delegate in the background and returns a `delegationId`, while new Agent-mode core tools `TaskWait`, `TaskList`, and `TaskStop` drive convergence, and the runtime's per-session registry stops delegates left running at run end, parent abort, or dispose.+- The system prompt gains a `## Delegation` section with positive triggers and convergence rules, `explorer` is rewritten in the omo-slim style, and a write-capable `fixer` (`maxTurns: 40`) ships.+- Definitions may declare `permission: inherit | ask | accept-edits | auto`, resolved by host-core per `tools.execute` call under the contract modes' hard deny and the external-path gate, and a project definition's declaration is dropped at parse time; `TaskWait` defaults to 600 seconds, clamps to 900, and the per-session running cap becomes 10.+- Decision D231 amends D201 / ADR 0062 and touches the sidecar, host-core permission resolution, the builtin definitions, the system prompt, and the renderer's tool presentation mapping.+See ADR 0089.## 2026-08-17 — Plugin panels leave the visible surface to plugins-Plugin panel windows are now frameless on macOS, Windows, and Linux. Related decisions: D234, D218, D232. See ADR 0081, ADR 0082, ADR 0092.+- Plugin panel windows are frameless on macOS, Windows, and Linux: the preload reserves the same transparent 46px safe area on every platform and draws only a fixed top-right capsule with minimize, maximize/restore, and close.+- The host no longer renders the manifest title or a development safe-area reminder, so authors own the title, toolbar, background, and other visible panel UI, using `--pi-plugin-titlebar-height` and `-webkit-app-region: drag`.+- Decision D234 amends D218 / ADR 0081 and D232 / ADR 0082, leaving the sender-validated control channel, closed Shadow DOM, localized labels, theme-adaptive capsule, `window.pluginBridge`, protocol v9, and storage schema unchanged.+See ADR 0092.## 2026-08-17 — Plugin panels keep a strict 46px drag band-Plugin panels reserve exactly 46px for a transparent host drag band on every platform. Related decisions: D235, D234. See ADR 0092, ADR 0093.+- Plugin panels reserve exactly 46px for a transparent host drag band on every platform, offsetting normal-flow content by that value and leaving clicks in the band unavailable outside the capsule.+- The host renders no panel title: development panels show a localized, non-interactive drag-only reminder, production panels keep it hidden, and the minimal capsule stays fixed top-right inside the band.+- Decision D235 amends D234 / ADR 0092, keeping the page-adaptive capsule's closed Shadow DOM, localized labels, focus and reduced-motion behavior, private control channel, `window.pluginBridge`, protocol v9, and storage schema.+See ADR 0093.## 2026-08-18 — One desktop instance per data directory-Launching PI-Desktop while it is already running no longer starts a second app. Related decisions: D236, D002. See ADR 0094.+- Electron main takes the single-instance lock before it touches the data directory, so a duplicate launch quits before creating a window, a tray, a child process, or a log line.+- The running instance restores and focuses its main window through the tray's Show path, so a window closed or hidden into the tray comes back instead of a second shell appearing beside it.+- Decision D236 protects D002's single SQLite writer and the singletons around it, with the lock scoped to the installation so separate `PI_DESKTOP_DATA_DIR` runs still start.+See ADR 0094.## 2026-08-18 — Vendor-account (OAuth) login-A provider row can now be authenticated by a vendor subscription. Related decisions: D237, D028, D031. See ADR 0095.+- A provider row can be authenticated by a vendor subscription: the seven pi-ai OAuth vendors ship at once because the card list derives from `models.getProviders().filter(p => p.auth.oauth)`, with `registerBunOAuthFlows()` running once at startup for the dynamic import electron-vite cannot bundle.+- Credentials live beside (never instead of) the row's API key under `secret:provider:<id>:oauth`; `has_secret` widens to either credential, and `has_oauth` plus a non-secret `oauthAccountLabel` are new while `auth_kind` gains `oauth` inside unchanged protocol v9 and schema v10.+- Electron main owns login and logout, serializes `modify` per provider, and renders browser-callback, device-code, select, and paste-a-code steps through one `providersOauth*` stream, while the sidecar gets only a short-lived `ModelAuth` from `provider.resolveAuth`, checked against the binding table, and never a refresh token.+- Model discovery, the connection test, and `apiStyle` follow the account, Settings → Model configuration gains a Vendor accounts section, and decision D237 extends D028/D031 across host-core, main, the provider binding, and the settings UI.+See ADR 0095.## 2026-08-18 — Independent vendor OAuth accounts-D240 amends D237 / ADR 0095. The provider row id is the OAuth account identity, and every login creates a new row even when `vendorKey` is the same as an existing account. Related decisions: D240, D237. See ADR 0095, ADR 0098.+- D240 amends D237 / ADR 0095: the provider row id is the OAuth account identity, so every login creates a new row even for an existing `vendorKey`, and each row owns its own pi-ai collection, credential store, refresh chain, and `secret:provider:<id>:oauth` ref.+- Settings gains one owner per concept: Vendor accounts renders and removes OAuth rows, AI services renders API-key and custom rows, and removing an account clears or repairs a default pointing at the deleted id.+- The sidecar binds exact OAuth provider ids while main resolves auth by id, and subagent vendor or name aliases are accepted only when unique.+See ADR 0098.## 2026-08-18 — Builtin subagents inherit the parent permission mode-The builtin `fixer` no longer declares `permission: accept-edits`; like the other builtins, it defaults to `permission: inherit` and uses the parent session's effective permission mode. Related decisions: D242, D231. See ADR 0089, ADR 0100.+- The builtin `fixer` no longer declares `permission: accept-edits`; like the other builtins it defaults to `permission: inherit` and uses the parent session's effective permission mode.+- In `auto`, builtin delegate calls therefore auto-allow the same in-root, high-risk, and explicit external-path operations as the parent, while `ask` and `accept-edits` keep their approval boundaries and explicit non-`inherit` scopes remain intentional overrides.+- Decision D242 amends D231 / ADR 0089; host-core's external-path gate and containment checks are untouched, because this removes an accidental builtin override rather than weakening the boundary.+See ADR 0100.## 2026-08-18 — Model-aware image attachment transport-Clipboard images remain compact structured composer references instead of being inserted as base64 or forced into visible `@path` text. Related decisions: D243, D197, D392. See ADR 0059, ADR 0218, ADR 0101.+- Clipboard images stay compact structured composer references instead of base64 or visible `@path` text: main validates the source against the session roots and stores bytes under `<data>/attachments/<sha256>`, and the durable user message keeps only ref, kind, name, MIME type, and size.+- The exact pi-ai model record owns visual capability — `input.includes("image")` earns transient image blocks, unknown or non-vision models and images above the 10 MB inline bound fall back to a scratch or project path, and only an explicit `supportsImages` override can promote an unknown model.+- Decision D243 amends the image portion of D197 / ADR 0059, and D392 / ADR 0218 amends its capability-resolution rule, moving no provider logic into the renderer and putting no binary data into host persistence.+See ADR 0101.## 2026-09-11 — Effective image-input overrides across Composer and transport (D392)-Advanced model settings persist `supportsImages` per provider/model binding as a three-state value. Related decisions: D243. See ADR 0101, ADR 0218.+- Advanced model settings persist `supportsImages` per provider/model binding as three states: `null` or absent follows the published model record, while `true` or `false` explicitly enables or disables image input for that endpoint.+- Composer model rows, attachment status, and main-process transport all use the same effective binding capability; the published `ModelInfo` is not mutated and unknown or custom models stay conservative without an override.+- Decision D392 amends D243 / ADR 0101.+See ADR 0218.## 2026-08-19 — models.dev first replaces Pi as the primary model catalog (historical)-D266 amends D136 / ADR 0027. Electron main loads the public `https://models.dev/api.json` catalog with a bounded timeout and matches provider records by vendor key or normalized API URL. Related decisions: D266, D136, D639. See ADR 0027, ADR 0133.+- D266 amends D136 / ADR 0027: Electron main loads the public `https://models.dev/api.json` catalog with a bounded timeout and matches provider records by vendor key or normalized API URL, and Settings, Composer, and runtime metadata use the matching record first.+- Display names, context and output limits, input modalities, reasoning options, tool-call flags, and prices map onto the existing model surfaces, with no credentials in the request and a `catalogSource` marker separating models.dev from the pi-ai fallback in renderer metadata.+- D639 later removed the Pi sibling chat-metadata fallback; the historical decision stays here to preserve the record of the migration.+See ADR 0133.## 2026-10-02 — models.dev is the chat model metadata authority-- D639 supersedes the Pi 0.99.1 metadata decision and the Pi sibling fallback.- The bundled models.dev snapshot supplies chat context/output limits and- capabilities; the selected official publisher wins, followed by safe,- unambiguous third-party records. Missing or conflicting records stay generic.-- Live endpoint and OAuth responses still determine selectable IDs. Pi remains- the OAuth and transport adapter and supplies typed non-chat operations only.- Explicit user binding values remain pinned, and no provider secrets are sent- to models.dev. See ADR `models-dev-catalog-authority`.+- D639 supersedes the Pi 0.99.1 metadata decision and the Pi sibling fallback: the bundled models.dev snapshot supplies chat context and output limits plus capabilities, the selected official publisher wins, safe unambiguous third-party records follow, and missing or conflicting records stay generic.+- Live endpoint and OAuth responses still determine selectable IDs, Pi remains the OAuth and transport adapter for typed non-chat operations, explicit user binding values stay pinned, and no provider secret reaches models.dev.+See ADR `models-dev-catalog-authority`.## 2026-08-19 — The work panel becomes a plugin extension point-Decision D246. A plugin declares work panel surfaces with `contributes.views` (id, plain or localized title, icon token, HTML entry, order), gated by the new low-risk `ui.view` permission. Related decisions: D246, D100, D247. See ADR 0104, ADR 0105.+- Decision D246 lets a plugin declare work panel surfaces with `contributes.views` (id, plain or localized title, icon token, HTML entry, order) behind the new low-risk `ui.view` permission, independent of `ui.panel`, and each view renders as a main-process `WebContentsView` positioned from a renderer-measured rect, the mechanism the preview browser has used since D100.+- Views reuse the plugin's isolation wholesale — the same sandboxed preload, `persist:pi-plugin-<id>` partition, and `net.domains` egress filter, shared as functions so the two placements cannot drift — because an `<iframe>` cannot get its own partition; icons are tokens from a host-owned closed list, and permission, scope, and entry existence are re-checked on open.+- Decision D247 moves Review, Terminal, and Files out of the host onto that same channel as bundled first-party plugins, leaving Browser as the only built-in tool and giving the API a first-party consumer, with new `pi.review.*` and `pi.terminal.*` APIs and `terminal.pty` accepted deliberately as a critical permission.+See ADR 0104 and ADR 0105.## 2026-08-18 — Compact context usage summary-The context inspector keeps the click/keyboard trigger, remaining percentage, used/window counts, turn total, completed-turn speed, exact provider values, aggregate tool summary, checkpoint summary, body-level portal, placement, outside dismissal, and Escape focus return. Related decisions: D244, D103, D184. See ADR 0047, ADR 0103.+- The inspector keeps its click and keyboard trigger, remaining percentage, used/window counts, turn total, completed-turn speed, exact provider values, aggregate tool summary, checkpoint summary, body-level portal, placement, outside dismissal, and Escape focus return.+- The default panel becomes a short summary: turn and speed values unboxed, provider and tool usage as compact inline rows, and the per-tool rows, share bars, source badges, estimate paragraph, and used-capacity meter removed, with `~` still signalling an estimate.+- Decision D244 amends D103 / D184 / ADR 0047, leaving protocol, storage, runtime accounting, and model metadata unchanged.+See ADR 0103.## 2026-08-19 — OpenCode-style bounded provider 429 retry-HTTP 429 is now handled by one runtime-owned policy in both request setup and stream recovery. Related decisions: D258, D245, D186, D233. See ADR 0091.+- HTTP 429 is handled by one runtime-owned policy across request setup and stream recovery, with five retries after the initial request shared across phases and pi-ai's nested retry wrapper disabled.+- Retries stay silent and abortable: `retry-after-ms`, `retry-after` seconds, and HTTP-date values take precedence over a 2-second exponential fallback with positive 25% jitter and a 30-second cap, and failed status and headers are captured from fetch because pi-ai's response callback does not expose setup failures.+- Main sessions and builtin subagents reuse the visible assistant row and suppress intermediate events; exhaustion emits one terminal `PROVIDER_RATE_LIMITED` with `retryAttempt: 5`, aborting during the wait starts no later request, and auth, model-selection, malformed-request, and context failures stay terminal.+- Decision D245 amends D186 and D233; other transient failures kept one retry each until D258 gave them a shared budget.+See ADR 0091.## 2026-08-19 — Files ships as the first bundled plugin-Decision D248 implements the first step of D247. Related decisions: D248, D247. See ADR 0105.+- Decision D248 implements D247's first step: browsing the project is the bundled `pi.files` plugin, reached through `contributes.views` like any third-party one, so the host tool list no longer carries a Files entry while Review and Terminal stay built in.+- Bundled plugins carry `source: "builtin"`, and host-core reconciles its registry against `PI_DESKTOP_BUILTIN_PLUGINS_DIR` on every launch, refreshing version and contributions while the user-owned enabled and scope state carries across; they can be disabled but never uninstalled.+- Only the tool migrated: a `file:<path>` tab stays a host-owned transcript artifact, exactly like Review's artifacts.+- Writing the plugin proved D247's premise, since a flat 500-capped `fs.glob` cannot back a lazy tree, so `pi.fs.list` was added under `fs.read` with the same declared scope, deny-list, protected paths, and heavy-directory skips.+See ADR 0105.## 2026-08-19 — The builtin command surface is reduced to five core entries-Decision D250 freezes the first-party registry at `builtin.session.new`, `builtin.agent.compact`, and the three `builtin.mode.*` entries. Related decisions: D250. See ADR 0106, ADR 0024, ADR 0034.+- Decision D250 freezes the first-party registry at `builtin.session.new`, `builtin.agent.compact`, and the three `builtin.mode.*` entries, whose only builtin composer aliases are `/new`, `/compact`, `/agent-mode`, `/plan-mode`, and `/goal-mode`.+- Session deletion, abort, project, settings, plugin, log, rename, palette, reload-window, and DevTools entries leave the registry and renderer dispatch, along with the legacy `newChat`, `openProject`, and `openSettings` aliases, while dedicated UI workflows and plugin commands are unaffected.+- Mode aliases keep the one-shot `/mode <prompt>` behavior, and former aliases are no longer supported builtin contracts.+See ADR 0106.## 2026-08-19 — The panel's built-in interactive terminal is removed-Decision D251 supersedes D249 and the terminal clauses of ADR 0019/0105. Related decisions: D251, D249. See ADR 0019, ADR 0105, ADR 0108.+- Decision D251 supersedes D249 and the terminal clauses of ADR 0019/0105: the work panel no longer owns an interactive shell, and users take interactive shell work to an external terminal.+- Browser stays the host-built tool, Files stays a bundled plugin, Review and `file:<path>` stay artifact surfaces, and contributed plugin views remain available beside them.+- Agent Bash stays non-interactive and transcript-owned with its command, output, status, copy behavior, and terminal icon; only terminal-specific PTY UI, IPC, types, dependencies, packaging, and tests are deleted, the desktop protocol version does not change, and no plugin PTY permission or bundled replacement is introduced.+See ADR 0108.## 2026-08-24 — Windows taskbar minimize keeps the taskbar entry-Decision D252 amends D216 / ADR 0078 for the native Windows taskbar path. Related decisions: D252, D216. See ADR 0078, ADR 0117.+- Decision D252 amends D216 / ADR 0078 for the native Windows taskbar path: clicking the focused window's taskbar button completes the ordinary native minimize and keeps the taskbar entry, clicking it again restores and focuses the window, and clicking it while the window is merely covered still brings it to the front.+- Explicit renderer and menu minimize actions stay tray-resident, as do the macOS and Linux native paths, with the tray, background processes, bounds, IPC, and storage unchanged.+See ADR 0117.## 2026-08-24 — Renderer-owned queued prompts and graceful Send now-Decision D253 adds a per-session, renderer-local FIFO queue for prompts sent while an agent is running. Related decisions: D253. See ADR 0118.+- Decision D253 adds a per-session, renderer-local FIFO queue for prompts sent while an agent is running; it holds the visible prompt and its draft snapshot, supports independent removal, survives session switches, and is deliberately not persisted or replayed after restart.+- The composer has one submit slot: an active run with a non-empty draft renders Send and appends to the queue, an empty draft renders Stop, and after the owning session's `agent_end` the renderer drains one item through the existing `agent/prompt` path.+- Send now promotes one item and calls additive `pi-desktop/agent/stop`, setting pi-agent-core's one-shot `finishTurn` so the current response and tool batch complete before the prioritized prompt starts, while immediate abort keeps its behavior and never clears the queue.+- This changes renderer state ownership and adds one public IPC channel without changing host-core protocol v9, storage schema v11, or the one-running-turn constraint.+See ADR 0118.## 2026-08-24 — Subagents use event-driven idle and duration timeouts-Decision D254 replaces the default subagent turn cap with a 600-second idle watchdog and a 21,600-second total-duration ceiling. Related decisions: D254, D260. See ADR 0119.+- Decision D254 replaces the default subagent turn cap with a 600-second idle watchdog and a 21,600-second total-duration ceiling; the idle timer resets on turn, message, and tool lifecycle events and pauses during tool execution, while the duration timer includes it. (Amended by D260: the idle default is 300 seconds and every agent event resets the timer.)+- A timeout returns `timed_out` with `SUBAGENT_IDLE_TIMEOUT` or `SUBAGENT_DURATION_TIMEOUT`, keeping the latest partial output where available, while fatal provider errors, parent aborts, and explicit `maxTurns` are unchanged.+- `maxTurns` becomes optional, with `none`, `0`, and omission meaning unlimited and explicit values capped at 80; definitions may override the watchdogs through `idle-timeout` and `max-duration` within documented bounds, invalid values warn and fall back to defaults. (Amended by D260: each builtin declares an explicit backstop rather than running unlimited.)+- Builtin `explorer` gains `Bash` while `code-reviewer` stays read-only, and shared status types, runtime timing, delegation topology, i18n, and E2E coverage expose the new timeout outcome.+See ADR 0119.## 2026-08-25 — Collapsing the work panel restores the base window bounds-Decision D255 supersedes ADR 0033. The renderer still lays the work panel out as an in-flow flex column, but requests a native reservation equal to the committed panel width before presenting it. Related decisions: D255. See ADR 0033, ADR 0122.+- Decision D255 supersedes ADR 0033: the renderer still lays the work panel out as an in-flow flex column, but requests a native reservation equal to the committed panel width before presenting it, and exit keeps the panel mounted until the zero-width reservation succeeds, so the window returns to its chat-only bounds instead of letting MainChat consume the released column.+- The target-state reservation planner, constrained-display behavior, Browser measured-bounds sync, Main-owned native edge resize, and session-scoped panel state are unchanged.+See ADR 0122.## 2026-08-25 — Window controls use native taskbar minimize-Decision D256 amends D216 / D252 for Windows/Linux renderer and native-menu minimize actions. Related decisions: D256, D216, D252. See ADR 0123.+- Decision D256 amends D216 / D252 for Windows and Linux renderer and native-menu minimize: the custom top-right button now uses the native OS minimize transition so the taskbar entry stays available for restore, and close-to-tray remains governed only by the remembered close behavior.+- macOS native minimize stays tray-resident, and the tray, close preference, IPC shape, host protocol, and background lifecycle are otherwise unchanged.+See ADR 0123.## 2026-08-27 — Agent capability pages become one workbench-Decision D257 refines D193 / D194 and supersedes D202's page-shape clause for Settings > Agent > Skills / MCP / Subagents. Related decisions: D257, D193, D194, D202. See ADR 0126.+- Decision D257 refines D193 / D194 and supersedes D202's page-shape clause for Settings > Agent > Skills / MCP / Subagents: each page is one toolbar — segmented level filter with counts, one search field, project picker, primary actions — above one panel divided by level group headers.+- All three pages create, edit, and delete through host calls that predate the change, per-row busy replaces page-wide locking, skeletons are first-paint only, and enablement flips optimistically with a revert on host rejection.+- `skills.reveal` now carries `level` and `projectPath` so a project skill with no global counterpart resolves, while still accepting a bare id.+- Renderer-only apart from that payload widening: no host-core change, no new RPC, no storage or schema change, and every capability-state, precedence, and `.agents` path rule from D193 / D194 / D202 stands.+See ADR 0126.## 2026-08-27 — Release documentation is a version surface (D260)@@ -1506,23 +1807,41 @@ Decision D257 refines D193 / D194 and supersedes D202's page-shape clause for Se## 2026-08-26 — Transient provider failures share a bounded retry budget-Decision D259 amends D186 / D245 and ADR 0050 / ADR 0091. Related decisions: D259, D186, D245. See ADR 0050, ADR 0091, ADR 0128.+- Decision D259 amends D186 / D245 and ADR 0050 / ADR 0091: non-429 transient failures share one budget of four retries after the initial attempt across request setup and stream delivery, so an upstream gateway 502/503/504 recovers before headers or mid-stream and only the failed request is replayed.+- The budget admits `NETWORK_ERROR`, `TIMEOUT`, `STREAM_FAILED`, and retryable `PROVIDER_ERROR`, honoring `retry-after-ms`, `retry-after` seconds, then HTTP-date before a deterministic 1s/2s/4s/8s schedule capped at 8 seconds, with captured headers kept for every status that can state a delay.+- The main session, builtin subagents, and one-shot composer enhancement share one policy, the 429 five-retry budget stays separate, exhaustion records `retryAttempt: 4`, and authentication, model-selection, malformed-request, and context failures remain terminal.+See ADR 0128.## 2026-08-27 — The subagent idle watchdog bounds silence, not slowness-Decision D260 amends D254. Every agent event re-arms the idle timer, a single streamed token arriving as `message_update` included, so the watchdog fires only on total unresponsiveness. Related decisions: D260, D254. See ADR 0129.+- Decision D260 amends D254: every agent event, a single streamed token arriving as `message_update` included, re-arms the idle timer, so a delegate that keeps producing output is never idle-terminated however slow its turn, and the pause across tool execution is unchanged.+- Because the window measures dead air rather than work, the default idle timeout drops from 600 to 300 seconds, sized from the measured 174-second p99.9 wait and kept below the 600-second `TaskWait` default so a genuinely stuck delegate settles as `timed_out` within one wait.+- `TaskWait` expiry now reports "Still running after Ns" and states that this is not a failure and the delegates keep working, and the builtins gain turn backstops — `explorer` 60, `code-reviewer` 50, `test-runner` 40, `fixer` 80 — so a non-converging delegate ends as `truncated` with its partial report.+See ADR 0129.## 2026-08-27 — The mounted transcript is a window, not the loaded history (D261)-Decision D261 refines ADR 0120 / D258 in the renderer. Related decisions: D258. See ADR 0120, ADR 0130.+- Decision D261 refines ADR 0120 / D258 in the renderer: those bounded what crossed IPC and what locating a page costs, but the renderer still mounted every paged-in row and kept it mounted for the session's life.+- The mounted history becomes a trailing window of 15 rows in the first commit after a switch, a 60-row steady state, grown 40 at a time; reaching the top grows a partial window and fetches an older page only once it covers all loaded history.+- `content-visibility: auto` skipped layout and paint but retained React trees, Markdown ASTs, and Shiki tokens — the wrong resource on a low-memory Windows machine — so windowing bounds retained memory and per-frame reconciliation at once, using the same pre-paint scroll anchor as a fetched page and clamping per session.+- The minimap is built from mounted entries and resolves a click by finding the marker's node, so no dash points nowhere, at the cost of find-in-page reaching only mounted rows.+See ADR 0130.## 2026-08-28 — Large text pastes become session-scratch references (D262)-Text-only pastes at or below the persisted `largePasteThreshold` remain native textarea input; the default is 600 characters and valid values are integers from 1 through 1,000,000. See ADR 0131.+- Text-only pastes at or below the persisted `largePasteThreshold` (default 600 characters, valid from 1 through 1,000,000) stay native textarea input.+- Larger text travels as exact UTF-8 `text/plain` bytes through the existing paste bridge into `<data_dir>/scratch/<sessionId>/pasted/`, and the composer inserts a generated `@<temporary-name> ` token at the original caret and selection while keeping the canonical path mapping in the draft, cached and unanswered smart-Stop snapshots included.+- Dispatch resolves that token in place exactly once, never appending a basename, duplicating an attachment, or writing into the workspace, while clipboard file and image chips and scratch cleanup are unchanged.+- The setting is additive app-settings JSON, normalized to the default for older settings without a database migration.+See ADR 0131.## 2026-08-28 — A cross-display drag is user intent, not an OS adjustment (D263)-Decision D263 amends D255 / ADR 0122 in Main. Related decisions: D255. See ADR 0122, ADR 0132.+- Decision D263 amends D255 / ADR 0122 in Main: the reservation reconcile read every display change as one `displayChanged` boolean and reused the remembered base bounds, which is right for an OS re-fit and wrong for a window the user dragged to another display.+- Reported as issue #18 and reproducible from 0.10.0, the jump came from wiring that reconcile to each native `move`, so it ran mid-drag from the origin display's base bounds and the target work area clamped the result.+- The boolean becomes a `DisplayTransition` of `none`, `os-adjusted`, or `user-moved`: `os-adjusted` preserves ADR 0122 verbatim, while `user-moved` derives base bounds from where the window now is, keeps the size even on a smaller display, and lets the reservation absorb the shortfall.+- Attribution keys off an unaccounted native `move` stream that defers reconciliation until it goes quiet, a `user-moved` transition advances the remembered display key and persists it, and a forced Stage Manager recovery clears the pending attribution.+See ADR 0132.## 2026-08-28 — Composer typing is a measured latency path (D264)@@ -1564,15 +1883,27 @@ Decision D263 amends D255 / ADR 0122 in Main. Related decisions: D255. See ADR 0## 2026-08-29 — An expanded delegate run scrolls in place (D271)-Decision D271 refines D201 / D268 / ADR 0062 in the renderer. Related decisions: D201, D268. See ADR 0062.+- Decision D271 refines D201 / D268 / ADR 0062 in the renderer: opening one delegation node inlined the delegate's entire run, so a delegate that made forty tool calls added forty rows at once.+- Three unbounded surfaces were involved — `.subagent-run` had no height limit, `.tool-fields` lacked the 260px cap its siblings carried, and D268 routed the joined `TaskWait` reports into an uncapped `note`.+- The scroll sits on a new inner `.subagent-run-rows` wrapper rather than the run, because the collapse rail is absolutely positioned outside the run's padding box and an `overflow` there would clip it; the heading stays outside the scroll area so attribution cannot scroll away.+- The scroll area is a labelled, focusable `role="group"` so keyboard users can reach it.+See ADR 0062.## 2026-08-29 — A lifecycle row is a subagent row (D268)-Decision D268 refines D201 / D265 / ADR 0062 and ADR 0089 in the renderer. Related decisions: D201, D265. See ADR 0062, ADR 0089.+- Decision D268 refines D201 / D265 / ADR 0062 and ADR 0089 in the renderer: D265 made every `Task` a delegation card but left `TaskWait`/`TaskList`/`TaskStop` as generic tool rows, which is where a settled outcome actually appears.+- The defects were narrow — a bare UUID summary, pretty-printed `delegations[]` JSON, and a label reading "Delegated" — and the fix reads the roster the runtime already returns.+- `details.delegations[]` and `details.stopped[]` supply agent name, status, and registry timestamps, so the row summarizes by agent name with repeats counted, badges a rolled-up status from `chat.subagentStatus.*`, and renders a named field table led by the joined reports.+- A lifecycle row stays out of the topology and the subagent counts, the runtime's `delegationId` contract is untouched, and nothing but presentation moves.+See ADR 0062.## 2026-08-28 — One delegation reads as a card, like a fan-out (D265)-Decision D265 amends D201 / ADR 0062 in the renderer. Related decisions: D201. See ADR 0062.+- Decision D265 amends D201 / ADR 0062 in the renderer: that decision reserved the delegation card for two or more `Task` calls in one activity group, so the common single case lost the outcome, the recorded runtime, and the delegate's step count.+- Every `Task` call in an activity group now renders as a delegation card with a root node, a connector, and one node per delegate; the aggregate header, live-open-once rule, node disclosures, and print-the-report-once rule carry over unchanged.+- The aggregate header is count-aware: English gains `_one` forms and Chinese lets its single plural category carry every count, dropping the marker that made a one-node card read "1 个 Subagents".+- The card is still derived on live and reload from persisted `parentToolCallId` / `agentName` attribution, so no IPC, storage, host-protocol, or delegation-runtime change follows.+See ADR 0062.## 2026-08-28 — The titlebar band is reserved on every platform (D266)@@ -1624,7 +1955,11 @@ Decision D265 amends D201 / ADR 0062 in the renderer. Related decisions: D201. S## 2026-08-29 — History continuation keeps the conversation outline reachable (D269)-Decision D269 amends D108 / D261 / ADR 0130 in the renderer. Related decisions: D108, D261. See ADR 0130.+- Decision D269 amends D108 / D261 / ADR 0130 in the renderer: D261 fed the minimap the mounted entries, which was right about dashes but left the outline silent about the history it hid, and D108 then removed the rail when the mounted tail had fewer than two markers.+- A bounded tail can be one tool-heavy turn below a viewport and a fetched page can land outside the window, neither necessarily changing `scrollTop`, while the only escalation trigger was a native scroll event.+- The outline now stays while earlier history exists — `hiddenAbove > 0` or `hasMoreBefore` — with one dotted earlier-history continuation at its top that runs the same grow-then-fetch path, disables and labels itself while loading, and never claims a message preview.+- Progress also rides the transcript's existing top loading row: while it stays inside the near-top band after an underfilled tail, a withheld page, or a window transition, escalation continues, and once no earlier history remains D108's two-marker-plus-overflow rule applies again.+See ADR 0130.## 2026-08-30 — One model picker for both credential kinds (D270)@@ -1712,23 +2047,41 @@ Decision D269 amends D108 / D261 / ADR 0130 in the renderer. Related decisions:## 2026-08-31 — Retry an unchanged edited prompt (D274)-Decision D274 amends D137 in the renderer. Related decisions: D137. See ADR 0135.+- Decision D274 amends D137 in the renderer: confirming a valid user-prompt edit always dispatches the existing edit-resend/Regenerate path, even when the trimmed text is identical to the original.+- The inline controls read Retry and Cancel in the active locale; Retry keeps the revision archive, identity-based truncation, slash-command expansion, and attachment behavior, while Cancel and Escape leave the prompt untouched.+- Renderer and i18n only, with no IPC, storage, host-protocol, or runtime contract change.+See ADR 0135.## 2026-08-31 — Preserve the active task boundary across context compaction (D275)-Decision D275 amends D203 / ADR 0064 in the agent runtime. Related decisions: D203. See ADR 0064, ADR 0136.+- Decision D275 amends D203 / ADR 0064 in the agent runtime: checkpoints persist an opaque `details.retainedTailMode` boundary.+- While a provider must continue an active tool turn, the checkpoint retains only the latest user message within the existing 20,000-token limit; at a completed turn boundary, before a new prompt, or for manual compaction it retains no naked historical user messages, because the summary is authoritative.+- Legacy checkpoints without the mode normalize to their latest user message, and the visible transcript, host-owned storage, and protocol shape are unchanged.+See ADR 0136.## 2026-08-31 — A visited session keeps its own mounted pane (D276)-Decision D276 amends D162 and ADR 0130 clauses 4–5. Related decisions: D162. See ADR 0130, ADR 0137.+- Decision D276 amends D162 and ADR 0130 clauses 4–5: the chat surface mounts one pane per recently visited session, bounded to three, so switching is a visibility swap instead of re-pointing one transcript at different data.+- A warm switch reveals the destination pane with its own scroll position on the first frame; a cold switch keeps the current pane fully legible under the thin progress track with the composer inert, and the opacity dim is gone.+- First activation settles at the newest turn, a revisit restores that pane's offset, and hidden panes keep their layout box, stay inert, and perform no follow scrolling, pagination, or measurement.+- Renderer only: no IPC, storage, host-protocol, or runtime contract change.+See ADR 0137.## 2026-08-31 — Concurrent subagents may message each other directly (D277)-Decision D277 extends D201 / ADR 0062 / ADR 0089 without amending them. Related decisions: D201. See ADR 0062, ADR 0089, ADR 0140, ADR 0138.+- Decision D277 extends D201 / ADR 0062 / ADR 0089 without amending them: one opt-in tool, `Peer(action=...)`, gives concurrent delegates a session-scoped mailbox with `send`, `inbox`, and `wait` operations, the three that ADR 0140 folded from the original `PeerSend` / `PeerInbox` / `PeerWait`.+- It exists because the parent writes every brief before any delegate starts, the path lock prevents a torn write but not a stale premise, and relaying notes through a parent blocked in `TaskWait` would spend the context delegation exists to protect.+- Opt-in and default-off: no builtin declares `Peer`, addressing is by agent name with the sender bound at spawn, the tool is built per delegate and stays out of the session catalog, a definition declaring only `Peer` is refused at `Task` time, and messages stay in-process with no `permissionScope`, host-core call, or tool budget.+- Bounds are 2,000 characters, 64 inbox messages with loss reported, 60 sends per run, and a 120-second wait below the 300-second idle watchdog, with destructive draining; peer traffic never enters the parent's context, no cross-session, parent, nested, or durable channel exists, and no `AgentEventEnvelope` field is added.+See ADR 0138 and ADR 0140.## 2026-09-01 — Subagent model selection (D278)-Decision D278 extends D201 / ADR 0062 / ADR 0089 in the agent runtime and provider-model system. Related decisions: D201. See ADR 0062, ADR 0089, ADR subagent-model-opt-in.+- Decision D278 extends D201 / ADR 0062 / ADR 0089: `Task` gains an optional `model` (`"provider/modelId"`) that overrides the definition's frontmatter pin, resolving Task.model → definition pin → session model, while `ModelBinding.availableForSubagents` (default false) opts a binding into the delegation catalog injected into the parent's prompt.+- A model that is unconfigured or not opted in returns a tool error listing the available models, an exact repeat of the session model counts as inheritance, and models not pre-resolved at launch resolve on demand through `provider.resolveSubagentModel`.+- Per the 2026-09-13 clarification, `subagentProviders` may hold definition-only pins and is not an override allowlist: additive `subagentModelKeys` carries opt-in, defaults empty, joins runtime reuse, authorized on-demand results use a separate cache, and only unique provider ids match.+- Per the 2026-09-15 clarification for issue #386, the opt-in gates every entry point that picks a delegated model, so a spawn naming a non-opted `modelKey` is refused with `PERMISSION_DENIED` before a worker exists, while `models.list` reports a flag only Electron main treats as authoritative.+See ADR `subagent-model-opt-in`.## 2026-09-01 — Native window edge resize settles before recovery (D279)@@ -1746,19 +2099,33 @@ Decision D278 extends D201 / ADR 0062 / ADR 0089 in the agent runtime and provid## 2026-09-01 — Expanded sidebar width is user-resizable (D280; superseded by D408)-The expanded sidebar owns a persisted preferred width with a `240..520px` clamp and a `275px` default. Related decisions: D459. See ADR 0141, ADR 0290.+- The expanded sidebar owns a persisted preferred width clamped to `240..520px` with a `275px` default, previewed by a right-edge renderer handle from the pointer-down position, reflowing MainChat continuously, and saved only on pointer release.+- The handle is a vertical ARIA separator: Left and Right adjust by 16px, Home and End select the bounds, keyboard changes commit immediately, and Escape, pointer cancellation, lost ownership, or unmount rolls a gesture back to its starting width.+- Collapse stays independent of the preferred expanded width, and no IPC, native-window bounds, work-panel reservation, or project/session order contract changes.+- D408 later pinned the live shell at 275px and hid the handle, and D459 / ADR 0290 restores the resizable handle and adds collapse below 160px.+See ADR 0141.## 2026-09-01 — Non-loopback HTTP MCP endpoints are supported (D281)-User-owned and plugin-declared MCP servers accept absolute `http://` and `https://` URLs, including trusted LAN addresses. See ADR 0142.+- User-owned and plugin-declared MCP servers accept absolute `http://` and `https://` URLs, trusted LAN addresses included, while unsupported schemes and malformed URLs stay invalid.+- The user MCP editor warns about unencrypted non-loopback HTTP, and plugin-declared endpoints still need `mcp.server.remote` plus a host covered by `manifest.net.domains`.+- The client disables automatic redirects, limits the chain to five hops, accepts only HTTP(S) targets, and re-checks plugin egress for every hop, blocking a redirect to an undeclared host before the next request.+- Marketplace catalog and package download rules are unchanged, so non-loopback HTTP package downloads are still refused.+See ADR 0142.## 2026-09-01 — User-renamable task titles (D282)-A task name is session metadata and can be edited from the Sidebar session overflow/right-click menu or the Project archive task row. See ADR 0143.+- A task name is session metadata editable from the Sidebar session overflow/right-click menu or the Project archive task row, both opening one localized modal with focus management, Escape/Cancel dismissal, and a 1–80 code-point bound.+- The existing `session.rename` IPC/RPC path trims and validates at the host boundary, returning `INVALID_PARAMS` for blank or overlong values, and a successful rename updates only `sessions.title`.+- `updated_at`, transcript data, message count, project binding, empty-session state, and historical notification title snapshots are untouched, while a custom title still suppresses first-prompt generation and projects consistently after save and restart.+See ADR 0143.## 2026-09-01 — User-configurable thinking-level overrides (D283)-`ModelInfo` remains the raw models.dev record. See ADR 0144.+- `ModelInfo` remains the raw models.dev record: an existing `ModelBinding` no longer overwrites published reasoning fields or capability tags, so a catalogued reasoning model stays visible as such.+- Settings always renders the seven canonical levels, published levels seed new known-model bindings, and unknown or catalogued non-reasoning models show the same choices unselected but explicitly enableable for a compatible endpoint.+- The exact binding owns effective thinking capability, its explicit levels survive save time and are used unchanged by Composer, main, and the sidecar, and empty or `off`-only bindings resolve to `off` with no automatic reasoning inference.+See ADR 0144.## 2026-09-01 — Settings rail uses a compact label scale (D284)@@ -1775,11 +2142,17 @@ A task name is session metadata and can be edited from the Sidebar session overf## 2026-09-01 — Native macOS Intel release lane (D285)-D285 extends D126 and ADR 0145. Tag builds now use `macos-15` for arm64 and `macos-15-intel` for Intel x64, alongside the existing Windows x64 and Linux x64 lanes. Related decisions: D126. See ADR 0145.+- D285 extends D126 and ADR 0145: tag builds use `macos-15` for arm64 and `macos-15-intel` for Intel x64 beside the existing Windows x64 and Linux x64 lanes.+- The static macOS targets expose DMG and ZIP without a fixed architecture, each native runner passes the matching electron-builder flag and builds the Rust sidecar locally, and the workflow rejects a runner architecture that does not match its matrix entry.+- macOS updater feeds are renamed per architecture before upload and merged into one `latest-mac.yml` during publication, and macOS stays notify-and-link until a signed in-app channel is qualified.+See ADR 0145.## 2026-09-02 — Work panel outer and inner resize ownership (D286)-With the right work panel open, the outer native right edge and right corners resize the panel target (`244..720px`) while preserving the base conversation width. See ADR 0146.+- With the work panel open, the outer native right edge and right corners resize the panel target (`244..720px`) while preserving base conversation width, previewed and committed through an Electron-local event; left and other native edges keep resizing the base chat.+- The inner renderer divider resizes the base conversation width through the bounded `window/setWorkPanelChatWidth` channel (`1040..10000px`) with the panel reservation unchanged, serializing pointer updates and restoring the press-time target on cancellation.+- This is an Electron-local behavior change and the host protocol stays v9.+See ADR 0146.## 2026-09-03 — Transcript settle veil and pre-paint follow (D287)@@ -1831,45 +2204,45 @@ With the right work panel open, the outer native right edge and right corners re## 2026-09-03 — Explicitly disable application keyboard shortcuts (D289)-Application shortcut overrides have three states: an absent property uses the platform default, a valid portable binding string customizes it, and explicit JSON `null` means `Unbound` and dispatches nothing. See ADR 0148.+- Application shortcut overrides have three states: an absent property uses the platform default, a valid portable binding string customizes it, and explicit JSON `null` means `Unbound` and dispatches nothing, with invalid strings keeping the safe default fallback.+- Settings exposes Disable separately from Restore default with a localized Unbound state, unbound actions stay out of conflict detection but remain editable, and the shared state drives renderer matching, macOS menu accelerators, and the global plugin launcher.+- Unbinding `openPluginLauncher` unregisters any prior global shortcut, disables the Windows host hook, and removes the focused-window fallback, while configurable native-role menu items become role-less so Electron cannot restore a default accelerator.+See ADR 0148.## 2026-09-04 — Calm running status motion in the transcript (D290)-- Replace the high-contrast text shimmer used by the Working indicator and live- activity labels with static readable text plus compact status markers. The- pre-stream Working indicator uses three small staggered dots; active activity- labels use one small pulse marker, while tool spinners and the existing- assistant streaming rail retain their state feedback.-- The marker pulse is compositor-friendly, capped at a one-second loop, and is- disabled under `prefers-reduced-motion`; the status remains visible as static- text and dots. No protocol, storage, or runtime behavior changes. See ADR- 0149 and E2E-053/E2E-083.+- The high-contrast text shimmer in the Working indicator and live activity labels is replaced by static readable text plus compact markers: three staggered dots before streaming and one small pulse on active labels, while tool spinners and the assistant streaming rail keep their feedback.+- The pulse is compositor-friendly, capped at a one-second loop, and disabled under `prefers-reduced-motion`, leaving the status visible as static text and dots.+- No protocol, storage, or runtime behavior changes.+See ADR 0149.## 2026-09-04 — Replace the empty-home mascot sprite with a calm inline agent mark (D291)-Replace the randomized raster pose atlas in the empty-home hero with a 100px inline SVG containing a compact neutral agent, a thin orbit, and one signal point. See ADR 0150.+- The randomized raster pose atlas in the empty-home hero is replaced by a 100px inline SVG: a compact neutral agent, a thin orbit, and one signal point, with the core breathing slowly and the eyes blinking occasionally.+- The mark is deterministic and decorative; hover changes neither cadence nor geometry, and reduced motion freezes its CSS animation at the same size, placement, and semantic colors.+- No protocol, storage, or runtime behavior changes.+See ADR 0150.## 2026-09-04 — Keep the work panel inside the fixed application window (D292)-- The work panel remains an in-flow right column. Opening and collapsing it- animates flex allocation inside the existing client area instead of expanding- or shrinking the native BrowserWindow.-- The renderer-owned inner divider adjusts the persisted `244..720px` panel- width; native window edges resize only the application window and never rewrite- the panel preference. Escape, cancellation, and lost pointer capture restore- the press-time panel width.-- The `window/setWorkPanelReservation` seam is retained for compatibility but- normalizes every valid request to `{ requested: 0, reserved: 0 }`. The native- Browser view still follows the renderer-measured panel rectangle. See ADR- 0151 and E2E-056/E2E-160/E2E-167.+- The work panel remains an in-flow right column: opening and collapsing animates flex allocation inside the existing client area instead of expanding or shrinking the native window.+- The renderer-owned inner divider adjusts the persisted `244..720px` panel width, while native window edges resize only the application window and never rewrite the panel preference; Escape, cancellation, and lost pointer capture restore the press-time width.+- `window/setWorkPanelReservation` is retained for compatibility but normalizes every valid request to `{ requested: 0, reserved: 0 }`, and the native Browser view still follows the renderer-measured panel rectangle.+See ADR 0151.## 2026-09-04 — Play an eight-frame waving mascot on empty home (D293)-Replace the empty-home inline SVG agent mark with a processed eight-frame GIF in the existing 100px slot. See ADR 0152.+- The empty-home inline SVG agent mark is replaced by a processed eight-frame GIF in the same 100px slot, holding the idle frame briefly before the wave, with hover changing neither cadence nor geometry.+- Reduced motion swaps the GIF for the still first-frame PNG through CSS, and the mark stays decorative with no random selection, JavaScript timer, or hover state.+- No protocol, storage, or runtime behavior changes.+See ADR 0152.## 2026-09-04 — Theme-specific empty-home mascot GIFs (D294)-Replace the single empty-home mascot GIF with dedicated light and dark eight-frame assets plus matching still PNGs. See ADR 0152.+- The single empty-home mascot GIF is replaced by dedicated light and dark eight-frame assets plus matching still PNGs, with CSS following `document.documentElement[data-theme]` and anything other than `light` taking the dark pair.+- Reduced motion still swaps to the active theme's first-frame PNG, and playback, hover, and the decorative role are unchanged.+- No protocol, storage, or runtime behavior changes.+See ADR 0152.## 2026-09-04 — Notification inbox lists failures only (D295)@@ -1963,9 +2336,14 @@ Replace the single empty-home mascot GIF with dedicated light and dark eight-franew scheme per file. No protocol, storage, or runtime behavior changes.Supersedes the stroke rows of §6.4 in the UI design system and the D1480.5px field stroke.+## 2026-09-05 — Streaming replies are checkpointed and recovered (D299)-The assistant reply currently streaming in a session is checkpointed by Electron main to host-core at most every 1.5 s (`session.saveInflightMessage`) into `sessions/<id>.inflight.json`, one atomically replaced file per session. See ADR 0153.+- Streaming replies are checkpointed to `sessions/<id>.inflight.json` every 1.5 s, so a quit, crash, or restart no longer loses text already watched.+- The file is transient: a final row, a clean turn end, or the boot sweep removes it or lands a leftover as `aborted`.+- Quit flushes and waits 2 s, and renderer Stop settles in memory instead of rewriting the transcript.++See ADR 0153, E2E-171.## 2026-09-05 — Composer drafts survive remounts and window switches (D301)@@ -2029,7 +2407,11 @@ The assistant reply currently streaming in a session is checkpointed by Electron## 2026-09-05 — New Task reveals the empty destination before host IO (D305)-New Task used to await `session.list`, `session.create`, another `session.list`, and `session.get` before leaving the previous transcript. Related decisions: D252. See ADR 0113, ADR 0154.+- New Task awaited four host calls before leaving the old transcript, so the click felt stuck.+- Creating a session now clears the previous conversation on the first frame and inserts the durable row from the `session.create` summary, and keystrokes typed during create move onto it.+- Decision D305 amends D252 / ADR 0113 timing only.++See ADR 0154, E2E-011a / E2E-011d / E2E-011g.## 2026-09-05 — Startup splash shares the macOS sidebar glass (D304)@@ -2104,11 +2486,18 @@ New Task used to await `session.list`, `session.create`, another `session.list`,## 2026-09-05 — Zhipu / Z.AI named endpoint presets (D308)-Adding 智谱 required knowing which of four URLs to paste. Related decisions: D024. See ADR 0155.+- Four Zhipu URLs required guesswork, so the dialog now offers named presets for China and international API plus GLM Coding Plan, filling the name and locking the Base URL.+- Rows stay `openai_compatible` + `chat_completions`, and a matching URL or `vendorKey` sets `thinkingFormat: "zai"` and `zaiToolStream: true` because the stored id is a UUID.+- Decision D308 amends D024.++See ADR 0155, E2E-005D.## 2026-09-05 — Add-provider common path is Service + key (D309)-The add-provider form stacked Service, Name, Base URL, API key, and API format. Related decisions: D308. See ADR 0156.+- The form stacked five fields even though named endpoints know their name, URL, and format, so it now starts with Service and shows only Service, API key, and a host summary.+- Custom endpoint adds Name and Base URL, and OpenCode Go moves into the Service select. Decision D309 amends D308.++See ADR 0156, E2E-005 / E2E-005B.## 2026-09-05 — Custom format beside the key; top models.dev vendors (D310)@@ -2143,35 +2532,59 @@ The add-provider form stacked Service, Name, Base URL, API key, and API format.## 2026-09-05 — Shipped locale registry and language picker (D314)-Language in Settings → General was three preview cards (Auto / 简体中文 / English). Related decisions: D073. See ADR 0160.+- Language was three hard-coded cards; locales now ship from `@pi-desktop/i18n` (`en`, `zh-CN`, `tr`) with endonyms, and Auto still follows `app.getLocale()`.+- Language becomes a searchable picker while Theme keeps its cards, and plugin labels stay `en` + `zh-CN`. Decision D314 amends D073.++See ADR 0160, E2E-091.## 2026-09-05 — Grep prefers a system `rg` when installed (D315)-Codex searches with shell `rg` when the machine has it. Related decisions: D195. See ADR 0057.+- Grep stays the model-facing tool but uses a user-installed `rg` when one is on the process or login PATH.+- The result shape, budget, ordering, and ignore rules stay host-defined; `rg` runs with argv and null stdin, falling back to the in-process searcher. Decision D315 amends ADR 0057 / D195.++See ADR 0057, E2E-147.## 2026-09-05 — Searchable theme picker (D316)-Theme in Settings → General was three preview cards (System / Light / Dark), with plugin themes wrapping into the same grid. See ADR 0160, ADR 0161.+- Theme was three cards with plugin themes wrapped into the same grid, and now uses the Language picker's searchable form: System, Light, and Dark pinned above plugin themes.+- `AppSettings.theme` and the unavailable-plugin fallback to `system` are unchanged. Decision D316 amends ADR 0160.++See ADR 0161, E2E-091.## 2026-09-05 — A2A addressing spans sessions on the same host (D318)-Decision D318 amends ADR 0147. The local A2A broker stays in host-core with capability-token auth and durable tasks; same-context-only discovery and send are lifted so two A2A-capable delegates in different open sessions can coordinate. See ADR 0147, ADR 0162.+- Decision D318 amends ADR 0147: the same-host A2A broker keeps capability-token auth and durable tasks but lifts same-context-only discovery and send, so delegates in different open sessions coordinate.+- Peer ids become registry-unique, `a2a.task.event` / `a2a.push` carry `recipientContextId`, and task access follows membership; parents still cannot call `A2A`, and nothing nests.++See ADR 0162, E2E-165c.## 2026-09-05 — Live/durable transcript merge keeps chronological order (D317)-Revalidating a running session used the bounded durable page as the array prefix and appended every live-only row after it. Related decisions: D261. See ADR 0120, ADR 0137.+- Revalidation used the bounded durable page as prefix and appended live rows after it, so a long session hid the just-sent prompt under old history.+- `mergeLiveSessionMessages` now stitches chronologically and prefers the durable copy on overlap. Decision D317 amends ADR 0120 / D261 / ADR 0137.++See ADR 0120 / ADR 0137, E2E-177.## 2026-09-05 — Restore a missing sessions row from its transcript / outbox (D318)-A long session could vanish from the sidebar and reset the transcript to the first user row while hundreds of turns sat in `session-message-outbox.json`. Related decisions: D119. See ADR 0041.+- A vanished `sessions` row made `session.appendMessage` fail and froze the outbox, hiding hundreds of turns behind a reset transcript.+- Boot now restores every live JSONL whose row is missing, the append restores or inserts a stub, and delete drops outbox entries. Decision D318 amends ADR 0041 / D119.++See ADR 0041, E2E-178.## 2026-09-05 — Parent agents collaborate across conversations (D321)-Decision D321 amends ADR 0147 / ADR 0162. See ADR 0147, ADR 0162, ADR 0164.+- Decision D321 amends ADR 0147 / ADR 0162: Agent-mode runtimes register a `kind: "parent"` A2A card for their lifetime and expose `A2A` as a core parent tool.+- Discovery and send are kind-scoped, and an idle session prepends inbound parent events to the next prompt instead of starting a turn.++See ADR 0164, E2E-165d.## 2026-09-05 — Sent file references stay chips and open on click (D320)-Composer chips serialized to full `@path` text in the user bubble, so the node the user placed in the input became a long path after send. Related decisions: D209. See ADR 0070, ADR 0163.+- Chips serialized to full `@path` text in the bubble, so a placed node became a long path and scratch files were not clickable.+- The transcript now renders leaf-name chips, opening workspace HTML in the side browser and other allowed files through `pi-desktop/fs/open`. Decision D320 amends D209 / ADR 0070.++See ADR 0163, E2E-180.## 2026-09-05 — Relative transcript paths preview and open (D322)@@ -2197,31 +2610,52 @@ Composer chips serialized to full `@path` text in the user bubble, so the node t## 2026-09-05 — Idle session switch keeps a not-yet-flushed completed tail (D324)-After a turn finished, switching away and back reloaded the durable `session.get` page and dropped assistant/tool rows that were still only in the renderer (the persistence outbox had not flushed them yet). Related decisions: D317. See ADR 0137.+- An idle switch reloaded the durable page and dropped assistant and tool rows still only in the renderer.+- `selectSession` now merges live rows for an idle session until the durable page holds every live id. Decision D324 amends D317 / ADR 0137.++See ADR 0137, E2E-183.## 2026-09-05 — Parent A2A is always in the Agent catalog (D325)-D321 registered the parent only after a successful broker mint, then injected `A2A` into the catalog. Related decisions: D321. See ADR 0164.+- D321 registered the parent only after a successful broker mint, so a failed register left no `A2A` tool, and `ToolSearch` never lists core tools.+- Agent mode now puts `A2A` in the core catalog at construction and mints on first use. Decision D325 amends ADR 0164 / D321.++See ADR 0164, E2E-165d.## 2026-09-05 — Withdraw A2A and Peer coordination (D326)-The in-process `Peer` mailbox (D277 / ADR 0138 / ADR 0140) and the host-core A2A stack (ADR 0147 / ADR 0162 / ADR 0164 / D318 / D321 / D325) are withdrawn. Related decisions: D277, D318, D321, D325. See ADR 0138, ADR 0140, ADR 0147, ADR 0162, ADR 0164, ADR 0165.+- The `Peer` mailbox (D277 / ADR 0138 / ADR 0140) and the host-core A2A stack (ADR 0147 / ADR 0162 / ADR 0164 / D318 / D321 / D325) are withdrawn.+- `A2A` and `Peer` are no longer tools or `ToolSearch` results; handshake moves 10→11, and storage 12→13 drops the A2A tables. Decision D326 is ADR 0165, superseding ADR 0147, ADR 0162, and ADR 0164.++See ADR 0165, E2E-165.## 2026-09-06 — Completed replies survive process restart (D327)-Closing the app after a finished turn reloaded only user prompts (issue #42). Related decisions: D324, D299. See ADR 0153, ADR 0041.+- Closing the app after a turn reloaded only prompts, because assistant rows still waited in the outbox that D324 kept only in memory.+- `message_end` now checkpoints the snapshot before that append, and the handshake awaits the drain. Decision D327 amends D299 / ADR 0153 / ADR 0041.++See ADR 0153 / ADR 0041, E2E-171, E2E-184.## 2026-09-06 — Parent-judged subagent lifetime (D328)-The parent agent was aborting unfinished delegates because `TaskWait` expired, the model closed, and `agent_end` killed leftover runs. See ADR 0089, ADR 0119, ADR 0129, ADR 0166.+- The parent aborted unfinished delegates on `TaskWait` expiry, model close, and `agent_end`, with idle and duration watchdogs as a second kill.+- Decision D328 amends ADR 0089 / ADR 0119 / ADR 0129: no timers, no abort on parent idle, reports in the same turn, and only `TaskStop` or user Stop aborts.++See ADR 0166, E2E-155.## 2026-09-06 — Agent-chosen Bash timeout (D329)-The 300-second Bash override ceiling killed long builds and rejected explicit `timeout: 600` / `1800`. Related decisions: D190, D273. See ADR 0054, ADR 0167.+- The 300-second ceiling killed long builds and rejected explicit `timeout: 600` / `1800`; the 60-second default stands.+- Decision D329 amends D190 / D273 / ADR 0054: honour 1–21,600 seconds and read larger values as milliseconds.++See ADR 0167, E2E-115.## 2026-09-06 — Main-owned openExternal allowlist (D330)-Chat markdown, plugin panels, the launcher, OAuth, and the embedded preview could hand a raw URL to `shell.openExternal`. See ADR 0109, ADR 0168.+- Chat markdown, plugin panels, the launcher, OAuth, and the preview could hand any URL to `shell.openExternal`, reaching OS handlers for `file:`, `javascript:`, or custom schemes.+- Main now opens only http(s) with a hostname and `mailto:` with an address, throwing otherwise. Decision D330 amends ADR 0109.++See ADR 0168, E2E-185.## 2026-09-06 — Accepted `@` files stay as inline chips (D362)@@ -2239,55 +2673,94 @@ Chat markdown, plugin panels, the launcher, OAuth, and the embedded preview coul## 2026-09-06 — Bundled Files preview and live workspace events (D332)-The Files plugin could not preview images, did not expose Open with default app after reveal replaced the header action, polled for project switches, and missed theme/locale events while docked. See ADR 0169.+- The Files plugin could not preview images, lost its Open action, and missed project, theme, and locale events while docked.+- `fs.readPreview` now classifies one file as text, image, binary, or tooLarge under the existing `fs.read` gate, and `workspace:changed` reaches docked panels. Decision D332 is ADR 0169.++See ADR 0169, E2E-153.## 2026-09-06 — Work-panel browser is the bundled `pi.browser` plugin (D333)-The work-panel Browser launcher, chrome, and agent CDP were a host-built `HEADER_TOOLS` row plus a Main-owned guest. See ADR 0019, ADR 0104, ADR 0105, ADR 0108, ADR 0170.+- The Browser launcher, chrome, and agent CDP were a host-built row, while Files had proved a bundled plugin can own a first-party surface.+- Bundled `pi.browser` now owns chrome and the `Browser` tool, with the guest view and debugger host-owned behind `pi.browser.*` gated by `browser.cdp` and raw CDP allowlisted. Decision D333 amends ADR 0019 / 0104 / 0105 / 0108.++See ADR 0170, E2E-008b.## 2026-09-07 — Contained in-chat image display (D334)-Pasted/uploaded images are stored as extension-less `attachments/<sha256>` blobs. See ADR 0172.+- Images are extension-less `attachments/<sha256>` blobs the renderer origin cannot load, so history showed a chip instead of the picture.+- `fs/read`, `fs/reveal`, and `fs/open` now share `resolveOpenablePath`, and `fs/readImageDataUrl` returns a bounded data URL. Decision D334 is ADR 0172.++See ADR 0172, E2E-187.## 2026-09-07 — Host-owned plugin completions and session context (D336)-Plugins could register tools but could not list authenticated models, read the current LLM context, or spend the user's provider quota on a side call. Related decisions: D019. See ADR 0174.+- Plugins could register tools but not list models, read the LLM context, or spend the user's quota on a side call.+- `pi.models.list`, `pi.session.getLlmContext`, and `pi.agent.complete` are host APIs with credentials kept in main, and context binds to the in-flight session (D019 amended). Decision D336 is ADR 0174.++See ADR 0174, E2E-188 / E2E-189.## 2026-09-07 — OpenCode Go session routing headers (D337)-OpenCode Go rejects LLM requests that omit `x-opencode-session` (`MissingSessionID`). pi-ai 0.85 does not emit that header; the official Pi coding-agent injects it in the agent layer. See ADR 0116.+- OpenCode Go rejects requests without `x-opencode-session`, which pi-ai 0.85 never emits.+- Decision D337 amends ADR 0116: agent-runtime sends that header, `x-opencode-client: pi-desktop`, and a PI-Desktop `User-Agent` to OpenCode Go and `opencode.ai` hosts, keyed by the durable conversation id.++See ADR 0116, E2E-005D.## 2026-09-07 — Explain quiet active turns with live agent activity status (D338)-The transcript showed a generic running timer before the first event, but a provider wait, retry backoff, or parent-side delegated-work wait could still leave no row that explained the delay. See ADR 0175.+- A provider wait, retry backoff, or delegated-work wait explained nothing, so users could only infer activity from Stop.+- The `status` event now carries a runtime-owned `AgentActivity` phase (`starting`, `waiting-model`, `retrying`, `waiting-subagents`) rendered as one compact localized row. Decision D338 is ADR 0175.++See ADR 0175, E2E-008c / E2E-094.## 2026-09-07 — Per-provider User-Agent override (D339)-Gateways and vendor subscriptions inspect User-Agent. pi-ai, Anthropic OAuth, OpenCode, and Codex each stamp a different default, and Codex overwrites User-Agent after extra headers. See ADR 0176.+- Every adapter stamps a different User-Agent, Codex overwrites it, and the schema listed `headers` without storing them.+- Decision D339 lets a service row store optional `config_json.userAgent` as the last-writer header on its own outbound HTTP, Advanced UI only and included in `matches()`.++See ADR 0176, E2E-005G.## 2026-09-08 — Per-provider custom HTTP headers (D341)-Gateways need more than User-Agent. ADR 0176 left the schema `headers` map unimplemented and used a sparse single-field Advanced editor. See ADR 0176, ADR 0178.+- ADR 0176 left the schema `headers` map unimplemented behind a sparse single-field editor.+- Decision D341 stores optional `config_json.headers` as last-writer on the row's HTTP, migrates a leftover `userAgent` into `headers["User-Agent"]`, and rejects reserved auth and hop-by-hop keys.++See ADR 0178, E2E-005G.## 2026-09-08 — User-configurable outbound proxy (D340)-Model calls, marketplace downloads, updates, and the in-app browser each used a different HTTP stack, and none of them honored a product setting. See ADR 0177.+- Four HTTP stacks each ignored the OS proxy, so no product setting could route model calls, downloads, updates, or the browser.+- Settings → General → Network adds System / Direct / Custom shared by Chromium, `net.fetch`, sidecar undici, and marketplace curl, and workspace Bash inherits no credentials. Decision D340 is ADR 0177.++See ADR 0177, E2E-190.## 2026-09-08 — Main-owned picker capabilities (D344)-The composer picker previously returned native absolute paths to the renderer, which could then replay arbitrary paths through `composer/importFiles`; it also advertised folders while the importer rejected directories. See ADR 0181.+- The picker returned absolute paths the renderer could replay, and advertised folders the importer rejected.+- Picker IPC now keeps chosen paths in main behind a short-lived, sender-bound one-shot token, and import accepts only that token. Decision D344 is ADR 0181.++See ADR 0181, E2E-102h.## 2026-09-08 — Custom global UI type scale (D343)-The `--text-*` ramp is a frozen set of relative sizes. See ADR 0180.+- The `--text-*` ramp is a frozen relative set, and window zoom would leave two type sizes in one window.+- Appearance adds Tall / Grande / Venti / Trenta presets and an 80%–150% slider persisted as `AppSettings.fontScale`, setting `--font-scale` for text and icons. Decision D343 is ADR 0180.++See ADR 0180, E2E-193.## 2026-09-08 — P0 international shell locales (D346)-Ship complete German, Spanish, and French shell catalogs, searchable native names, regional base-locale resolution, and matching in-app changelog catalogs. See ADR 0183.+- Decision D346 ships German, Spanish, and French shell catalogs with native names, regional base-locale resolution, and matching changelogs.+- `AppSettings.language` gains `de`, `es`, and `fr` without a protocol, schema, or IPC version change.++See ADR 0183, E2E-091.## 2026-09-08 — Composer-docked context usage inspector (D347)-The compact context inspector hung under the newest assistant turn and scrolled out of reach. Related decisions: D297. See ADR 0184.+- The inspector hung under the newest assistant turn and scrolled out of reach, so its single entry moves beside the model picker rather than duplicating the numbers.+- Decision D347 docks it in the composer toolbar, mirroring the last usage-bearing turn, with no inner section rules (D297).++See ADR 0184, E2E-060d.## 2026-09-08 — macOS sidebar uses the source-list vibrancy material (D348)@@ -2310,51 +2783,86 @@ The compact context inspector hung under the newest assistant turn and scrolled## 2026-09-08 — Session title summaries and focus-aware native task notifications (historical title decision superseded by D652; D350 remains active)-At the time, the initial prompt appeared immediately as a normalized 48-character fallback. Related decisions: D117. See ADR 0323, ADR 0186, ADR 0187.+- The first prompt showed a 48-character fallback, and after one turn Electron ran a main-owned `session/summarizeTitle` one-shot that the renderer persisted through `session.rename`; D652 / ADR 0323 removed that and made titles an optional plugin.+- Task alerts are suppressed while the window is visible and focused, interactive prompts keep exact-visible-session suppression, and durable insertion stays D117's visibility decision.++See ADR 0186 / ADR 0187, E2E-021a / E2E-065.## 2026-09-08 — Preserve distinct credentials during model configuration import (D351)-CC Switch can store multiple named profiles at one gateway endpoint. Related decisions: D342. See ADR 0179, ADR 0188.+- CC Switch can hold several named profiles at one gateway, and endpoint-only matching skipped the ones with different keys.+- Import equivalence now includes the credential, so those profiles become independent providers while unchanged ones stay idempotently skipped, and keys stay behind the host secret boundary. Decision D351 amends D342 and ADR 0179 as ADR 0188.++See ADR 0188, E2E-209.## 2026-09-08 — Parent fatal error aborts leftover delegates (D352)-D328 kept leftover delegates running after parent idle so long jobs could finish. Related decisions: D328. See ADR 0166, ADR 0189.+- D328 kept delegates alive after parent idle, yet a terminal parent 429 closed the durable turn while a subagent on another model stayed `isRunning`.+- Decision D352 amends D328 / ADR 0166: parent idle is unchanged, a terminal parent error aborts leftovers, skips the resume prompt, and keeps the failed card.++See ADR 0189, E2E-155.## 2026-09-09 — Disambiguate Intel macOS release artifacts (D353)-The native macOS lanes could produce generic version-only installer names, making the Intel download easy to confuse with the arm64 download. Related decisions: D285. See ADR 0145.+- Version-only installer names made the Intel download easy to confuse with the arm64 one.+- Decision D353 amends D285 / ADR 0145: the x64 lane publishes `-Intel.dmg` and `-Intel-mac.zip` with its feed keeping those URLs and checksums, while arm64 keeps the generic names.++See ADR 0145, E2E-092.## 2026-09-09 — Label both macOS release architectures (D354)-D353 left the arm64 macOS asset with a generic version-only name while using `-Intel` only for the x64 asset, so `PI-Desktop-0.14.4.dmg` still did not identify its architecture. Related decisions: D353. See ADR 0145.+- D353 used `-Intel` only for x64 and left arm64 generic, so the name still did not identify its architecture.+- Decision D354 amends D353 / ADR 0145: both lanes publish `-arm64` or `-x64` DMG and ZIP suffixes, with the per-architecture feeds keeping the URLs.++See ADR 0145, E2E-092.## 2026-09-09 — Last-request occupancy in the context inspector (D355)-The composer inspector mixed last-message occupancy with a visual-turn sum, so cache read and turn total could exceed the context window after a tool loop. Related decisions: D103, D184, D244, D347. See ADR 0047, ADR 0103, ADR 0184, ADR 0193.+- The inspector mixed last-message occupancy with a visual-turn sum, so cache read plus turn total could exceed the window after a tool loop.+- Decision D355 amends D103 / D184 / D244 / D347 / ADR 0047 / ADR 0103 / ADR 0184: every count and cache figure reads the last usage-bearing assistant message, with `reasoningTokens` never added again because `output` already contains it.++See ADR 0193, E2E-060d.## 2026-09-09 — Optional subagent thinking override and readable selected levels (D356)-The subagent editor now offers inherit-session, do-not-send, and the seven canonical thinking levels. See ADR 0194.+- The subagent editor now offers inherit-session, do-not-send (`thinkingLevel: omit`), and the seven canonical levels.+- `omit` keeps bookkeeping at `off` but uses the low-level provider stream, and selected thinking chips get an accent/inverted state. Decision D356 is ADR 0194.++See ADR 0194, E2E-203.## 2026-09-09 — Viewport-fixed work panel toggle (D357)-Decision D357 amends D128 / D207 / D221 and ADR 0068 / ADR 0085. Related decisions: D128, D207, D221. See ADR 0068, ADR 0085, ADR 0195.+- Decision D357 amends D128 / D207 / D221 and ADR 0068 / ADR 0085: AppShell owns one viewport-fixed toggle at the top-right of every non-Settings route, the pointer equivalent of `Cmd/Ctrl + J`.+- It is the sole panel-level collapse control, the header keeps resource close only, and no IPC or native menu command is added.++See ADR 0195, E2E-056 / E2E-070.## 2026-09-09 — Windows portable exe without installer (D364)-Windows tag releases published only `PI-Desktop-Setup-<version>.exe`, which company environments that whitelist a single executable or block installers cannot run. Related decisions: D120, D126. See ADR 0022, ADR 0197.+- Installer-only Windows releases blocked environments that whitelist a single executable.+- Decision D364 amends D120 / D126 / ADR 0022: the x64 lane adds `PI-Desktop-Portable-<version>.exe` with notify-and-link updates and no `latest.yml`, keeping the existing data directory and user execution level.++See ADR 0197, E2E-211.## 2026-09-22 — Trust the network endpoints the user enters themselves (D604)-An endpoint the user typed themselves — a model base URL, an MCP server, a market source, a git remote, a generated-image URL — may resolve to loopback, RFC1918, CGNAT, link-local, ULA, site-local or `.local`. See ADR 0304.+- An endpoint the user typed themselves may resolve to loopback or private ranges, and plain `http` there is usable.+- One switch decides it: `settings.networkPolicy.mode`, `relaxed` by default otherwise `strict`, replacing the per-surface acknowledgements and migrating a stored `allowInsecureUserEndpoints: false`.+- Third-party content keeps the public-only policy, cloud metadata and reserved addresses stay refused, and the proxy bypass list gains the private ranges.++See ADR 0304.## 2026-09-22 — Windows portable delivery uses a normal ZIP (D603)-Decision D603 amends D364 / ADR 0022 / ADR 0197. Related decisions: D364. See ADR 0022, ADR 0197.+- Decision D603 amends D364 / ADR 0022 / ADR 0197: the x64 lane publishes a `PI-Desktop-Portable-<version>.zip` stamped `piDistribution = "zip"` and writes no `latest.yml`.+- Users extract and run `PI-Desktop.exe`, keeping notify-and-link updates while the updater still recognizes `PORTABLE_EXECUTABLE_FILE`.++See ADR 0197, E2E-211.## 2026-09-09 — Name every quiet interval on the live activity row (D365)-ADR 0175 named only `waiting-model`, `retrying`, and `waiting-subagents`. Related decisions: D338, D366, D367, D376, D374, D375. See ADR 0175, ADR 0198, ADR 0200, ADR 0199.+- ADR 0175 named only three phases, so compaction, silent-turn recovery, the post-tool gap, and `starting` still looked like a stuck generic wait.+- Decision D365 amends D338 / ADR 0175: `AgentActivity` adds `preparing`, `compacting`, and `recovering`, and `waiting-subagents` carries a live child snapshot without restoring a capsule.> D366 is unassigned. It was first used for the plugin session import decision,> which was renumbered to D367 / ADR 0200 while syncing with `main`, and then@@ -2364,57 +2872,99 @@ ADR 0175 named only `waiting-model`, `retrying`, and `waiting-subagents`. Relate> amendment it briefly carried to D374 and assigned D375 to the rollout> sequence, so D376 stays retired too.+See ADR 0198, E2E-008c / E2E-094.+## 2026-09-09 — Host-owned plugin session import and ownership API (D367)-External-history plugins need durable import/read/update/delete operations, but the existing in-flight `session.getLlmContext` and core `session.import` boundaries are not safe plugin ownership boundaries. See ADR 0200.+- External-history plugins need durable import and ownership, and the in-flight context read plus core `session.import` are not safe boundaries.+- Decision D367 / ADR 0200 adds `pi.session` import, batch, list, get, messages, rename, and delete behind `contributes.sessionSources`, with host-generated ids and `(pluginId, source, externalId)` scoping; schema v14 adds `session_import_origins`.++See ADR 0200, E2E-214/E2E-215.## 2026-09-09 — Explicit plugin project ids and host-owned session refresh (D368)-Imported sessions need an explicit way to belong to a durable project, but exposing `workspace.set` to plugins would also change the user's active workspace. See ADR 0201.+- Plugins needed explicit project membership without changing the user's active workspace, plus a host-owned refresh path.+- Decision D368 / ADR 0201 adds `pi.project.create({ path })`, accepts an existing `projectId` in imports, and emits `pi-desktop/session/event/changed` after writes so the renderer can refresh.++See ADR 0201, E2E-216.## 2026-09-09 — Effective subagent thinking metadata (D369)-Delegation cards need the thinking level actually passed to each child run, not a value re-derived from the parent or definition after the target model clamps it. Related decisions: D395. See ADR 0202, ADR 0221.+- Cards need the level actually passed to each child, not one re-derived after the model clamps it.+- Decision D369 / ADR 0202 adds effective `modelId` and `thinkingLevel` to `Task`, `SubagentRunResult`, and lifecycle snapshots, shown as the raw non-`off` level; D395 / ADR 0221 removes canonical translation.++See ADR 0202, E2E-219.## 2026-09-09 — Explicit unsigned macOS first-launch helper (D371; amended by D406)-The default macOS lane remains unsigned, and a downloaded trusted artifact can still be blocked by Apple's quarantine check with a misleading damaged-app message. See ADR 0204.+- An unsigned build can still be blocked by quarantine with a misleading damaged-app message, and the old `xattr -cr` note was terminal-only and too broad.+- Decision D371 / ADR 0204 ships `PI-Desktop-macOS-open.command` in a visible DMG first-launch row, which verifies `com.pi-desktop.app` and clears only `com.apple.quarantine`, never using `sudo`.++See ADR 0204, E2E-196b.## 2026-09-09 — Local MCP control plane for desktop operations (D370)-An external Agent needs to drive the running desktop for project, session, Agent, workspace, and reviewed application operations, while the deferred remote Gateway / WebUI boundary remains unchanged. See ADR 0203.+- An external Agent needs to drive the desktop while the deferred remote Gateway boundary stays unchanged.+- Decision D370 / ADR 0203 adds an opt-in loopback Streamable HTTP MCP server in main with a bearer token, Origin checks, a mode-restricted manifest, and the same IPC handlers the renderer uses.++See ADR 0203, E2E-220.## 2026-09-10 — Tighten the local MCP control-plane boundary (D372)-D370's first catalog still exposed native pickers (`plugin/loadDev`), secret-write provider/OAuth/MCP paths, and `session/configure` without confirmation, and treated session reads as renderer mutations. Related decisions: D370. See ADR 0203.+- D370's catalog still exposed native pickers, secret-write paths, and an unconfirmed `session/configure`, and read session reads as mutations.+- Decision D372 amends ADR 0203 by narrowing the v1 catalog, stripping secret-shaped arguments, negotiating protocol versions, and bounding results.++See ADR 0203, E2E-220.## 2026-09-10 — Remote Agent Control uses a dedicated Host boundary (D373)-Remote control is a post-MVP capability and must not expose the existing Electron IPC, `host.proxy`, or Rust host-core stdio boundary. See ADR 0205.+- Remote control must not expose Electron IPC, `host.proxy`, or the host-core stdio boundary.+- Decision D373 / ADR 0205 defines a logical Agent Host owning sessions, turns, cursors, approvals, and recovery, with a Gateway owning identity and the Host connecting outbound; RACP v1 keeps one operation model across WebSocket, HTTP/SSE, and gRPC.++See ADR 0205, E2E-221 through E2E-230.## 2026-09-10 — Amend the remote Agent Control target before implementation (D374)-A review of the D373 draft against the shipped desktop found that the remote approval vocabulary was narrower than the local `allow-once` / `allow-session` / `deny` and Plan/Goal permission-mode contracts, that pending permission requests were connection state rather than Host state, that per-token deltas would exhaust the replay window, that three required bindings … Related decisions: D373. See ADR 0205.+- Review found the remote approvals narrower than the local vocabulary, pending permissions held as connection state, and three bindings beyond v1.+- Decision D374 amends ADR 0205: `RACP-WS` is normative with HTTP as the browser profile, typebox is the single contract source, and `packages/agent-host` is the first deliverable.+- Cursors become `{ epoch, sequence }`, the turn queue moves into the Host, approvals keep the full vocabulary under a default `ask` ceiling, and deployment is single-tenant.++See ADR 0205, E2E-221 through E2E-230.## 2026-09-10 — Sequence remote control around recorded demand (D375)-Issues #176 and #140 ask to operate projects on a remote Linux or WSL machine from the local desktop; issue #100 asks for task and approval notifications on Telegram, WeChat, Slack, or a webhook with simple commands back. See ADR 0205.+- Issues #176 and #140 ask for remote project operation over SSH and #100 for chat notifications, while no one asked for a browser client.+- Decision D375 amends ADR 0205 again: R2 is the SSH-tunnel remote Host with a checksummed `pi-host` bundle, port forward, and unchanged renderer, gaining the remote-host profile and tool relay, and R3 becomes outbound messaging with webhook first.++See ADR 0205, E2E-231 / E2E-232.## 2026-09-10 — Remote control stays user-local: no first-party identity (D385)-The maintainer requires that a user's client never authenticate through a service the project operates and that remote control stay entirely on the user's own machines and infrastructure. Related decisions: D375. See ADR 0205.+- The maintainer requires that no client authenticate through a service the project operates.+- Decision D385 amends ADR 0205 a third time and withdraws D375 item 10: the only credential is a Host-issued device token, any Gateway is user-hosted, and OIDC federation is out of scope.++See ADR 0205.## 2026-09-10 — Persist the Host-owned turn queue in host-core (D386)-D375 moved queued prompts into the Host and chose persistence; the headless Agent Host module needs a store that survives a restart and never starts work by itself, and host-core owns SQLite exclusively. Related decisions: D375. See ADR 0213.+- D375 left the Host owning queued prompts, so persistence needs host-core's SQLite and a store that never starts work by itself.+- Decision D386 / ADR 0213 adds schema v15 `turn_queue` with `queuePush`, `queueList`, `queueRemove`, and `queuePrioritize`: idempotent, capped at eight, and drained only after a terminal event.++See ADR 0213.## 2026-09-10 — Trusted extensions run in the Agent sidecar (D387)-Plugins are sandboxed and run outside the agent, which is right for distributed, untrusted code but leaves no surface for code that must sit on the agent loop itself: tools that execute in-process, hooks on every turn and provider request, and slash commands with session context. Related decisions: D007. See ADR 0214.+- Plugins are sandboxed outside the agent, leaving no surface for in-process tools, per-turn hooks, and commands with session context.+- Decision D387 / ADR 0214 adopts the `pi-coding-agent` `ExtensionAPI` in the sidecar, disabled until enabled per entry, with D007 intact and unsupported members inert rather than throwing.++See ADR 0214, E2E-241 to E2E-245.## 2026-09-10 — Extend provider retries and show bounded progress (D378)-The runtime-owned provider retry budgets surfaced short provider outages earlier than the product target, and the active-turn row showed only a retry number without the current wait or its bound. Related decisions: D245, D259. See ADR 0091, ADR 0128, ADR 0206.+- The retry budgets surfaced short outages too early, and the active row showed only a retry number with no wait or bound.+- Decision D378 amends D245 / D259 and ADR 0091 / ADR 0128: ten retries per error class, nested retries off, an 8-second cap, and a countdown with the attempt bound.++See ADR 0206, E2E-096 / E2E-149.## 2026-09-10 — Name downgraded and non-native builds at boot (D380)@@ -2435,35 +2985,64 @@ The runtime-owned provider retry budgets surfaced short provider outages earlier## 2026-09-10 — Allow three same-path mutation recovery failures (D379)-The previous repeat guard ended a prompt after two counted failures on one `Edit` path or recognized shell patch key. Related decisions: D186. See ADR 0087, ADR 0207.+- Two counted failures ended a prompt while the model was still applying a distinct recovery hint.+- Decision D379 amends D186 and ADR 0087 / ADR 0207: three counted failures per prompt, then `terminate: true` with `MUTATION_RETRY_BUDGET_EXHAUSTED`, which also covers shell patch commands.++See ADR 0207, E2E-140 / E2E-141.## 2026-09-10 — Plugin desktop control requires native user consent (D377)-A code and documentation review found that a plugin holding `desktop.control` could run `dangerous` catalog operations (session delete, permission-mode change, tool approval) with no human in the loop: the shared controller's `confirm: true` is set by the plugin itself, and the only confirmation was whatever card the plugin chose to draw. Related decisions: D372. See ADR 0208.+- A plugin holding `desktop.control` could run `dangerous` operations with no human in the loop, and the review also found redirect escapes and uncontained plugin paths.+- Decision D377 (ADR 0208) requires the plugin's `confirm: true` and then the user's answer to a host-owned native dialog naming only the operation, with `PERMISSION_DENIED` on refusal; the MCP contract (D372) is unchanged and the fetch, path, denylist, and unknown-session holes are closed.++See ADR 0208, E2E-234 through E2E-238.## 2026-09-10 — PowerShell 7 as a selectable Windows command shell (D381)-Issue #151: a Windows user who installs PowerShell 7 (`pwsh.exe`) had no way to run `Bash` under it. See ADR 0054, ADR 0209.+- PowerShell 7 installs beside the in-box 5.1, so no catalog entry could run `Bash` under `pwsh.exe` (issue #151).+- Decision D381 (ADR 0209) adds the `windows-pwsh` id, amending ADR 0054 §1: it resolves `%ProgramFiles%\\PowerShell\\7\\pwsh.exe` then PATH, and is never selected implicitly.++See ADR 0209, E2E-112.## 2026-09-10 — A settled subagent reads back why it failed (D382)-A delegate that ended `failed`, `timed_out`, or `aborted` showed only its outcome capsule and an elapsed time. See ADR 0089.+- A failed delegate showed only a capsule and elapsed time, because the roster error had no reader.+- Decision D382 collects `error: { code, message }` from the lifecycle rows and closes the dock with an error card that never appears on a completed run.++See ADR 0089, E2E-198.## 2026-09-10 — A delegate can declare its own output limit (D383)-A subagent definition could bound its turns but not its response length. See ADR 0210.+- Definitions could bound turns but not response length without raising `maxTokens` for every caller of the model.+- Decision D383 (ADR 0210) lets a definition declare `maxTokens` under the `maxTurns` spellings with a 200000 ceiling, stored in frontmatter and shown in the Advanced disclosure.++See ADR 0210, E2E-119 / E2E-155.## 2026-09-10 — Plan-safe plugin actions and summon-window shortcut (D384)-*(the summon-window half is superseded by D438, which replaced the pair, and by D439, which moved the toggle off the macOS close-window chord; the plan-safe plugin-action opt-in below stays)* Related decisions: D438, D439. See ADR 0052, ADR 0053, ADR 0211.+*(the summon-window half is superseded by D438, which replaced the pair, and by+D439, which moved the toggle off the macOS close-window chord; the plan-safe+plugin-action opt-in below stays)*++- Plan and Goal modes could not invoke plugin tools at all, even read-only actions like fetching a URL through the bundled Browser plugin.+- Decision D384 amends ADR 0052 / ADR 0053 with a per-action `planSafeActions` opt-in that the runtime, host, and desktop runner all enforce; the bundled Browser plugin declares four read-only actions, and the catalog also gained `summonWindow` beside `closeWindow`.++See ADR 0211, E2E-PLAN-005.## 2026-09-17 — One window toggle replaces the summon/close pair (#360, D438)-Issue #360 item 3 asks for the summon-window and hide/close-window global shortcuts to become one key. Related decisions: D384, D435, D437, D439. See ADR 0211.+- Issue #360 item 3 asks for one key, so D438 supersedes exactly the summon/close half of D384, skips D435 and D437 claimed elsewhere, and leaves the plan-safe opt-in intact.+- The catalog ships `toggleWindow`, whose action hides a visible window or shows it without reaching the close-behaviour prompt, and `migrateKeybindingOverrides` folds retired `closeWindow` / `summonWindow` values in both processes; D439 later moved the default off `Mod+W`.++See ADR 0211 (amended), E2E-072.## 2026-09-17 — The window toggle avoids the macOS close-window chord (#360, D439)-D438 merged the pair onto `Mod+W`, but that binding cannot be the default of a *process-wide* accelerator: macOS spends `Cmd+W` on its own close-window command, so claiming it globally takes the chord away from every other application instead of only closing this window. Related decisions: D438, D435, D437, D440. See ADR 0273, ADR 0211.+- A process-wide accelerator cannot default to `Mod+W`, because macOS owns that chord in every other application.+- Decision D439 puts `toggleWindow` on `Alt+Shift+W`, refuses `Mod+W` to plugins, and drops a stored value that only repeats a superseded default while real rebinds and explicit unbinds survive.+- The numbering skips D435 and D437: this log still carries two D438 entries, and the later Git-checkout one needs to move to D440, which this entry does not rewrite.++See ADR 0211 (amended again), E2E-072.## 2026-09-10 — Remove diagnostic timing log streams (D385)@@ -2481,7 +3060,10 @@ D438 merged the pair onto `Mod+W`, but that binding cannot be the default of a *## 2026-09-11 — Agent extensions are a plugin contribution (D388)-D387 shipped ExtensionAPI modules as a second surface with its own registry, settings tab, and enablement store. Related decisions: D387. See ADR 0215.+- D387 shipped its own registry, settings tab, and enablement store, while the maintainer wants one surface where a pi extension is installed, enabled, and scoped like a plugin.+- Decision D388 / ADR 0215 amends D387: modules are `contributes.agentExtensions` gated by the high-risk `agent.extension`, and the standalone registry, store, Settings destination, and its channels are removed.++See ADR 0215, E2E-241 to E2E-245.## 2026-09-10 — DeepSeek reasoning_content replay on aggregators (D389)@@ -2499,173 +3081,192 @@ D387 shipped ExtensionAPI modules as a second surface with its own registry, set## 2026-09-10 — Regenerates truncate under the host RPC lock-Retry, regenerate, and edit-resend used to load the whole transcript in Electron main, archive the discarded tail, and `session.replaceMessages` the kept prefix. Related decisions: D390. See ADR 0216.+- Retry, regenerate, and edit-resend shipped a whole transcript over one NDJSON line, exceeding the 64 MiB stdin cap and racing the 130 s deadline on an 80 MB session (issue #211).+- `session.truncateFrom` now cuts, aborts the leftover turn, and archives the discarded branch inside one host call, and an oversized control-pipe line answers `LIMIT_EXCEEDED` instead of killing the reader. Decision D390 is recorded as ADR 0216.++See ADR 0216, E2E-246.## 2026-09-11 — Host stdout sender must not outlive serve-ADR 0216 stopped regenerate from shipping the kept transcript and stopped an oversize line from killing the stdin reader. Related decisions: D391. See ADR 0216, ADR 0217.+- ADR 0216 was not enough on Windows: the Alt+Space hook held a strong stdout sender, so the writer never stopped after stdin ended and Electron timed out.+- The hook now holds a weak sender, serve waits at most 5 s, and Electron rejects request lines over 64 MiB. Decision D391 is recorded as ADR 0217.++See ADR 0217, E2E-247.## 2026-09-11 — Selection overlay for quotes (D-LOCAL-selection-overlay)-*(Retired by ADR 0268 on 2026-09-16: the feature and its surfaces were removed, and these IDs stay retired and must not be reused. Related decisions: D-LOCAL-message-quotes. See ADR 0268, ADR message-quotes-and-side-chats.+*(Retired by ADR 0268 on 2026-09-16: the feature and its surfaces were removed, and these IDs stay retired and must not be reused. The record is kept for history.)*++- A non-empty selection inside one transcript row floated one overlay above it, clamped into its clipping ancestors and following the thread as it scrolled.+- It offered Add to chat under D-LOCAL-message-quotes's quote contract, Ask in side chat, and Copy, and every action shared one DOM-based excerpt recovery for formulas, code fences, and table rows.++See ADR message-quotes-and-side-chats, E2E-CHAT-selection-markdown.## 2026-09-11 — Response annotations as prompt attachments (D-LOCAL-response-annotations)-*(Retired by ADR 0268 on 2026-09-16: the feature and its surfaces were removed, and these IDs stay retired and must not be reused. Related decisions: D209, D301, D-LOCAL-message-quotes. See ADR 0268, ADR response-annotations, ADR floating-annotation-index.+*(Retired by ADR 0268 on 2026-09-16: the feature and its surfaces were removed, and these IDs stay retired and must not be reused. The record is kept for history.)*++- Selecting text in an assistant turn attached a numbered annotation as renderer-owned session state, never persisted or sent alone.+- A send composed a `# Response annotations:` block and consumed it, leaving the draft, optimistic row, and edit seed clean, so D209's smart Stop and D301's draft retention were untouched.+- Later amendments added a comment editor and the floating index, while D-LOCAL-message-quotes's draft quote still covered user quotes.++See ADR response-annotations, E2E-CHAT-annotation-attachments.## 2026-09-11 — Right panel uses a tab strip and data-driven add menu (D399)-Issue #229 replaces the right panel's combined resource menu with a horizontally scrollable header tab strip and a fixed tight `+` trigger. See ADR 0224.+- Issue #229 replaces the resource menu with a scrollable header tab strip using ARIA tab semantics, plus a fixed `+` trigger that only scrolls its own group.+- The menu has one Tools & panels group fed by `contributes.views` and shared with the New launcher, and the viewport-fixed toggle stays the sole collapse control. Decision D399 is ADR 0224.++See ADR 0224, E2E-056.## 2026-09-11 — Reserve chat width for composer controls (D401)-MainPane and its chat surface retain a 515px minimum when the sidebar or in-flow work panel changes width. Related decisions: D408. See ADR 0226.+- MainPane keeps a 515px minimum when the sidebar or work panel resizes, and the composer toolbar stays on one non-shrinking row with ellipsized mode and permission labels.+- Decision D401 is ADR 0226, and D408 supersedes that floor with a 450px MainChat minimum.++See ADR 0226, E2E-168.## 2026-09-11 — Long-press the project title to reorder (D402)-Retained project groups no longer render a reorder grip. Related decisions: D399, D093. See ADR 0227, ADR 0228.+- Retained project groups lost their reorder grip: a 400 ms still press on the title arms a pointer reorder, and travel beyond 8px before that cancels it so a click still selects.+- Release inserts before or after the target from the pointer's midpoint, and arrow keys stay the keyboard path.+- Decision D402 amends D399 / D093 / ADR 0227. See ADR 0228, E2E-253.## 2026-09-11 — Press-and-move project title reorder (D403)-Mouse and pen reorder by pressing the project title and moving 8px. Related decisions: D402, D093. See ADR 0228, ADR 0229.+- Mouse and pen reorder by pressing the title and moving 8px, while a click with no movement still selects, and touch never starts a reorder so the list scrolls.+- An accent insertion line shows before or after the target. Decision D403 amends D402 / D093 / ADR 0228. See ADR 0229, E2E-253.## 2026-09-11 — Skill ships with the Agent core tool set (D404)-`Skill` joins the Agent-mode core tool set, so its schema is present on the first provider request whenever the skill catalog is non-empty. Related decisions: D174, D185. See ADR 0048, ADR 0219, ADR 0230.+- `Skill` joins the Agent-mode core set, so its schema is present on the first provider request whenever the catalog is non-empty and it never appears under on-demand tools.+- Registration is unchanged: no catalog means no tool, Plan and Goal still omit it, and `ToolSearch` stays lazy. Decision D404 amends D174 / D185 / ADR 0048 / ADR 0219.++See ADR 0230, E2E-254.## 2026-09-11 — Ideographic comma opens the slash menu (D405)-A `、` committed as the first character of an empty composer draft is rewritten to `/` before trigger detection runs, so a Chinese IME reaches the ordinary slash menu without switching input methods. Related decisions: D123, D139. See ADR 0024, ADR 0231.+- A `、` committed as the first character of an empty draft is rewritten to `/` before trigger detection, so a Chinese IME reaches the slash menu without switching.+- Only that position is rewritten; later `、` stays punctuation and the `@` menu is unaffected. Decision D405 amends D123 / D139 / ADR 0024.++See ADR 0231, E2E-255.## 2026-09-12 — Keep macOS DMG opening guidance text-only (D406)-macOS DMGs expose `PI-Desktop-macOS-opening-help.txt` with the Finder label `If app won't open, read this.txt` and no longer include or expose the executable `PI-Desktop-macOS-open.command`. Related decisions: D371. See ADR 0204, ADR 0232.+- macOS DMGs now expose only `PI-Desktop-macOS-opening-help.txt`, labelled `If app won't open, read this.txt`, and no longer ship the executable helper.+- ZIP packages keep both, since the note carries the narrow Terminal fallback trusted unsigned builds need. Decision D406 amends D371 / ADR 0204.++See ADR 0232, E2E-196b.## 2026-09-12 — Restore archived projects after session import (D407)-A core or plugin import that adds a new project-bound session clears the renderer's archived presentation state for that session's normalized project path during the import-triggered refresh. See ADR 0236.+- An import that adds a new project-bound session now clears the renderer's archived presentation state for that normalized path during the import refresh (issue #250).+- Pathless sessions, skipped imports, and ordinary refreshes preserve archive state, and the host model and contracts stay unchanged.++See ADR 0236, E2E-257.## 2026-09-13 — Prioritize MainChat in the three-column shell (D408)-The in-flow shell treats MainChat as the first-priority column: a hard 450px minimum, a panel capped by the live budget (`client width - 450px - expanded sidebar`, no fixed maximum), and an expanded sidebar that yields at the threshold while its exit animation still counts toward the shared budget. See ADR 0238.+- The in-flow shell gives MainChat a hard 450px minimum, caps the panel by the live budget, and yields the expanded sidebar at the threshold while its exit animation still counts.+- A manual reopen spends panel width first and otherwise targets 460px, and closing the panel restores only a sidebar the layout collapsed. Decision D408 records issue #267.++See ADR 0238, E2E-LAYOUT-three-column-width-priority.## 2026-09-13 — Host-owned session collaboration messages (D409)-Rust host-core owns a durable ledger for plugin-mediated messages between real Session IDs. See ADR 0237, ADR 0165, ADR 0213, ADR 0239.+- Host-core now owns a durable ledger for plugin-mediated messages between real Session IDs, binding each delivery to its target turn and deriving the result from that turn's terminal state.+- The gateway authenticates the source from the active tool invocation, provenance is immutable across regeneration, and completion callbacks are durable and at-most-once.+- Decision D409 amends ADR 0237, ADR 0165, and ADR 0213.++See ADR 0239, E2E-PLUGIN-session-orchestrator-real-workers.## 2026-09-13 — Independent session discovery and navigable collaboration projections (D410)-The reviewed plugin gateway exposes a bounded `session/collaboration/list` read for non-deleted Agent sessions, including sessions created outside Session Orchestrator. See ADR 0239, ADR 0240.+- The plugin gateway exposes a bounded `session/collaboration/list` over non-deleted Agent sessions without project paths, credentials, transcripts, or previews.+- Sidebar summaries carry readable provider and model labels plus bounded creator and created-session references, rendered as focusable navigation that opens through the existing selection path.+- Decision D410 amends ADR 0239.++See ADR 0240, E2E-SESSION-independent-top-level-communication.## 2026-09-12 — Steer the active turn with Alt+Enter-- Normal Send/Enter remains a Host-owned follow-up; Alt+Enter submits input to- the current durable turn using a required expected turn id.-- Reuse pi-agent-core steering at the next model-request boundary, preserve- started tools, and retain the active model/workspace/permission configuration.-- Stop and ended targets reject without redirecting input to another turn.- Accepted input remains history without independent replay after cancellation.-- Journal accepted user input with a provisional preceding reply when needed;- finalize only an indexed streaming assistant in place and retain completed- message idempotency. See ADR active-turn-steering and E2E-AGENT-alt-enter-steers-active-turn.+- Normal Send stays a Host-owned follow-up, while Alt+Enter submits to the current durable turn under a required expected turn id.+- It reuses pi-agent-core steering at the next model-request boundary, keeps started tools and configuration, and rejects Stop or ended targets instead of redirecting the input.### Unified transcript reading and complete search navigation-[ADR transcript-reading-ownership](/adr/transcript-reading-ownership) amends-[ADR session-content-search](/adr/session-content-search) with one renderer-reading view for ordinary history and search, shared by MainChat and the subagent-dock. Live/model caches remain canonical. Nested targets receive capped parent-Task context through additive `navigationParent`; parser source offsets locate-hidden Markdown and file-chip matches. Read ownership rejects interrupted pages,-and explicit message actions hydrate canonical input when history is partial or-text is capped. Validation: E2E-SESSION-content-search-and-message-navigation.+[ADR transcript-reading-ownership](/adr/transcript-reading-ownership) amends [ADR session-content-search](/adr/session-content-search) with one renderer reading view shared by MainChat and the subagent dock, keeping live caches canonical and rejecting interrupted pages.++See ADR active-turn-steering, E2E-AGENT-alt-enter-steers-active-turn.## 2026-09-13 — Harden session collaboration navigation and delivery-- Collaboration references now carry `available`. A reference to a session that was- deleted or is otherwise gone is reported with `available: false`; the renderer renders- it as text instead of a navigation control, and opening a session that no longer exists- reports a visible error instead of committing an empty transcript.- `session_collaboration_messages.source_session_id` intentionally has no foreign key, so- a delivery record survives deletion of its sender and is reported as unavailable.-- The six `session/collaboration/*` operations are first-party-plugin-only: they require- an authenticated plugin tool invocation context, so they are excluded from the- MCP-visible catalog while remaining available through `pi.desktop.listOperations` and- `pi.desktop.invoke`. This amends the "same reviewed operation catalog" claim of- ADR 0203 / D370 and the `desktop.control` row of the plugin permission matrix.-- Settling a delivery now asserts that the conditional `queued` to `running` claim- actually changed a row, so losing that race cannot create a second turn for one- delivery, and `spawn` evaluates its worker limits inside the same transaction as the- session insert.-- Electron delivery settlement no longer drops a settlement recorded before a host- restart, and a drain that is already running picks up settlements queued during it- instead of deferring them to an unrelated trigger. A persisted delivery failure keeps a- stable `CODE: message` form.-- Review fixes for the orchestration refresh path bound the model-catalog lookup work per- read instead of relying on cache eviction, and replace E2E boot conditions that could- not fail with observations the probe does not itself guarantee.-- See ADR 0239, ADR 0240, E2E-SESSION-hover-card-model-and-links.+- Collaboration references carry `available`, so a deleted session renders as text, opening it reports a visible error, and a delivery record survives its sender's deletion.+- The six `session/collaboration/*` operations are first-party-plugin-only and excluded from the MCP-visible catalog, amending the "same reviewed operation catalog" claim of ADR 0203 / D370.+- Settlement now asserts the `queued` to `running` claim, and Electron no longer drops one recorded before a restart.### Global sidebar conversation pins (issue #306)-[ADR global-sidebar-pins](/adr/global-sidebar-pins) amends ADR 0016: conversation-pins occupy one global section above standalone and project history, including-closed or collapsed projects. Archive visibility and session sorting still-apply. Pins carry project context and are removed from normal history before-date grouping and row limits. Persisted metadata and host ownership stay intact.-Validation contract: E2E-SIDEBAR-global-pinned-conversations.+[ADR global-sidebar-pins](/adr/global-sidebar-pins) amends ADR 0016 so pins occupy one global section above standalone and project history, with archive visibility and sorting still applying.++See ADR 0239, ADR 0240, E2E-SESSION-hover-card-model-and-links.## 2026-09-13 — Vendor the file view as an updatable plugin (issue #304)-The work panel's file view is no longer `pi.files`. See ADR 0241, ADR 0105, ADR 0104.+- The work panel's file view is now a vendored copy of the third-party `pi.file-manager` release, shipped from `apps/desktop/resources/plugins/` with its own `UPSTREAM.md`.+- Bundled means default and non-removable, not frozen: a marketplace update survives the next launch, a strictly newer shipped build still wins, and `uninstall` refuses by shipped ID rather than row source.+- Editing writes stay inside the plugin's own jail, and the host gateway cannot mediate or declare a whole-tree write.++See ADR 0241 (supersedes ADR 0105), ADR 0104, E2E-153.## 2026-09-14 — Delta-only coalesced streaming updates (D412)-Append-only `message_update` frames carry `stream: "delta"` and the new chunk only. See ADR 0242.+- Append-only `message_update` frames now carry `stream: "delta"` and only the new chunk, while retry replacements still send a full snapshot.+- A 16 ms coalescer concatenates pending deltas and flushes before tool, terminal, retry, and error events, and checkpoints reconstruct the snapshot from the same deltas.+- Protocol stays v11. See ADR 0242, E2E-STREAM-long-turn-keeps-realtime.## 2026-09-13 — Skill market public-HTTPS catalog fetch (D413)-Skill Market search/fetch run in Electron main. See ADR 0243.+- Skill Market search and fetch run in Electron main while the renderer CSP still forbids the network, installing through the existing `skills.create`.+- The shared syntactic classifier plus a main-side DNS and per-redirect re-check guard the boundary, and previews over 128 KiB are not written. See ADR 0243.## 2026-09-14 — Harden the MCP market public-network boundary (D414)-MCP market source and catalog endpoint validation is shared by Renderer and Electron Main. See ADR 0142, ADR 0245.+- Market source and catalog endpoints accept credentials-free public HTTPS only, rejecting loopback, private, CGNAT, link-local, multicast, reserved, documentation, benchmark, ULA, and site-local ranges.+- Main resolves each hostname just before the request and pins the public address to the socket, following at most five checked redirects, with bounded responses and caches.+- Manual user-owned MCP configuration keeps ADR 0142's local and LAN policy. See ADR 0245, E2E-MCP-MARKET-*.## 2026-09-14 — Opt-in subagent inheritance of the parent tool catalog (D415)-- A subagent definition may declare `tools: inherit` (alone or with assignable- extras). Builtins stay on today's whitelist.-- At spawn the runtime unions the live `toolCatalog` minus Task*, mode- switches, `asktool`, `new_context`, and `ToolSearch`. Skill/MCP/plugin tools- the parent is allowed to call are included; child ToolSearch/new_context do- not mutate parent runtime state.-- host-core keeps the `inherit` token so inherit-only documents load and- Settings round-trips them. See ADR 0246, issue #215, PR #319, and- E2E-SUBAGENT-inherit-parent-tools.+- A subagent definition may declare `tools: inherit`, alone or with assignable extras, while builtins stay on today's whitelist.+- At spawn the runtime unions the live catalog minus Task*, mode switches, `asktool`, `new_context`, and `ToolSearch`, and children cannot mutate parent runtime state.### Tray session shortcuts (issue #293)-[ADR tray-session-shortcuts](/adr/tray-session-shortcuts) amends the D216 native-tray menu with Running, Unread, and Pinned groups after global priority-assignment: each non-empty group keeps up to three rows, then overflowing groups-reclaim the share smaller groups leave unused, in priority order, up to nine rows-in total. Host session/inbox reads and runtime events remain the-source of truth; renderer organization is mirrored without a persistence-change. macOS single-click opens the menu without restoring the window;-selection is delivered after bootstrap and uses normal session navigation.-Validation contract: E2E-TRAY-bounded-session-navigation.+[ADR tray-session-shortcuts](/adr/tray-session-shortcuts) amends the D216 native tray menu with Running, Unread, and Pinned groups bounded to nine rows in priority order.++See ADR 0246, E2E-SUBAGENT-inherit-parent-tools.## 2026-09-14 — Preserve local annotation and side-chat contracts across upstream integration-*(Retired by ADR 0268 on 2026-09-16: the feature and its surfaces were removed, and these IDs stay retired and must not be reused. Related decisions: D398, D400. See ADR 0268, ADR response-annotations.+*(Retired by ADR 0268 on 2026-09-16: the feature and its surfaces were removed, and these IDs stay retired and must not be reused. The record is kept for history.)*++- Local ADRs took semantic names (`message-quotes-and-side-chats`, `response-annotations`, `floating-annotation-index`) because local 0223–0225 collided with upstream, and local D398–D400 references use `D-LOCAL-*` with E2E-249–259 as `E2E-CHAT-*`.+- Upstream transcript, composer, store, delta, work-panel, and Alt+Enter modules stay canonical, with quote and side-chat surfaces as renderer-owned additions at those seams.++See ADR response-annotations, E2E-CHAT-annotation-ack-and-steering.## 2026-09-14 — Native Pi session continuation (D421)-Native Pi v3 sessions are discovered as source-discriminated projections and continued through the coding-agent SDK against their original JSONL. See ADR 0254.+- Native Pi v3 sessions are discovered as source-discriminated projections and continued through the coding-agent SDK against their original JSONL.+- Host-core stays authoritative for Desktop storage, and exact version, cwd, and lease checks make uncertain ownership fail closed. Decision D421 is ADR 0254.++See ADR 0254, E2E-SESSION-native-pi-*.## 2026-09-14 — Git clone accepts only syntactically public hosts (D416)-Home Clone git project still accepts https/http/ssh/`git@host:path` remotes without embedded passwords or `file:` URLs. See ADR 0247.+- Home Clone still accepts https/http/ssh and `git@host:path` remotes without embedded passwords or `file:` URLs, and classifies hosts with the shared `isPublicHostname`.+- Private and loopback literals fail in the parser, while Git's own DNS and SSH stay unchanged with no Main pin. See ADR 0247.## 2026-09-14 — Theme CSS validation only inspects CSS that runs (D417)@@ -2682,7 +3283,10 @@ Home Clone git project still accepts https/http/ssh/`git@host:path` remotes with## 2026-09-14 — Themed package assets and native window backgrounds (D418)-`contributes.themes[].assets` declares package-relative image and font files (whitelisted extensions, 4 MB summed). See ADR 0248.+- `contributes.themes[].assets` declares package-relative images and fonts under a whitelist and 4 MB budget, rewritten to `plugin-asset://` and served through a privileged host scheme, with every existing refusal intact and `ui.theme` unchanged.+- `contributes.windowAppearance.backgroundColor` applies off macOS under the new `ui.window.appearance` grant and is re-derived rather than stored, and built-in themes read one shared table so both paths cannot drift.++See ADR 0248, E2E-024J.## 2026-09-14 — The dock column is a token, not a literal (D419)@@ -2701,43 +3305,71 @@ Home Clone git project still accepts https/http/ssh/`git@host:path` remotes with## 2026-09-14 — Structured, bounded, and redacted process logs (D420)-Every app/host/agent NDJSON record has a stable dot-separated `event` and top-level correlation fields. See ADR 0250.+- Every record now carries a stable dot-separated `event` with top-level correlation fields, and one tool call emits one completion or failure record.+- Central logging redacts credential formats, sensitive keys, and local paths, bounds values, and caps `data` at 8 KiB, keeping result summaries instead of raw arguments or output. See ADR 0250.## 2026-09-15 — Deleting a project removes its owned sessions (D421)-`projects.remove({ path })` is the new additive host RPC. See ADR 0251.+- `projects.remove({ path })` removes the durable project row, its sessions, their files, and project memory, never the folder on disk, and answers `removed: false` for an unknown path.+- Deletion also clears the renderer-local recent record and refuses a multi-folder group root or a project with a running turn (1008 / `CONFLICT`), and it stays out of `CONTROL_OPERATION_SPECS`.++See ADR 0251, E2E-PROJECT-delete-removes-project-and-owned-sessions.## 2026-09-13 — Host turn-end event for plugins (D422)-`session:turnEnded` is delivered to plugin processes, plugin panel pages, and docked views with `{ sessionId, turnId, reason }`, where `reason` is `completed`, `aborted`, or `error`, once per turn actually started by `session.beginTurn` (a user submission, an approved plan execution, or a scheduled run). See ADR 0252.+- `session:turnEnded` reaches plugin processes and views with `{ sessionId, turnId, reason }`, once per turn actually started, announced at the end of teardown.+- The finalizer requires an explicit `turnId` and keys by `(sessionId, turnId)`, so a repeat settles nothing; the event has no permission, ack, or replay guarantee. Decision D422 is ADR 0252.++See ADR 0252.## 2026-09-15 — Remove the subagent turn limit (D423)-`maxTurns` was the last definition-level kill switch left after ADR 0166 withdrew the idle and duration watchdogs, and the parent cannot size it: it cannot see the delegate's live work, so it cannot tell a delegate that is one turn from converging from one that never will. Related decisions: D328. See ADR 0166, ADR 0253.+- `maxTurns` was the last definition-level kill switch, and a parent that cannot see the delegate's work cannot size it.+- Decision D423 removes the field from the definition, parser, records, registry, built-ins, presets, and editor, and drops the `truncated` status; an existing document keeps loading with the key ignored like any unknown key.+- No protocol, schema, or storage change. See ADR 0253, E2E-155.## 2026-09-15 — Theme assets are absolute paths (D422)-ADR 0248 required theme assets to be package-relative, which forced a plugin to copy a user-chosen image into its own package. See ADR 0248, ADR 0255.+- Package-relative assets forced a copy inside the package, which a watched development plugin reloaded, closing its own panel.+- `normalizeThemeAssetPath` now accepts absolute paths only, and `pi.themes.upsert` registers assets for as long as the plugin stays loaded while the whitelist, budget, and revocation are unchanged.++See ADR 0255.## 2026-09-15 — DeepSeek reasoning across compaction (D424)-OpenCode / third-party DeepSeek relays reject empty `reasoning_*` echoes after context compaction drops assistant thinking (#296). Related decisions: D389. See ADR 0136, ADR 0256.+- OpenCode and third-party DeepSeek relays reject empty `reasoning_*` echoes after compaction drops thinking, while official `deepseek.com` accepts them.+- Decision D424 amends D389 / ADR 0136: retained thinking is replayed after the summary, and non-official rows set `requiresNonEmptyReasoningReplay` so the patch fills a documented placeholder.++See ADR 0256, E2E-005E.## 2026-09-15 — Plugin real-time capabilities (D425)-Plugins gain four host-mediated capabilities: background microphone capture, background playback, system-wide accelerators, and real-time bidirectional connections. See ADR 0257.+- Plugins gain host-mediated background audio capture and playback, system-wide accelerators, and real-time connections, exchanging typed frames instead of device handles or sockets.+- `keyboard.globalShortcut` and `net.websocket` ship here and refuse conflicts rather than taking a chord over, while the two audio permissions answer a coded `UNSUPPORTED` until the device service lands.++See ADR 0257, E2E-PLUGIN-global-shortcut-owns-only-its-own-command.## 2026-09-15 — Trusted extension custom agents (D426)- See ADR 0258.+- A trusted extension may register bounded model metadata plus a `stream` or `complete` callback and own its endpoint and authentication, with the sidecar exposing a redacted registry and routing idle `setModel` through the host-owned `session.configure`.+- The host never receives or persists plugin transport credentials, and `registerProvider` remains a compatibility alias. Decision D426 is ADR 0258.++See ADR 0258.## 2026-09-15 — Plugin-declared providers are Host-owned rows (D427)- Related decisions: D647. See ADR 0259, ADR 0320.+- `contributes.providers` entries become Host-owned provider rows (`providers.owner_plugin_id`, schema v17), re-read on every load and authoritative for their fields, behind the high-risk `provider.register` permission.+- Dropping an entry deletes the row and both credential references, and `providers.update` / `providers.delete` refuse with `PROVIDER_OWNED_BY_PLUGIN`; D647 amends the OAuth exclusion with `provider.oauth`.++See ADR 0259, ADR 0320.## 2026-09-15 — Side chats materialize on first Send (#421)-*(Retired by ADR 0268 on 2026-09-16: the feature and its surfaces were removed, and these IDs stay retired and must not be reused. See ADR 0268.+*(Retired by ADR 0268 on 2026-09-16: the feature and its surfaces were removed, and these IDs stay retired and must not be reused. The record is kept for history.)*++Side-chat opening and selection quote prefill were renderer-only drafts: the first nonempty Send created the anchored child, deduplicating concurrent submissions and keeping failed drafts, while closing an unsent draft created no history.++See ADR 0268, [message quotes and side chats](../../adr/message-quotes-and-side-chats.md), E2E-CHAT-side-chat-fork.## 2026-09-15 — A tooltip never outlives its trigger (D428)@@ -2774,7 +3406,11 @@ its menu instead of the conversation.## 2026-09-15 — Turn-queue priority block and row actions (D429)-"Send now" becomes a priority block instead of a head jump: a promoted entry takes `MAX(priority) + 1` inside its session (schema v18, nullable `priority`), so several promotions are delivered in the order they were clicked and the waiting queue keeps its own `position` order behind them. See ADR 0265.+- "Send now" promotes an entry to `MAX(priority) + 1` in its session (schema v18), so promotions keep click order above the waiting queue, and promoting twice is `CONFLICT`.+- The row gains move up, move down, and edit through `session.queueReorder`, editing returns the captured draft, and a promoted row stays locked until delivery.+- A promoted block ships as adjacent user messages, and a settled turn closes the queue so "Send now, then Stop" cannot stall it.++See ADR 0265, E2E-QUEUE-promote-orders-delivery-by-click.## 2026-09-16 — A manual disclosure keeps the reader's place (D430)@@ -2815,17 +3451,28 @@ its menu instead of the conversation.Readers reported that clicking a tool, thinking or activity title to expand itdragged the whole transcript up by the height of the opened detail, in a sessionthat was sitting at the bottom — including after the turn had finished.+## 2026-09-16 — The delete dialog, not the menu, owns the running-task refusal (#360, D431)-Amends the renderer half of D421. The sidebar menu and the Projects index menu refused Delete project with a transient `project.deleteRunningBlocked` warning whenever any of the project's sessions was running, and returned before `ProjectDeleteDialog` was ever mounted. Related decisions: D421. See ADR 0251.+- The menus refused Delete project with a transient warning and returned before `ProjectDeleteDialog` mounted, so a project with one live task could not be deleted at all (#360).+- Both menus now always open the dialog with the live running ids, and confirming aborts exactly those sessions before `deleteProject`; the host 1008 / `CONFLICT` guard and the `project.deleteRunningBlocked` fallback are unchanged.++See ADR 0251, D421, E2E-PROJECT-delete-running-sessions-are-named-and-stopped.## 2026-09-16 — Plugin `workspace` fs roots follow the calling session (D432)-Every plugin `pi.fs.*` call whose mode root is `workspace` resolved the one window-global visible workspace, so a plugin agent tool invoked from session B (project B) read project A's root as soon as the user switched tabs, and failed `NOT_FOUND` for every session at once when no workspace was visible (D093 fixed the same rule for built-in tool execution; it … Related decisions: D093. See ADR 0266.+- Every `workspace`-rooted `pi.fs.*` call resolved the window-global workspace, so a tool invoked from another session read the wrong project, or failed for all sessions when none was visible (D093 never reached plugins).+- `plugin-runtime.ts` now resolves the invoking session's project through `getWorkspacePathForSession`, while panel calls keep the visible workspace and the permission, containment, and consent gates are unchanged.++See ADR 0266, E2E-PLUGIN-fs-root-follows-the-calling-session.## 2026-09-16 — Quotes, annotations, and side chats are removed (ADR 0268)-Quote, the text-selection overlay, response annotations (comment editor, floating index, source badges, composer attachment), and renderer-owned side chats are removed from every surface. Related decisions: D-LOCAL-message-quotes, D-LOCAL-selection-overlay, D-LOCAL-response-annotations. See ADR 0268.+- Quote, the selection overlay, response annotations, and renderer-owned side chats are removed everywhere, while Copy, Edit, Delete, Fork, Retry, Regenerate, drafts, and chips stay.+- Sends no longer compose a `# Response annotations:` block, so a stored prompt shows exactly as it was stored in the transcript, edit seed, and queue preview.+- `D-LOCAL-message-quotes`, `D-LOCAL-selection-overlay`, `D-LOCAL-response-annotations`, `D-native-sidechat-stream`, and the `E2E-CHAT-*` scenarios stay retired and never reusable, with no protocol, schema, or IPC change.++See ADR 0268.## 2026-09-16 — A control with no label states its square geometry@@ -2960,11 +3607,16 @@ Quote, the text-selection overlay, response annotations (comment editor, floatin## 2026-09-17 — Builtin subagents can be switched off (D434)-Settings > Agent > Subagents listed the five shipped defaults as read-only rows while the user's own documents had an enablement switch, so one delegate could not be turned off at all: copying a builtin and disabling the copy left the shipped definition in the catalog, because disabled user documents are filtered out before the loader merges and so shadowed nothing. See ADR 0270.+- Builtins were read-only rows, so one delegate could not be turned off: copying and disabling left the shipped definition in the catalog, because disabled user documents are filtered out before the loader merges.+- Every Built-in row now carries the switch, stored in `subagent-builtins.json` and exposed through `agents.disabledBuiltins` / `agents.setBuiltinEnabled`, and a switched-off builtin keeps a dimmed row.++See ADR 0270, E2E-SUBAGENT-settings-lists-builtin-defaults.## 2026-09-17 — Judge a public-network address on the route the request will dial (D436)-The skill market's main-process guard classified the target host with a *local* resolver while `net.fetch` dials through Chromium's proxy stack (ADR 0177). See ADR 0177, ADR 0245, ADR 0272.+- The market guard classified hosts with a local resolver while `net.fetch` dials through Chromium's proxy stack (ADR 0177), so a TUN or fake-IP resolver made every source look blocked (issue #419).+- Each hop now asks `Session.resolveProxy`: a `proxied` route tolerates only benchmark placeholders, while `direct` and `unknown` stay strict, and the MCP market keeps its pinned guard on direct hops.+- Refusals carry the route. See ADR 0272, ADR 0245, E2E-SKILL-MARKET-NET-BOUNDARY.## 2026-09-17 — The dock question card is a composer plate (#360, D437)@@ -2998,15 +3650,26 @@ The skill market's main-process guard classified the target host with a *local*## 2026-09-17 — A git checkout is a Create project source (D438)-The Create project dialog only collected a project name and local folders (ADR 0233), and the home switcher's Clone git project entry renders inside the hero of a project-bound session. See ADR 0233, ADR 0247, ADR 0273.+- The Create project dialog collected only a name and folders (ADR 0233), so a fresh installation had to open an unrelated folder before cloning.+- It now offers two equal sources, This computer and Git repository, parsing URLs with the switcher's rules so private, loopback, or credential-bearing remotes keep Create disabled (ADR 0247).+- Main adds `project/cloneCheckout({ url, parentPath })` without touching the active workspace, and both sources still write one project group.++See ADR 0273, E2E-258.## 2026-09-16 — Draggable chat content width (D439)-The centered conversation band, empty-home stack, and composer share one preferred max width, default 760px, persisted as `AppSettings.chatContentMaxWidth`. See ADR 0277.+- The conversation band, empty-home stack, and composer share one preferred max width, default 760px and persisted as `AppSettings.chatContentMaxWidth`, changed together by dual edge handles with a 560px drag floor.+- Used width stays `min(pane minus 24px gutters, preferred)`, so a squeezed panel compresses the band without rewriting the preference, and the collapsed-sidebar ceiling is gone.++See ADR 0277, E2E-208.## 2026-09-17 — Session and project rows delete on the second click (D441)-Project menus now open `ProjectDeleteDialog` immediately, including for idle projects; the project-menu Close action is removed in favor of reversible Archive. Related decisions: D431, D438, D439, D440, D421. See ADR 0273.+- **Amended 2026-10-09**: project menus now always open `ProjectDeleteDialog` and Close becomes Archive, so only the dialog's confirm deletes while session deletion keeps its two-click arm.+- `hooks/use-armed-delete.ts` owns one 3200 ms arm keyed on `session.id` or a `project:` prefix, cleared by an outside press, Escape, or expiry, and a live-turn project still routes through the dialog.+- The number is D441 because D438 was claimed twice — by the window-toggle merge (#360, with the D439 rebind) and the Git checkout that moves to D440.++See ADR 0273, D421, D431, E2E-PROJECT-delete-removes-project-and-owned-sessions.## 2026-09-16 — The sidebar list rhythm is 1px / 2px / 8px@@ -3039,7 +3702,6 @@ Project menus now open `ProjectDeleteDialog` immediately, including for idle pro- Renderer only: no protocol, storage, host, permission, or migration change.See `04-ux/07-ui-design-system.md` §6.1 and §13, and`04-ux/08-component-spec.md` §6.2 and §6.6.-## 2026-09-16 — The sidebar project group folds as one grid row- The rhythm above shipped with the group fold animating `max-height: 2000px →@@ -3151,35 +3813,96 @@ Project menus now open `ProjectDeleteDialog` immediately, including for idle pro## 2026-09-18 — Prompt enhancement ships a substantive rewrite with user-overridable templates (D447)-The default enhancement prompt moves from one conservative sentence to a structured system prompt plus a templated user message: role, analysis, rewrite principles, an explicit do-not list, language-following rules that forbid language meta notes, a length brake (about twice the draft; no 800-character cap), and an output contract. See ADR 0121.+- D447 replaces the one-sentence enhancement prompt with a built-in structured+ system prompt and a user-owned template carrying `{{draft}}`.+- The template override lives in `AppSettings`; a blank value or the exact+ default text clears it, so later default improvements still reach users.+- The rewrite runs on its own provider, model, and reasoning level (default+ `off`), clamped and 60s-bounded; `prompt/enhance` is unchanged.++See ADR 0121.## 2026-09-19 — Restore resizable sidebar width with collapse-below-threshold (D459)-Amend D408 / ADR 0238 and restore ADR 0141: the expanded sidebar is again a renderer-owned `240px..520px` column (default `275px`). Related decisions: D408. See ADR 0238, ADR 0141, ADR 0290.+- D459 amends D408 / ADR 0238 and restores ADR 0141: the expanded sidebar is+ again a renderer-owned `240px..520px` column (default `275px`) with a+ previewing right-edge handle and keyboard resize.+- A pointer width below `160px` collapses it without overwriting the preferred+ width; Escape, cancellation, lost capture, and unmount restore the press-time+ width.+- The live maximum is the three-column remainder, so a chosen width does not+ trip D408's yield; renderer only.++See ADR 0290.## 2026-09-19 — MCP catalogs are bounded by protocol guards, not truncated (D452)-Amend D176 / ADR 0038: the per-server `tools/list` bound stops being a silent truncation at 64 tools and 8 pages. Related decisions: D176. See ADR 0038.+- D452 amends D176: the per-server `tools/list` bound stops truncating silently+ at 64 tools and 8 pages.+- Pagination is followed to the last page under Codex-parity guards (2048 tools,+ 100 pages, a repeated cursor, 30s), and a server breaking one loses its+ handshake.+- `plugin.mcp.tools.truncated` is gone; the refusal is audited and reaches the+ user as the server's status message.++See ADR 0038.## 2026-09-19 — The Voice settings card is removed (ADR 0291)-Settings → AI no longer carries a speech section: `VoiceSettingsCard` and `features/settings/voice-settings.tsx`, the AI destination's `settings.speechTitle` / `settings.speechTranscribe` / `settings.speechSynthesize` search keywords, the `.settings-speech-*` styles, the thirteen `settings.speech*` keys in all eight shipped locale catalogs, and the seven unreferenced … See ADR 0281, ADR 0291.+- Settings → AI no longer carries a speech section: the Voice card, its search+ keywords, styles, catalog keys, and the withdrawn Composer speech copy are+ gone.+- The host capability stays: `speech/*` methods, `AppSettings.speech` validation,+ both built-in protocols, and `speech.adapter.register`.+- This repairs the docs for the Composer entry point ADR 0281 item 5 described;+ no stored binding or IPC, schema, or permission changes.++See ADR 0291.## 2026-09-19 — SSH bootstrap for remote hosts (D453)-The desktop installs and pairs a `pi-host` on a machine the user already reaches over SSH using the system `ssh` client, so `~/.ssh/config`, the agent, and jump hosts apply unchanged and the app holds no SSH secret; `BatchMode=yes` makes a host that needs an interactive password or passphrase fail with a typed error instead of hanging behind an invisible prompt. Related decisions: D375. See ADR 0292.+- D453 installs and pairs a `pi-host` over the system `ssh` client, so config,+ agent, and jump hosts apply unchanged and the app holds no SSH secret.+- The bundle is resolved at the desktop's version and its published SHA-256+ verified, so no executable bytes cross the channel.+- The script runs under `umask 077`, the token stays in a work file, a mismatch is+ `HOST_VERSION_MISMATCH` (D375), and a paired host stores a descriptor.++See ADR 0292.## 2026-09-19 — SSH password authentication for the bootstrap (D454)-ADR 0292 kept the app free of SSH secrets and made `BatchMode=yes` the enforcer, which is the right default but leaves a machine whose only credential is a password unreachable from the app — the user has to install a key from a terminal first, which is the detour the bootstrap exists to remove. See ADR 0292, ADR 0293.+- D454 lets a password replace a key per host, opt-in: with no password the argv+ and every other behaviour are unchanged.+- The secret reaches `ssh` through OpenSSH's askpass helper, never as an argument+ or environment value, and its material is deleted once no child can prompt.+- `BatchMode=no` with one password prompt applies only to such a target; the+ secret is stored encrypted through the OS keychain and never reaches the+ renderer.++See ADR 0293.## 2026-09-20 — Project archive is a list + inspector (D455)-Decision D455 revises D267's expanding rows for Settings → Project archive. Related decisions: D267, D133. See ADR 0294.+- D455 revises D267's expanding rows: the archive keeps its intro and toolbar,+ and the list becomes compact rows with a full-width inspector under the+ selection.+- Clicking selects and keeps Settings open; double-click, Enter, or Open+ activates the project and returns to chat, while archive and close keep the+ destination open (D133).+- Folders, batched chats, and the menu live in the inspector; presentation only.++See ADR 0294.## 2026-09-20 — Prompt-enhancement model card moves to Settings → AI-Amend ADR 0121 and the 2026-09-18 D447 placement: the Enhancement prompt card (default model + reasoning) leaves Settings → Models and sits on Settings → AI immediately below Prompt enhancement, so the template and the rewrite model for the same Composer action live on one destination. Related decisions: D447. See ADR 0121.+- This amends ADR 0121 and the 2026-09-18 D447 placement: the Enhancement prompt+ card moves from Settings → Models to Settings → AI below Prompt enhancement.+- The card keeps a title because the picker needs heading, value, and control,+ and Settings search indexes those rows on the AI tab.+- Presentation only: no IPC, storage, or host-protocol change.++See ADR 0121.## 2026-09-20 — Prompt enhancement is one Settings → AI card@@ -3191,15 +3914,37 @@ Amend ADR 0121 and the 2026-09-18 D447 placement: the Enhancement prompt card (d## 2026-09-20 — Session thinking-parameter omission (D456)-Composer, session storage, and host validation accept `thinkingLevel: omit` next to the seven canonical levels. See ADR 0295.+- D456 accepts `thinkingLevel: omit` beside the seven canonical levels in the+ Composer, session storage, and host validation.+- The parent stream takes the subagent omit path so adapters send no thinking+ field; explicit `off` still disables thinking.+- The Composer menu prepends `omit` when the model exposes canonical levels, and+ schema v19 rebuilds `sessions` so the CHECK allows it.++See ADR 0295.## 2026-09-19 — Drain poison outbox entries; accept steering into a delivery turn (D597)-Decision D597 amends ADR 0041, ADR 0239, ADR active-turn-steering, and D444. Related decisions: D444. See ADR 0041, ADR 0239, ADR active-turn-steering.+- D597 amends ADR 0041, ADR 0239, ADR active-turn-steering, and D444: a+ `PERMISSION_DENIED:` prefixed append is permanent, so the outbox drops the row+ and keeps draining.+- Substring matches such as `PLUGIN_PERMISSION_DENIED` and other host failures+ still pause, so one poison head cannot fill the cap.+- Steering into a claimed delivery turn is exempt from the delivery contract and+ has client `session_message` stripped.++See ADR 0041.## 2026-09-20 — Project archive reads as an inset grouped card list-Revise D455's presentation only: the destination stays one column with the detail under the selected row and no side-by-side pane, but the index is now an inset grouped list in the iOS sense. Related decisions: D455. See ADR 0294.+- This revises D455's presentation only: the index becomes an inset grouped card+ list, identity left and detail right, tiles separated by the row gap.+- The selected row is its own card header, so the detail repeats no name, path,+ or status tag, and one shared toggle closes it.+- Arrow keys walk the rendered order and move focus; no IPC, storage, or+ activation change.++See ADR 0294.## 2026-09-20 — Project archive opens closed and keeps no page-level prose@@ -3247,15 +3992,37 @@ Revise D455's presentation only: the destination stays one column with the detai## 2026-09-20 — A development build is its own installation (D599)-A packaged PI-Desktop and a `pnpm dev` host no longer share the two directories that define an installation. Related decisions: D236. See ADR 0094.+- D599 narrows D236: a development build runs under `PI-Desktop Dev` and reads+ `~/.pi-desktop-dev`, while a packaged installation keeps its two directories.+- The two never share one single-instance lock, `pi.sqlite`, outbox, or log tree;+ `PI_DESKTOP_DATA_DIR` still wins and is made absolute.+- No IPC channel, host protocol, storage schema, or packaged path changed.++See ADR 0094.## 2026-09-20 — The app ships no fonts (D598)-Decision D598 amends D232 / ADR 0083. The four bundled families (Geist, Inter, Noto Sans SC, LXGW WenKai), their `woff2` files, their OFL license texts, `styles/fonts.css`, and its `@import` are gone, together with `BUNDLED_FONTS`, the `BundledFont` type, `FontOption.license`, the picker's license badge, and the `settings.fontBundled` key in all eight catalogs. Related decisions: D232. See ADR 0083, ADR 0298.+- D598 amends D232 / ADR 0083: the four bundled families, their `woff2` files+ and licences, `styles/fonts.css`, the license badge, and the bundled picker+ group are gone.+- The Font picker keeps its shape: System default persists the empty string, and+ installed families come from Electron main.+- Generated stacks append the system-only CJK tier, a stored bundled stack+ survives under Saved, and no migration is required.++See ADR 0298.## 2026-09-20 — Stdio MCP spawn uses the login-shell PATH (D600, issue #571)-Finder/Dock launches Electron with `/usr/bin:/bin:/usr/sbin:/sbin`. See ADR 0045.+- D600 fixes launches that inherit a minimal PATH, which left `uvx` and `npx`+ failing as `spawn … ENOENT` while a terminal worked.+- Electron main probes the login shell the way host-core already does for Bash+ (ADR 0045), 5s-bounded and cached, and merges the user bin directories that+ exist.+- Windows stays on the inherited PATH, and a missing executable reads+ `command not found: <name>`.++See ADR 0045.## 2026-09-20 — Settings explain themselves on demand (D601)@@ -3368,7 +4135,14 @@ Finder/Dock launches Electron with `/usr/bin:/bin:/usr/sbin:/sbin`. See ADR 0045## 2026-09-20 — The Create project name defaults to the primary folder (D609)-The Create project dialog required a typed name before Create became available, so a local folder pick could not be confirmed without inventing a title; the git source already seeded the field from the repository name (D438, ADR 0273). Related decisions: D438. See ADR 0273, ADR 0233.+- D609 makes the Create project name optional for both sources, seeding it from+ the first folder or the repository name (D438 / ADR 0273) and stopping once+ the user types.+- Create is gated by the source alone and an empty field falls back to the+ derived name, cut to `MAX_PROJECT_NAME_CHARS` (80) for stored preferences.+- Renderer only: no protocol, storage, host, permission, or migration change.++See ADR 0233.## 2026-09-21 — A stored model binding array is read entry by entry (D610, issue #784)@@ -3545,11 +4319,28 @@ The Create project dialog required a typed name before Create became available,## 2026-09-22 — A failed compaction keeps the recent window (D617, issue #827)-An automatic compaction whose summary request failed installed a retained-tail checkpoint that carried at most the latest user message, and a rebuild narrowed a stored checkpoint's tail the same way. See ADR 0302, ADR 0049, ADR 0282.+- D617 keeps the real recent window when an automatic compaction's summary+ fails: the newest contiguous messages, every role, bounded by the keep-recent+ target.+- The checkpoint marks it with `details.retainedTailShape`, so a rebuild replays+ it, while an unmarked checkpoint normalizes to the latest user message.+- A prompt still too large after one reduced pass is split into at most 16+ contiguous chunks, each carrying the previous summary (ADR 0049, ADR 0282).++See ADR 0302.## 2026-09-20 — A copied formula is its TeX source (D619, issue #414)-Math boundaries remain parseable after copying: touching inline fences get one separator, and every prose dollar in the copied text is escaped, together with backslash runs that would otherwise escape a fence. See ADR 0268.+- D619 makes a copy covering rendered math read the TeX back from the MathML+ `annotation`, as `$…$` inline or `$$…$$` on its own lines, delimiters widened+ past inner runs.+- Only formulas are rewritten; the rest is read back through+ `Selection.toString()`, since a hand-written walk would rewrite whitespace the+ platform gets right.+- One clipboard flavour, `text/plain`, so a rich target cannot show every+ formula twice; D619 rests on the clipboard ADR 0268 already relied on.++See ADR 0268.## 2026-09-22 — pi's file-op collector is fed the names it reads (D618, issue #827)@@ -3570,7 +4361,14 @@ Math boundaries remain parseable after copying: touching inline fences get one s## 2026-09-22 — Provider header values fold fullwidth input instead of failing the turn (D621)-A custom provider header value holding a fullwidth character — `0` (U+FF10) is what an IME or a fullwidth-formatted page gives for `0` — reached `Headers.set` and made undici throw `TypeError: Cannot convert argument to a ByteString because the character at index N has a value of X which is greater than 255`. See ADR 0178.+- D621 folds the fullwidth block and the ideographic space onto ASCII, then+ requires HTAB, printable ASCII, or the Latin-1 supplement; NFKC is rejected.+- The fold runs on read as well as write, so an older stored value starts+ working; keys fold on both sides without being refused at save.+- The editor refuses and names the character, a stored map folds and drops, and+ a sync bundle folds first.++See ADR 0178.## 2026-09-22 — Catalog aliases enrich metadata without changing model identity (D622)@@ -3592,11 +4390,25 @@ A custom provider header value holding a fullwidth character — `0` (U+FF10)## 2026-09-23 — Compact before the hard request budget (D623, issue #970)-Automatic session and subagent compaction now starts at 90% of the derived `hardLimit`, inline at the next request boundary. See ADR 0064.+- D623 starts automatic session and subagent compaction at 90% of the derived+ `hardLimit`, inline at the next request boundary.+- New prompts join the preflight estimate and tool results are measured before+ the follow-up request; `hardLimit` stays the boundary that never reaches the+ provider.+- The runtime stays inline-only, with no background summary, setting, or+ protocol change.++See ADR 0064.## 2026-09-24 — Windows stdio MCP resolves official Node and fnm npx (D624, issue #789)-Amend D176 / D600 / ADR 0038. D600 probes the login-shell PATH on Unix and explicitly keeps Windows on the inherited PATH. Related decisions: D176, D600, D018. See ADR 0038.+- D624 amends D176 and D600: `spawn` without a shell starts neither `npx` nor its+ `.cmd` shim, so Electron main resolves bare command names first.+- An official PATH `node.exe` wins, then fnm, nvm-windows, and Volta;+ `npx-cli.js` runs through `node` and other `.cmd` files through `cmd.exe`.+- Secrets still do not cross (D018) and names stay bare.++See ADR 0038.## 2026-09-24 — The transcript occludes itself instead of the dock painting a band (D624, issue #728)@@ -3630,7 +4442,15 @@ Amend D176 / D600 / ADR 0038. D600 probes the login-shell PATH on Unix and expli## 2026-09-25 — Model settings unify around one AI service list and a chosen-models summary (D625)-The model settings page asked too much before a user could connect anything. Related decisions: D297, D310. See ADR 0098.+- D625 collapses model settings into one AI service list: API-key,+ plugin-declared, and vendor-subscription rows share it, and a row itself opens+ its editor.+- Adding starts on a searchable chooser whose custom endpoint comes last, then a+ two-view form with credential rows in `ProviderConnectionFields` (D310).+- Dialogs open on a chosen-models summary, a new service preselects recommended+ tool-capable models, and the D297 tone is kept.++See ADR 0098.## 2026-09-25 — The custom endpoint leads the API-key group (D626)@@ -3691,7 +4511,14 @@ The model settings page asked too much before a user could connect anything. Rel## 2026-09-26 — Bound aggregate image history without an arbitrary message cutoff (D629)-Vision history restoration keeps the existing 10 MB per-image ceiling and adds a 30 MB aggregate raw-byte budget per runtime rebuild. See ADR 0101.+- D629 keeps the 10 MB per-image ceiling and adds a 30 MB aggregate budget per+ runtime rebuild, considering eligible refs newest-first.+- Images inside the budget stay provider blocks; older attachments fall back to+ a safe `@path`, and the current prompt row is excluded.+- The sidecar reads only admitted files, and durable host messages stay+ metadata-only.++See ADR 0101.## 2026-09-27 — Routed model metadata uses conservative last-segment matching (D630, PR #1047)@@ -3719,7 +4546,16 @@ Vision history restoration keeps the existing 10 MB per-image ceiling and adds a## 2026-09-27 — Agent workspace search is available from turn one (D631)-Amend D185 / D208 and ADR 0069's Agent activation boundary: `Glob` and `Grep` are included with `Read`, `Bash`, `Edit`, and `Write` in the first Agent request. Related decisions: D185, D208. See ADR 0069, ADR 0048, ADR 0230.+- D631 amends D185, D208, and ADR 0069's Agent activation boundary: `Glob` and+ `Grep` join `Read`, `Bash`, `Edit`, and `Write` in the first Agent request.+- Routine workspace discovery therefore no longer needs a `ToolSearch` round+ trip, while `BrowserPreview`, plugin tools, and plugin-development helpers stay+ deferred.+- ToolSearch, successful-activation restoration, host permissions, and the+ Plan/Goal tool sets are unchanged, as are the ADR 0048 and ADR 0230+ amendments.++See ADR 0069.## 2026-09-27 — Composer recalls its own conversation's submissions with ArrowUp/ArrowDown (D632)@@ -3776,27 +4612,70 @@ Amend D185 / D208 and ADR 0069's Agent activation boundary: `Glob` and `Grep` ar## 2026-09-27 — Completed turn-process disclosures fold by default (D633)-Detailed mode opens the whole-process disclosure while a turn is active. See ADR turn-process-and-thinking-display.+- D633 keeps Detailed mode opening the whole-process disclosure while a turn is+ active, and defaults untouched process details to closed once the turn settles.+- Explicit user choices remain authoritative, and search reveals plus actionable+ or error surfaces outside the process are unchanged.+- Renderer presentation only: no transcript, persistence, provider-thinking, or+ host behavior changes.++See ADR turn-process-and-thinking-display.## 2026-09-27 — Remove bundled macOS first-launch guidance (D634)-The DMG remains a two-icon app/Applications install, and the ZIP contains `PI-Desktop.app` at its root. Related decisions: D457. See ADR 0296, ADR 0232, ADR 0204, ADR 0309.+- D634 amends D457 / ADR 0296 and supersedes ADR 0232 and ADR 0204 for macOS+ distribution: the DMG stays a two-icon install and the ZIP holds the app at+ its root.+- Neither ships an opening note or a quarantine-clearing helper, including for+ unsigned debug builds.+- Signing, notarization, stapling, and updater lanes are unchanged.++See ADR 0309.## 2026-09-29 — Work-area-capped 800×560 window minimum (D635)-The app-wide window minimum is 800×560 DIP. Related decisions: D156, D447. See ADR 0029, ADR 0238, ADR 0146.+- D635 makes the window minimum 800×560 DIP and caps it to the display work+ area wherever Main sets it.+- The chat width accepts `800..10000px` from one shared floor, and the+ three-column budget still caps a docked panel so MainChat keeps 450px.+- This supersedes the 1040×700 minimum of D156 and D447 (and the matching+ ADR 0029 / ADR 0238 clauses) and ADR 0146's range; saved panel widths are not+ rewritten.++See ADR 0029.## 2026-09-29 — Local permission approvals remain pending until resolved (D636)-D636 amends D005 / ADR 0011 for the local desktop permission gate. Related decisions: D005. See ADR 0011, ADR 0310.+- D636 amends D005 / ADR 0011: a permission-gated `tools.execute` request has+ no deadline,+ so host-core keeps it pending and the renderer keeps the inline card.+- Allow once, allow for session, deny, cancellation, and shutdown remain the+ settlement paths; no transport timer is installed.+- The request carries no `timeoutMs` and snapshots expose no `expiresAt`;+ command, plugin, Plan/Goal, and RACP budgets are unchanged.++See ADR 0310.## 2026-09-29 — Remove the Windows frameless resize rim (D637)-The Windows main window disables Electron's thick frame, removing the native left, bottom, and right rim. Related decisions: D635. See ADR 0317.+- D637 disables Electron's thick frame on the Windows main window, removing the+ native rim while its frameless edge and corner hit test remain.+- The window defaults to the 12 DIP `--radius-md` native shape, a themed size may+ pick 0 to 24 DIP, and no resize path or geometry IPC is added.+- macOS, Linux, work-panel resize ownership, and D635's minimum stay in force.++See ADR 0317.## 2026-10-01 — Publish native Linux arm64 artifacts (D638)-Tag releases publish Linux arm64 AppImage, deb, and rpm packages beside the x64 ones. Related decisions: D375. See ADR 0292, ADR 0318.+- D638 publishes Linux arm64 AppImage, deb, and rpm packages beside the x64 ones,+ each lane on a native Ubuntu 22.04 runner packing the sidecar it built.+- Targets stop pinning `arch`, so each lane passes its own flag, verifies+ `uname -m`, and names the AppImage by architecture, renaming the x64 asset.+- Each feed is named after its architecture, and `linux-arm64` joins+ `PUBLISHED_TARGETS` so an arm64 desktop can bootstrap a matching host (D375).++See ADR 0318.## 2026-10-03 — User MCP tools keep the normal approval path (D640)@@ -3854,7 +4733,15 @@ Tag releases publish Linux arm64 AppImage, deb, and rpm packages beside the x64in `crates/host-core/src/config_sync/domains.rs`.## 2026-10-04 — External imports live with their Settings destination (D645)-D645 removes the standalone Settings `import` destination. See ADR 0319.+- D645 removes the standalone Settings `import` destination: model+ configuration, external skills, and external MCP scans open inline from their+ own pages.+- Capability imports follow the selected global or project level, and project+ scans bind to the selected project.+- Settings no longer scans core sessions; plugins keep their import API, and no+ IPC, permission, protocol, or persistence contract changes.++See ADR 0319.## 2026-10-04 — The empty home names the open project before its first session (D646)@@ -3874,11 +4761,27 @@ D645 removes the standalone Settings `import` destination. See ADR 0319.## 2026-10-06 — Plugin providers can own OAuth sign-in through a scoped callback (D647)-D647 amends ADR 0259: a plugin provider may declare `authKind: "oauth"` when it has `provider.register`, the separate high-risk `provider.oauth` grant, and an `onProviderOAuth` callback. See ADR 0259, ADR 0320.+- D647 amends ADR 0259: a plugin provider may declare `authKind: "oauth"` with+ `provider.register`, the `provider.oauth` grant, and an `onProviderOAuth`+ callback.+- The Host owns the login UI, encrypted storage, refresh serialization, and the+ auth resolver; the callback reads only its own credential.+- The runtime receives only an access token and the renderer none; sign-out+ clears the credential without deleting the declared row.++See ADR 0320.## 2026-10-06 — Skill Market pins an acceptable address for mixed direct DNS answers (D648)-On a direct route, the Skill Market selects and pins an acceptable address when a DNS response mixes acceptable and rejected addresses. See ADR 0272, ADR 0321.+- D648 pins an acceptable address when a direct answer mixes acceptable and+ rejected ones, preferring a public third-party address with the `benchmark`+ opt-in as the only alternative.+- ULA-only results stay blocked, and proxied or unreadable routes keep the+ ADR 0272 policy.+- The pinned request preserves the hostname for SNI and `Host`, and every+ redirect is checked and pinned again.++See ADR 0321.## 2026-10-07 — Cloud backup stays closed to users (D649)@@ -3897,11 +4800,26 @@ On a direct route, the Skill Market selects and pins an acceptable address when## 2026-10-08 — Plugin providers appear in Add Service (D650)-ADR 0322 adds provider category and optional short-description metadata to a Host-rendered Add Service projection for unconfigured API-key providers from loaded plugins with `provider.register`. See ADR 0322.+- ADR 0322 adds provider category and optional short-description metadata to a+ Host-rendered Add Service projection for unconfigured plugin API-key providers.+- Tiles show the name with its introduction on hover or focus, and there is no+ per-plugin cap.+- An empty model list discovers endpoint models after a key is saved; the key+ uses the existing secret path, and OAuth and no-auth declarations do not+ appear.++See ADR 0322.## 2026-10-08 — Make session title generation a standalone plugin (D652)-The core keeps one automatic title path: the deterministic first-prompt fallback (D654). Related decisions: D654. See ADR 0323.+- D652 makes title generation a standalone plugin: the core keeps only the+ deterministic first-prompt fallback (D654) and runs no completion.+- The `session.autoTitle` permission exposes bounded first-turn text and a+ compare-and-set update, and schema v23 tracks title ownership.+- The plugin owns its template, model, and thinking level, and manual rename wins+ any concurrent update.++See ADR 0323.## 2026-10-08 — Transcript tool rows never auto-open (D651)@@ -3920,7 +4838,14 @@ The core keeps one automatic title path: the deterministic first-prompt fallback## 2026-10-08 — Keep the deterministic first-prompt session title (D654)-`session.deriveTitle` restores the immediate label a new session used to get from its first prompt: the renderer collapses whitespace and caps the request at 48 characters, and host-core writes it only while the stored title is still a recognized placeholder with the `default` source. See ADR 0323.+- D654 restores the immediate label a new session used to get: the renderer+ collapses whitespace and caps the request at 48 characters.+- host-core writes it only for a recognized placeholder with the `default`+ source and keeps that source, so the plugin can still upgrade it.+- Placeholder recognition now covers every shipped locale, and a remote session+ derives on its own Host.++See ADR 0323.## 2026-10-21 — Cloud sync opens in packaged builds as Experimental (D655)@@ -3937,11 +4862,26 @@ The core keeps one automatic title path: the deterministic first-prompt fallback## 2026-10-11 — Quarantine appends the host keeps refusing (D656)-D656 amends ADR 0041, D318, D444, and D597: the outbox retries an unclassifiable host failure on a bounded backoff (5s, doubling to a 60s cap) and, after five consecutive failures on the same head, quarantines that append into an application-owned dead-letter file and keeps draining the later entries. Related decisions: D318, D444, D597. See ADR 0041.+- D656 amends ADR 0041, D318, D444, and D597: an unclassifiable host failure+ retries on a bounded backoff and, after five consecutive failures, is+ quarantined.+- The append keeps its payload, session id, timestamp, and host error in a+ dead-letter file, is never replayed, and the flush keeps draining.+- The backoff compares the Host generation, `session.delete` drops quarantined+ appends with the queued ones, and only the newest 256 are retained.++See ADR 0041.## 2026-10-13 — Open local files in the embedded Browser (D657)-D657 amends ADR 0170: explicit absolute paths and `file:` URLs can open any existing regular local file, and local-file pages can follow links to other local files. See ADR 0170, ADR 0328.+- D657 amends ADR 0170: absolute paths and `file:` URLs may open any existing+ regular local file, and local pages may follow links to other local files.+- Relative paths stay workspace-rooted, and an HTTP(S) page cannot leave the+ workspace through a file link.+- `pi.browser.navigate` follows the same policy under `browser.cdp`, while+ `BrowserPreview` and the sidecar keep workspace-rooted validation.++See ADR 0328.## 2026-10-13 — Session identity on endpoints the adapters leave anonymous (D658)@@ -3972,7 +4912,15 @@ D657 amends ADR 0170: explicit absolute paths and `file:` URLs can open any exis## 2026-10-14 — Composer file menu rows always show the full relative path (D660)-D660 amends the `@` file-completion row contract in `04-ux/08-component-spec.md` §11.8, `04-ux/09-interaction-patterns.md` §8a.1, and E2E-102a: each row persists the leaf name (directories keep the trailing `/`) followed by the entry's complete workspace-relative path in a de-emphasized mono span that renders the raw `entry.path` without a trailing slash. Related decisions: D209, D362. See ADR 0024, ADR 0070.+- D660 amends the `@` row contract: each row keeps the leaf name then the+ complete workspace-relative path in a de-emphasized mono span.+- The span takes the remaining width and ellipsizes before the leaf name can, so+ a short leaf never truncates and no row overflows.+- The tooltip keeps the full path and the accessible name becomes the path+ alone; reference chips (D209/D362, ADR 0024 / ADR 0070) and serialization are+ unchanged.++See ADR 0024.## 2026-10-16 — Segmented turn process and independent thinking preference (D661)@@ -4005,7 +4953,14 @@ D660 amends the `@` file-completion row contract in `04-ux/08-component-spec.md`## 2026-10-16 — Open scoped HTML files in the work-panel Browser from plugins (D662)-Add `pi.fs.openInBrowser(pathFromRoot)` under `fs.read`. See ADR 0330.+- D662 adds `pi.fs.openInBrowser(pathFromRoot)` under `fs.read`: Main applies the+ plugin's ordinary read gates and accepts existing HTML files only.+- Each call is audited, and Main then sends a dedicated event so the renderer+ opens the file in a Browser tab for the active local session.+- The Browser plugin must be enabled, and the action grants no CDP and exposes no+ controls.++See ADR 0330.## 2026-10-17 — Composer mode control opens a menu instead of cycling (D663)@@ -4037,15 +4992,39 @@ Add `pi.fs.openInBrowser(pathFromRoot)` under `fs.read`. See ADR 0330.## 2026-10-16 — macOS paints an opaque native window surface (D665)-D665 supersedes the macOS `vibrancy: "sidebar"` + `transparent: true` window backing from D348. Related decisions: D348. See ADR 0248, ADR 0332, ADR 0260.+- D665 supersedes D348's macOS vibrancy over a transparent backing, where+ WindowServer recomposited every dirty frame and held an idle window near 40%+ GPU.+- macOS now paints the opaque background the other platforms use, keeping the+ `hiddenInset` titlebar and the renderer's sidebar tint.+- `window.setBackgroundColor` no longer returns early on darwin, so a granted+ theme background applies, and bounded idle animations stay in force (ADR 0248,+ ADR 0260).++See ADR 0332.## 2026-10-20 — macOS translucency is a window setting (D666, amended by D667)-D666 amends D665 / ADR 0332: the macOS main window still paints an opaque native surface by default, and `AppSettings.macosWindowTranslucency` lets a user opt back into the `sidebar` vibrancy material behind a transparent backing. Related decisions: D665. See ADR 0332.+- D666 amends D665: macOS paints an opaque surface by default, and+ `AppSettings.macosWindowTranslucency` opts back into the vibrancy material.+- `macosWindowSurfaceOptions` is the single surface declaration, and+ `mainWindowBackgroundOptions("darwin", color)` keeps the opaque result.+- Electron fixes `transparent` at creation, so the preference is read before+ `new BrowserWindow` and the row shows a restart hint instead of mutating.++See ADR 0332.## 2026-10-20 — macOS translucency stays the default (D667)-D667 amends D665 / D666 and ADR 0332: the macOS main window ships translucent again — `vibrancy: "sidebar"`, `visualEffectState: "followWindow"`, and a transparent `#00000000` backing — and `AppSettings.macosWindowTranslucency` is the opt-out. Related decisions: D665, D666. See ADR 0332, ADR 0248.+- D667 amends D665 and D666: the macOS window ships **translucent** again, with+ the `sidebar` material and a transparent backing, and the setting becomes the+ opt-out.+- Absent and `true` mean the material, only `false` paints the opaque surface,+ and the store defaults to translucent.+- A translucent window owns its pixels, so `applyMainWindowBackground` skips it;+ no migration is needed, and an explicit `false` keeps a chosen opaque surface.++See ADR 0332.## 2026-10-21 — One process disclosure per turn, with three transcript display modes (D668)@@ -4253,7 +5232,16 @@ D667 amends D665 / D666 and ADR 0332: the macOS main window ships translucent ag## 2026-10-28 — One DeepSeek reasoning field per replayed row (D677)-D677 amends ADR 0256 decision 3 (issue #1945). See ADR 0256.+- D677 amends ADR 0256 decision 3: the pi-ai fill pass picks the reasoning field+ of the newest assistant row with real reasoning, then normalizes every row to+ it.+- Real reasoning under another field moves there and the others are removed, so+ a row never carries two, which relays reject.+- The placeholder fills only rows with no reasoning, and+ `withoutReasoningReplayPlaceholder` drops a leading echo from rebuilt history+ and the thinking panel.++See ADR 0256.## 2026-10-29 — Radial context menu rebuilt and moved to General (D678)@@ -4277,19 +5265,52 @@ D677 amends ADR 0256 decision 3 (issue #1945). See ADR 0256.## 2026-11-03 — User-supplied startup animation (D679)-D679 lets a user own the boot surface. A video in `<dataDir>/startup/` replaces the brand splash for that launch: it plays to its last frame, holds the window under the same opaque black it played on until the shell has its initial state, then fades that black out over 1000ms (`--motion-startup-reveal`, the one duration outside the motion ramp). See ADR 0338.+- D679 lets a user own the boot surface: a video in `<dataDir>/startup/` replaces+ the splash, plays to its last frame, then fades under opaque black over 1000ms.+- Discovery is filesystem-only and creates nothing, ranked `webm` > `mp4` >+ `m4v` > `mov`, served over `pi-startup://animation` so no path reaches the+ renderer.+- Three bounds (2s, 15s, the 180s watchdog) keep it recoverable, and+ `AppSettings.startupAnimation` holds `enabled` and `skipWhenReady`.++See ADR 0338.## 2026-10-20 — Plugin session scope: `.all` grants and message-level writes (D680)-D680 / ADR 0340 opens `pi.session` beyond the ADR 0200 import boundary. See ADR 0340, ADR 0200, ADR 0323.+- D680 opens `pi.session` beyond the ADR 0200 boundary with `session.read.all`,+ `session.update.all`, and `session.delete.all`, additions rather than a+ widening.+- Main resolves the scope from granted permissions, host-core enforces it and+ treats an absent `scope` as `own`, and message-level writes exist for the first+ time.+- A rewrite is refused with `TURN_RUNNING` while a turn owns the session,+ `rename` claims the manual title source, and every call audits its scope.++See ADR 0340.## 2026-11-04 — Computer use is a host-owned capability behind a scope grant (D681)-D681 / ADR 0342 accepts bounded native application control as a design. See ADR 0342.+- D681 accepts bounded native application control as a contract, not an+ implementation: a `computer.*` host-core domain behind one high-risk tool,+ `Computer`.+- Authority is one user-minted grant naming a window or application, with+ revision, budget, expiry, input policy, and capture mode; the model cannot+ widen it.+- Identity is accessibility-first, with coordinates only against a captured+ `basis`, and **the agent's cursor is drawn, not stolen**.++See ADR 0342.## 2026-11-05 — Computer use grants the whole desktop automatically (D682)-D682 / ADR 0344 amends ADR 0342 §4 and §6. See ADR 0344, ADR 0342.+- D682 amends ADR 0342 §4 and §6: the picker is removed, a `Grant` carries+ `scope`, and the `Computer` handler mints a `desktop` grant on a first call.+- A desktop grant binds one window at a time, and every rebind moves the+ revision, so older `uid`s and `basis` values stop validating.+- A closed window falls back to the frontmost usable window, runs default to+ `autonomous-in-scope`, and Stop ends it with `COMPUTER_STOPPED_BY_USER`.++See ADR 0344.## 2026-11-05 — The accessibility window is joined by window id, not geometry (D683)