@blackbelt-technology/pi-agent-dashboard 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +20 -17
- package/README.md +6 -0
- package/docs/architecture.md +1834 -119
- package/package.json +32 -17
- package/packages/extension/package.json +22 -11
- package/packages/extension/src/AGENTS.md +25 -3
- package/packages/extension/src/__tests__/agent-settled.test.ts +33 -3
- package/packages/extension/src/__tests__/auto-session-namer.test.ts +814 -27
- package/packages/extension/src/__tests__/autostart-guard.test.ts +103 -0
- package/packages/extension/src/__tests__/autostart-lock.test.ts +167 -0
- package/packages/extension/src/__tests__/bridge-context-window.test.ts +126 -0
- package/packages/extension/src/__tests__/bridge-default-thinking-level-apply.test.ts +131 -0
- package/packages/extension/src/__tests__/bridge-followup-drain-entries.test.ts +121 -0
- package/packages/extension/src/__tests__/bridge-queue-update-forward.test.ts +142 -1
- package/packages/extension/src/__tests__/bridge-ticket-client.test.ts +92 -0
- package/packages/extension/src/__tests__/command-handler.test.ts +451 -11
- package/packages/extension/src/__tests__/command-path-mapping.test.ts +77 -0
- package/packages/extension/src/__tests__/commit-draft-agent-session.test.ts +129 -0
- package/packages/extension/src/__tests__/connect-target.test.ts +154 -0
- package/packages/extension/src/__tests__/connection-inbound-drop-report.test.ts +256 -0
- package/packages/extension/src/__tests__/connection-inbound-pump.test.ts +661 -0
- package/packages/extension/src/__tests__/connection-register-rejected.test.ts +128 -0
- package/packages/extension/src/__tests__/connection-suppress-auto-start.test.ts +9 -0
- package/packages/extension/src/__tests__/connection.test.ts +200 -1
- package/packages/extension/src/__tests__/custom-provider-apikey-roundtrip.test.ts +45 -0
- package/packages/extension/src/__tests__/doctor/checks.test.ts +6 -42
- package/packages/extension/src/__tests__/doctor/modules.test.ts +1 -0
- package/packages/extension/src/__tests__/doctor/router.test.ts +5 -1
- package/packages/extension/src/__tests__/endpoint-resolution.test.ts +179 -0
- package/packages/extension/src/__tests__/enrich-model-metadata.test.ts +128 -2
- package/packages/extension/src/__tests__/eventbus-foreign-emit-forwarding.test.ts +177 -0
- package/packages/extension/src/__tests__/followup-buffer.test.ts +309 -0
- package/packages/extension/src/__tests__/followup-content.test.ts +125 -0
- package/packages/extension/src/__tests__/helpers/settle-prompts.ts +42 -0
- package/packages/extension/src/__tests__/instance-verification.test.ts +171 -0
- package/packages/extension/src/__tests__/local-token-header.test.ts +67 -0
- package/packages/extension/src/__tests__/model-refresh-timeout.test.ts +61 -0
- package/packages/extension/src/__tests__/openspec-activity-detector.test.ts +119 -55
- package/packages/extension/src/__tests__/pi-retry-settings.test.ts +66 -0
- package/packages/extension/src/__tests__/pi-version-tracker.test.ts +69 -0
- package/packages/extension/src/__tests__/prompt-bus-inflight-settle.test.ts +133 -0
- package/packages/extension/src/__tests__/prompt-bus-wiring.test.ts +123 -26
- package/packages/extension/src/__tests__/prompt-bus.test.ts +44 -29
- package/packages/extension/src/__tests__/provider-register-reload.test.ts +215 -0
- package/packages/extension/src/__tests__/provider-register-thinking-levels.test.ts +37 -0
- package/packages/extension/src/__tests__/remote-registration-gate.test.ts +113 -0
- package/packages/extension/src/__tests__/removed-typebox-api-audit.test.ts +51 -0
- package/packages/extension/src/__tests__/request-models-refresh-errors.test.ts +132 -0
- package/packages/extension/src/__tests__/retry-tracker.test.ts +439 -97
- package/packages/extension/src/__tests__/role-manager.test.ts +57 -0
- package/packages/extension/src/__tests__/role-model-tools-scoped-models.test.ts +83 -0
- package/packages/extension/src/__tests__/server-auto-start-guarded.test.ts +266 -0
- package/packages/extension/src/__tests__/server-auto-start.test.ts +16 -0
- package/packages/extension/src/__tests__/server-pin-store.test.ts +123 -0
- package/packages/extension/src/__tests__/session-move.test.ts +521 -0
- package/packages/extension/src/__tests__/session-register-carries-pid.test.ts +98 -0
- package/packages/extension/src/__tests__/subagent-forward-sites.test.ts +199 -0
- package/packages/extension/src/__tests__/subagent-frame-strip.test.ts +179 -0
- package/packages/extension/src/__tests__/subagent-tick-growth.test.ts +94 -0
- package/packages/extension/src/__tests__/subagent-tick-throttle.test.ts +402 -0
- package/packages/extension/src/__tests__/transcript-backfill.test.ts +148 -0
- package/packages/extension/src/__tests__/transcript-request-guard.test.ts +102 -0
- package/packages/extension/src/__tests__/transport-diagnostics.test.ts +93 -0
- package/packages/extension/src/__tests__/tui-prompt-adapter.test.ts +18 -11
- package/packages/extension/src/__tests__/turn-actionability.test.ts +19 -0
- package/packages/extension/src/__tests__/typebox-nullable-array-validation.test.ts +40 -0
- package/packages/extension/src/__tests__/ui-stale-guard.test.ts +181 -0
- package/packages/extension/src/abort-latch.ts.AGENTS.md +2 -0
- package/packages/extension/src/agent-settled.ts +27 -9
- package/packages/extension/src/agent-settled.ts.AGENTS.md +1 -1
- package/packages/extension/src/auto-session-namer.ts +486 -70
- package/packages/extension/src/auto-session-namer.ts.AGENTS.md +1 -1
- package/packages/extension/src/autostart-guard.ts +99 -0
- package/packages/extension/src/autostart-lock.ts +258 -0
- package/packages/extension/src/bridge-context.ts +86 -5
- package/packages/extension/src/bridge-context.ts.AGENTS.md +1 -1
- package/packages/extension/src/bridge-ticket-client.ts +105 -0
- package/packages/extension/src/bridge.ts +917 -213
- package/packages/extension/src/bridge.ts.AGENTS.md +4 -1
- package/packages/extension/src/command-handler.ts +332 -57
- package/packages/extension/src/command-handler.ts.AGENTS.md +3 -1
- package/packages/extension/src/connect-target.ts +130 -0
- package/packages/extension/src/connection.ts +371 -7
- package/packages/extension/src/connection.ts.AGENTS.md +3 -0
- package/packages/extension/src/endpoint-resolution.ts +221 -0
- package/packages/extension/src/endpoint-resolution.ts.AGENTS.md +11 -0
- package/packages/extension/src/flow-event-wiring.ts +125 -3
- package/packages/extension/src/flow-event-wiring.ts.AGENTS.md +2 -0
- package/packages/extension/src/followup-buffer.ts +217 -0
- package/packages/extension/src/instance-verification.ts +125 -0
- package/packages/extension/src/local-token-header.ts +44 -0
- package/packages/extension/src/model-refresh.ts +95 -0
- package/packages/extension/src/notify-proxy.ts +33 -0
- package/packages/extension/src/pi-env.d.ts +4 -0
- package/packages/extension/src/pi-retry-settings.ts +91 -0
- package/packages/extension/src/provider-register.ts +86 -21
- package/packages/extension/src/remote-registration-gate.ts +102 -0
- package/packages/extension/src/retry-tracker.ts +265 -86
- package/packages/extension/src/retry-tracker.ts.AGENTS.md +7 -1
- package/packages/extension/src/role-manager.ts +20 -0
- package/packages/extension/src/role-manager.ts.AGENTS.md +1 -1
- package/packages/extension/src/role-model-tools.ts +38 -3
- package/packages/extension/src/server-auto-start.ts +144 -2
- package/packages/extension/src/server-auto-start.ts.AGENTS.md +2 -0
- package/packages/extension/src/server-pin-store.ts +92 -0
- package/packages/extension/src/session-move.ts +275 -0
- package/packages/extension/src/session-sync.ts +24 -5
- package/packages/extension/src/session-sync.ts.AGENTS.md +1 -1
- package/packages/extension/src/subagent-forward-sites.ts +69 -0
- package/packages/extension/src/subagent-frame-buffer.ts +24 -3
- package/packages/extension/src/subagent-frame-strip.ts +109 -0
- package/packages/extension/src/subagent-tick-throttle.ts +250 -0
- package/packages/extension/src/transcript-backfill.ts +151 -0
- package/packages/extension/src/transcript-request-guard.ts +76 -0
- package/packages/extension/src/transport-diagnostics.ts +76 -0
- package/packages/extension/src/turn-actionability.ts +20 -0
- package/packages/extension/src/ui-stale-guard.ts +58 -0
- package/packages/server/bin/pi-dashboard.mjs +43 -1
- package/packages/server/package.json +17 -10
- package/packages/server/src/AGENTS.md +7 -5
- package/packages/server/src/__tests__/auth-plugin.test.ts +64 -0
- package/packages/server/src/__tests__/auth-provider-delete.test.ts +233 -0
- package/packages/server/src/__tests__/auth-redirect-base.test.ts +659 -0
- package/packages/server/src/__tests__/auth.test.ts +46 -11
- package/packages/server/src/__tests__/auto-attach-locality.test.ts +338 -0
- package/packages/server/src/__tests__/auto-name-outcomes-route.test.ts +60 -0
- package/packages/server/src/__tests__/boot-async-owners.test.ts +107 -0
- package/packages/server/src/__tests__/boot-state.test.ts +121 -0
- package/packages/server/src/__tests__/bounded-startup.test.ts +150 -0
- package/packages/server/src/__tests__/bridge-contention.test.ts +300 -0
- package/packages/server/src/__tests__/bridge-local-token-upgrade.test.ts +106 -0
- package/packages/server/src/__tests__/bridge-ticket-eligibility.test.ts +116 -0
- package/packages/server/src/__tests__/bridge-ticket-scope.test.ts +114 -0
- package/packages/server/src/__tests__/bridge-upgrade-auth.test.ts +327 -0
- package/packages/server/src/__tests__/browser-gateway-load.test.ts +289 -1
- package/packages/server/src/__tests__/browser-gateway-register-handler.test.ts +102 -0
- package/packages/server/src/__tests__/browser-gateway-retry-session.test.ts +91 -0
- package/packages/server/src/__tests__/browser-gateway-shutdown-reject.test.ts +112 -0
- package/packages/server/src/__tests__/browser-gateway-snapshot-on-connect.test.ts +114 -2
- package/packages/server/src/__tests__/cli-parse.test.ts +51 -1
- package/packages/server/src/__tests__/cli-signal-forwarding.test.ts +97 -0
- package/packages/server/src/__tests__/collapse-replay-equivalence.test.ts +296 -0
- package/packages/server/src/__tests__/concurrent-launch.test.ts +3 -2
- package/packages/server/src/__tests__/config-api.test.ts +288 -3
- package/packages/server/src/__tests__/contention-performance.test.ts +190 -0
- package/packages/server/src/__tests__/contention-prompt-and-resume-guard.test.ts +234 -0
- package/packages/server/src/__tests__/contention-refusal-side-effects.test.ts +194 -0
- package/packages/server/src/__tests__/contention-resume-guard-api.test.ts +363 -0
- package/packages/server/src/__tests__/cors.test.ts +228 -1
- package/packages/server/src/__tests__/crash-recovery.test.ts +3 -2
- package/packages/server/src/__tests__/directory-service-openspec-enabled.test.ts +2 -1
- package/packages/server/src/__tests__/directory-service-refresh-force.test.ts +2 -1
- package/packages/server/src/__tests__/directory-service-specs-mtime.test.ts +2 -1
- package/packages/server/src/__tests__/directory-service-toctou.test.ts +2 -1
- package/packages/server/src/__tests__/directory-service.test.ts +2 -1
- package/packages/server/src/__tests__/dispatch-extension-command-router.test.ts +3 -2
- package/packages/server/src/__tests__/dispatch-reload-rollout.test.ts +99 -0
- package/packages/server/src/__tests__/doctor-route.test.ts +8 -4
- package/packages/server/src/__tests__/ended-session-endedat.test.ts +302 -0
- package/packages/server/src/__tests__/event-status-extraction.test.ts +100 -3
- package/packages/server/src/__tests__/event-wiring-queue-state.test.ts +145 -7
- package/packages/server/src/__tests__/exit-intent-paths.test.ts +73 -0
- package/packages/server/src/__tests__/faux-agent-ticks.unit.test.ts +287 -0
- package/packages/server/src/__tests__/fixtures/replay-streams.ts +219 -0
- package/packages/server/src/__tests__/folder-head-integration.test.ts +249 -4
- package/packages/server/src/__tests__/folder-head-poll.test.ts +149 -8
- package/packages/server/src/__tests__/force-kill-handler.test.ts +1 -0
- package/packages/server/src/__tests__/fork-empty-session-preflight.test.ts +6 -2
- package/packages/server/src/__tests__/forwarded-ip-trust.test.ts +136 -0
- package/packages/server/src/__tests__/gateway-listener-wiring.test.ts +81 -0
- package/packages/server/src/__tests__/gateway-socket-bind.test.ts +272 -0
- package/packages/server/src/__tests__/gateway-transport-policy.test.ts +64 -0
- package/packages/server/src/__tests__/genuine-local.test.ts +1 -1
- package/packages/server/src/__tests__/git-worktree-lifecycle-ops.test.ts +260 -3
- package/packages/server/src/__tests__/git-worktree-lifecycle-routes.test.ts +292 -5
- package/packages/server/src/__tests__/git-worktree-lifecycle.test.ts +43 -3
- package/packages/server/src/__tests__/git-worktree.test.ts +92 -6
- package/packages/server/src/__tests__/headless-pid-registry.test.ts +204 -0
- package/packages/server/src/__tests__/health-endpoint.test.ts +88 -0
- package/packages/server/src/__tests__/health-shape.test.ts +93 -1
- package/packages/server/src/__tests__/helpers/load-fixtures.ts +145 -1
- package/packages/server/src/__tests__/home-lock-escape-hatch.test.ts +3 -2
- package/packages/server/src/__tests__/home-lock.test.ts +390 -16
- package/packages/server/src/__tests__/home-rendezvous.test.ts +150 -0
- package/packages/server/src/__tests__/identity.test.ts +50 -0
- package/packages/server/src/__tests__/inline-terminal-handler.test.ts +102 -10
- package/packages/server/src/__tests__/is-unread-trigger.test.ts +56 -0
- package/packages/server/src/__tests__/keeper-manager.test.ts +99 -0
- package/packages/server/src/__tests__/liveness-stamp-wiring.test.ts +13 -3
- package/packages/server/src/__tests__/local-token.test.ts +44 -0
- package/packages/server/src/__tests__/localhost-guard.test.ts +57 -2
- package/packages/server/src/__tests__/memory-event-store.test.ts +865 -23
- package/packages/server/src/__tests__/memory-session-manager.test.ts +46 -2
- package/packages/server/src/__tests__/move-folder-handler.test.ts +151 -0
- package/packages/server/src/__tests__/node-cap-message-matches-engines.test.ts +55 -0
- package/packages/server/src/__tests__/node-guard.test.ts +23 -10
- package/packages/server/src/__tests__/notify-log-persistence.test.ts +98 -0
- package/packages/server/src/__tests__/openspec-locality.test.ts +170 -0
- package/packages/server/src/__tests__/openspec-poll-worker.test.ts +53 -1
- package/packages/server/src/__tests__/pairing.test.ts +24 -0
- package/packages/server/src/__tests__/pending-attach-registry.test.ts +15 -0
- package/packages/server/src/__tests__/pending-client-correlations.test.ts +77 -0
- package/packages/server/src/__tests__/pending-fork-registry.test.ts +43 -17
- package/packages/server/src/__tests__/pending-prompt-acks.test.ts +105 -0
- package/packages/server/src/__tests__/pending-resume-intent-registry.test.ts +15 -0
- package/packages/server/src/__tests__/pi-agent-settings.test.ts +193 -0
- package/packages/server/src/__tests__/pi-gateway-bind-host.test.ts +76 -3
- package/packages/server/src/__tests__/pi-gateway-duplicate-register.test.ts +819 -0
- package/packages/server/src/__tests__/pi-gateway-socket-transport.test.ts +372 -0
- package/packages/server/src/__tests__/pi-gateway-teardown.test.ts +45 -0
- package/packages/server/src/__tests__/pi-resource-activation-timeout.test.ts +85 -0
- package/packages/server/src/__tests__/pi-resource-scanner.test.ts +299 -28
- package/packages/server/src/__tests__/pi-runtime-divergence.test.ts +251 -0
- package/packages/server/src/__tests__/pi-runtime-routes.test.ts +273 -0
- package/packages/server/src/__tests__/pi-version-skew-recommended-0-84.test.ts +48 -0
- package/packages/server/src/__tests__/pi-version-skew.test.ts +103 -0
- package/packages/server/src/__tests__/plugin-pi-message-attribution.test.ts +150 -0
- package/packages/server/src/__tests__/preferences-store-move-folder.test.ts +141 -0
- package/packages/server/src/__tests__/preferences-store.test.ts +87 -0
- package/packages/server/src/__tests__/process-manager-codes.test.ts +3 -0
- package/packages/server/src/__tests__/process-manager-keeper-spawn.test.ts +1 -0
- package/packages/server/src/__tests__/process-manager.test.ts +315 -28
- package/packages/server/src/__tests__/prompt-derived-tool-state.integration.test.ts +796 -0
- package/packages/server/src/__tests__/provider-health-cache-route.test.ts +229 -0
- package/packages/server/src/__tests__/provisional-register-routing.test.ts +598 -0
- package/packages/server/src/__tests__/reattach-placement.test.ts +2 -1
- package/packages/server/src/__tests__/recommended-routes.test.ts +222 -5
- package/packages/server/src/__tests__/recovery-e2e.test.ts +12 -5
- package/packages/server/src/__tests__/recovery-exit-intent.test.ts +252 -0
- package/packages/server/src/__tests__/recovery-offer.test.ts +33 -21
- package/packages/server/src/__tests__/recovery-reattach-retraction.test.ts +6 -2
- package/packages/server/src/__tests__/recovery-reinstall-reject.test.ts +89 -0
- package/packages/server/src/__tests__/recovery-server.test.ts +56 -0
- package/packages/server/src/__tests__/replay-compaction-equivalence.test.ts +89 -0
- package/packages/server/src/__tests__/replay-compaction.test.ts +208 -0
- package/packages/server/src/__tests__/replay-streams-fixtures.test.ts +67 -0
- package/packages/server/src/__tests__/resource-activation-routes.test.ts +405 -9
- package/packages/server/src/__tests__/resource-activation-toggle.test.ts +870 -117
- package/packages/server/src/__tests__/restart-helper.test.ts +51 -0
- package/packages/server/src/__tests__/resume-remote-origin-bus.test.ts +160 -0
- package/packages/server/src/__tests__/routes-git-worktree-init.test.ts +95 -7
- package/packages/server/src/__tests__/session-action-handler-followup-queue.test.ts +16 -9
- package/packages/server/src/__tests__/session-action-handler-headless-reload.test.ts +255 -4
- package/packages/server/src/__tests__/session-action-handler-reload-predicate.test.ts +131 -42
- package/packages/server/src/__tests__/session-api.test.ts +41 -4
- package/packages/server/src/__tests__/session-card-ordering-gates.test.ts +138 -0
- package/packages/server/src/__tests__/session-load-worker.test.ts +46 -1
- package/packages/server/src/__tests__/session-name-provenance-persistence.test.ts +48 -0
- package/packages/server/src/__tests__/session-order-manager.test.ts +1 -0
- package/packages/server/src/__tests__/session-order-reboot.test.ts +2 -1
- package/packages/server/src/__tests__/session-ordering-integration.test.ts +2 -1
- package/packages/server/src/__tests__/session-skill-registry.test.ts +295 -0
- package/packages/server/src/__tests__/shutdown-orphan-signal.test.ts +108 -0
- package/packages/server/src/__tests__/shutdown-terminates-any-strategy.test.ts +294 -0
- package/packages/server/src/__tests__/spawn-correlation-performance.test.ts +125 -0
- package/packages/server/src/__tests__/spawn-correlation-token-integration.test.ts +2 -2
- package/packages/server/src/__tests__/spawn-correlation-ttl-derivation.test.ts +182 -0
- package/packages/server/src/__tests__/spawn-register-watchdog.test.ts +487 -2
- package/packages/server/src/__tests__/spawn-token.test.ts +65 -1
- package/packages/server/src/__tests__/start-teardown-wiring.test.ts +64 -0
- package/packages/server/src/__tests__/subscription-handler-backfill.test.ts +693 -0
- package/packages/server/src/__tests__/subscription-handler-compaction.test.ts +227 -0
- package/packages/server/src/__tests__/subscription-handler-window.test.ts +473 -0
- package/packages/server/src/__tests__/subscription-handler.test.ts +236 -7
- package/packages/server/src/__tests__/terminal-gateway.test.ts +3 -0
- package/packages/server/src/__tests__/terminal-manager.test.ts +318 -16
- package/packages/server/src/__tests__/thin-subagent-tick-downstream.test.ts +81 -0
- package/packages/server/src/__tests__/tool-routes.test.ts +68 -7
- package/packages/server/src/__tests__/trusted-networks-config.test.ts +108 -3
- package/packages/server/src/__tests__/tunnel-concurrency-wiring.test.ts +215 -0
- package/packages/server/src/__tests__/tunnel-core-executor.test.ts +88 -0
- package/packages/server/src/__tests__/tunnel-readiness.test.ts +328 -0
- package/packages/server/src/__tests__/tunnel-reserved-name-route.test.ts +317 -0
- package/packages/server/src/__tests__/tunnel.test.ts +54 -0
- package/packages/server/src/__tests__/ui-decorators-replay.test.ts +1 -0
- package/packages/server/src/__tests__/ui-modules-replay.test.ts +17 -2
- package/packages/server/src/__tests__/ws-ticket.test.ts +66 -1
- package/packages/server/src/__tests__/zrok-reserved-name.test.ts +326 -0
- package/packages/server/src/attachments/AGENTS.md +15 -0
- package/packages/server/src/attachments/__tests__/attachment-ingest.test.ts +236 -0
- package/packages/server/src/attachments/__tests__/attachment-resolver.test.ts +339 -0
- package/packages/server/src/attachments/__tests__/display-fit-perf.test.ts +247 -0
- package/packages/server/src/attachments/__tests__/display-fit.test.ts +397 -0
- package/packages/server/src/attachments/__tests__/fit-worker-pool-fallback.test.ts +158 -0
- package/packages/server/src/attachments/__tests__/fit-worker-pool.test.ts +105 -0
- package/packages/server/src/attachments/__tests__/fit-worker-total.test.ts +27 -0
- package/packages/server/src/attachments/__tests__/original-store.test.ts +185 -0
- package/packages/server/src/attachments/attachment-ingest.ts +165 -0
- package/packages/server/src/attachments/attachment-resolver.ts +172 -0
- package/packages/server/src/attachments/display-fit.ts +307 -0
- package/packages/server/src/attachments/fit-worker-pool.ts +367 -0
- package/packages/server/src/attachments/fit-worker.ts +89 -0
- package/packages/server/src/attachments/gif.ts +124 -0
- package/packages/server/src/attachments/image-mime.ts +52 -0
- package/packages/server/src/attachments/original-store.ts +133 -0
- package/packages/server/src/auth/AGENTS.md +5 -2
- package/packages/server/src/auth/auth-plugin.ts +56 -20
- package/packages/server/src/auth/auth-plugin.ts.AGENTS.md +3 -1
- package/packages/server/src/auth/auth.ts +128 -4
- package/packages/server/src/auth/auth.ts.AGENTS.md +1 -1
- package/packages/server/src/auth/bind-reachability-service.ts +132 -0
- package/packages/server/src/auth/bridge-ticket-eligibility.ts +78 -0
- package/packages/server/src/auth/cors-origin.ts +26 -0
- package/packages/server/src/auth/local-token.ts +13 -3
- package/packages/server/src/auth/local-token.ts.AGENTS.md +2 -0
- package/packages/server/src/auth/localhost-guard.ts +11 -12
- package/packages/server/src/auth/localhost-guard.ts.AGENTS.md +3 -1
- package/packages/server/src/auth/loopback.ts +17 -0
- package/packages/server/src/auth/node-guard.ts +2 -2
- package/packages/server/src/auth/ws-ticket.ts +43 -8
- package/packages/server/src/auth/ws-ticket.ts.AGENTS.md +2 -0
- package/packages/server/src/auto-name-outcome-store.ts +92 -0
- package/packages/server/src/browser-handlers/AGENTS.md +5 -5
- package/packages/server/src/browser-handlers/__tests__/directory-handler.test.ts +96 -0
- package/packages/server/src/browser-handlers/__tests__/session-action-handler.test.ts +191 -2
- package/packages/server/src/browser-handlers/__tests__/session-meta-handler.test.ts +41 -1
- package/packages/server/src/browser-handlers/directory-handler.ts +73 -7
- package/packages/server/src/browser-handlers/handler-context.ts +36 -0
- package/packages/server/src/browser-handlers/session-action-handler.ts +468 -25
- package/packages/server/src/browser-handlers/session-action-helpers.ts +14 -17
- package/packages/server/src/browser-handlers/session-meta-handler.ts +12 -4
- package/packages/server/src/browser-handlers/subscription-handler.ts +669 -43
- package/packages/server/src/browser-handlers/terminal-handler.ts +34 -5
- package/packages/server/src/cli.ts +96 -23
- package/packages/server/src/cli.ts.AGENTS.md +1 -1
- package/packages/server/src/config-api.ts +79 -1
- package/packages/server/src/config-api.ts.AGENTS.md +2 -0
- package/packages/server/src/config-snapshot.ts +84 -0
- package/packages/server/src/directory-service.ts +105 -7
- package/packages/server/src/embed-lifecycle/AGENTS.md +1 -1
- package/packages/server/src/embed-lifecycle/__tests__/embed-lifecycle-controller.test.ts +110 -0
- package/packages/server/src/embed-lifecycle/__tests__/visitor-session-registry.test.ts +6 -1
- package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +17 -1
- package/packages/server/src/event-wiring.ts +622 -88
- package/packages/server/src/event-wiring.ts.AGENTS.md +4 -1
- package/packages/server/src/git-worktree/folder-head-poll.ts +34 -20
- package/packages/server/src/git-worktree/git-operations.ts +128 -8
- package/packages/server/src/git-worktree/git-operations.ts.AGENTS.md +1 -1
- package/packages/server/src/git-worktree/git-worktree-lifecycle.ts +43 -6
- package/packages/server/src/git-worktree/git-worktree-lifecycle.ts.AGENTS.md +1 -1
- package/packages/server/src/git-worktree/git-worktree.ts +8 -0
- package/packages/server/src/git-worktree/git-worktree.ts.AGENTS.md +1 -1
- package/packages/server/src/goal/goal-supervisor.ts +1 -1
- package/packages/server/src/lib/grep.ts +3 -1
- package/packages/server/src/lifecycle/AGENTS.md +4 -1
- package/packages/server/src/lifecycle/bounded-startup.ts +106 -0
- package/packages/server/src/lifecycle/home-lock.ts +174 -25
- package/packages/server/src/lifecycle/home-rendezvous.ts +169 -0
- package/packages/server/src/lifecycle/instance-id.ts +118 -0
- package/packages/server/src/lifecycle/recovery-server.ts +68 -13
- package/packages/server/src/lifecycle/recovery-server.ts.AGENTS.md +1 -1
- package/packages/server/src/model-proxy/__tests__/internal-auth-storage-refresh.test.ts +148 -0
- package/packages/server/src/model-proxy/__tests__/internal-registry-native-merge.test.ts +124 -0
- package/packages/server/src/model-proxy/__tests__/internal-registry.test.ts +101 -0
- package/packages/server/src/model-proxy/__tests__/read-native-models.test.ts +40 -0
- package/packages/server/src/model-proxy/custom-provider-discovery.ts +18 -10
- package/packages/server/src/model-proxy/internal-auth-storage.ts +64 -18
- package/packages/server/src/model-proxy/internal-registry.ts +33 -3
- package/packages/server/src/openspec/openspec-poll-worker-pool.ts +14 -1
- package/packages/server/src/package/__tests__/provider-probe-metadata.test.ts +313 -0
- package/packages/server/src/package/provider-probe.ts +45 -9
- package/packages/server/src/pairing/AGENTS.md +3 -1
- package/packages/server/src/pairing/__tests__/subagent-resync-routing.test.ts +93 -0
- package/packages/server/src/pairing/browser-gateway.ts +222 -5
- package/packages/server/src/pairing/browser-gateway.ts.AGENTS.md +2 -1
- package/packages/server/src/pairing/notify-log.ts +100 -0
- package/packages/server/src/pairing/subagent-resync-routing.ts +76 -0
- package/packages/server/src/pending/AGENTS.md +3 -2
- package/packages/server/src/pending/pending-client-correlations.ts +15 -16
- package/packages/server/src/pending/pending-client-correlations.ts.AGENTS.md +1 -1
- package/packages/server/src/pending/pending-fork-registry.ts +14 -8
- package/packages/server/src/pending/pending-fork-registry.ts.AGENTS.md +1 -1
- package/packages/server/src/pending/pending-prompt-acks.ts +116 -0
- package/packages/server/src/pending/pending-prompt-acks.ts.AGENTS.md +3 -0
- package/packages/server/src/persistence/AGENTS.md +1 -0
- package/packages/server/src/persistence/boot-state.ts +127 -0
- package/packages/server/src/persistence/memory-event-store.ts +577 -23
- package/packages/server/src/persistence/memory-event-store.ts.AGENTS.md +3 -1
- package/packages/server/src/persistence/preferences-store.ts +56 -1
- package/packages/server/src/persistence/preferences-store.ts.AGENTS.md +2 -1
- package/packages/server/src/pi/AGENTS.md +12 -2
- package/packages/server/src/pi/__tests__/provisional-registration.test.ts +176 -0
- package/packages/server/src/pi/bridge-contention.ts +220 -0
- package/packages/server/src/pi/bridge-contention.ts.AGENTS.md +9 -0
- package/packages/server/src/pi/bridge-upgrade-auth.ts +161 -0
- package/packages/server/src/pi/gateway-socket-bind.ts +268 -0
- package/packages/server/src/pi/gateway-socket-bind.ts.AGENTS.md +15 -0
- package/packages/server/src/pi/gateway-transport-policy.ts +65 -0
- package/packages/server/src/pi/pi-gateway.ts +752 -65
- package/packages/server/src/pi/pi-gateway.ts.AGENTS.md +3 -0
- package/packages/server/src/pi/pi-resource-activation.ts +46 -3
- package/packages/server/src/pi/pi-resource-activation.ts.AGENTS.md +1 -1
- package/packages/server/src/pi/pi-resource-scanner.ts +186 -12
- package/packages/server/src/pi/pi-resource-scanner.ts.AGENTS.md +1 -1
- package/packages/server/src/pi/pi-runtime.ts +240 -0
- package/packages/server/src/pi/pi-version-skew.ts +18 -65
- package/packages/server/src/pi/provisional-registration.ts +152 -0
- package/packages/server/src/pi/resource-activation-toggle.ts +376 -91
- package/packages/server/src/pi/resource-activation-toggle.ts.AGENTS.md +1 -1
- package/packages/server/src/pi/resource-entry-ownership.ts +93 -0
- package/packages/server/src/pi/resource-entry-ownership.ts.AGENTS.md +3 -0
- package/packages/server/src/pi/resource-origin.ts +183 -0
- package/packages/server/src/pi/resource-origin.ts.AGENTS.md +3 -0
- package/packages/server/src/pi/resource-toggle-trust.ts +161 -0
- package/packages/server/src/pi/resource-toggle-trust.ts.AGENTS.md +3 -0
- package/packages/server/src/pi/session-skill-registry.ts +249 -0
- package/packages/server/src/pi/session-skill-registry.ts.AGENTS.md +3 -0
- package/packages/server/src/pi-agent-settings.ts +209 -0
- package/packages/server/src/routes/AGENTS.md +35 -30
- package/packages/server/src/routes/__tests__/attachment-routes.test.ts +161 -0
- package/packages/server/src/routes/__tests__/pi-retry-routes.test.ts +84 -0
- package/packages/server/src/routes/attachment-routes.ts +87 -0
- package/packages/server/src/routes/attachment-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/doctor-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/file-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/git-routes.ts +153 -19
- package/packages/server/src/routes/git-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/goal-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/known-servers-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/live-server-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/manifest-route.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/model-proxy-api-key-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/model-proxy-diagnostics-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/model-proxy-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/models-introspection-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/network-interfaces.ts +64 -0
- package/packages/server/src/routes/network-interfaces.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/openspec-group-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/openspec-routes.ts +17 -2
- package/packages/server/src/routes/openspec-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/package-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/pairing-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/pi-changelog-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/pi-core-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/pi-retry-routes.ts +57 -0
- package/packages/server/src/routes/pi-retry-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/pi-runtime-routes.ts +181 -0
- package/packages/server/src/routes/plugin-activation-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/plugin-config-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/preferences-auto-name-routes.ts +16 -1
- package/packages/server/src/routes/preferences-auto-name-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/preferences-display-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/preferences-worktree-init-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/provider-auth-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/provider-health-cache.ts +46 -0
- package/packages/server/src/routes/provider-health-cache.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/provider-routes.ts +50 -9
- package/packages/server/src/routes/provider-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/recommended-routes.ts +91 -10
- package/packages/server/src/routes/recommended-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/resource-activation-routes.ts +150 -14
- package/packages/server/src/routes/resource-activation-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/route-deps.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/session-routes.ts +16 -0
- package/packages/server/src/routes/session-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/system-routes.ts +486 -45
- package/packages/server/src/routes/system-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/routes/tool-routes.ts +32 -3
- package/packages/server/src/routes/tool-routes.ts.AGENTS.md +3 -0
- package/packages/server/src/rpc-keeper/AGENTS.md +2 -1
- package/packages/server/src/rpc-keeper/__tests__/keeper.test.ts +107 -0
- package/packages/server/src/rpc-keeper/dispatch-reload.ts +212 -0
- package/packages/server/src/rpc-keeper/keeper-manager.ts +79 -3
- package/packages/server/src/rpc-keeper/keeper.cjs +38 -1
- package/packages/server/src/server.ts +590 -95
- package/packages/server/src/server.ts.AGENTS.md +7 -1
- package/packages/server/src/session/AGENTS.md +9 -4
- package/packages/server/src/session/__tests__/remote-transcript-store.test.ts +176 -0
- package/packages/server/src/session/__tests__/session-origin.test.ts +153 -0
- package/packages/server/src/session/active-sessions-in-cwd.ts +6 -23
- package/packages/server/src/session/derive-ended-at.ts +56 -0
- package/packages/server/src/session/event-status-extraction.ts +42 -2
- package/packages/server/src/session/event-status-extraction.ts.AGENTS.md +1 -1
- package/packages/server/src/session/memory-session-manager.ts +84 -6
- package/packages/server/src/session/memory-session-manager.ts.AGENTS.md +2 -0
- package/packages/server/src/session/openspec-locality.ts +112 -0
- package/packages/server/src/session/remote-transcript-store.ts +150 -0
- package/packages/server/src/session/replay-compaction.ts +125 -0
- package/packages/server/src/session/replay-compaction.ts.AGENTS.md +5 -0
- package/packages/server/src/session/session-api.ts +152 -19
- package/packages/server/src/session/session-api.ts.AGENTS.md +4 -0
- package/packages/server/src/session/session-bootstrap.ts +9 -0
- package/packages/server/src/session/session-load-worker-pool.ts +14 -1
- package/packages/server/src/session/session-origin.ts +128 -0
- package/packages/server/src/session/session-scanner.ts +28 -18
- package/packages/server/src/session/session-to-meta.ts +14 -1
- package/packages/server/src/spawn-process/AGENTS.md +4 -3
- package/packages/server/src/spawn-process/headless-pid-registry.ts +78 -7
- package/packages/server/src/spawn-process/headless-pid-registry.ts.AGENTS.md +1 -1
- package/packages/server/src/spawn-process/process-manager.ts +86 -31
- package/packages/server/src/spawn-process/process-manager.ts.AGENTS.md +3 -1
- package/packages/server/src/spawn-process/restart-helper.ts +27 -1
- package/packages/server/src/spawn-process/spawn-failure-log.ts +7 -0
- package/packages/server/src/spawn-process/spawn-failure-log.ts.AGENTS.md +3 -0
- package/packages/server/src/spawn-process/spawn-recovery-window.ts +37 -0
- package/packages/server/src/spawn-process/spawn-recovery-window.ts.AGENTS.md +3 -0
- package/packages/server/src/spawn-process/spawn-register-watchdog.ts +284 -87
- package/packages/server/src/spawn-process/spawn-register-watchdog.ts.AGENTS.md +3 -0
- package/packages/server/src/terminal/terminal-manager.ts +172 -11
- package/packages/server/src/terminal/terminal-manager.ts.AGENTS.md +9 -1
- package/packages/server/src/test-support/AGENTS.md +3 -1
- package/packages/server/src/test-support/__tests__/event-loop-lag.test.ts +48 -0
- package/packages/server/src/test-support/event-loop-lag.ts +63 -0
- package/packages/server/src/test-support/test-server.ts +3 -0
- package/packages/server/src/tunnel/AGENTS.md +2 -1
- package/packages/server/src/tunnel/tunnel-block-events.ts +1 -1
- package/packages/server/src/tunnel/tunnel-core.ts +22 -3
- package/packages/server/src/tunnel/tunnel-readiness.ts +208 -0
- package/packages/server/src/tunnel/tunnel.ts +282 -8
- package/packages/server/src/tunnel-providers/AGENTS.md +2 -1
- package/packages/server/src/tunnel-providers/daemon-exec.ts +52 -0
- package/packages/server/src/tunnel-providers/ngrok.ts +22 -0
- package/packages/server/src/tunnel-providers/tailscale.ts +91 -1
- package/packages/server/src/tunnel-providers/zerotier.ts +54 -1
- package/packages/server/src/tunnel-providers/zrok.ts +207 -15
- package/packages/shared/package.json +18 -3
- package/packages/shared/src/AGENTS.md +57 -41
- package/packages/shared/src/__tests__/browser-protocol-types.test.ts +59 -2
- package/packages/shared/src/__tests__/client-build-deps-runtime.test.ts +79 -0
- package/packages/shared/src/__tests__/client-build-deps-runtime.test.ts.AGENTS.md +3 -0
- package/packages/shared/src/__tests__/config.test.ts +304 -3
- package/packages/shared/src/__tests__/content-view-claims-predicated.test.ts +105 -0
- package/packages/shared/src/__tests__/dashboard-paths.test.ts +56 -0
- package/packages/shared/src/__tests__/display-prefs.test.ts +257 -0
- package/packages/shared/src/__tests__/image-block.test.ts +96 -0
- package/packages/shared/src/__tests__/instance-directory.test.ts +131 -0
- package/packages/shared/src/__tests__/knip-workflow-contract.test.ts +89 -0
- package/packages/shared/src/__tests__/model-catalogue.test.ts +115 -0
- package/packages/shared/src/__tests__/models-json-reader.test.ts +35 -0
- package/packages/shared/src/__tests__/nightly-workflow-contract.test.ts.AGENTS.md +3 -0
- package/packages/shared/src/__tests__/no-flow-command-route-claims.test.ts +9 -1
- package/packages/shared/src/__tests__/node-cap-single-source.test.ts +123 -0
- package/packages/shared/src/__tests__/node-cap-single-source.test.ts.AGENTS.md +3 -0
- package/packages/shared/src/__tests__/node-version.test.ts +26 -3
- package/packages/shared/src/__tests__/openspec-poller-derive.test.ts +14 -1
- package/packages/shared/src/__tests__/overlay-claims-declare-depth.test.ts +139 -0
- package/packages/shared/src/__tests__/plugin-activation-contracts.test.ts +8 -12
- package/packages/shared/src/__tests__/pnpm-migration-contract.test.ts +11 -1
- package/packages/shared/src/__tests__/process-identify.test.ts +94 -2
- package/packages/shared/src/__tests__/publish-tarball-hygiene.test.ts +100 -0
- package/packages/shared/src/__tests__/recommended-extensions.test.ts +21 -1
- package/packages/shared/src/__tests__/recovery-timing.test.ts +28 -0
- package/packages/shared/src/__tests__/rendezvous.test.ts +146 -0
- package/packages/shared/src/__tests__/server-launcher.test.ts +42 -0
- package/packages/shared/src/__tests__/server-pinning.test.ts +182 -0
- package/packages/shared/src/__tests__/smoke-node-matrix.test.ts +107 -0
- package/packages/shared/src/__tests__/smoke-node-matrix.test.ts.AGENTS.md +3 -0
- package/packages/shared/src/__tests__/source-matching.test.ts +13 -0
- package/packages/shared/src/__tests__/spawn-mechanism.test.ts +11 -0
- package/packages/shared/src/__tests__/tunnel-concurrency.test.ts +161 -0
- package/packages/shared/src/__tests__/tunnel-config-migration.test.ts +48 -0
- package/packages/shared/src/__tests__/verify-lockfile-versions.test.ts +130 -0
- package/packages/shared/src/__tests__/virtualizer-drain-scope.test.ts +81 -0
- package/packages/shared/src/bind-reachability.ts +452 -0
- package/packages/shared/src/boot-state.ts +64 -0
- package/packages/shared/src/boot-state.ts.AGENTS.md +3 -0
- package/packages/shared/src/browser-protocol.ts +228 -3
- package/packages/shared/src/browser-protocol.ts.AGENTS.md +7 -0
- package/packages/shared/src/config.ts +287 -30
- package/packages/shared/src/config.ts.AGENTS.md +5 -0
- package/packages/shared/src/credential-detect.ts.AGENTS.md +3 -0
- package/packages/shared/src/dashboard-paths.ts +65 -0
- package/packages/shared/src/dashboard-paths.ts.AGENTS.md +3 -0
- package/packages/shared/src/dashboard-plugin/AGENTS.md +6 -6
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +48 -0
- package/packages/shared/src/dashboard-plugin/plugin-status.ts +7 -0
- package/packages/shared/src/dashboard-plugin/route-descriptor.ts +6 -1
- package/packages/shared/src/dashboard-plugin/slot-props.ts +19 -1
- package/packages/shared/src/dashboard-plugin/slot-types.ts +6 -0
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +47 -1
- package/packages/shared/src/dashboard-starter.ts.AGENTS.md +3 -0
- package/packages/shared/src/diff-types.ts.AGENTS.md +3 -0
- package/packages/shared/src/display-prefs.ts +114 -0
- package/packages/shared/src/display-prefs.ts.AGENTS.md +3 -0
- package/packages/shared/src/doctor-core.ts.AGENTS.md +3 -0
- package/packages/shared/src/file-kind.ts.AGENTS.md +3 -0
- package/packages/shared/src/git-worktree-helpers.ts.AGENTS.md +3 -0
- package/packages/shared/src/grammar-types.ts +88 -0
- package/packages/shared/src/image-block.ts +118 -0
- package/packages/shared/src/index.ts.AGENTS.md +3 -0
- package/packages/shared/src/instance-directory.ts +124 -0
- package/packages/shared/src/legacy-managed-dir.ts.AGENTS.md +3 -0
- package/packages/shared/src/live-server.ts.AGENTS.md +3 -0
- package/packages/shared/src/managed-paths.ts.AGENTS.md +3 -0
- package/packages/shared/src/mdns-discovery.ts.AGENTS.md +3 -0
- package/packages/shared/src/memory-limits.ts +89 -0
- package/packages/shared/src/model-catalogue.ts +78 -0
- package/packages/shared/src/model-id.ts.AGENTS.md +3 -0
- package/packages/shared/src/models-json-reader.ts +7 -0
- package/packages/shared/src/models-json-reader.ts.AGENTS.md +3 -0
- package/packages/shared/src/node-version.ts +21 -9
- package/packages/shared/src/node-version.ts.AGENTS.md +3 -0
- package/packages/shared/src/notify.ts +16 -0
- package/packages/shared/src/notify.ts.AGENTS.md +3 -0
- package/packages/shared/src/openspec-activity-detector.ts +74 -6
- package/packages/shared/src/openspec-activity-detector.ts.AGENTS.md +5 -0
- package/packages/shared/src/openspec-design-evidence.ts.AGENTS.md +3 -0
- package/packages/shared/src/openspec-poller.ts +11 -5
- package/packages/shared/src/openspec-poller.ts.AGENTS.md +3 -0
- package/packages/shared/src/openspec-specs-evidence.ts.AGENTS.md +3 -0
- package/packages/shared/src/path-containment.ts +41 -0
- package/packages/shared/src/pi-installs/AGENTS.md +13 -0
- package/packages/shared/src/pi-installs/__tests__/candidates.test.ts +351 -0
- package/packages/shared/src/pi-installs/__tests__/installs.test.ts +113 -0
- package/packages/shared/src/pi-installs/candidates.ts +355 -0
- package/packages/shared/src/pi-installs/index.ts +45 -0
- package/packages/shared/src/pi-installs/installs.ts +149 -0
- package/packages/shared/src/pi-installs/validate.ts +111 -0
- package/packages/shared/src/pi-installs/versions.ts +65 -0
- package/packages/shared/src/pi-package-resolver.ts +12 -3
- package/packages/shared/src/pi-package-resolver.ts.AGENTS.md +3 -0
- package/packages/shared/src/platform/AGENTS.md +1 -1
- package/packages/shared/src/platform/paths.ts +30 -0
- package/packages/shared/src/platform/process-identify.ts +93 -0
- package/packages/shared/src/plugin-bridge-register.ts.AGENTS.md +3 -0
- package/packages/shared/src/protocol.ts +379 -4
- package/packages/shared/src/protocol.ts.AGENTS.md +6 -0
- package/packages/shared/src/provider-model-metadata.ts +135 -0
- package/packages/shared/src/recommended-extensions.ts +165 -0
- package/packages/shared/src/recommended-extensions.ts.AGENTS.md +3 -0
- package/packages/shared/src/recovery-timing.ts +34 -0
- package/packages/shared/src/recovery-timing.ts.AGENTS.md +3 -0
- package/packages/shared/src/rendezvous.ts +94 -0
- package/packages/shared/src/rendezvous.ts.AGENTS.md +13 -0
- package/packages/shared/src/rest-api.ts +216 -1
- package/packages/shared/src/rest-api.ts.AGENTS.md +3 -0
- package/packages/shared/src/role-name-validation.ts.AGENTS.md +3 -0
- package/packages/shared/src/semaphore.ts.AGENTS.md +3 -0
- package/packages/shared/src/server-identity.ts.AGENTS.md +3 -0
- package/packages/shared/src/server-launcher.ts +34 -2
- package/packages/shared/src/server-pinning.ts +179 -0
- package/packages/shared/src/session-group-path.ts.AGENTS.md +3 -0
- package/packages/shared/src/session-meta.ts +18 -0
- package/packages/shared/src/session-meta.ts.AGENTS.md +3 -0
- package/packages/shared/src/skill-block-parser.ts.AGENTS.md +3 -0
- package/packages/shared/src/source-matching.ts.AGENTS.md +3 -0
- package/packages/shared/src/state-replay.ts.AGENTS.md +3 -0
- package/packages/shared/src/stats-extractor.ts.AGENTS.md +3 -0
- package/packages/shared/src/test-support/AGENTS.md +1 -1
- package/packages/shared/src/test-support/setup-home-perfile.ts +8 -1
- package/packages/shared/src/tool-registry/AGENTS.md +1 -1
- package/packages/shared/src/tool-registry/__tests__/fixtures/strategies.pre-change.ts.txt +480 -0
- package/packages/shared/src/tool-registry/__tests__/resolver-order-preservation.test.ts +305 -0
- package/packages/shared/src/tool-registry/overrides.ts +24 -2
- package/packages/shared/src/tool-registry/registry.ts +29 -2
- package/packages/shared/src/tool-registry/strategies.ts +65 -28
- package/packages/shared/src/tunnel-concurrency.ts +158 -0
- package/packages/shared/src/tunnel-provider.ts +113 -0
- package/packages/shared/src/tunnel-provider.ts.AGENTS.md +3 -0
- package/packages/shared/src/types.ts +152 -11
- package/packages/shared/src/types.ts.AGENTS.md +5 -0
- package/packages/shared/src/zrok-env.ts.AGENTS.md +3 -0
- package/packages/server/src/home-lock.d.ts +0 -124
- package/packages/server/src/home-lock.js +0 -330
- package/packages/server/src/home-lock.js.AGENTS.md +0 -3
- package/packages/server/src/home-lock.js.map +0 -1
package/docs/architecture.md
CHANGED
|
@@ -11,17 +11,11 @@
|
|
|
11
11
|
|
|
12
12
|
PI Dashboard: web-based dashboard for monitoring + interacting with pi agent sessions. Three components:
|
|
13
13
|
|
|
14
|
-
```
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
└─────────────┘ └──────────────┘ └─────────────┘
|
|
20
|
-
│
|
|
21
|
-
┌─────┴─────┐
|
|
22
|
-
│ In-Memory │
|
|
23
|
-
│ + JSON │
|
|
24
|
-
└───────────┘
|
|
14
|
+
```mermaid
|
|
15
|
+
flowchart LR
|
|
16
|
+
Bridge["Bridge Extension (per pi)"] <-->|"WebSocket (port 9999)"| Server["Dashboard Server (Node.js)"]
|
|
17
|
+
Server <-->|"WebSocket (port 8000)"| Client["Web Client (React)"]
|
|
18
|
+
Server --> Storage["In-Memory + JSON"]
|
|
25
19
|
```
|
|
26
20
|
|
|
27
21
|
## Components
|
|
@@ -39,7 +33,7 @@ Global pi extension running in every pi session. It:
|
|
|
39
33
|
- **Attached-proposal artifact summary** in the content-window header (`SessionHeader.tsx`, both desktop branch and `MobileHeader`): when `session.attachedProposal` matches an entry in the polled `openspecChanges` list, the header renders the `ArtifactLettersButton` (P/D/T/S letters colored by per-artifact status, single button → opens the proposal artifact) plus a `(completedTasks/totalTasks)` counter. Surface is gated on the explicit user attach only — auto-detected `openspecChange` does not trigger it. Wired via the new `onReadArtifact` prop, threaded from `App.tsx` (`handleReadArtifact` from `useContentViews`). See change: add-attached-proposal-header-summary.
|
|
40
34
|
- **Duplicate bridge prevention**: Uses `process`-level shared state (not `globalThis`) with a monotonic generation counter. When the extension is loaded multiple times (e.g., local + global npm package), only the latest instance's event handlers are active — stale listeners bail out immediately. All previous connections and timers are tracked and cleaned up on re-init.
|
|
41
35
|
- **Subagent re-entry guard**: When pi-subagents launches an Agent tool, the subagent creates its own `AgentSession` which loads extensions (including the bridge) in the same process. Without protection, this would overwrite the parent bridge's global state, disconnect its WebSocket, and prevent `tool_execution_end`/`agent_end` from being forwarded — leaving the parent session stuck at "streaming" forever. The bridge stores a reference to its owning `pi` instance and skips initialization when called from a different instance (subagent).
|
|
42
|
-
- Routes `ctx.ui` dialog methods (confirm, select, input, editor, multiselect
|
|
36
|
+
- Routes `ctx.ui` dialog methods (confirm, select, input, editor, multiselect) through `PromptBus` (`prompt-bus.ts`). `notify` split out — direct `notify` frame via `notify-proxy.ts`, never PromptBus. See Notify Flow.
|
|
43
37
|
- Adapters register to handle prompts: `DashboardDefaultAdapter` renders generic dialogs inline; extensions (e.g. pi-flows) can register custom adapters via `prompt:register-adapter` event
|
|
44
38
|
- First-response-wins: multiple adapters (TUI, dashboard, custom) can claim a prompt; the first to respond resolves it, others are dismissed
|
|
45
39
|
- Bridge's TUI adapter is registered inline (captures original `ctx.ui` methods before patching) and presents `select`/`input`/`confirm`/`editor` prompts in the terminal with AbortController-based cancellation. Multiselect bypasses the TUI adapter entirely and uses the bus-routed `ctx.ui.multiselect` patch → `DashboardDefaultAdapter` → client `MultiselectRenderer` exclusively (pi 0.70 RPC's `ctx.ui.custom` is a no-op, so a TUI arm would auto-cancel the dashboard render in <1s). See changes: fix-multiselect-auto-cancel-on-dashboard, fix-multiselect-tui-arm-self-cancel.
|
|
@@ -76,6 +70,27 @@ Node.js HTTP + WebSocket server that:
|
|
|
76
70
|
|
|
77
71
|
See change: configurable-bind-host.
|
|
78
72
|
|
|
73
|
+
**Bind-vs-trust reachability.** Two settings on two different Settings pages govern whether a LAN device can reach the dashboard. `bindHost` (Server page, default `127.0.0.1`, restart-required) + `auth.bypassHosts` / top-level `trustedNetworks` (Security page, live-reloaded). A loopback or specific-NIC bind silently voids a trusted entry outside its range: TCP refused before any handler runs, so `blockEvents.record()` never fires. The entries stay listed and configured — what is missing is any SIGNAL: no block event, so `BlockEventTrustBanner` early-returns `null` and the operator gets no hint the entries are inert.
|
|
74
|
+
|
|
75
|
+
- Coupling pre-existed one direction. `SettingsPanel.tsx` passes `hasGuardConfig(config)` into `ListenInterfaceField`. Server page reads Security state for the all-interfaces exposure warning. Return edge (Security reads bind state) = this change.
|
|
76
|
+
- Predicate home: `packages/shared/src/bind-reachability.ts`. ONE implementation, imported by both client + server. No per-package copy, so drift structurally impossible.
|
|
77
|
+
- `unreachableTrustedEntries(bindHost, entries)` returns offending ENTRIES, not a boolean. Evaluation order per entry: (1) loopback-only entry → reachable; (2) bind host not IPv4 literal (`::`, hostname) → FAIL OPEN; (3) bind host `0.0.0.0` → reachable; (4) malformed entry → skipped, never reported; (5) bind host in `127.0.0.0/8` → unreachable; (6) otherwise reachable iff entry covers bind host.
|
|
78
|
+
- `127.0.0.0/8` loopback-only. `127.0.0.0/7` NOT — also covers `126.x`.
|
|
79
|
+
- Predicate reads UNION of `trustedNetworks` + `auth.bypassHosts` (`collectTrustedEntries`). Mirrors `hasGuardConfig()` + runtime guard.
|
|
80
|
+
- ADVISORY only. Guard code untouched — no request allowed or denied differently. ADDRESS test, not routing test: trusted `10.0.0.0/8` scores reachable for bind `10.0.0.5` even with no route to wider network.
|
|
81
|
+
- Bind-host chain: `--host` → `PI_DASHBOARD_HOST` → `config.bindHost` → `127.0.0.1` (`resolveBindHost`). `resolvedBindHost` = frozen at boot, what THIS process bound. `pendingBindHost` = re-resolved against current config, what NEXT start binds. `ServerConfig.hostFlag` retains raw `--host`, so flag still wins on re-resolution. Unsaved client draft outranks both (`pendingEffectiveHost`).
|
|
82
|
+
- Predicate input = RESOLVED bind host, never `config.bindHost`. Container seeds no `bindHost` key, so `config.bindHost` reads as `127.0.0.1` default while server binds `0.0.0.0` from `PI_DASHBOARD_HOST` (`docker/compose.yml`). Scoring config value would fire advisory in every container with a trusted network.
|
|
83
|
+
- Surfaces: (a) `console.warn` prefixed `[bind-reachability]` at startup, matching `[openspec-poll]` / `[hydration]` convention; (b) top-level `reachability` object `{ resolvedBindHost, pendingBindHost, unreachable[] }` on `GET /api/config`, failure-isolated like `eventLoopDelay` / `storeTrim` / `notifyLog`; (c) `reachability_updated` `ServerToBrowserMessage` broadcast when `pendingBindHost` changes, replayed on connect.
|
|
84
|
+
- `reachability` COMPUTED, never persisted. Stripped on config write path in `packages/server/src/config-api.ts`, alongside `resolvedTrustedNetworks`.
|
|
85
|
+
- Deliberately NOT on `/api/health`. `/api/health` carries no `preHandler`; `/api/config` carries `networkGuard`. Resolved bind host + unreachable entries describe operator's private network topology, not server health — publishing unguarded hands any peer that can reach the port a map of internal subnets.
|
|
86
|
+
- Advisory + `BlockEventTrustBanner` INDEPENDENT, not mutually exclusive. `bindHost=10.0.0.5` + trusted `192.168.1.0/24`: peer at `10.0.0.9` accepted by NIC, denied by guard, recorded — both banners render, advisory first.
|
|
87
|
+
- `/api/network-interfaces` entries gain `label`, `pointToPoint`, `suggestions`. ONE entry per address kept: `ListenInterfaceField` renders one option per address and keys on it, so server-side dedupe would make a bind address unselectable. Trusted-networks dropdown dedupes at render time, keyed on suggestion `value` — two tunnels with different `/32` cidrs both offer `100.64.0.0/10`.
|
|
88
|
+
- Interface offer table: broadcast NIC (`/24`, `/16`, …) → netmask-derived CIDR, narrow. Point-to-point `/32` in a known range → containing range, wide. Point-to-point outside every known range → no offer, shown unofferable with explanation.
|
|
89
|
+
- Tailscale gives each node its own `/32` from `100.64.0.0/10`. Old netmask-only offer was `<self>/32` — an entry trusting nobody new, host already loopback-exempt.
|
|
90
|
+
- One well-known-range table backs BOTH interface path + block-event path (`suggestTrustEntries`). Two routes to same decision cannot contradict.
|
|
91
|
+
|
|
92
|
+
See change: warn-unreachable-trusted-networks.
|
|
93
|
+
|
|
79
94
|
**Server decomposition:** The server is split into focused modules:
|
|
80
95
|
- `server.ts` — Orchestrator: creates services, composes modules, manages lifecycle
|
|
81
96
|
- `routes/` — REST API routes grouped by domain (session, git, file, openspec, system)
|
|
@@ -95,12 +110,18 @@ React-based responsive web UI that:
|
|
|
95
110
|
- Provides command autocomplete with `/` prefix
|
|
96
111
|
- Supports bidirectional interaction (send prompts, run commands)
|
|
97
112
|
- Works on mobile with responsive layout and swipe gestures
|
|
98
|
-
- Shows an onboarding `LandingPage` whenever the main pane is empty, narrating the three steps needed to go from install → first running session (Setup credentials → Add folder → Start session). Each step is a card in **pending**, **done**, or **locked** state, derived purely from client state: `useProvidersReady()` (from `GET /api/providers`), `pinnedDirectories.length`, and `sessions.size`. Satisfied steps collapse to single-line ✔ rows, so returning users see a compact status strip rather than a full onboarding wall.
|
|
113
|
+
- Shows an onboarding `LandingPage` whenever the main pane is empty, narrating the three steps needed to go from install → first running session (Setup credentials → Add folder → Start session). Each step is a card in **pending**, **done**, or **locked** state, derived purely from client state: `useProvidersReady()` (from `GET /api/providers`), `pinnedDirectories.length`, and `sessions.size`. Satisfied steps collapse to single-line ✔ rows, so returning users see a compact status strip rather than a full onboarding wall. Step ② sidebar "Add folder" button opens multi-select `AddFoldersDialog` (destination: None); pinning implicit (adding folder pins it). App uses `pinDialogOpen` state to gate dialog.
|
|
99
114
|
|
|
100
|
-
**Unified dialog system** (`packages/client-utils/`): `Dialog` primitive + `Confirm` preset + `useFocusTrap` hook. `Dialog` owns portal/overlay (`bg-black/60`)/Esc/click-outside/focus-trap/ARIA/`z-
|
|
115
|
+
**Unified dialog system** (`packages/client-utils/`): `Dialog` primitive + `Confirm` preset + `useFocusTrap` hook. `Dialog` owns portal/overlay (`bg-black/60`)/Esc/click-outside/focus-trap/ARIA/`z-dialog`/size variants (sm/md/lg)/header+footer slots (`Dialog.Footer`/`Dialog.Cancel`/`Dialog.Action`). `Confirm` wraps `Dialog` (size sm) for confirm flows. `ui:dialog` registry key exposes shell to plugins; `ui:confirm-dialog` re-skinned as adapter over `Confirm`. ~20 dialogs migrated. Legacy `ConfirmDialog` removed. See changes: unify-dialog-system, add-route-backed-overlay-dialogs.
|
|
101
116
|
|
|
102
117
|
**Global Escape dismissal** (`packages/client-utils/src/escape-stack.ts`): single module-stable `document` `keydown` listener arbitrates Escape dismissal for portaled dismissible surfaces via LIFO stack. On Escape, only TOPMOST registered layer's `onEscape` fires (`preventDefault` + `stopImmediatePropagation`). Guarded against `e.repeat` + `e.defaultPrevented`. Listener attaches once on first registration; never detaches. New dismissible portaled overlays SHOULD use `useEscapeDismiss(active, onEscape)` hook; stacked surfaces peel one layer per Escape instead of collapsing multiple layers at once. Adopted by `Dialog`, `ImageLightbox`, `FilePreviewOverlay`; `MermaidBlock` deferred (inline, not portaled). See change: fix-stacked-escape-closes-layers.
|
|
103
118
|
|
|
119
|
+
**Overlay layering (z-index)** (change: add-overlay-layering-system): single stacking order source. `packages/client/src/index.css` defines CSS custom properties `--z-base:0`, `--z-raised:10`, `--z-sidebar:20`, `--z-overlay:30`, `--z-popover:40`, `--z-dialog:50`, `--z-toast:60`, `--z-lightbox:70`. Ascending values = paints later = on top. Theme-independent; one scale covers all themes. Matching Tailwind utilities `z-base` through `z-lightbox` bind to the vars. Layer roles: base = flow content; raised = sticky headers; sidebar = sidebar/folder chrome; overlay = scrims/mobile backdrops; popover = menus/dropdowns/folder flyouts; dialog = modals/full-pane; toast = notifications; lightbox = full-screen media. Toast (60) > dialog (50) intentional — notification visible over modal. Shared `Dialog` (`packages/client-utils/src/Dialog.tsx:77`) uses `z-dialog` utility (`--z-dialog: 50`), not raw `z-[60]`. Nested dialogs tie at 50; later portal/DOM mount wins — repo-standard for stacked dialogs. Gate gap: `z-layer-lint` `SCAN_DIR = "packages/client/src"` excludes `packages/client-utils`; raw `z-[60]` survived there (raw-z gate blind spot). See change: add-route-backed-overlay-dialogs.
|
|
120
|
+
|
|
121
|
+
**Portal-or-perish rule:** any box-escaping overlay (menu/popover/dropdown/dialog/toast/lightbox) MUST portal to top-level layer root (`document.body`), never inline `position:absolute`. Reason: numeric z-index orders only within nearest ancestor stacking context. Inline absolute overlay trapped by ancestor `transform`/`will-change`/`opacity`/`isolate`/`z-*`. `SessionCard` sets `isolate` per card → trapped folder popover UNDERLAPS cards. Portaling escapes contexts; token then orders portaled layers. Portal primitives: `packages/client-utils/src/LayerPortal.tsx` (portal to body, no scroll lock) for menus/popovers; `DialogPortal.tsx` (portal + body scroll lock) for modals. Portaled panel positions `fixed` from `usePopoverFlip` `triggerRect`; capture-phase window scroll re-measure → tracks ancestor (sidebar) scroll.
|
|
122
|
+
|
|
123
|
+
**Enforcement:** `scripts/z-layer-lint.mjs` frozen baseline ratchet (`scripts/z-layer-baseline.json`). Freezes current raw `z-[NNNN]`/`z-<n>` in `packages/client/src`; FAILS on new occurrence outside `z-<layer>` utilities; baseline may only shrink. Wired into `quality:changed`. Phased: FolderActionsMenu fixed + Tier-A already-portaled overlays token-swapped now. ~12 inline-absolute popovers + FilePreviewOverlay deferred to follow-up `portal-inline-popovers` (allowlisted in baseline). Spec: `openspec/changes/add-overlay-layering-system/specs/overlay-layering/spec.md`.
|
|
124
|
+
|
|
104
125
|
### 4. Shared Types (`src/shared/`)
|
|
105
126
|
TypeScript type definitions shared across all components:
|
|
106
127
|
|
|
@@ -136,8 +157,221 @@ TypeScript type definitions shared across all components:
|
|
|
136
157
|
- **Needs-you precedence.** `error > ask_user(chat-routed) > resuming/retry > working(streaming) > active/idle > ended`. Applied uniformly across left-gutter dot (`deriveDotColorWithFlags`), rail (`deriveRailBgColor`), icon tint (`deriveIconStatusColor`, converts `bg-[var(...)]`→`text-[var(...)]`). All in `session-status-visuals.ts`. `flags.hasWidgetBarPrompt` excludes widget-bar ask_user from needs-you so only chat-routed prompts escalate (`isChatRoutedAskUser`).
|
|
137
158
|
- **Non-hue shape channel.** `deriveStatusShape` + `statusShapeIcon` map status to filled/half/ring/cross marker. `SessionCard.tsx::StatusShapeBadge` overlays marker on session-status-icon (`data-status-shape`). Color-blind-safe redundant encoding.
|
|
138
159
|
- **Label split.** `ActivityIndicator`: ask_user → "Needs you" (`--status-needs-you`); idle/active → "Idle" (muted). "Waiting for input" retired.
|
|
139
|
-
- **Folder
|
|
140
|
-
- **Opt-in urgency sort.** `useFolderUrgencySort` per-folder pref, default off, localStorage `dashboard:folder-urgency-sort`. When on, `SessionList` floats ask_user sessions first within active tier via `floatAskUserFirst`. Toggle `mdiSortVariant`
|
|
160
|
+
- **Folder status capsule** (change: unify-folder-status-capsule). `FolderStatusCapsule` = folder header's ONLY liveness surface. Renders in BOTH collapse states. Replaces `FolderNeedsYouPill` + collapsed-only `FolderStatusRollup` + raw `(N)` count — all DELETED, incl. `countStatusRollup`. Segments by `countStatusCapsule(sessions, flags)` (`packages/client/src/lib/session/session-status-visuals.ts`). Fixed severity order `CAPSULE_SEGMENT_ORDER` = needs-you > error > working > idle; magnitude never reorders. Zero-count segments absent; no countable sessions → no capsule at all (all-ended folder shows none; its `N ended` disclosure row still reports size). Excludes `ended` + `hidden` before shape derivation. `flags.widgetBar` tri-state `(id) => boolean | undefined`; `true` or `undefined` excludes that ask_user session from EVERY bucket. Still per-session `WidgetBarProbe` + `useHasWidgetBarPrompt`, now capsule-owned. needs-you uses explicit predicate, not `deriveStatusShape`; re-adds `!hasError` guard — errored ask_user counts once, as error. `notice` shape folds into `idle` bucket; retrying counts as `working`. Counts cap at `999+`. Non-idle segments = `<button>`s → first session of that state via `firstIds[bucket]`; idle = inert `<span>` + aria-label. Activation `stopPropagation()` → SessionList reveal path (`onSeekToCard` / `revealRequest`): inherits guarded expand, layout-settled scroll, hidden/filtered degrade toasts. Colors from `--status-*` family only, never `--severity-*`; no new CSS custom property. Capsule `flex-none` + `whitespace-nowrap`; sheds nothing; folder name absorbs width pressure. Test ids: `folder-status-capsule-<cwd>`, `folder-capsule-seg-{needs-you,error,working,idle}-<cwd>`.
|
|
161
|
+
- **Opt-in urgency sort.** `useFolderUrgencySort` per-folder pref, default off, localStorage `dashboard:folder-urgency-sort`. When on, `SessionList` floats ask_user sessions first within active tier via `floatAskUserFirst`. Toggle = folder actions menu item `urgency-sort` (`mdiSortVariant`), `aria-pressed` bound to `urgencySort.isOn(cwd)`. Per-folder persisted preference unchanged.
|
|
162
|
+
|
|
163
|
+
### EventBus Forwarding Mechanism (subscription-based, change: fix-automation-run-lifecycle)
|
|
164
|
+
|
|
165
|
+
**Host topology.**
|
|
166
|
+
|
|
167
|
+
- `EventBus` = `node:events` wrapper. `pi-coding-agent/dist/core/event-bus.js`. Methods: `emit` / `on` / `clear`. NO wildcard channel.
|
|
168
|
+
- One bus per pi process. Shared by all extensions.
|
|
169
|
+
- `pi.events` = PER-EXTENSION facade over that bus. `createExtensionAPI` -> `events: { emit, on }`. `pi-coding-agent/dist/core/extensions/loader.js`.
|
|
170
|
+
|
|
171
|
+
**Why NOT an emit intercept.**
|
|
172
|
+
|
|
173
|
+
- Patching `pi.events.emit` mutates only the patching extension's facade.
|
|
174
|
+
- Foreign emissions bypass the patch. Emitters affected: pi-flows, pi-subagents.
|
|
175
|
+
- Old bridge patched `emit`. Consequence: zero live `flow_*` / `subagent_*` `event_forward` ever left the bridge.
|
|
176
|
+
- Flow cards rebuilt from persisted `custom/flow-event` JSONL. `packages/shared/src/state-replay.ts`.
|
|
177
|
+
- Automation runs with a `flows.run` action stayed `status: "running"`.
|
|
178
|
+
- Stale-run reaper finalized them `error: "run exceeded max age"` ~30 min later.
|
|
179
|
+
- Measured: 101 runs, 0 reached `done`.
|
|
180
|
+
- Proof: bridge `pi.events.on("flow:complete")` fired; patched `emit` never entered for that channel.
|
|
181
|
+
|
|
182
|
+
**Current mechanism.**
|
|
183
|
+
|
|
184
|
+
- `registerEventBusForwarding`. `packages/extension/src/flow-event-wiring.ts`.
|
|
185
|
+
- ONE `pi.events.on(channel, ...)` subscription per declared channel.
|
|
186
|
+
- `on()` observes every emitter.
|
|
187
|
+
- Declared set = keys of `FLOW_EVENT_MAP` + `SUBAGENT_EVENT_MAP` + optional `extraMaps` (currently none passed).
|
|
188
|
+
- Channel list IS the contract. Undeclared channel -> never forwarded.
|
|
189
|
+
- New channel -> new map entry. Identity entry when no rename wanted.
|
|
190
|
+
- Retired: wildcard forwarding of any unknown channel. Unimplementable without an emit intercept.
|
|
191
|
+
|
|
192
|
+
**Forward gates.** `forwardBusEvent`, same file.
|
|
193
|
+
|
|
194
|
+
- Subagent channel -> forward only when `sessionReady && isActive() && connection.isConnected`.
|
|
195
|
+
- Else buffer latest-wins per agent in `SubagentFrameBuffer`. Flushed on re-register / reconnect.
|
|
196
|
+
- Other declared channel -> forward when `sessionReady && isActive()`.
|
|
197
|
+
- Forwarding failure never propagates to the emitter.
|
|
198
|
+
- Forwarding failure drops that live frame. Nothing re-sends it. Subagent frames are the exception (buffered).
|
|
199
|
+
|
|
200
|
+
**Teardown.** dispose returned by `registerEventBusForwarding`.
|
|
201
|
+
|
|
202
|
+
- Removes only the bridge's own subscriptions.
|
|
203
|
+
- Restores nothing. Bridge never replaces a host function.
|
|
204
|
+
|
|
205
|
+
### Subagent Timeline Push/Pull Split (change: reduce-subagent-details-payload)
|
|
206
|
+
|
|
207
|
+
**Why thin ticks.**
|
|
208
|
+
|
|
209
|
+
- Producer builds ONE `snapshotDetails()` object.
|
|
210
|
+
- Feeds BOTH carriers: `subagents:*` EventBus frame + pi-core `tool_execution_update`.
|
|
211
|
+
- `entries[]` append-only → tick size grows linearly with run length.
|
|
212
|
+
- Long run = fat intermediate ticks.
|
|
213
|
+
- Solution: strip timeline from intermediate ticks.
|
|
214
|
+
- Push terminal frame fat.
|
|
215
|
+
- Pull full timeline on demand.
|
|
216
|
+
|
|
217
|
+
**Strip module.**
|
|
218
|
+
|
|
219
|
+
- File: `packages/extension/src/subagent-frame-strip.ts`.
|
|
220
|
+
- Exports `stripSubagentEntries`, `stripForForward`, `NON_TERMINAL_STATUSES`.
|
|
221
|
+
- Strips `details.entries` on FORWARD path when frame status `queued` or `running`.
|
|
222
|
+
|
|
223
|
+
**Allowlist, never negation.**
|
|
224
|
+
|
|
225
|
+
- `NON_TERMINAL_STATUSES` = explicit allowlist.
|
|
226
|
+
- Never `!terminal`.
|
|
227
|
+
- `AgentStatus` also has `stopped`; negation would strip it and lose that run's timeline.
|
|
228
|
+
- `stopped` counts as terminal: never stripped.
|
|
229
|
+
|
|
230
|
+
**Strip clones.**
|
|
231
|
+
|
|
232
|
+
- Strip CLONES data.
|
|
233
|
+
- `SubagentFrameBuffer` retains frames BY REFERENCE.
|
|
234
|
+
- Mutating strip would corrupt the pull source.
|
|
235
|
+
- Fat snapshot survives intact for resync.
|
|
236
|
+
|
|
237
|
+
**Call-site allowlist.**
|
|
238
|
+
|
|
239
|
+
- Strip applied at explicit call sites.
|
|
240
|
+
- NEVER inside `sendEventForward`.
|
|
241
|
+
- Sites: EventBus forward path (`flow-event-wiring.ts` `forwardBusEvent`).
|
|
242
|
+
- Sites: buffered-frame flush + resync reply (`packages/extension/src/subagent-forward-sites.ts` — `flushBufferedSubagentFrames` strips, `serveSubagentResync` does NOT).
|
|
243
|
+
- Sites: `tool_execution_update` carrier in `bridge.ts`.
|
|
244
|
+
- Strip inside `sendEventForward` would strip the resync reply.
|
|
245
|
+
- EventBus-only strip would leak every frame drained by the buffer.
|
|
246
|
+
|
|
247
|
+
**Terminal frames never stripped.**
|
|
248
|
+
|
|
249
|
+
- `completed`/`failed`/`aborted`/`stopped`/`error` forward full.
|
|
250
|
+
- Terminal frame = durable record behind `tool_execution_end` backfill.
|
|
251
|
+
- Second independent terminal guard: `stripForForward(data, channel)` never strips when `channel` in `TERMINAL_CHANNELS` (`subagents:completed`, `subagents:failed`).
|
|
252
|
+
- Guard fires regardless of `details.status`.
|
|
253
|
+
- Both signals must be wrong to lose a timeline.
|
|
254
|
+
|
|
255
|
+
**Full-snapshot invariant preserved.**
|
|
256
|
+
|
|
257
|
+
- Every frame still an idempotent FULL snapshot.
|
|
258
|
+
- Latest-supersedes.
|
|
259
|
+
- No delta encoding.
|
|
260
|
+
- No wire key.
|
|
261
|
+
- No version negotiation.
|
|
262
|
+
- No producer change.
|
|
263
|
+
- Dropped thin tick leaves no permanent hole.
|
|
264
|
+
|
|
265
|
+
**Pull path.**
|
|
266
|
+
|
|
267
|
+
- Client requests `subagent_resync_request`.
|
|
268
|
+
- Bridge answers from retained fat snapshot as synthetic `subagents:started` frame.
|
|
269
|
+
|
|
270
|
+
**Server resync locator.**
|
|
271
|
+
|
|
272
|
+
- `locateSubagentTimeline` (`packages/server/src/persistence/memory-event-store.ts`) now also matches `subagent_*` eventTypes carrying `details.entries`.
|
|
273
|
+
- Before: resync reply fell to generic pass.
|
|
274
|
+
- Before: any array > 20 items became string `"[array truncated]"`.
|
|
275
|
+
- Before: reducer rendered no timeline.
|
|
276
|
+
- Head-tail budget now applies: head + `⋯ N steps hidden ⋯` sentinel + tail.
|
|
277
|
+
- `DEFAULT_MAX_EVENT_DATA_SIZE` = 262144.
|
|
278
|
+
|
|
279
|
+
**Open-inspector liveness.**
|
|
280
|
+
|
|
281
|
+
- File: `packages/client/src/hooks/useSubagentResyncCadence.ts`.
|
|
282
|
+
- Mounted detail view re-fires `subagent_resync_request` on backoff cadence.
|
|
283
|
+
- Base 2000 ms, doubles per idle tick, ceiling 30000 ms, resets on entry growth.
|
|
284
|
+
- ONE timer per subagent → inline inspector + popout do not double-fire.
|
|
285
|
+
- No `emptyTimeline` precondition on this trigger (open-time trigger keeps it).
|
|
286
|
+
|
|
287
|
+
**Requester-scoped delivery.**
|
|
288
|
+
|
|
289
|
+
- Request carries `requestId`.
|
|
290
|
+
- Bridge echoes it on reply as `__resyncRequestId`.
|
|
291
|
+
- Server routes reply to that one connection (`packages/server/src/pairing/subagent-resync-routing.ts`, `ResyncRequesterRegistry`, TTL 30000 ms).
|
|
292
|
+
- Unknown/expired token falls back to normal broadcast.
|
|
293
|
+
|
|
294
|
+
**Counters.**
|
|
295
|
+
|
|
296
|
+
- `storeTrim.subagentTicks` / `subagentTickBytes` / `subagentFatTicks` / `subagentTickFatBytes` on `/api/health` (additive).
|
|
297
|
+
- Bridge `SubagentFrameStats.resyncCadence` counts pull-loop requests.
|
|
298
|
+
|
|
299
|
+
**Rollback. PARTIAL, not total.**
|
|
300
|
+
|
|
301
|
+
- One flag: `PI_DASHBOARD_SUBAGENT_STRIP=0` forwards unstripped.
|
|
302
|
+
- Flag disables STRIPPING ONLY.
|
|
303
|
+
- Wire payload returns to pre-change shape: intermediate ticks fat again.
|
|
304
|
+
- These stay ACTIVE under the flag: `locateSubagentTimeline` `subagent_*` gate.
|
|
305
|
+
- Stay active: resync cadence in `useSubagentResyncCadence.ts`.
|
|
306
|
+
- Stay active: requester-scoped routing (`requestId` / `__resyncRequestId`).
|
|
307
|
+
- Stay active: additive `storeTrim` subagent-tick counters.
|
|
308
|
+
- Each of those is additive or a bug fix. None depends on the strip.
|
|
309
|
+
- No producer, protocol, or store rollback exists to do.
|
|
310
|
+
|
|
311
|
+
**Known regression, stated deliberately.**
|
|
312
|
+
|
|
313
|
+
- Run dying with NO terminal frame (crash/kill) leaves only thin ticks in store.
|
|
314
|
+
- Recovery needs a LIVE bridge with agent still in the 64-slot `SubagentFrameBuffer`.
|
|
315
|
+
- Evicted or post-reset agents answer `resyncNoop`.
|
|
316
|
+
- Client keeps its last rendered state.
|
|
317
|
+
|
|
318
|
+
### Retry Lifecycle (change: retry-forever-with-stop-control)
|
|
319
|
+
|
|
320
|
+
Pi owns the retry loop. Dashboard configures + observes + renders it. Attempts fire sequentially; each produces ONE complete `agent_start` … `agent_end` event cycle. Final attempt produces ONE `agent_settled` event terminal marker.
|
|
321
|
+
|
|
322
|
+
**1. Retry ownership & settings.**
|
|
323
|
+
|
|
324
|
+
- Pi `RetrySettings` = `{ enabled, maxRetries, baseDelayMs, provider: {timeoutMs, maxRetries, maxRetryDelayMs} }`.
|
|
325
|
+
- Session-layer delay = `baseDelayMs * 2^(attempt-1)`. Uncapped. No ceiling.
|
|
326
|
+
- `retry.maxDelayMs` REMOVED from session layer. pi migrates to `retry.provider.maxRetryDelayMs` (different layer, different semantics).
|
|
327
|
+
- Overshoot consequence: next attempt lands ~2x elapsed. Scale-invariant. Tuning `baseDelayMs` shifts which attempt lands where, never the ratio.
|
|
328
|
+
- Dashboard runs NO retry loop. Raising `retry.maxRetries` is the whole "retry forever" mechanism.
|
|
329
|
+
- `resume mode:"continue"` cannot re-drive live turn (refused `resume.already_active`). For ended session resolves to `pi --session <file>` which reopens IDLE + drives no turn. No re-drive mechanism exists — none needed, since pi never settles turn while budget remains.
|
|
330
|
+
|
|
331
|
+
**2. Bridge observation model** (`packages/extension/src/retry-tracker.ts`).
|
|
332
|
+
|
|
333
|
+
- pi fires ONE FULL `agent_start` … `agent_end` cycle PER ATTEMPT. Exactly one `agent_settled` after final `agent_end`.
|
|
334
|
+
- Old model keyed on "error `message_end` then fresh assistant `message_start` in same turn". Never matched. Emitted ZERO events. Retry surface was dead in production.
|
|
335
|
+
- New rules: error `message_end` records pending error text → emits nothing. Error `agent_end` = attempt over + another coming → emits `auto_retry_start` + `auto_retry_waiting` (carries `attempt`, `delayMs`, `nextAttemptAt`), does NOT clear chain. `agent_settled` = SOLE terminal → emits `auto_retry_end`, clears chain.
|
|
336
|
+
- Waiting signal suppressed once `attempt >= maxAttempts`.
|
|
337
|
+
- `agent_settled` carries NO `messages` (verified pi 0.81.1/0.83), so tracker remembers terminal disposition via `lastEndWasError` at `agent_end`.
|
|
338
|
+
- `-1` sentinels REMOVED. `maxAttempts` / `delayMs` sourced read-only from pi settings via `packages/extension/src/pi-retry-settings.ts` (defaults 3 / 2000; unreadable → `delayMs: 0` → surface renders elapsed-only).
|
|
339
|
+
- pi 0.83 exposes retry lifecycle events to RPC/SDK consumers ONLY. ExtensionAPI has no `auto_retry_*` and nothing on EventBus. `willRetry` in 0.83 is compaction-only (`session_before_compact`/`session_compact`). Bridge is extension → must observe-synthesize.
|
|
340
|
+
|
|
341
|
+
**3. Settings write + reload-on-save** (`packages/server/src/pi-agent-settings.ts`).
|
|
342
|
+
|
|
343
|
+
- Reads/writes all SIX native fields: `retry.{enabled,maxRetries,baseDelayMs}` + `retry.provider.{timeoutMs,maxRetries,maxRetryDelayMs}` in GLOBAL `~/.pi/agent/settings.json`. Blank `provider.timeoutMs` OMITTED on write (never `0`/`null`).
|
|
344
|
+
- Write is MERGE-PRESERVING: every other key survives, including `retry.provider.*`.
|
|
345
|
+
- Project `<cwd>/.pi/settings.json` NEVER written.
|
|
346
|
+
- Distinct from `config-api.ts`, which writes dashboard's own `~/.pi/dashboard/config.json`.
|
|
347
|
+
- Validation: `maxRetries` non-negative integer; `baseDelayMs` positive integer. Invalid → nothing written.
|
|
348
|
+
- No UI cap on `maxRetries`; long tail WARNED, never capped.
|
|
349
|
+
- REST: `GET/PUT /api/pi-retry` (`packages/server/src/routes/pi-retry-routes.ts`), auth-gated by same network guard as `/api/config`.
|
|
350
|
+
- pi reads settings only at session construction. Write alone inert for running sessions.
|
|
351
|
+
- On successful save server routes every target through `dispatchReload`.
|
|
352
|
+
- Target set = `reloadTargetSessionIds` = `piGateway.getConnectedSessionIds()` ∪ `headlessPidRegistry.listSessions()`.
|
|
353
|
+
- Connected-only set missed headless sessions with dead bridge WS. See change: fix-out-of-band-reload.
|
|
354
|
+
- Failed write reloads nothing.
|
|
355
|
+
- **UI placement + save.** Editor renders on Settings **Sessions** tab (NOT Providers). Reason: 3 fields (`enabled`, `maxRetries`, `baseDelayMs`) turn-level not provider-scoped; observable effect on session (waiting / attempt n / countdown / Stop). Sibling turn-lifecycle settings co-located.
|
|
356
|
+
- Enclosing section titled "Retry".
|
|
357
|
+
- NO private Save button. Registers with panel unified-Save draft registry via `useSettingsDraftSource({id:"pi-retry", page:"sessions", isDirty, commit, reset})`. See change: unify-settings-save-contract.
|
|
358
|
+
- Consequences: one Save commits every dirty store. Sessions nav shows per-page dirty dot. Leave guard offers Save / Discard / Cancel.
|
|
359
|
+
- `commit` THROWS on invalid input or failed PUT → host `Promise.allSettled` keeps source dirty + names it in `settings.savePartialFail`. Never false success.
|
|
360
|
+
- `reset` restores loaded policy (powers Discard).
|
|
361
|
+
- Registered `page` MUST match mount tab or dirty dot lands on wrong nav item.
|
|
362
|
+
- `retry.provider.*` fields surfaced in UI under subheading "Provider / SDK request controls". WARNING: wait routed through that layer emits no event and no callback → renders as ordinary streaming with no attempt count, no countdown. Invisible-wait fact true + reason warning exists.
|
|
363
|
+
|
|
364
|
+
**4. Collapse-vs-dismiss rule** (`packages/client/src/components/session/SessionBanner.tsx`).
|
|
365
|
+
|
|
366
|
+
- While retry pending, dismiss DEGRADES TO COLLAPSE. Never clears state.
|
|
367
|
+
- Collapsed pill carries: error text, bare attempt number, countdown, Stop retrying, expand control.
|
|
368
|
+
- State-clearing dismiss offered ONLY when no retry sub-status carried.
|
|
369
|
+
- Collapse sticky PER FAILURE CHAIN: later attempts of same chain stay collapsed; new chain renders expanded.
|
|
370
|
+
- Attempt rendered BARE ("attempt 7"), never "of N" — `maxRetries` user-set + typically large.
|
|
371
|
+
- Countdown from `nextAttemptAt`, else computed `startedAt + delayMs`; degrades to "still waiting… (N s elapsed)" on overrun or when `delayMs` is 0.
|
|
372
|
+
- "Stop retrying" aborts session → cancels pi's chain. Sole abort control in banner. Session Stop has identical effect, honored even while collapsed. Measured: abort during 16 s backoff terminated chain in 2 ms (`ctx.abort()` → `AgentSession.abort()` → `abortRetry()`).
|
|
373
|
+
- NO Retry control on settled surface (would need missing re-drive mechanism).
|
|
374
|
+
- Sidebar session card shows only amber working-token mark (no per-card countdown — avoids N timers in render-hot component).
|
|
141
375
|
|
|
142
376
|
### Interactive UI Flow (PromptBus — extension dialog → browser → response)
|
|
143
377
|
1. Extension calls `ctx.ui.confirm()` / `select()` / `input()` / `editor()` / bridge-patched `multiselect()`
|
|
@@ -174,6 +408,31 @@ TypeScript type definitions shared across all components:
|
|
|
174
408
|
- **Page refresh**: Server replays pending `prompt_request` messages when a browser subscribes. Client deduplicates by `requestId` or pending title match.
|
|
175
409
|
- **Bridge reconnect**: Bridge replays pending PromptBus requests on WebSocket reconnect so dashboard dialogs survive server restarts.
|
|
176
410
|
|
|
411
|
+
### Notify Flow (`ctx.ui.notify` → browser, split from prompt_request)
|
|
412
|
+
|
|
413
|
+
Change: `split-notify-from-prompt-request`. `ctx.ui.notify` used to ship over `prompt_request`. Every consumer treated it as an unanswered ask → `trackPromptRequest` → `currentTool="ask_user"` re-armed on every quiescent moment → permanent "Needs you", false unread, `questionFirst` reorder, and a session the embed-lifecycle reaper could never reclaim. Now a dedicated `notify` message type end to end.
|
|
414
|
+
|
|
415
|
+
**Protocol:**
|
|
416
|
+
- `NotifyMessage` in `packages/shared/src/protocol.ts` (`ExtensionToServerMessage`): `{ type: "notify", sessionId, notifyId, message, level? }`. No `promptId`, no `component`, no `placement`.
|
|
417
|
+
- `BrowserNotifyMessage` in `packages/shared/src/browser-protocol.ts` (`ServerToBrowserMessage`), same shape.
|
|
418
|
+
- `NotifyLevel` = `"info" | "success" | "warning" | "error"` in `packages/shared/src/types.ts`. Normalized by `normalizeNotifyLevel` (`packages/shared/src/notify.ts`): unrecognized → `"info"`; omitted when caller passes none.
|
|
419
|
+
|
|
420
|
+
**Bridge** (`packages/extension/src/notify-proxy.ts`): `createNotifyProxy` builds the `ctx.ui.notify` replacement `bridge.ts` installs. Calls pi's original notify, then sends the `notify` frame. Never PromptBus.
|
|
421
|
+
|
|
422
|
+
**Server routing** (`packages/server/src/event-wiring.ts`): `msg.type === "notify"` branch = owner/`ended` guard → append to notify log → `sendToSubscribers`. No `trackPromptRequest`, no `currentTool` write, no unread stamp, no `questionFirst` reorder, no `session_updated` broadcast.
|
|
423
|
+
|
|
424
|
+
**Permanent version-skew guard:** pre-split bridge publishes to npm independently of the server. The `prompt_request` branch early-outs on `prompt.type === "notify"` AFTER the owner/`ended` guard and BEFORE `trackPromptRequest`, via `fromLegacyPromptRequest(msg)` (`packages/server/src/pairing/notify-log.ts`). Reads `component.props.message`/`level`, falls back to `prompt.question`, normalizes level. Server owns the normalization, so a browser never receives the raw legacy frame and the client needs no legacy branch.
|
|
425
|
+
|
|
426
|
+
**Notify log** (`packages/server/src/pairing/notify-log.ts`, wired in `packages/server/src/pairing/browser-gateway.ts`): bounded per-session, `NOTIFY_LOG_CAP = 50`, oldest-first eviction. Strictly separate from `pendingPromptRequests`: never feeds `hasPendingPromptRequests`, the reaper's `hasPendingAsk` union, or the `currentTool` fold. NOT cleared in `clearPendingRequestsForSession` — an ended session keeps its rows; reapability protected by exclusion, not deletion.
|
|
427
|
+
|
|
428
|
+
**Durability:** a notify is not a `DashboardEvent`, so `event_replay` cannot restore it. `appendNotify` mirrors the log onto `DashboardSession.notifyLog`; `sessionToMeta` enumerates it (full-overwrite `.meta.json` save); `sessionFromMeta` restores it on cold start; `memory-session-manager.register()` carries it across a bridge reattach. `replayNotifyLog(ws, sessionId)` re-sends on browser subscribe, called at ALL FOUR sites in `packages/server/src/browser-handlers/subscription-handler.ts` right after `replayPendingUiRequests` (stale-lastSeq full replay, delta with events, delta without events, cold on-disk hydration). Deliberately a sibling function, not folded into `replayPendingUiRequests`. `hydrateNotifyLog(sessionId)` (`packages/server/src/pairing/browser-gateway.ts`) seeds the in-memory log from restored `DashboardSession.notifyLog`; called at the top of BOTH `replayNotifyLog` AND `appendNotify`. Reason: append onto an empty in-memory list mirrors back a one-row array via `sessionManager.update` — wipes persisted history before any browser saw it (restart + bridge-reattach path).
|
|
429
|
+
|
|
430
|
+
**Client:** `addNotify` in `packages/client/src/lib/chat/event-reducer.ts` appends ONLY an `interactiveUi` row (`ui-<notifyId>`, content `notify`) to `messages`, never an `interactiveRequests` entry — transcript position is insertion order in `messages`. Dedup by `notifyId`, not message text, so a warm reconnect replay is idempotent. Handled in BOTH reducers: `packages/client/src/hooks/useMessageHandler.ts` (main app) and `packages/client/src/hooks/useSessionState.ts` (embed). `NotifyRenderer` still reached via the interactive-renderer registry (`["notify", NotifyRenderer]`).
|
|
431
|
+
|
|
432
|
+
**Accepted skew:** old client + new server resolves on reload (client ships with the server). Old server + new bridge drops the notification for the skew window — no catch-all forward, no version handshake; accepted, bounded.
|
|
433
|
+
|
|
434
|
+
See change: `split-notify-from-prompt-request`.
|
|
435
|
+
|
|
177
436
|
### Command Flow (browser → pi)
|
|
178
437
|
1. User types prompt or command in browser
|
|
179
438
|
2. Browser sends `send_prompt` via WebSocket
|
|
@@ -258,7 +517,7 @@ Key properties:
|
|
|
258
517
|
| extension → server → browser | `ui_data_list { sessionId, event, items }` | Row data for `table`/`grid` views. |
|
|
259
518
|
| browser → server → extension | `ui_management { sessionId, action, event, params }` | Data fetch (`action: "list"`) or user action. |
|
|
260
519
|
|
|
261
|
-
**Replay on reconnect:** Server caches `Session.uiModules` and `Session.uiDataMap` (per-event item cap = 1000, last-write-wins on overflow). The replay site is `replayUiState(ws, sessionId, ctx)` in `packages/server/src/browser-handlers/subscription-handler.ts`, called immediately after every
|
|
520
|
+
**Replay on reconnect:** Server caches `Session.uiModules` and `Session.uiDataMap` (per-event item cap = 1000, last-write-wins on overflow). The replay site is `replayUiState(ws, sessionId, ctx)` in `packages/server/src/browser-handlers/subscription-handler.ts`, called immediately after every `replayNotifyLog` site (4 sites: stale-lastSeq full replay, delta replay, no-events path, lazy load from disk). Replay ordering: events → pending UI requests → notify log → UI module state.
|
|
262
521
|
|
|
263
522
|
**Phase-2 surface (shipped):**
|
|
264
523
|
|
|
@@ -317,7 +576,7 @@ sequenceDiagram
|
|
|
317
576
|
|
|
318
577
|
**Relationship to existing capabilities:**
|
|
319
578
|
- `interactive-ui-dialogs` / `ui-proxy` / PromptBus — handle one-shot `ctx.ui.*` dialogs (request/response, awaited). The extension-ui-system handles persistent push-based descriptors (no awaiting). Orthogonal mechanisms; both ship.
|
|
320
|
-
- `extension-ui-forwarding` (catch-all `pi.events.emit` forwarding) — kept for arbitrary extension events; the new system is the *declarative* path for UI specifically.
|
|
579
|
+
- `extension-ui-forwarding` (catch-all `pi.events.emit` forwarding) — kept for arbitrary extension events; the new system is the *declarative* path for UI specifically. Runtime behaviour stands. No authored spec — file removed (0-byte placeholder since initial commit). See change: repair-corrupted-main-specs.
|
|
321
580
|
- pi-flows: in Phase 3 pi-flows itself adopts the system to surface registered workflows (breadcrumb), gates, and cards (agent-metric) for any flow-using extension automatically.
|
|
322
581
|
|
|
323
582
|
**No-dashboard fallback:** When no bridge is connected, `ui:list-modules` is never emitted; extension listeners are dormant; slash commands fall back to existing text-output behavior. Extensions remain pi-runnable in pure-pi mode without code changes.
|
|
@@ -352,11 +611,12 @@ Descriptor-only slots (existing in `extension-ui-system`): `management-modal`, `
|
|
|
352
611
|
|
|
353
612
|
`packages/dashboard-plugin-runtime/` is a new workspace package containing all runtime pieces:
|
|
354
613
|
|
|
355
|
-
- **`src/slot-registry.ts`** — `createSlotRegistry()` returns a typed `Map<SlotId, ClaimEntry[]>` sorted by `(priority, pluginId)`. Filter helpers: `forSession`, `
|
|
356
|
-
- **`src/manifest-validator.ts`** — hand-rolled manifest validator; throws `ManifestValidationError` with `pluginId` and `reason`.
|
|
614
|
+
- **`src/slot-registry.ts`** — `createSlotRegistry()` returns a typed `Map<SlotId, ClaimEntry[]>` sorted by `(priority, pluginId)`. Filter helpers: `forSession`, `forSessionRendered`, `forFolder`, `forCommand`, `forToolName`, `forActionId`. Registry also exposes read-only `isPluginEnabled(id)`.
|
|
615
|
+
- **`src/manifest-validator.ts`** — hand-rolled manifest validator; throws `ManifestValidationError` with `pluginId` and `reason`. Validates `shell-overlay-route` `presentation` is `"page"`|`"dialog"`; unknown value FATAL, not warn-and-default — typo like `"modal"` would silently restore the behaviour the author opted out of. See change: add-route-backed-overlay-dialogs.
|
|
357
616
|
- **`src/plugin-context.tsx`** — `PluginContextProvider` wraps the entire app. A nested `CurrentPluginLayer` is pushed per contribution so `usePluginConfig<T>()` and `logger` resolve to the contributing plugin's id. `applyPluginConfigUpdate` updates the in-memory config store and re-renders subscribers.
|
|
358
|
-
- **`src/slot-consumers.tsx`** — one component per slot id. Each wraps contributions in a `SlotErrorBoundary` (per-claim scope). Reads registry from the provider.
|
|
617
|
+
- **`src/slot-consumers.tsx`** — one component per slot id. Each wraps contributions in a `SlotErrorBoundary` (per-claim scope). Reads registry from the provider. `ShellOverlayRouteSlot` renders matched claim body ONLY, inside `flex-1 min-h-0 relative` height wrapper. No dialog chrome, no container selection. `dialogContainer` prop + `OverlayContainerProps`/`OverlayContainerComponent` types removed. Container choice belongs to HOST (`App.tsx`): reads claim's effective `presentation` via exported `useShellOverlayRoutePresentation` hook (default `"dialog"`; `"page"` opts out → full viewport desktop + mobile), lifts dialog claim out of content region into `RouteBackedOverlay`. Seam could not work — underlay must cover VIEWPORT; wrapping from inside slot puts underlay inside content region. Hook returns string, avoids `client-utils` → `dashboard-plugin-runtime` dependency cycle. Rationale: design D2a (SUPERSEDED). See change: add-route-backed-overlay-dialogs.
|
|
359
618
|
- **`src/slot-error-boundary.tsx`** — React error boundary scoped to one claim. Logs with plugin id and slot id; renders nothing for the failing claim without suppressing siblings.
|
|
619
|
+
- **`src/__tests__/bundled-overlay-claims.test.ts`** — repo gate on BUNDLED `shell-overlay-route` claims: explicit `depth`; `depth: 2` requires `parentPath`; `parentPath` interpolable from claim path's own `:params`; claim nested under `/folder/:x` or `/session/:x` must NOT declare `depth: 1`. Third-party manifests keep runtime degradation to `/` as safety net. See change: add-route-backed-overlay-dialogs.
|
|
360
620
|
- **`src/vite-plugin/index.ts`** — `viteDashboardPluginsPlugin` generates `packages/client/src/generated/plugin-registry.tsx` with named imports (tree-shaking). Watches manifests during dev and triggers HMR.
|
|
361
621
|
- **`src/server/loader.ts`** — `discoverPlugins(repoRoot?)` (single module-level cache), `loadServerEntries(deps)` (per-plugin dynamic-import, failure isolated), `getPluginStatusStore()`.
|
|
362
622
|
- **`src/server/server-context.ts`** — `createServerPluginContext(deps, pluginId)` — namespaced logger, typed config accessors.
|
|
@@ -382,10 +642,12 @@ Descriptor-only slots (existing in `extension-ui-system`): `management-modal`, `
|
|
|
382
642
|
|
|
383
643
|
#### Health endpoint observability
|
|
384
644
|
|
|
385
|
-
`/api/health` exposes
|
|
645
|
+
`/api/health` exposes five additive measurement fields (no behavior change). Existing clients ignore unknown fields. See change: instrument-session-hydration-timing.
|
|
386
646
|
- `eventLoopDelay: { meanMs, p99Ms, maxMs }` — `perf_hooks.monitorEventLoopDelay` histogram, ns→ms. Resets window each read.
|
|
387
647
|
- `hydration: HydrationSample[]` — ring buffer, ≤20 newest-first samples. Process-local, no persistence. Sample `{ sessionId, wallMs, fileBytes, entryCount, eventCount, at }` recorded by `loadSessionEvents`.
|
|
388
648
|
- `eventLoopSpikes: { at, ms, turn }[]` — ring buffer, ≤50 newest-first, process-local, additive. Retains worst-case event-loop stalls. Two feeds: dedicated `monitorEventLoopDelay` sampler (own instance, never the boot histogram `/api/health` resets → no reset race; records `turn: null` for stalls no poll turn owns) + per-turn self-records from the openspec poll path (`turn: "tickOpen" \| "dirPollPre" \| "dirPollPost"`). Sub-threshold ~700 ms stall retained even when nobody polls `/api/health`. See change: attribute-openspec-poll-eventloop-stalls.
|
|
649
|
+
- `notifyLog: { evictedEntries, bySession }` — from `browserGateway.getNotifyLogStats()` (`packages/server/src/pairing/notify-log.ts` `getStats()`). `evictedEntries` = total cap-50 evictions; `bySession` = per-session counts. Cap-50 eviction = silent transcript loss → counted beside `droppedFrames` / `storeTrim`. See change: split-notify-from-prompt-request.
|
|
650
|
+
- `storeTrim: { trimmedEvents: { total, toolExecutionEnd, bySession }, evictedSessions, collapsedUpdates }` — from `eventStore.getTrimStats()` (`packages/server/src/persistence/memory-event-store.ts`). `trimmedEvents` + `evictedSessions` pre-existing: per-session cap trims, whole-session LRU evictions. See change: instrument-event-store-trim. NEW `collapsedUpdates`: cumulative count of superseded `tool_execution_update` events dropped at retention. Collapse keeps ≤2 `tool_execution_update` per `toolCallId`: pinned creating tick (first-wins `type`/`description`) + newest tail. Retention-only — never suppresses live broadcast; browser still receives every tick. Predecessor dropped only when successor subsumes it (superset gate on `partialResult.details`). Counters cumulative for process lifetime, never reset on read. No event store wired → `EMPTY_TRIM_STATS` (all-zero), exported from store. Harness A/B (4 sessions × 4 sustained subagent rounds): retained `tool_execution_update` per buffer 36 → 2; buffer share 18.4% → 1.2%. See change: collapse-superseded-tool-execution-updates.
|
|
389
651
|
|
|
390
652
|
**Bundled-by-default plugins:** The plugin loader treats all plugins identically (same manifest, same discovery, same `enabled` flag, same failure isolation). What distinguishes "bundled-by-default" plugins (initial set: `git-plugin`) is purely operational — the build pipeline always includes them in `packages/`. Their absence is a deliberate user opt-out, not a normal state. OpenSpec, Flows, and Subagents plugins are bundled in standard builds but their absence is a normal use case (e.g. a workspace without OpenSpec).
|
|
391
653
|
|
|
@@ -445,19 +707,63 @@ Settings ▸ Plugins tab lists every discovered plugin (enabled or not) with dis
|
|
|
445
707
|
|
|
446
708
|
**Toggle workflow.** `PluginsSection` calls `POST /api/plugins/:id/toggle` (`packages/server/src/routes/plugin-activation-routes.ts`). Route writes `plugins.<id>.enabled` via config-api partial merge, broadcasts `plugin_config_update { id, config }` to every browser. Effect is **restart-required**: runtime claim filter (`SlotRegistry.setEnabledSet`) only re-reads enabled-set when client mounts or receives `plugin-config-update` event for the bundle's current plugin set; flipping `enabled` for a plugin whose server entry already loaded doesn't unload it. UI surfaces restart-required banner by comparing toggle timestamp to `/api/health.startedAt`.
|
|
447
709
|
|
|
448
|
-
**Declarative requirements.** Plugins declare `requires: { piExtensions?, binaries?, services? }` in their manifest (`PluginManifest.requires`, validated by `manifest-validator.ts`). At plugin load, `loader.ts` runs `runRequirementProbes(manifest.requires, requirementDeps)` from `packages/dashboard-plugin-runtime/src/server/requirement-probes.ts`. Probes:
|
|
710
|
+
**Declarative requirements.** Plugins declare `requires: { piExtensions?, binaries?, services?, paths? }` in their manifest (`PluginManifest.requires`, validated by `manifest-validator.ts`). At plugin load, `loader.ts` runs `runRequirementProbes(manifest.requires, requirementDeps)` from `packages/dashboard-plugin-runtime/src/server/requirement-probes.ts`. Probes:
|
|
449
711
|
|
|
450
712
|
- `probePiExtension(id)` cross-refs installed pi-extension set (deps.listInstalled).
|
|
451
713
|
- `probeBinary(name)` resolves via tool registry.
|
|
452
714
|
- `probeService(name)` dispatches to service-probe map (e.g. `service-probes/pi-model-proxy.ts::detectPiModelProxy`).
|
|
715
|
+
- `probePath(rawPath, deps)` — existence check on absolute path. Never executes, never shells.
|
|
453
716
|
|
|
454
717
|
Results populate `PluginStatus.requirements` + flat `missingRequirements: string[]`; surfaced via `GET /api/plugins`. 30s in-process cache keyed by category+name. `server.ts` invokes `refreshRequirementProbesFor(pluginIds)` on every successful `package_operation_complete` + broadcasts `plugin_config_update` for any plugin whose missing-set changed — install/uninstall of a pi-extension lights up dependent plugin without restart.
|
|
455
718
|
|
|
719
|
+
**Path requirements (`paths`).** Fourth category, after `piExtensions`/`binaries`/`services`. Declared `PluginRequirements.paths?: string[]` in `packages/shared/src/dashboard-plugin/manifest-types.ts` — absolute filesystem paths that must exist (e.g. `.app`-bundled binaries not on PATH). Report field `PluginRequirementReport.paths: {name,satisfied}[]` (`packages/shared/src/dashboard-plugin/plugin-status.ts`) always present, `[]` when none declared.
|
|
720
|
+
|
|
721
|
+
`probePath(rawPath, deps)` (`packages/dashboard-plugin-runtime/src/server/requirement-probes.ts`) = existence check only (fs.existsSync-class). Never executes path, never shells. A `paths` entry MAY be exactly one `${configKey}` placeholder (regex `^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$`). Resolved from declaring plugin's validated config — schema defaults applied, config read not shell expansion. Key must exist in `configSchema`; resolved value must be absolute. Failure → `satisfied: false`, never throws.
|
|
722
|
+
|
|
723
|
+
Wiring: `runRequirementProbesFor` probes `paths` after `services` — preserves category ordering. `missingFromReport` appends unsatisfied paths last. Paths share existing 30s TTL cache.
|
|
724
|
+
|
|
725
|
+
Reconciliation: `shouldReconcilePath` (`packages/apple-tools/src/reconcile.ts`) writes discovered non-default path back to `imcpServerPath` via `updatePluginConfig` — only when config unset/empty or at schema default. Never overwrites explicit operator override. Runs in plugin server (owns store), not CLI.
|
|
726
|
+
|
|
727
|
+
Client: unsatisfied `paths` requirement renders non-actionable warning pill — no [Install] — in `packages/client/src/components/packages/PluginsSection.tsx` (data-testid `missing-path-<name>`).
|
|
728
|
+
|
|
456
729
|
**UI cross-references.** `RecommendedExtensions.tsx` reads `EnrichedRecommendedExtension.dashboardPluginInstalled` (computed server-side in `recommended-routes.ts::enrichEntry` from `RecommendedExtension.dashboardPlugin`) + renders `+plugin: <id>` badge linking to Plugins tab.
|
|
457
730
|
|
|
458
731
|
**Restart-required model.** `usePluginEnabledSet` snapshots `/api/health.startedAt` ISO timestamp on first load. Subsequent `plugin_config_update` events update enabled-set live for claim filtering, but components that consumed plugin server entries (already loaded) require a restart to drop. `PluginsSection` compares toggle time to snapshot and renders "Restart required" banner when divergent.
|
|
459
732
|
|
|
460
|
-
**Settings consolidation.** Plugin-contributed `settings-section` claims render
|
|
733
|
+
**Settings consolidation.** Plugin-contributed `settings-section` claims render on owning plugin's dedicated left-nav page `/settings/plugins/<id>` — contract in `#### Plugin settings pages` below. Legacy `claim.tab` manifest field preserved for back-compat manifests but inert; `SettingsPanel` no longer consumes it. See change: add-plugin-activation-ui (settings-consolidation).
|
|
734
|
+
|
|
735
|
+
#### Plugin settings pages (`plugin-settings-pages`)
|
|
736
|
+
|
|
737
|
+
Plugin-contributed `settings-section` claims render on owning plugin's dedicated page `/settings/plugins/<id>`. One render path only: `SettingsSectionByPluginSlot` inside `PluginSettingsPage.tsx`. See change: plugin-settings-pages.
|
|
738
|
+
|
|
739
|
+
**Slot contract.**
|
|
740
|
+
|
|
741
|
+
- `SettingsSectionByPluginSlot` = only consumer. Consumes BOTH refs claims AND intent broadcasts (`useSlotIntents("settings-section", null)`).
|
|
742
|
+
- Order: claims first, registry comparator (ascending `priority`, tie-break `pluginId.localeCompare`); then intents in store order. `IntentNode` carries no priority.
|
|
743
|
+
- `SettingsSectionSlot` inert — returns `null` for any `tab`. `SettingsPanel.tsx` mounts zero of them; repo-lint enforces in `packages/shared/src/__tests__/plugin-activation-contracts.test.ts`. `forTab` deleted from `slot-registry.ts`.
|
|
744
|
+
- `claim.tab` accepted by manifest but INERT. `manifest-validator.ts` no longer throws on unknown `tab`.
|
|
745
|
+
|
|
746
|
+
**Page chrome — host-owned, no opt-out.** `PluginSettingsPage.tsx` renders identity, status pill, enable toggle, metadata chips, error + missing-requirement banners. Plugin supplies body only. Chrome renders only fields `GET /api/plugins` returns (`PluginRow`): no `version`/`description`/`source`/`icon`.
|
|
747
|
+
|
|
748
|
+
**Routes.** `/settings/:page?/:sub?` at BOTH `App.tsx` and `SettingsPanel.tsx`. `:sub` interpreted only when `:page === "plugins"` (design D2). `VALID_SETTINGS_TABS` unchanged. Unknown id or settings-less plugin → activation index + not-found notice.
|
|
749
|
+
|
|
750
|
+
Folder-scoped `/folder/:encodedCwd/settings/:page?` unchanged; `VALID_FOLDER_SETTINGS_PAGES` excludes `plugins`.
|
|
751
|
+
|
|
752
|
+
**Settings eligibility.** Plugin contributes settings = registers `settings-section` refs claim OR holds `settings-section` intent in intent store. One predicate governs all three: nav-rail child membership, activation-index cog affordance, route eligibility for `/settings/plugins/<id>`. `PluginRow.claims` built from manifest only (`plugin-activation-routes.ts`) — intents invisible. Claims-only test strands intent-only plugin: slot renders contribution, nav child absent, URL bounces to activation index. Implementation: `contributesSettings()` in `packages/client/src/components/settings/SettingsPanel.tsx`; passed to `PluginsSection` — all three sites share it.
|
|
753
|
+
|
|
754
|
+
**Nav rail children.** Plugins where `enabled !== false` AND contributes settings (claim OR intent), sorted by display name, each with health dot. Keys on `enabled`, NOT `loaded` — failed-load plugin must stay reachable (design D4).
|
|
755
|
+
|
|
756
|
+
**Disabled plugin page.** Chrome + disabled notice + re-enable affordance. No body; component never mounts. Intent filtering happens in consumer, not registry: `SettingsSectionByPluginSlot` calls `isPluginEnabled(pluginId)` and drops plugin's intent when it returns false. `SlotRegistry.isPluginEnabled(id)` = read-only accessor — `true` before any `setEnabledSet` call, else set membership. Added because registry previously exposed `setEnabledSet` with no getter. Registry's own filter (inside `getClaims`) covers claims only — exactly why consumer must filter intents itself (design D6/D7/D8).
|
|
757
|
+
|
|
758
|
+
**Enable state = desired state, not runtime.** `POST /api/plugins/:id/toggle` writes `config.plugins.<id>.enabled`, broadcasts `plugin_config_update`, returns `restartRequired: true`. `GET /api/plugins`.status + `GET /api/health`.plugins[] both come from `getPluginStatusStore()` — runtime load state captured at server boot — neither reflects flip until restart. `usePluginList` (`packages/client/src/hooks/usePluginToggle.tsx`) keeps desired-state overlay: seeded from `GET /api/config`.plugins on mount (survives reload), updated from `plugin_config_update` payload + toggle response cascade. `status.loaded` untouched — stays runtime truth, explained by restart-required banner.
|
|
759
|
+
|
|
760
|
+
**Save stays global, one fan-out.** `SettingsDraftSource.page` now OPTIONAL. `PluginSettingsPageProvider` supplies owning plugin id; `useSettingsDraftSource` rewrites `page` → `plugins/<pluginId>` BEFORE `registry.upsert`. Rewrite lives in hook, not registry — `draftRegistry` memoized in `SettingsPanel` scope, above plugin page; ancestor closure cannot read descendant's context.
|
|
761
|
+
|
|
762
|
+
**Save Bar.** Names every dirty page, no cap; plugin pages labelled `Plugins › <Display Name>`; each entry navigates. Header carries changed-page count badge.
|
|
763
|
+
|
|
764
|
+
**Nav guards.** Rail navigation guards ONLY when leaving plugin page whose own sources dirty — plugin draft state dies on unmount. Built-in→built-in unguarded — built-in draft state lives in `SettingsPanel`'s `useState`.
|
|
765
|
+
|
|
766
|
+
**Disable-on-dirty.** Disabling plugin from its own dirty page resolves unsaved-changes confirm BEFORE rail drops nav child.
|
|
461
767
|
|
|
462
768
|
#### Plugin bridge↔server channel (generic)
|
|
463
769
|
|
|
@@ -494,7 +800,10 @@ Automation plugin = `packages/automation-plugin/`. Schedule-triggered background
|
|
|
494
800
|
- Folder format `<scope>/.pi/automation/<name>/automation.yaml` (+`prompt.md` for prompt action). Dual scope: per-folder + global (`~/.pi/automation/`).
|
|
495
801
|
- Central server-owned scheduler arms trigger registry. Phase-1 trigger kind `schedule` (5-field cron).
|
|
496
802
|
- Fired run spawns pi session stamped `kind="automation"` via `ServerPluginContext.spawnSession` hook (gated priority<=100).
|
|
497
|
-
- Board hides run unless effective visibility `shown`. Run always watchable in Automation view (`/
|
|
803
|
+
- Board hides run unless effective visibility `shown`. Run always watchable in Automation view (`/folder/:encodedCwd/automations/run/:sid`).
|
|
804
|
+
- Old path `/automation/run/:sid` declared `parentPath` `/folder/:encodedCwd/automations` but never captured `:encodedCwd`. `interpolateParentPath` returned null; back degraded to `/`.
|
|
805
|
+
- New path carries board cwd. Cold-load back resolves to owning board.
|
|
806
|
+
- See change: add-route-backed-overlay-dialogs.
|
|
498
807
|
- Run results `runs/<date>-<name>/result.md`. Auto-archive empty. Keep-100 retention.
|
|
499
808
|
- UI via shell slots: sidebar-folder-section, command-route `/automation`, shell-overlay-route, session-card-badge, settings-section general.
|
|
500
809
|
- See change: add-automation-plugin.
|
|
@@ -513,6 +822,76 @@ New package `packages/hermes-memory-plugin` (client + server + shared). Settings
|
|
|
513
822
|
- Runtime caveat: hermes reads config once at extension load → edits apply to newly started sessions only ("applies to new sessions" notice in the UI), not running ones.
|
|
514
823
|
- Structured logging: path + field count on read/write success, failure reason on error, NEVER field values (config may hold model/provider hints).
|
|
515
824
|
|
|
825
|
+
### MCP Endpoint (`add-dashboard-mcp-server`)
|
|
826
|
+
|
|
827
|
+
New plugin `packages/mcp-server-plugin/`. Headless — no client entry, `claims: []`. Mounts `POST /mcp` on `ctx.fastify`, the shared Fastify instance every plugin gets. Seven other plugins register routes the same way.
|
|
828
|
+
|
|
829
|
+
**Protocol.** Implements MCP revision `2026-07-28` ONLY. No legacy `2025-06-18` / `2025-11-25`. Both reintroduce `initialize` + `Mcp-Session-Id`, the two mechanisms this endpoint exists to refuse. Unsupported version → `UnsupportedProtocolVersionError`. Stateless: no `initialize` handshake. No `Mcp-Session-Id` (never minted, never echoed, ignored on input). No `Last-Event-ID` resumption.
|
|
830
|
+
|
|
831
|
+
`MCP-Protocol-Version` header required on EVERY POST. Must agree with `params._meta["io.modelcontextprotocol/protocolVersion"]`. Disagreement → `400 HeaderMismatch`. Check order observable:
|
|
832
|
+
- absent header → `MissingHeader`
|
|
833
|
+
- absent `_meta` → `MissingMeta`
|
|
834
|
+
- non-string body version → `UnsupportedProtocolVersion`
|
|
835
|
+
- only then judged supported
|
|
836
|
+
|
|
837
|
+
**Method / error mapping.**
|
|
838
|
+
- Unknown method → `404` + JSON-RPC `-32601`. Unknown tool → `404` + `-32601`.
|
|
839
|
+
- Malformed body → `-32700` (unparseable) or `-32600` (valid JSON, not JSON-RPC).
|
|
840
|
+
- Fastify body-parse failure normalised into JSON-RPC parse error.
|
|
841
|
+
- Never `500`. Handler rejection → `-32603`, never an unhandled rejection.
|
|
842
|
+
- Non-POST methods → `405` + `Allow: POST`.
|
|
843
|
+
- Explicitly registered: GET, DELETE, PUT, PATCH, OPTIONS.
|
|
844
|
+
- HEAD NOT registered. Fastify derives HEAD from GET. Returns same 405. Asserted in tests, not registered.
|
|
845
|
+
- Reason: Fastify falls an unmatched method through to `setNotFoundHandler`. In `--dev`, that proxies Vite and returns 200 + SPA HTML. Conformance failure that looks like success.
|
|
846
|
+
|
|
847
|
+
**Encapsulated scope.** Routes register inside a Fastify `register` scope, not on the shared instance. Load-bearing: `setErrorHandler` global on the instance called on. Call on `ctx.fastify` → replaces dashboard handler, breaks SPA fallback.
|
|
848
|
+
|
|
849
|
+
**Auth boundary.** `createNetworkGuard` applied per-route. `/mcp` sits outside it, self-guards. Every request needs a bearer credential, INCLUDING loopback. No `isGenuinelyLocal` parameter exists. Handler reads `Authorization` directly, never `request.isAuthenticated` (global hooks set that for cookies + device tokens). Cookie-authenticated browser cannot reach `/mcp`.
|
|
850
|
+
|
|
851
|
+
Two credential kinds resolve to one `McpCaller`:
|
|
852
|
+
- session-scoped MCP tokens → `{ kind:"session", sessionId }`, has originating session
|
|
853
|
+
- paired-device bearers → `{ kind:"device", deviceId }`, no originating session
|
|
854
|
+
|
|
855
|
+
**Session tokens.** Opaque 256-bit. `mcp_` prefix. SHA-256 at rest. Plaintext returned once at mint. Constant-time compare. Flat-array scan, no membership-timing leak. No independent expiry — a token's lifetime IS its session's lifetime. IN-MEMORY only: no `mcp-tokens.json`. Registry dies with the plugin. All die on restart. Sessions re-mint when bridge re-registers. Revocation: `onSessionEnded` / bridge disconnect (primary), explicit `mcp/revoke-token`, process exit / plugin unload.
|
|
856
|
+
|
|
857
|
+
**Minting.** `mcp/mint-token` over the session's own bridge WebSocket. Server attributes it to the session the CONNECTION registered as (`currentSessionId`), never `msg.sessionId`. `mcp/revoke-token` revokes by session.
|
|
858
|
+
|
|
859
|
+
`plugin_pi_message.sessionId` a REQUIRED protocol field (`protocol.ts:593`), always present. `pi-gateway.ts` previously preferred it over the connection — a bridge could name any session and receive that session's credential. `plugin_pi_message` now excluded from body-sessionId precedence. Other message types keep prior behaviour.
|
|
860
|
+
|
|
861
|
+
Guarantee stated exactly: "the session this connection registered as". Not spoofable per-message — what the self-target guard needs. NOT a claim about pi-gateway port authentication. `currentSessionId` itself set from the first `register` message. Pre-existing bridge trust model. Out of scope here.
|
|
862
|
+
|
|
863
|
+
**Self-target guard.** Refuses a session-targeting tool call (`send_prompt`, `abort`) whose target equals the caller's own resolved session. Target normalised for equality (trim, one quote pair, lowercase) — bypass-proof. Catches DIRECT self-targeting only. Indirect A→B→A loop permitted, documented out of scope. Device callers have no originating session, structurally outside the guard.
|
|
864
|
+
|
|
865
|
+
**Tool surface.** Curated allowlist over `ServerPluginContext`. 5 of 19 allowlisted (`sessionManager`, `sendToSession`, `spawnSession`, `abortSession`, `onEvent`), 14 denied. Partition total — future member fails `assertContextPartitionTotal`. Tools: `list_sessions`, `send_prompt`, `spawn_session`, `abort`. `abort` maps to `abortSession` (soft-only, false on a disconnected bridge), NOT `abortSpawnedRun`. `sessionId` an ordinary required argument (revision removed protocol sessions).
|
|
866
|
+
|
|
867
|
+
**Streaming.** `subscriptions/listen`, a long-lived POST-response stream. `params.sessionIds[]` required; absent/empty/non-array → `-32602`. No subscribe-to-all. Filter applied per subscription before write. Authorisation re-checked per delivery. Revoked mid-stream → terminates it. Slow consumer → subscription TERMINATED at `MAX_BUFFERED_EVENTS` (1000) buffered events. Does NOT silently drop events. Subscription dies with its request.
|
|
868
|
+
|
|
869
|
+
**Provisioning.** Writes `~/.pi/agent/mcp.json` key `pi-dashboard` on server start. HTTP `url` shape, not stdio `command` (iMCP writes `command`). `protocolVersion` pinned `2026-07-28` — never omitted, else legacy handshake. Merge-only. Atomic rename. Refuses unparseable file. Foreign shape under the reserved key → refuses the whole write, file untouched. Failure logged, never thrown — provisioning a convenience, not a precondition for serving `/mcp`.
|
|
870
|
+
|
|
871
|
+
**Prerequisite.** `pi-mcp-adapter >= 2.20.0` for the local-pi path. Below that, "legacy remains the default", handshake silently degrades. Runtime probe reports floor + installed + failure mode (`absent` / `below-floor` / `unparseable`).
|
|
872
|
+
|
|
873
|
+
**Config reference.** `MCP_BODY_LIMIT_BYTES` 1 MiB body cap. `MAX_BUFFERED_EVENTS` 1000 buffered events.
|
|
874
|
+
|
|
875
|
+
```mermaid
|
|
876
|
+
sequenceDiagram
|
|
877
|
+
participant C as MCP client
|
|
878
|
+
participant S as /mcp (encapsulated scope)
|
|
879
|
+
participant R as McpTokenRegistry
|
|
880
|
+
participant B as Bridge (session socket)
|
|
881
|
+
C->>S: POST /mcp (Authorization: Bearer, MCP-Protocol-Version)
|
|
882
|
+
S->>S: authenticate(header) → McpCaller
|
|
883
|
+
S->>S: resolveProtocolVersion(header, params._meta)
|
|
884
|
+
S->>S: dispatchRpc (method allowlist)
|
|
885
|
+
Note over S,R: session token kind
|
|
886
|
+
B->>S: mcp/mint-token (over session's own socket)
|
|
887
|
+
S->>R: mintForSession(sessionId from socket key)
|
|
888
|
+
R-->>B: plaintext token (once)
|
|
889
|
+
```
|
|
890
|
+
|
|
891
|
+
**Seam change.** `RegisterPiHandlerFn` widened to `(msg, sessionId)`. Gateway passes its socket key through `dispatchPluginPiMessage`. Additive — `(msg)`-only handlers still valid. `sessionId` from the socket key, never the message body — a plugin can attribute a bridge message as a trust decision.
|
|
892
|
+
|
|
893
|
+
See change: add-dashboard-mcp-server.
|
|
894
|
+
|
|
516
895
|
### Bootstrap & First Run (R3, immutable bundle)
|
|
517
896
|
|
|
518
897
|
pi/openspec/tsx are regular npm dependencies of `@blackbelt-technology/pi-dashboard-server`. There is no runtime install pyramid. All three arms (Electron, standalone `npm i -g`, bridge) start ready.
|
|
@@ -531,6 +910,28 @@ Pre-R3 builds installed pi/openspec/tsx into `~/.pi-dashboard/node_modules/` at
|
|
|
531
910
|
|
|
532
911
|
See change: eliminate-electron-runtime-install.
|
|
533
912
|
|
|
913
|
+
### Cold-Start Session Recovery (Exit Intent & Boot State)
|
|
914
|
+
|
|
915
|
+
Offer sessions for recovery after server restart. Distinguish crashes (sessions lost) from deliberate exits (sessions live, will reattach). See change: fix-recovery-exit-intent.
|
|
916
|
+
|
|
917
|
+
**Boot record.** File `~/.pi/dashboard/boot-state.json`. One O(1) write per exit, not per session (exit paths have ~100 ms and cannot walk sidecars). Shape: `{ bootId, exitIntent, at, ring: BootRecord[] }`. `bootId` = server `liveEpoch`. `ring` = 8 most recent prior boots (`BOOT_RING_SIZE`). Atomic write via `writeJsonFile` (tmp + rename). Owner: `packages/server/src/persistence/boot-state.ts`. Exports `stampBootStart(bootId)`, `recordExitIntent(intent)`, `resolveExitIntent(liveEpoch)`, `readBootState()`, `_resetBootStateForTests()`.
|
|
918
|
+
|
|
919
|
+
**Exit intent vocabulary.** `packages/shared/src/boot-state.ts`. `ExitIntent = "restart" | "shutdown" | "user-quit" | "idle" | "signal"`. Null = crash (nothing recorded). Function `isRecoveryAllowed(intent)` returns false ONLY for `restart` and `shutdown` — those exits leave sessions RUNNING and announce a bridge quiesce longer than the reattach grace window, so sessions reattach after any window that could retract them. Other exits + null allow recovery via the liveness gate: offer session, retract if it re-registers inside the grace window.
|
|
920
|
+
|
|
921
|
+
**Recording points.** `POST /api/restart` → `restart`. `POST /api/shutdown` → `shutdown`, or `user-quit` when request body is `{userQuit:true}` (Electron `stopServerIfNeeded` in `packages/electron/src/lib/server-lifecycle.ts` sends it). Idle timer → `server.stop()` → `idle`. New SIGTERM/SIGINT handler in `packages/server/src/cli.ts::runForeground()` → `signal` then `server.flush()` then `process.exit(0)`. Crash/SIGKILL records nothing → stays null. `recordExitIntent` is write-once per boot (first writer wins), so `spawnRestart`'s SIGTERM→SIGKILL ladder cannot overwrite `restart` with `signal`. Write failure logged, never thrown; unwritten intent = dirty boot = over-offer (conservative direction).
|
|
922
|
+
|
|
923
|
+
**Classification.** `packages/server/src/server.ts` gains one conjunct: `isRecoveryAllowed(resolveExitIntent(session.liveEpoch))`. Resolution matches session's `liveEpoch` against current record then ring; unresolvable → null → allowed (back-compat: absent record behaves exactly like old build).
|
|
924
|
+
|
|
925
|
+
**Behavior change.** `server.stop()` NO LONGER clears per-session `live` markers. Records `exitIntent:"idle"` instead. Marker consumption on dismiss / liveness-retract / offer-broadcast unchanged.
|
|
926
|
+
|
|
927
|
+
**Timing constants.** `packages/shared/src/recovery-timing.ts`: `RESTART_QUIESCE_MS = 5000`, `RECONNECT_HEADROOM_MS = 2000`, `RECOVERY_REATTACH_GRACE_MS = RESTART_QUIESCE_MS + RECONNECT_HEADROOM_MS` (7000). Previously grace was 2500, closed BEFORE the quiesce window, made bridge-reattach liveness unreachable on restart path.
|
|
928
|
+
|
|
929
|
+
**Offer broadcast timing.** `ask` mode NO LONGER broadcasts offer immediately. Deferred until grace window closes, then sent once with only surviving candidates. `graceUntil` still on wire for mid-window client connect.
|
|
930
|
+
|
|
931
|
+
**Resume gate.** `resume_session` `mode:"continue"` probes keeper sidecar: `KeeperManager.isKeeperAlive(sessionId)` reads `<sid>.rpc.sock.pid`, checks keeper PID + pi PID. Refuses with `code:"resume.already_active"` when alive, so stale offer never double-spawns one sessionId.
|
|
932
|
+
|
|
933
|
+
**Observability.** Logs: `[recovery] <id>: suppressed-by-intent (boot <epoch> exited via <intent>)`, `[recovery] N candidate(s) after exit-intent gate; awaiting liveness`, `[recovery] grace window closed; offering N candidate(s)`, `[recovery] retracted candidate <id> (<reason>)`, `[recovery] refused reopen of <id>: keeper still alive`, `[boot-state] exit intent recorded: <intent> (boot <id>)`.
|
|
934
|
+
|
|
534
935
|
### Force Kill Escalation
|
|
535
936
|
The Stop button supports two-click escalation for stuck sessions:
|
|
536
937
|
1. **Click 1 (Abort)**: Sends `abort` → bridge → `ctx.abort()`. Button transitions to orange pulsing "Force Stop".
|
|
@@ -602,6 +1003,110 @@ Failure modes (placeholders are visible, not silent):
|
|
|
602
1003
|
|
|
603
1004
|
See change: `chat-markdown-local-images-and-math`.
|
|
604
1005
|
|
|
1006
|
+
### User image attachments — two-phase display fit
|
|
1007
|
+
|
|
1008
|
+
Distinct path from local-image inlining above.
|
|
1009
|
+
That feature rides existing event/asset stream.
|
|
1010
|
+
Adds no HTTP route.
|
|
1011
|
+
This one adds `GET /api/sessions/:sessionId/attachments/:attachmentId`.
|
|
1012
|
+
Same `{type:"image"}` events.
|
|
1013
|
+
Different handling.
|
|
1014
|
+
|
|
1015
|
+
**Problem.** pi delivers pasted screenshots as full-resolution base64 inside the event. Shape: `{type:"image", data, mimeType}`. `memory-event-store.ts` bounds each event by total serialized size. Over-ceiling event data replaced by `{__truncated}` placeholder. Result: image-bearing user message lost `data.message` entirely. Row never rendered. Silent. Measured size distribution n=1587 over 3137 transcripts: p50 125.7 KB, p90 757.3 KB, p99 2233.3 KB, max 10.5 MB.
|
|
1016
|
+
|
|
1017
|
+
**Design.** Fit each image block to a DISPLAY derivative before store.
|
|
1018
|
+
768 px long edge.
|
|
1019
|
+
JPEG q75 when re-encoding.
|
|
1020
|
+
`DEFAULT_MAX_EVENT_DATA_SIZE` raised 20_000 -> 262_144 (256 KiB).
|
|
1021
|
+
Raise sound only WITH the fit.
|
|
1022
|
+
Raw payloads at 256 KiB cover just 74.9%.
|
|
1023
|
+
Fitted output bounded.
|
|
1024
|
+
`DEFAULT_TRANSCRIPT_CAP_BYTES` derives 0.75 x ceiling.
|
|
1025
|
+
Moves 15 KB -> 192 KiB (D9, accepted, coupling kept).
|
|
1026
|
+
|
|
1027
|
+
**Two-phase flow** (key data-flow fact):
|
|
1028
|
+
|
|
1029
|
+
```mermaid
|
|
1030
|
+
sequenceDiagram
|
|
1031
|
+
participant pi as pi (agent)
|
|
1032
|
+
participant bridge as Bridge (extension)
|
|
1033
|
+
participant server as Dashboard server
|
|
1034
|
+
participant fit as Fit worker pool
|
|
1035
|
+
participant client as Browser (event-reducer)
|
|
1036
|
+
|
|
1037
|
+
pi->>bridge: pasted screenshot<br/>{type:"image", data: base64, mimeType}
|
|
1038
|
+
bridge->>server: event_forward (image event)
|
|
1039
|
+
server->>server: prepareEventForIngest()<br/>(attachment-ingest.ts) strips image bytes
|
|
1040
|
+
server->>server: placeholder block<br/>{data:"", attachmentId, attachmentState:"pending"}<br/>attachmentId = sha256(original base64)
|
|
1041
|
+
server->>client: row event stored + broadcast IMMEDIATELY
|
|
1042
|
+
server->>fit: fit-worker-pool.ts fits off main loop<br/>(768px long edge, JPEG q75)
|
|
1043
|
+
fit-->>server: fitted derivative
|
|
1044
|
+
server->>client: SEPARATE stored+broadcast attachment_fitted<br/>{attachmentId, data, mimeType, state:"ready"|"failed"}
|
|
1045
|
+
client->>client: event-reducer.ts patches pending block by attachmentId
|
|
1046
|
+
client->>client: user clicks image → lightbox (fitted derivative as fallbackSrc)
|
|
1047
|
+
client->>server: GET /api/sessions/:sessionId/attachments/:attachmentId<br/>(original bytes, zoom view)
|
|
1048
|
+
```
|
|
1049
|
+
|
|
1050
|
+
- Phase 1: `prepareEventForIngest()` (`packages/server/src/attachments/attachment-ingest.ts`) strips image bytes, leaves placeholder block `{data:"", attachmentId, attachmentState:"pending"}`. Row event stored + broadcast IMMEDIATELY.
|
|
1051
|
+
- Phase 2: `fit-worker-pool.ts` fits off the main loop. `attachment-resolver.ts` emits a SEPARATE stored+broadcast event `attachment_fitted` with `{attachmentId, data, mimeType, state:"ready"|"failed"}`.
|
|
1052
|
+
- In-process fallback (workers disabled/unspawnable) capped at pool `size`. Unbounded fallback ran N concurrent jimp decodes on the MAIN thread. Exact event-loop stall the pool exists to prevent.
|
|
1053
|
+
- Client reducer (`event-reducer.ts`) patches the pending block by `attachmentId`.
|
|
1054
|
+
- `attachmentId` = sha256 of the ORIGINAL base64. Content-addressed.
|
|
1055
|
+
- Addressed by hash NOT by seq: client live fold is append-only and never sees a seq; replay can reorder; hash is also the originals-endpoint key.
|
|
1056
|
+
- One resolution patches EVERY occurrence of that hash (same screenshot pasted twice shares one id).
|
|
1057
|
+
- BOTH ingest paths fit: live `event-wiring.ts` AND session hydration in `subscription-handler.ts`. Hydration rebuilds events from the transcript with full-resolution bytes, so skipping it would re-trigger the original bug on reload.
|
|
1058
|
+
|
|
1059
|
+
**MIME admission.** `image-mime.ts` (`packages/server/src/attachments/image-mime.ts`) single source of truth for which inline image mimes the pipeline takes OWNERSHIP of. Exports `isFittableImageMime(mime)`. Two gates consume it, MUST agree: `prepareEventForIngest` (what to strip into pending) + `fitImageBlockForDisplay` (what it can fit). They diverged once. Ingest stripped ANY image block. Fit returned non-allow-listed mime UNCHANGED. Resolution event then carried full-resolution bytes it existed to replace. Busted per-event ceiling. Truncated. Block stranded on "pending" forever. Block rejected here never PROMISED a resolution. Stays inline under existing ceiling. `image/svg+xml` absent on purpose. Script-bearing markup, not safely re-encodable bitmap. Deliberately jimp-free. Ingest path runs on the event loop for EVERY event.
|
|
1060
|
+
|
|
1061
|
+
**Input-size guard.** Every other budget in module measures OUTPUT. `Jimp.read` allocates `width*height*4`. Driven by the HEADER. 20000x20000 PNG: few KB on the wire, ~1.6 GB decoded. Guard parses declared w/h from PNG/GIF/JPEG/WebP header. No pixel decode. Refuses >40 MP or >25 MB BEFORE decode. Constants `DISPLAY_MAX_DECODE_PIXELS` = 40_000_000, `DISPLAY_MAX_INPUT_BYTES` = 25_000_000. Exports `readImageDimensions(bytes)`. Fails CLOSED. Unparseable header ⇒ `failed`, never unbounded decode. 40 MP clears any real screen capture. 6K display ~20 MP.
|
|
1062
|
+
|
|
1063
|
+
**Budget guarantee.** `DISPLAY_MAX_BYTES` = 240_000. Measured in BASE64 bytes (what the store stores). Below 256 KiB ceiling with envelope headroom. Fit enforces the budget. PNG first. Then JPEG quality ladder 75/60/45/30. Then up to 2 halvings. Reports `failed` if it cannot comply. Reason: over-budget derivative makes its OWN `attachment_fitted` event exceed the ceiling -> `{__truncated}` -> `attachmentId` destroyed -> placeholder stuck pending forever.
|
|
1064
|
+
|
|
1065
|
+
**Originals endpoint.** `GET /api/sessions/:sessionId/attachments/:attachmentId` (`packages/server/src/routes/attachment-routes.ts`).
|
|
1066
|
+
Backed by session transcript (`original-store.ts`).
|
|
1067
|
+
Transcript already holds full-resolution bytes.
|
|
1068
|
+
No new durable store.
|
|
1069
|
+
Eviction inherently safe.
|
|
1070
|
+
Transcript scanned line-by-line.
|
|
1071
|
+
Peak memory bounded by largest entry, not file size.
|
|
1072
|
+
NOT load-bearing.
|
|
1073
|
+
Fitted image already inline.
|
|
1074
|
+
Failure degrades only the zoom view.
|
|
1075
|
+
Client passes fitted derivative as lightbox `fallbackSrc`.
|
|
1076
|
+
|
|
1077
|
+
Gates, in order: `networkGuard`; session exists + has `sessionFile`, else 404.
|
|
1078
|
+
Then id shape-checked `^[0-9a-f]{64}$` (400).
|
|
1079
|
+
Check precedes transcript recovery, not every lookup.
|
|
1080
|
+
Request input never becomes a path component.
|
|
1081
|
+
Lookup scoped to that session's transcript.
|
|
1082
|
+
Valid digest from another session simply not found.
|
|
1083
|
+
No ownership table needed.
|
|
1084
|
+
Allow-list png/jpeg/jpg/gif/webp.
|
|
1085
|
+
`image/jpg` added. Alias of already-served format.
|
|
1086
|
+
Was fittable but not servable.
|
|
1087
|
+
Rendered fitted, 404'd on zoom.
|
|
1088
|
+
Test asserts invariant: fittable ⊆ servable.
|
|
1089
|
+
Lists cannot drift apart silently again.
|
|
1090
|
+
Serving stays stricter in general.
|
|
1091
|
+
`image/svg+xml` refused by both.
|
|
1092
|
+
Unknown session + unknown hash both return 404.
|
|
1093
|
+
Route cannot probe which session ids exist.
|
|
1094
|
+
Responses carry `nosniff` + `default-src 'none'; sandbox`.
|
|
1095
|
+
Cache-Control: `no-store, private`.
|
|
1096
|
+
Endpoint authenticated.
|
|
1097
|
+
Serves private user screenshots.
|
|
1098
|
+
Year-long `max-age` persisted bytes to browser/proxy disk caches.
|
|
1099
|
+
Bytes outlived session + credential that unlocked them (CWE-524).
|
|
1100
|
+
Content-addressing makes bytes immutable.
|
|
1101
|
+
Does NOT make them safe to persist.
|
|
1102
|
+
Cost: zoom re-fetches each time.
|
|
1103
|
+
Thumbnail unaffected.
|
|
1104
|
+
Fitted derivative already inline.
|
|
1105
|
+
|
|
1106
|
+
**Animated GIF.** Exempt from fitting (D11). Resize would flatten animation. Detected by counting Image Descriptor `0x2C` blocks, short-circuit at 2. Stays subject to the existing ceiling.
|
|
1107
|
+
|
|
1108
|
+
See change: fit-attachments-for-display.
|
|
1109
|
+
|
|
605
1110
|
### Edit Tool Diff Rendering (desktop vs mobile)
|
|
606
1111
|
`ToolCallStep` gates renderer mounting with `{expanded && <Renderer />}` — Edit cards default to collapsed, so no diff tokenization runs until the user expands. On expand, `EditToolRenderer` branches on `useMobile()` (the project-wide `width < 768px OR height < 600px` predicate):
|
|
607
1112
|
- **Desktop** (`!isMobile`): renders `<RichDiff oldText newText filePath maxHeight="20rem" />` — syntax-highlighted via `@git-diff-view/react` + lowlight, matching `FileDiffView` quality; height capped for chat scroll UX.
|
|
@@ -621,29 +1126,64 @@ The shared `<RichDiff>` component is also consumed by `DiffPanel` (Path A / chan
|
|
|
621
1126
|
- `index.ts`: `flow:abort` and `flow:toggle-autonomous` event listeners added
|
|
622
1127
|
- `flow-tui.ts`: `autonomousMode` included in `flow:flow-started` event data
|
|
623
1128
|
|
|
624
|
-
### `/reload` Flow (
|
|
625
|
-
Reload from the dashboard
|
|
1129
|
+
### `/reload` Flow (server-side dispatch ladder)
|
|
1130
|
+
Reload from the dashboard routes through a single server entry point: `dispatchReload(sessionId)` in `packages/server/src/rpc-keeper/dispatch-reload.ts`. Dispatch is a four-step ladder — busy check, kill-and-respawn, bridge forward, terminal error — selected by how the session was spawned. Falls through until one path succeeds.
|
|
626
1131
|
|
|
627
1132
|
```mermaid
|
|
628
1133
|
flowchart TD
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
1134
|
+
T[Six triggers]
|
|
1135
|
+
E[dispatchReload sessionId]
|
|
1136
|
+
B{isReloadBusy?}
|
|
1137
|
+
REF[command_feedback error refuse]
|
|
1138
|
+
P{headlessPidRegistry getPid defined?}
|
|
1139
|
+
S[handleHeadlessReload SIGTERM + spawnPiSession continue]
|
|
1140
|
+
C{piGateway isSessionConnected?}
|
|
1141
|
+
F[piGateway.sendToSession send_prompt text /reload]
|
|
1142
|
+
DONE[command_feedback completed keyed /reload]
|
|
1143
|
+
ERR[command_feedback error no path]
|
|
1144
|
+
|
|
1145
|
+
T --> E
|
|
1146
|
+
E --> B
|
|
1147
|
+
B -->|compacting OR streaming + bridge| REF
|
|
1148
|
+
B -->|not busy| P
|
|
1149
|
+
P -->|PID defined| S
|
|
1150
|
+
P -->|no PID| C
|
|
1151
|
+
C -->|connected| F
|
|
1152
|
+
C -->|not connected| ERR
|
|
1153
|
+
F -->|delivered| DONE
|
|
1154
|
+
F -->|send failed| ERR
|
|
1155
|
+
S --> DONE
|
|
644
1156
|
```
|
|
645
1157
|
|
|
646
|
-
**
|
|
1158
|
+
**Triggers** — six sources route through `dispatchReload`; pi-core update is the one exception:
|
|
1159
|
+
1. Reload button / `/reload` in composer → browser `send_prompt` → `packages/server/src/browser-handlers/session-action-handler.ts` `handleSendPrompt`.
|
|
1160
|
+
2. `scripts/reload-all.sh` → same browser path.
|
|
1161
|
+
3. pi retry-policy settings save → `server.ts` `reloadConnectedSessions`.
|
|
1162
|
+
4. Package install/remove → `packageManagerWrapper.setReloadSessions`.
|
|
1163
|
+
5. pi-core update complete → `piCoreUpdater.onAllComplete` → `respawnForRuntimeSwap` (NOT `dispatchReload`).
|
|
1164
|
+
6. `POST /api/resources/reload` → `routes/resource-activation-routes.ts`.
|
|
1165
|
+
|
|
1166
|
+
**Predicate gate** — `isBareReloadCommand` in `browser-handlers/session-action-helpers.ts`. `text === "/reload"` exactly, zero images, says nothing about session shape. Replaced old `shouldInterceptReload`, which also required a headless PID and thereby made kill-and-respawn the default.
|
|
1167
|
+
|
|
1168
|
+
**Why no in-process path.** Earlier revision wrote `/__dashboard_reload` to the session's RPC keeper, on the claim that pi RPC mode runs the line through `session.prompt()` WITH command handling. Measured in the docker harness with `keeperLog.capturePiOutput = true`: it does not. pi's RPC `{type:"prompt"}` performs NO slash-command dispatch. Dispatched `/__dashboard_reload` arrived at the model as an ordinary user prompt and produced a full agent turn (`agent_start` → user message → assistant reply → `agent_end`). Control: pi built-in `/help` written to the same socket behaved identically — so not the `__` prefix, not our registration. Consequence: kill-and-respawn is the ONLY mechanism that reloads a headless session. Note: `rpc-keeper/dispatch-router.ts` `dispatch_extension_command` uses the same `writeRpc` + `{type:"prompt"}` mechanism and therefore has the same defect — separate live bug, own change.
|
|
1169
|
+
|
|
1170
|
+
**Ladder step 1 — busy check.** `isReloadBusy` runs FIRST. Refuse if `session.compacting === true`. Refuse if `status === "streaming"` AND `piGateway.isSessionConnected(sessionId)`. Stale `streaming` on a bridge-dead session does NOT refuse — pinned there forever, and exactly what respawn rescues.
|
|
1171
|
+
|
|
1172
|
+
**Ladder step 2 — kill-and-respawn.** `headlessPidRegistry.getPid(sessionId)` defined → `handleHeadlessReload` (SIGTERM + `spawnPiSession` `mode:"continue"`), streaming guard suppressed. Registered PID wins over a live bridge: the bridge path is a no-op for a dashboard-spawned session whose `globalThis[RELOAD_KEY]` was never captured in a TUI.
|
|
1173
|
+
|
|
1174
|
+
**Ladder step 3 — bridge forward.** No PID, `isSessionConnected` true → `piGateway.sendToSession(sid, {type:"send_prompt", text:"/reload"})`. Gated on the RETURN VALUE, not the probe: the socket can close between the two.
|
|
1175
|
+
|
|
1176
|
+
**Ladder step 4 — terminal error.** Neither → terminal `command_feedback {status:"error"}`. A session with NO registered PID is NEVER respawned: would start a second pi against a terminal-hosted session's file.
|
|
1177
|
+
|
|
1178
|
+
**Feedback contract** — exactly one terminal `command_feedback` per reload, `command` field always `/reload`.
|
|
1179
|
+
|
|
1180
|
+
**Bridge side** — `packages/extension/src/command-handler.ts` no longer emits an unconditional `completed`. `BridgeCommandOptions.reload` returns a `ReloadOutcome` (`{ok:true} | {ok:false, reason}`). `bridge.ts` wraps the captured `globalThis[RELOAD_KEY]` call in try/catch, including a SYNCHRONOUS throw: the captured fn is single-use per process because the first `ctx.reload()` invalidates the runner, so a second call throws out of `assertActive()` where a `.catch()` cannot reach it.
|
|
1181
|
+
|
|
1182
|
+
**Compaction signal** — `DashboardSession.compacting` (new, `packages/shared/src/types.ts`). Derived in `packages/server/src/session/event-status-extraction.ts` from bridge-forwarded `session_before_compact` (true) and `session_compact` (false). Cleared in `memory-session-manager.unregister`; never carried onto a re-registration.
|
|
1183
|
+
|
|
1184
|
+
**Fan-out target set** — `reloadTargetSessionIds(connectedIds, registry)` = `piGateway.getConnectedSessionIds()` UNION `headlessPidRegistry.listSessions()`. The old connected-only fan-out could never reach a headless session whose bridge WS had died.
|
|
1185
|
+
|
|
1186
|
+
**pi-core update is a BINARY swap** — `ctx.reload()` cannot replace pi-core, so `respawnForRuntimeSwap` respawns unconditionally (including connected + streaming), and reports `error` for a session with no `sessionFile` or no registered PID. See change: fix-out-of-band-reload.
|
|
647
1187
|
|
|
648
1188
|
### Server Restart (single-orchestrator path)
|
|
649
1189
|
|
|
@@ -698,6 +1238,74 @@ Adoption ratchet: `packages/client/src/__tests__/state-feedback-adoption.test.ts
|
|
|
698
1238
|
|
|
699
1239
|
Reference: `--status-*` tokens defined once in `index.css` (owned by change improve-dashboard-attention-routing). `statusPresentation` references, does not redefine.
|
|
700
1240
|
|
|
1241
|
+
### Composer grammar check
|
|
1242
|
+
|
|
1243
|
+
Opt-in grammar + spell + writing-improvement check for composer draft. LLM-only backend. Gate: `~/.pi/dashboard/config.json` `plugins.grammar.enabled` (default `false`). Change: `add-composer-grammar-check`, `grammar-llm-only-with-explore`.
|
|
1244
|
+
|
|
1245
|
+
**Configuration.** Owned by grammar plugin. Config namespace `plugins.grammar.*` in `packages/shared/src/config.ts`. `parseGrammarConfig` validates + clamps; drops any legacy persisted keys (`backend`, `languagetool.url`). Values:
|
|
1246
|
+
- `enabled` (boolean, default `false`)
|
|
1247
|
+
- `llm.provider` (string) — model provider (Anthropic/Google)
|
|
1248
|
+
- `llm.model` (string) — model ID. See `docs/grammar-model-guidance.md` for recommendations
|
|
1249
|
+
- `autoCheck` (boolean, default `true`) — debounced auto-check on keystroke
|
|
1250
|
+
- `debounceMs` (integer, default 1200, clamp 300–10000)
|
|
1251
|
+
- `minChars` (integer, default 12, clamp 1–500) — skip check below this length
|
|
1252
|
+
- `maxChars` (integer, default 4000, clamp 100–20000) — truncate draft if longer
|
|
1253
|
+
- `language` (`"auto"`, default `"auto"`)
|
|
1254
|
+
|
|
1255
|
+
**Legacy config coercion.** Pre-LLM configs persisted `backend="languagetool"` + `languagetool.url`. Server-side `migrateLegacyConfig()` prunes on first request (no-throw, silent). Schema `additionalProperties:false` rejects unknown keys on write.
|
|
1256
|
+
|
|
1257
|
+
**Wire contract.** `packages/shared/src/grammar-types.ts`:
|
|
1258
|
+
- `GrammarSuggestion` — `{ offset, length, original, replacement, kind, message }`. `original` source-of-truth for apply.
|
|
1259
|
+
- `GrammarCheckResult` — `{ correctedText, suggestions[], summary, language, truncated }`. No `backend` field (LLM-only).
|
|
1260
|
+
- `GrammarHealth` — config probe response. No `languagetool` block.
|
|
1261
|
+
- `GrammarErrorCode` — error discriminant. `GrammarBackendKind` = `"llm"` (1-member enum).
|
|
1262
|
+
|
|
1263
|
+
**Server.** Grammar plugin: `packages/grammar-plugin/src/server/`:
|
|
1264
|
+
- `grammar-service.ts` `checkGrammar()` — gate `enabled → grammar_disabled`; empty text → `empty_text`; clip to `maxChars` → `truncated` flag; never throws.
|
|
1265
|
+
- `getGrammarHealth()` — config + LLM model availability probe.
|
|
1266
|
+
- `backends/llm.ts` — resolve provider creds via `InternalRegistry.getModelRegistry()` + `getStreamSimpleFn()`. Model dispatch via pi-ai `streamSimple`. Temperature 0. Offsets relocated by `original` token, never trusted. Prompt hardens against injection: `<text>…</text>` wrapper, "proofread only" directive. System prompt asks for corrections + writing improvement. Output cap 8192 tokens, timeout 45 s.
|
|
1267
|
+
- `abort.ts` `withTimeoutSignal` — abort in-flight requests.
|
|
1268
|
+
- Routes: `packages/grammar-plugin/src/server/routes/grammar-routes.ts`, registered in dashboard server:
|
|
1269
|
+
- `POST /api/grammar/check { text, language? }` — auth-gated (`networkGuard`). Route opt-out of Fastify `connectionTimeout` (relaxes for long-running models).
|
|
1270
|
+
- `GET /api/grammar/health` — auth-gated.
|
|
1271
|
+
- Config re-read per request → model switch needs no restart.
|
|
1272
|
+
- Error → HTTP: `grammar_disabled` 409, `empty_text` 400, `backend_unconfigured` 400, `backend_unreachable` / `backend_bad_response` 502, `backend_timeout` 504.
|
|
1273
|
+
- One structured `[grammar]` log line per call. NO draft text logged.
|
|
1274
|
+
|
|
1275
|
+
**Client.** `packages/client/src/hooks/useGrammarCheck.ts`:
|
|
1276
|
+
- Fetch `/api/grammar/health` once for config.
|
|
1277
|
+
- Manual `checkNow` + debounced auto-check.
|
|
1278
|
+
- Abort in-flight on new keystroke / session switch.
|
|
1279
|
+
- Skip auto-check while streaming, below `minChars`, or on `/` · `!` · `!!` prefixed drafts.
|
|
1280
|
+
- Offset-safe `applyAll()` / `accept()` / `dismiss()`.
|
|
1281
|
+
|
|
1282
|
+
**UI.** Grammar panel mounts in two places:
|
|
1283
|
+
- Composer draft (main chat): `packages/client/src/components/chat/GrammarPanel.tsx` renders above composer (sibling to `QueuePanel` in `App.tsx`).
|
|
1284
|
+
- Explore/New Change dialogs: `ComposerPanelSlot` in draft editors (explorers, change filer).
|
|
1285
|
+
- Diff-highlighted corrections + summary. Per-suggestion Accept/Dismiss + Apply-all button.
|
|
1286
|
+
- `CommandInput.tsx` Check toolbar button + ⌘G shortcut (`onGrammarCheck` prop). Same panel renders both surfaces.
|
|
1287
|
+
|
|
1288
|
+
**Privacy.** LLM backend: draft leaves machine to provider. Provider credentials resolved server-side, never reach browser.
|
|
1289
|
+
|
|
1290
|
+
**Model recommendations.** See `docs/grammar-model-guidance.md`: latency/quality/cost tradeoffs, recommended defaults (claude-haiku-4-5), weak-model warnings.
|
|
1291
|
+
|
|
1292
|
+
**Data flow:**
|
|
1293
|
+
|
|
1294
|
+
```mermaid
|
|
1295
|
+
flowchart LR
|
|
1296
|
+
A["Composer draft"] --> B["debounce | ⌘G / Check button"]
|
|
1297
|
+
B --> C["useGrammarCheck"]
|
|
1298
|
+
C --> D["POST /api/grammar/check"]
|
|
1299
|
+
D --> E["grammar-service"]
|
|
1300
|
+
E --> F["LLM backend"]
|
|
1301
|
+
F --> G["Provider API"]
|
|
1302
|
+
G --> H["GrammarCheckResult"]
|
|
1303
|
+
H --> I["GrammarPanel"]
|
|
1304
|
+
I --> J{"User action"}
|
|
1305
|
+
J -->|Apply-all| K["onDraftChange updates draft"]
|
|
1306
|
+
J -->|Accept/Dismiss| K
|
|
1307
|
+
```
|
|
1308
|
+
|
|
701
1309
|
### Auto-Resume on Prompt
|
|
702
1310
|
When a user sends a prompt to an ended session, the server automatically resumes it:
|
|
703
1311
|
1. Server detects `send_prompt` for a session with `status === "ended"` and a valid `sessionFile`
|
|
@@ -746,6 +1354,104 @@ Plugin content-view claims (e.g. flows-plugin) remain predicate-driven, out of s
|
|
|
746
1354
|
6. Thinking level changes (via pi keybinding) are detected when `model_select` events fire, on reconnect, and immediately after `set_thinking_level` commands
|
|
747
1355
|
7. Browser can send `set_thinking_level` to change thinking level remotely
|
|
748
1356
|
|
|
1357
|
+
### Model selector pairing rule
|
|
1358
|
+
|
|
1359
|
+
Two classes of model selector exist:
|
|
1360
|
+
|
|
1361
|
+
- RUN-CONFIGURING: picks the model a session/run EXECUTES with. MUST pair a thinking-level control.
|
|
1362
|
+
- REFERENCE-LISTING: names a model for an allow-list, ordering, or alias mapping. MUST NOT pair one.
|
|
1363
|
+
|
|
1364
|
+
```mermaid
|
|
1365
|
+
flowchart TD
|
|
1366
|
+
A[Model selector] --> B{RUN-CONFIGURING?}
|
|
1367
|
+
B -->|yes| C[MUST pair thinking-level control]
|
|
1368
|
+
B -->|no| D[REFERENCE-LISTING: MUST NOT pair]
|
|
1369
|
+
```
|
|
1370
|
+
|
|
1371
|
+
Run-configuring surfaces, all five now paired:
|
|
1372
|
+
|
|
1373
|
+
- Chat composer model row — `packages/client/src/components/chat/CommandInput.tsx`
|
|
1374
|
+
- Settings → Sessions → Default Model — `packages/client/src/components/settings/SettingsPanel.tsx`, persists `config.defaultThinkingLevel`
|
|
1375
|
+
- OpenSpec run-config row — `packages/client/src/components/openspec/useOpenSpecRunConfigRow.tsx`
|
|
1376
|
+
- Roles → assign model to `@role` — `packages/roles-plugin/src/RolesSettingsSection.tsx`
|
|
1377
|
+
- Automation → Create, direct-model branch — `packages/automation-plugin/src/client/CreateAutomationDialog.tsx`
|
|
1378
|
+
|
|
1379
|
+
Reference-listing surfaces, deliberately excluded: Model Proxy preferred-models list and Model Proxy alias→model table, both in `packages/client/src/components/settings/ModelProxySection.tsx`.
|
|
1380
|
+
|
|
1381
|
+
Encoding. Roles + automation carry level as `:<level>` suffix on the EXISTING model ref string: `"<provider>/<id>:<level>"`. No second field. No parallel level map. pi parses it with `splitThinkingSuffix` (`packages/extension/src/provider-register.ts`). Reason: second field drifts from refs written by pi's own `/roles` command.
|
|
1382
|
+
|
|
1383
|
+
Canonical levels: `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`. `off` = no override → writes bare ref. Split takes the LAST `:` only when the tail is a canonical level, so provider ids containing `:` (e.g. `openrouter/vendor:free`) survive.
|
|
1384
|
+
|
|
1385
|
+
No server change. `resolveModel()` (automation-plugin `server/model-resolver.ts`) passes suffixed ref through. `sessionFlagsToArgv()` (`packages/shared/src/platform/spawn-mechanism.ts`) emits `["--model", ref]` verbatim. Nothing in that chain inspects or strips the suffix. Both guarded by tests.
|
|
1386
|
+
|
|
1387
|
+
`@role` automation branch renders NO level control — role's own ref owns the level. One owner per value.
|
|
1388
|
+
|
|
1389
|
+
UI shape named `ModelLevelPair`: model left, level right, one bordered container, persistent `MODEL`/`THINKING` captions, saved ref echoed in mono below. Full contract: `openspec/changes/add-default-thinking-level/mockups/ui-plan.md`.
|
|
1390
|
+
|
|
1391
|
+
See change: add-default-thinking-level.
|
|
1392
|
+
|
|
1393
|
+
### Auto Session Naming (change: fix-auto-naming-reasoning-model)
|
|
1394
|
+
|
|
1395
|
+
Bridge-side. `packages/extension/src/auto-session-namer.ts`. After each terminal turn (`agent_end`), eligible session asks naming model for short topic title. Gate: `autoNameSessions` preference (`preferences_update` message).
|
|
1396
|
+
|
|
1397
|
+
**Naming model resolution.**
|
|
1398
|
+
|
|
1399
|
+
- `@naming` first, fallback `@fast`. `resolveNamingModel()` in `packages/extension/src/role-manager.ts`.
|
|
1400
|
+
- `naming` in `DEFAULT_ROLE_NAMES`.
|
|
1401
|
+
- Unassigned `naming` ⇒ `@fast` ⇒ identical resolution to pre-role behavior.
|
|
1402
|
+
- Neither configured ⇒ permanent stop + one `auto_name_error` naming both slots.
|
|
1403
|
+
- Configured in Settings → Roles (Roles panel, `/settings/plugins/roles`), NOT inline on sessions page. Auto-name toggle carries pointer `auto-name-model-pointer`.
|
|
1404
|
+
|
|
1405
|
+
**Adaptive output cap.**
|
|
1406
|
+
|
|
1407
|
+
- `TITLE_MAX_TOKENS_BASE = 1024` on first attempt.
|
|
1408
|
+
- `TITLE_MAX_TOKENS_ESCALATED = 2048` once session records a `starved` verdict.
|
|
1409
|
+
- Cap = ceiling, not charge. Non-reasoning model bills ~2 output tokens.
|
|
1410
|
+
- Measured on `deepseek/deepseek-v4-flash` + summarizer prompt.
|
|
1411
|
+
- Caps 16/64/256/512: `finish_reason=length`, empty content.
|
|
1412
|
+
- Cap 1024: returned `NULL`. 24 reasoning tokens.
|
|
1413
|
+
- Cap 2048: returned title. 724 reasoning tokens.
|
|
1414
|
+
- Reasoning spend nondeterministic. No cap guarantees a title.
|
|
1415
|
+
|
|
1416
|
+
**Starvation failure mode.**
|
|
1417
|
+
|
|
1418
|
+
- Reasoning model spends whole cap on reasoning tokens.
|
|
1419
|
+
- Stream ends truncated. `done` reason `"length"`. No text.
|
|
1420
|
+
- Old bug: empty text mapped onto `wait`.
|
|
1421
|
+
- `wait` = same verdict as legitimate `NULL` sentinel. Non-terminal.
|
|
1422
|
+
- Result: naming retried forever, applied nothing, emitted nothing.
|
|
1423
|
+
- Measured: 0 of 3380 sessions `nameSource: "auto"`.
|
|
1424
|
+
- Measured: 0 `auto_name_error` lines in 6.8 MB `server.log`.
|
|
1425
|
+
- Fix: parse keys on stream stop reason BEFORE text.
|
|
1426
|
+
- `length` / `toolUse` ⇒ `starved`. Text NEVER applied.
|
|
1427
|
+
- `stop` + empty ⇒ `starved`.
|
|
1428
|
+
- `NULL` / over-40-chars / over-6-words ⇒ `waiting`.
|
|
1429
|
+
|
|
1430
|
+
**Attempt budget.**
|
|
1431
|
+
|
|
1432
|
+
- 3 attempts per session (`ATTEMPT_BUDGET`), shared by `starved` + `waiting`.
|
|
1433
|
+
- Exhaustion ⇒ permanent stop + exactly one `auto_name_error`. Remedy matches dominant cause; tie ⇒ `starved`.
|
|
1434
|
+
- Transient errors + aborts spend no budget.
|
|
1435
|
+
|
|
1436
|
+
**Persistence.**
|
|
1437
|
+
|
|
1438
|
+
- Stop persists in session `.meta.json` (`autoNamerState`), survives process restart.
|
|
1439
|
+
- Clears when RESOLVED naming reference changes or blocking cause (credentials/registry) resolves.
|
|
1440
|
+
- Clearing resets budget AND re-arms error.
|
|
1441
|
+
|
|
1442
|
+
**Diagnostics.**
|
|
1443
|
+
|
|
1444
|
+
- Every attempt reports exactly one deduplicated outcome.
|
|
1445
|
+
- Server retains last outcome per session — `packages/server/src/auto-name-outcome-store.ts`.
|
|
1446
|
+
- Bound 500. ABSOLUTE.
|
|
1447
|
+
- Eviction prefers non-`stopped` entries.
|
|
1448
|
+
- `stopped` entries alone at the bound: OLDEST `stopped` evicted.
|
|
1449
|
+
- Protection is an ORDER, never indefinite retention.
|
|
1450
|
+
- Readable at `GET /api/auto-name-outcomes`.
|
|
1451
|
+
- Rendered in Settings → Diagnostics. `starved` shown distinctly from `waiting`.
|
|
1452
|
+
|
|
1453
|
+
See change: fix-auto-naming-reasoning-model.
|
|
1454
|
+
|
|
749
1455
|
### Context Usage Tracking
|
|
750
1456
|
1. On each `turn_end`, the bridge calls pi's `ctx.getContextUsage()` API to get real-time context usage (tokens used + actual context window from the provider)
|
|
751
1457
|
2. Bridge enriches the `turn_end` event with this `contextUsage` data before forwarding to the server
|
|
@@ -783,10 +1489,16 @@ See change: add-session-uncommitted-indicator-and-commit.
|
|
|
783
1489
|
Dashboard derives new worktree path as `<repoRoot>/.worktrees/<slugifyBranch(branch)>` when `POST /api/git/worktree` body omits `path`. `addWorktree` calls `ensureWorktreeExcludeLine(cwd)` first — idempotently appends `.worktrees/` to `<repoRoot>/.git/info/exclude` so parent repo ignores nested checkouts (untouched if line already present). Bridge `detectWorktree` populates `GitInfo.gitWorktree.mainPath`; `resolveSessionGroupPath` collapses worktree sessions under parent repo's pinned-directory group. See change: add-worktree-spawn-dialog.
|
|
784
1490
|
|
|
785
1491
|
### Git worktree lifecycle (push / PR / merge / close)
|
|
786
|
-
Dashboard exposes
|
|
787
|
-
`/remove`
|
|
1492
|
+
Dashboard exposes 7 endpoints under `/api/git/worktree/*`: `remove`, `remove-batch`, `prune`, `merge`, `push`, `pr`, `diff-stat`. Localhost-gated. Each forwards stable `{code, stderr}` errors (`active_sessions`, `dirty_worktree`, `branch_not_merged`, `dirty_main`, `merge_conflict`, `base_not_found`, `no_remote`, `auth_failed`, `non_fast_forward`, `gh_not_found`, `gh_not_authed`, `pr_exists`, `pushed_but_pr_failed`, `cwd_invalid`, `is_main_worktree`) produced by pure stderr→code mappers in `git-worktree-lifecycle.ts`.
|
|
1493
|
+
`/remove-batch` body `{ items: Array<{cwd, force?, deleteBranch?}> }`. Cap 50 items enforced before any git runs — `batch_too_large` 400; non-array `items` → `items_invalid` 400. Returns `{ results }` in INPUT ORDER, one per item. Never aborts on first failure. Item result: `{ cwd, ok, code, sessionIds?, branchDeleted?, branchDeleteCode? }`. `code` widens `RemoveCode` with `active_sessions | cwd_invalid | is_main_worktree`. Sits behind `networkGuard` + `validateCwd`.
|
|
1494
|
+
`/prune` wraps `git worktree prune` in resolved main worktree. Returns `{ pruned }`. REPO-GLOBAL — clears every stale registration, not one row. Sits behind `networkGuard` + `validateCwd`.
|
|
1495
|
+
`/remove` pre-flight calls `activeSessionsUnder(path, sessions)`: non-empty → returns `active_sessions` + `sessionIds`; client `CloseWorktreeDialog` shuts those sessions down then retries with `--force`. `remove` gains `deleteBranch?: boolean`. Runs `git branch -d <branch>` (NEVER `-D`) in main worktree after successful removal. Branch name captured BEFORE removal (unrecoverable after). Success payload widens to `{ removed: true, branchDeleted: boolean, branchDeleteCode? }`. Refused branch delete still HTTP 200 — removal succeeded. `remove` also rejects main worktree removal with `is_main_worktree` 400; previously mapped to `git_failed` → 500. `mergeWorktree` runs `git merge --no-ff` into `resolveDefaultBase(cwd, head)` (origin/HEAD → `develop` → `main` → `master`). `gh` resolved via shared tool registry. Client probes `gh` via `/api/tools/gh` at `WorktreeActionsMenu` mount (module-level cache); hides Open PR when unavailable; View PR #N link survives without gh because it opens an existing URL.
|
|
788
1496
|
Cwd-loss detection probes at three sites feed `DashboardSession.cwdMissing`: (1) bridge VCS 30 s tick (`sendCwdMissingIfChanged`, debounced via `BridgeContext.lastCwdMissing`) emits new `cwd_missing` extension message; (2) server `session-scanner.ts` stamps ended sessions at boot; (3) `/api/git/worktree/remove` optimistic broadcast for every session under removed path. New `cwdMissing?: boolean` on `DashboardSession` + `cwd_missing` protocol message both additive — older bridges harmless `undefined`. `spawn-preflight.ts` emits BOTH legacy `DIR_MISSING` reason and new `cwd_missing` code during one-release overlap.
|
|
789
1497
|
See change: add-worktree-lifecycle-actions.
|
|
1498
|
+
`BranchDeleteCode = "deleted" | "unmerged" | "no_branch" | "branch_gone" | "delete_failed"` DISJOINT from `RemoveCode` (asserted by a test). Generic failure `delete_failed`, not `git_failed`. Never reuses `branch_not_merged` — that `RemoveCode` makes `CloseWorktreeDialog` auto-tick `--force` and retry.
|
|
1499
|
+
`GET /api/git/worktrees` entries gain `exists: boolean` (one `statSync` per entry). Consumers MUST treat `undefined` as present — falsy test marks every row missing when new client pairs with older server.
|
|
1500
|
+
Manage-worktrees surface removes worktrees with NO entry in session map. `active_sessions` guard does not fire. Menu gate on folder being a git repository, never on live sessions.
|
|
1501
|
+
See change: manage-worktrees-filter-cleanup.
|
|
790
1502
|
|
|
791
1503
|
### Child Process Scanning
|
|
792
1504
|
1. Bridge scans child processes every 10s via `process-scanner.ts` (two-phase: capture new PGIDs during active bash calls, then check tracked PGIDs)
|
|
@@ -797,6 +1509,56 @@ See change: add-worktree-lifecycle-actions.
|
|
|
797
1509
|
6. New browser connections receive current processes via the initial `session_added` message
|
|
798
1510
|
7. Session cards display processes with elapsed time and a kill button (sends SIGTERM to process group)
|
|
799
1511
|
|
|
1512
|
+
### Folder → workspace add flow (redesign-folder-workspace-add-flow)
|
|
1513
|
+
|
|
1514
|
+
**DirectoryHomeView eligibility guard removed.** Any groupable cwd renders home page (session list + spawn prompt). Gone: props `pinnedDirectories`, `workspaceFolders`, `pinnedDirectoriesLoaded`, `workspacesLoaded`, `onPinDirectory`; testids `directory-home-loading`, `directory-home-not-pinned`; i18n keys `directoryHome.notPinnedTitle`, `notPinnedBody`, `pinCta`. App drops `workspaceFolderSet` memo + `pinnedDirsLoaded`, `workspacesLoaded` state + their `useMessageHandler` setters (handlers `pinned_dirs_updated`, `workspaces_updated` no longer flip loaded flags).
|
|
1515
|
+
|
|
1516
|
+
**Pin now implicit visibility primitive.** Adding folder always pins (`pin_directory`). `AddToWorkspaceMenu` + add dialog offer NO "Pin to dashboard". Safe: `visibleTopPinned`/`visibleTopUnpinned` already filter workspace-owned cwd out of top tier (renders once); redundant pin = fallback so removing from workspace leaves folder visible at root.
|
|
1517
|
+
|
|
1518
|
+
**Add-to-workspace affordance.** LABELLED PILL: `mdiViewGridPlus` glyph + visible text label "Workspace", lives inside folder actions menu WORKSPACE group. Session-card copy removed. `aria-haspopup="menu"` + `aria-expanded` + `aria-label`/`title` "Add to workspace…". Popover state keyed by SCOPE (`folder:<cwd>`). Old `+ws` text token removed. `renderAddToWorkspaceButton(cwd,label,scopeKey,testId,wrapperClass)` builds pill, passes as `headerAction?: React.ReactNode` to `renderGroup` (5th param); `renderGroup` routes it into the menu instead of the cluster. See change: add-folder-actions-menu.
|
|
1519
|
+
|
|
1520
|
+
**Folder-header cluster never wraps.** `folder-header-cluster-<cwd>` = `flex-none whitespace-nowrap`; name region `folder-header-name-<cwd>` = `min-w-0` absorbs squeeze; parent path `folder-header-parent-<cwd>` = `flex-[0_1_auto] min-w-0` collapses first; leaf `folder-header-leaf-<cwd>` = `min-w-[6ch]` floor.
|
|
1521
|
+
|
|
1522
|
+
**PathPicker opt-in multi-select.** `selection?: {selected:Set<string>; onToggle}` (absent = single-select, unchanged for existing callers e.g. PinDirectoryDialog). Multi-select: row body navigates (never `onSelect`), per-row checkbox (`path-picker-check-<path>`, `role=checkbox`, `stopPropagation`) toggles basket, trailing chevron (`path-picker-open-<path>`) descends; Space toggles highlighted row, Enter descends. Emoji → `@mdi/js` (`mdiArrowUp`, `mdiFolder`, `mdiFolderPlusOutline`); git/pi stay text badges. Optional `sessionCounts?: Map<pathKey,number>` → session badge (`path-picker-sessions-<path>`). `userEditedRef` mount-race guard (change compact-warm-replay-stream) preserved.
|
|
1523
|
+
|
|
1524
|
+
**AddFoldersDialog** (`packages/client/src/components/workspace/AddFoldersDialog.tsx`): multi-select picker + removable-pill basket (persists across navigation) + single-select workspace destination (radio, default None, empty state "None — no workspaces yet", eager `+ New workspace…` that becomes selected once `workspaces_updated` echo lands) + count-bearing commit (`add-folders-commit`). Commit sends `pin_directory` for every path FIRST, then `add_folder_to_workspace` per path when destination set (pins first → folder never momentarily invisible). Reuses existing per-path messages, no new protocol. Wired to both entry points: App sidebar `+ Add Folder` → dest None; `SessionList` workspace-scoped `+ Add Folder` → that workspace preselected. `PinDirectoryDialog` retained ONLY for packages move-to-local single-select picker (`UnifiedPackagesSection`).
|
|
1525
|
+
|
|
1526
|
+
See change: redesign-folder-workspace-add-flow.
|
|
1527
|
+
|
|
1528
|
+
### Folder actions menu (add-folder-actions-menu)
|
|
1529
|
+
|
|
1530
|
+
**Cluster = one control.** `folder-header-cluster-<cwd>` holds EXACTLY ONE control: `FolderActionsMenu` trigger. Component `packages/client/src/components/folder/FolderActionsMenu.tsx`. Exports `FolderActionsMenu`, `FolderMenuItem`, `FOLDER_MENU_GROUPS`, `FolderMenuGroup`.
|
|
1531
|
+
|
|
1532
|
+
**Trigger.** Glyph `mdiFolderCogOutline`. `mdiDotsHorizontal` REJECTED — `WorktreeActionsMenu` renders it on worktree session cards inside the folder body; two identical triggers, different scopes, one card. Testid `folder-actions-menu-<cwd>`. Carries `aria-haspopup="menu"` + `aria-expanded`. `onClick` calls `stopPropagation` — header row navigates to the directory home page, so opening must not navigate nor toggle collapse.
|
|
1533
|
+
|
|
1534
|
+
**Panel.** Testid `folder-actions-menu-panel-<cwd>`, `role="menu"`, `data-menu-form="sheet"|"popover"`. Items carry `role="menuitem"`, testid `folder-menu-item-<id>`. Keyboard: ArrowDown/ArrowUp rove focus over `[role=menuitem]`; Escape closes + returns focus to trigger. Outside `mousedown`/`touchstart` closes.
|
|
1535
|
+
|
|
1536
|
+
**Groups.** Host-owned fixed taxonomy, stable order: `workspace` then `directory` (`FOLDER_MENU_GROUPS`). Group heading testid `folder-menu-group-<group>`. Group renders only when it holds >=1 item. Item ids: `add-to-workspace`, `remove-from-workspace`, `pin`, `urgency-sort`, `directory-settings`. Directory-group order: pin, urgency-sort, directory-settings.
|
|
1537
|
+
|
|
1538
|
+
**Open state.** `SessionList` owns `folderMenuFor`, keyed by SCOPE `folder:<cwd>` — mirrors `addToWsMenuFor`; a cwd key would co-open a folder row and a same-cwd card.
|
|
1539
|
+
|
|
1540
|
+
**Form factor.** Mobile: `useMobile()` (compound `<768w OR <600h`, reused verbatim) → full-width sheet via `DialogPortal`, `data-menu-form="sheet"`. Desktop → `usePopoverFlip` popover, `data-menu-form="popover"`.
|
|
1541
|
+
|
|
1542
|
+
**Node escape hatch.** `FolderMenuItem.node`: item that carries its own popover + testid renders its own node. Only user today = add-to-workspace, so `renderAddToWorkspaceButton(cwd,label,scopeKey,testId,wrapperClass,asMenuItem)` keeps `add-to-workspace-btn-<cwd>` + `AddToWorkspaceMenu` popover verbatim; `asMenuItem` adds `role="menuitem"`.
|
|
1543
|
+
|
|
1544
|
+
**Placement gating preserved, not widened.** add-to-workspace only on top-level rows gated `onCreateWorkspace || workspaces.length`; remove-from-workspace only on workspace-owned rows; pin only outside a workspace container.
|
|
1545
|
+
|
|
1546
|
+
**Pinned indicator.** Inert indicator, testid `folder-pinned-indicator-<cwd>`, `aria-hidden="true"`, `mdiPin`, NOT a button, no tabindex. Lives in name region, not cluster — keeps cluster at exactly one control. Pin/unpin action lives in the menu.
|
|
1547
|
+
|
|
1548
|
+
**Open-home button deleted.** `mdiOpenInNew` GONE. Testid `folder-open-home-<cwd>` GONE. Header row `folder-home-row-<cwd>` = only open affordance; leaf `folder-header-leaf-<cwd>` gains `group-hover:underline`, row gains `group`.
|
|
1549
|
+
|
|
1550
|
+
**SessionCard prop removed.** `renderAddToWorkspace` REMOVED. Testid `session-card-add-to-workspace-<id>` GONE. Workspace membership is directory-scoped; per-session rendering produced N identical buttons with one effect.
|
|
1551
|
+
|
|
1552
|
+
**FolderActionBar Directory Settings.** `mdiCog` REMOVED (moved to menu item `directory-settings`). `FolderActionBar` returns `null` when it holds nothing — predicate composed from exported `shouldShowProjectInit(status,onInitializeProject)` (`ProjectInitButton.tsx`) + `shouldShowWorktreeInitButton(status)` (`WorktreeInitButton.tsx`) + `useInitRun(cwd)` + cleanup gate, so it cannot drift from what the buttons render.
|
|
1553
|
+
|
|
1554
|
+
**Prop rename.** `onOpenPiResources` → `onOpenDirectorySettings` on `SessionList`; `useContentViews` `handleOpenPiResources` → `handleOpenDirectorySettings`. Route unchanged: `buildFolderSettingsUrl(cwd)` (page segment omitted → route handler defaults `packages`). Only the name lagged; label + `aria-label` already read "Directory Settings".
|
|
1555
|
+
|
|
1556
|
+
**Accepted echoes (recorded, not fixed).** Trigger cog vs item `mdiCog`; `mdiPin` indicator vs `mdiPin` action.
|
|
1557
|
+
|
|
1558
|
+
**Known dead path, PRE-EXISTING, NOT fixed.** `AddToWorkspaceMenu` remove entry unreachable on folder rows — renders only when `currentWorkspaceId !== null`, but `visibleTopPinned`/`visibleTopUnpinned` filter workspace-owned folders out of the top tiers, the only rows carrying the affordance.
|
|
1559
|
+
|
|
1560
|
+
See change: add-folder-actions-menu.
|
|
1561
|
+
|
|
800
1562
|
### OpenSpec Polling (Server-Side)
|
|
801
1563
|
|
|
802
1564
|
**Master gate**: `DashboardConfig.openspec.enabled` (boolean, default `true`).
|
|
@@ -849,6 +1611,32 @@ Board route `/folder/:encodedCwd/openspec` (`OpenSpecBoardView`) replaces inline
|
|
|
849
1611
|
|
|
850
1612
|
Groups = columns. Always-present Ungrouped column. Proposal cards draggable (@dnd-kit): reassign group + reorder within group.
|
|
851
1613
|
|
|
1614
|
+
**Drop-target resolution.** Collision detection = `pointerWithin`, single `DndContext` prop; applies to card AND column drags. No `closestCorners` fallback: `closestCorners` empty only when zero droppables exist; fallback makes `over` non-null in the board gutter, turns intended cancel into commit into a neighbouring column. Null `over` = real cancel.
|
|
1615
|
+
|
|
1616
|
+
Drop slot resolved by ONE midpoint rule, direction- and scope-independent: `index` = count of cards in target column (excluding moved card) whose rect midpoint Y is at/above pointer Y; exact midpoint resolves after. Result = index into the without-moved list — `computeReorder`'s existing contract, so no caller `+1`.
|
|
1617
|
+
|
|
1618
|
+
Pure resolver `resolveDropSlot` in `packages/client/src/lib/openspec/openspec-board-order.ts`; `computeReorder` unchanged.
|
|
1619
|
+
|
|
1620
|
+
Resolution runs on `onDragMove`, not `onDragOver` (`onDragOver` deps are `[overId]` — does not fire on a midpoint crossing inside one droppable).
|
|
1621
|
+
|
|
1622
|
+
Resolution lives in `DropSlotProbe`, headless child of `<DndContext>`: `droppableRects` reachable only through `useDndContext()`; the parent of `<DndContext>` measures 0 rects. `pointerY = activatorEvent.clientY + delta.y`. Rects read via scroll-live `rect.top`/`rect.bottom` getters, not the frozen `rect.rect` snapshot.
|
|
1623
|
+
|
|
1624
|
+
`handleDragEnd` only commits. Re-resolves slot from end event itself, via `resolveMoveSlot` — no trust in last `onDragMove`. Rect map reaches it through `dropRectsRef`, ref `DropSlotProbe` keeps current; parent still never calls `useDndContext()` (would measure 0 rects). `dropSlot` state drives INDICATOR only, not the commit.
|
|
1625
|
+
|
|
1626
|
+
colKey-only guard insufficient: one-frame flick off append rail onto card in SAME column agrees on column, disagrees on index → colKey-only guard commits stale "last" slot. Found by CodeRabbit on PR #438.
|
|
1627
|
+
|
|
1628
|
+
Commit bails when `over` null (gutter / page margin) and when re-resolved slot's column ≠ end event's target.
|
|
1629
|
+
|
|
1630
|
+
Whole column accepts drops: body keeps its `useDroppable` (dnd-kit auto-scroll walks the OVER NODE's ancestors → scroller must stay on the drop path) plus a second `col-root:<groupKey>` droppable on the column root for header + outer padding.
|
|
1631
|
+
|
|
1632
|
+
Drag-only append rail `rail:<groupKey>`: sticky to the body's visible bottom edge, ≥44px, present in empty columns; resolves to last position. `resolveDropTarget` normalises `rail:<k>`/`col-root:<k>` back to the bare group key in ONE place — a namespaced droppable id never persists as a group key.
|
|
1633
|
+
|
|
1634
|
+
Indication: insertion marker painted into the existing flex gap via a pseudo-element on the card following the slot (no inserted flex child). Final slot has no following card → the rail's active state indicates it — driven by the resolved slot being last, not pointer-over-rail. Vertical `SortableContext` strategy neutralised with an explicit no-op (`strategy={undefined}` falls back to `rectSortingStrategy` and still displaces → decouples visual position from data order, invalidates the midpoint count).
|
|
1635
|
+
|
|
1636
|
+
Production test hooks: `data-drop-target` (column root), `data-drop-slot="<index>"` (column body), `data-rail-active` (rail).
|
|
1637
|
+
|
|
1638
|
+
No persistence/protocol change: `changeOrder[]` keeps its shape. See change: fix-openspec-board-drop-targeting.
|
|
1639
|
+
|
|
852
1640
|
Per-change order persisted in groups.json `changeOrder` keyed by groupId (`__ungrouped__` sentinel = `OPENSPEC_UNGROUPED_KEY`). Mutated via PUT `/api/openspec/groups/change-order` → `store.setChangeOrder`. Broadcast via `openspec_groups_update`. Ordering applied client-side by `orderChangesForGroup` (`openspec-board-order.ts`): persisted names first, unordered appended by `defaultChangeSort`, stale entries ignored.
|
|
853
1641
|
|
|
854
1642
|
Worktree delta derived read-only from per-cwd OpenSpec poll. `deriveWorktreeProgress` (`openspec-board-worktree.ts`) reads worktree own OpenSpecData by `session.cwd`, computes `delta` = worktree-done minus main-done. No extra server poll.
|
|
@@ -924,6 +1712,65 @@ Why a separate system? Pi's `DefaultPackageManager` only manages packages listed
|
|
|
924
1712
|
|
|
925
1713
|
Core update progress delivered via typed `pi_core_update_progress` / `pi_core_update_complete` browser-protocol messages (not `package_progress` channel). Fanned out to `UnifiedPackagesSection` + `PiUpdateBadge` via `pi-core-event` DOM event. Successful core update triggers `/reload` to connected pi sessions, same as extension updates.
|
|
926
1714
|
|
|
1715
|
+
### Project-scope disable of global resources
|
|
1716
|
+
|
|
1717
|
+
Disabling a resource for one project writes the pi-standard settings form for the resource's *origin*. Writer: `packages/server/src/pi/resource-activation-toggle.ts`. pi itself enforces the result — no dashboard-side enforcement, no spawn flags. Endpoint: `POST /api/resources/toggle`.
|
|
1718
|
+
|
|
1719
|
+
**Origin classification — by path, never by metadata.**
|
|
1720
|
+
|
|
1721
|
+
- Longest-prefix match of the resolved absolute path against candidate base dirs.
|
|
1722
|
+
- Candidates: every package root, every `.agents` base dir pi reported, `<cwd>/.pi`, `~/.pi/agent`, `~/.agents`. Module: `resource-origin.ts::collectOriginCandidates`.
|
|
1723
|
+
- NOT by `metadata.scope` / `metadata.source` / `metadata.baseDir`.
|
|
1724
|
+
- A project-scope disable of a global resource mutates exactly those fields: `scope` → `project`, `source` → `local`, `baseDir` undefined.
|
|
1725
|
+
- Metadata-keyed classifier cannot recognise, on re-enable, the resource it re-declared. Path stable across the operation; metadata not.
|
|
1726
|
+
- Longest-prefix order-independent. `cwd === $HOME` makes `<cwd>/.pi` a strict ancestor of `~/.pi/agent`; an ordered scan would misclassify.
|
|
1727
|
+
|
|
1728
|
+
**Four origins, four project-scope forms:**
|
|
1729
|
+
|
|
1730
|
+
| origin | written form |
|
|
1731
|
+
|---|---|
|
|
1732
|
+
| loose under `<cwd>/.pi` | `-<rel to .pi>` in `skills`/`extensions`/`prompts`/`themes` |
|
|
1733
|
+
| loose under an `.agents` base dir | `-<rel to that base dir>` |
|
|
1734
|
+
| package-contributed | `{ source, autoload: false, <type>: ["-<rel to package root>"] }` in `packages` |
|
|
1735
|
+
| loose under a global base dir | resource's own FILE as `~`-prefixed plain entry + anchored glob exclusion `!**/<agent dir rel to home>/<rel>` |
|
|
1736
|
+
|
|
1737
|
+
**Package delta rules.**
|
|
1738
|
+
|
|
1739
|
+
- `autoload: false` mandatory on a project delta; destructive to omit. Without it pi resolves the entry at project scope, misses the user install path, drops the package's entire contribution.
|
|
1740
|
+
- Delta form project-scope only. At global scope `dedupePackages` discards a second same-scope entry; the toggle mutates the existing entry in place.
|
|
1741
|
+
- Entries matched by normalised identity, never raw source string. npm → name without version. git → host/path unified across SSH + HTTPS. local → resolved path. (`packageIdentity` mirrors pi's `getPackageIdentity`.)
|
|
1742
|
+
- A genuinely project-owned non-delta entry keeps ordinary filter semantics; never gains `autoload: false`.
|
|
1743
|
+
|
|
1744
|
+
**Global-loose rules.**
|
|
1745
|
+
|
|
1746
|
+
- Re-declares the resource's own FILE, never a directory. Prompts, themes and flat `.md` skills have the shared root as their directory; re-declaring a root pulls every sibling into project-scope pattern evaluation.
|
|
1747
|
+
- Exclusion is an anchored glob. Absolute path machine-local; `~` pattern inert everywhere (`normalizeExactPattern` never expands `~`).
|
|
1748
|
+
- Re-enable removes the exclusion and writes nothing in its place. No `+` force-include.
|
|
1749
|
+
- Re-declared resource reports `scope: project` / `source: local`.
|
|
1750
|
+
|
|
1751
|
+
**Ownership, trust, tracking.**
|
|
1752
|
+
|
|
1753
|
+
- Plain-entry ownership recorded in `~/.pi/dashboard/resource-entry-ownership.json`, NOT in `.pi/settings.json`. Keeps the settings file pi-standard, one settings write per toggle, ownership machine-local.
|
|
1754
|
+
- Re-enable removes the plain entry only when this dashboard wrote it (`resource-entry-ownership.ts`). Un-owned entry left behind; residue inert.
|
|
1755
|
+
- `<cwd>/.pi/settings.json` git-tracked → a project-scope disable shared with collaborators + inherited by every worktree.
|
|
1756
|
+
- `POST /api/resources/trust` — persists a project-trust decision through pi's `ProjectTrustStore`. Client names an option id only (`trust` / `trust-parent` / `decline`); server re-derives that option's updates via `trustOptionsFor`. Requires an outstanding trust challenge raised by a real toggle — none → 409.
|
|
1757
|
+
- Toggle returns `trust_required` (403) when the folder needs a decision; client presents the dialog, then retries. Gate: `resource-toggle-trust.ts::resolveToggleTrust`.
|
|
1758
|
+
|
|
1759
|
+
**`defaultProjectTrust` consequence.**
|
|
1760
|
+
|
|
1761
|
+
- Toggle guarantees an explicit recorded trust decision exists after the write.
|
|
1762
|
+
- EXCEPT `defaultProjectTrust: always` — proceeds WITHOUT recording. Deliberate: folders the user merely toggled are not enrolled into a durable trust record.
|
|
1763
|
+
- CONSEQUENCE: tightening `always` → `ask`/`never` later stops previously written disables applying until the folder is trusted explicitly.
|
|
1764
|
+
- Writing `.pi/settings.json` itself makes a folder trust-requiring (`TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES` begins with `settings.json`). First toggle in a fresh folder prompts once where pi would not have.
|
|
1765
|
+
|
|
1766
|
+
**Settings-write caveat.**
|
|
1767
|
+
|
|
1768
|
+
- pi's write is NOT JSONC-preserving. `persistScopedSettings` does a whole-file `JSON.parse` → `JSON.stringify(mergedSettings, null, 2)` round trip: comments discarded, file reformatted.
|
|
1769
|
+
- A settings file containing comments fails to parse; pi retains `projectSettingsLoadError` and `saveProjectSettings` returns WITHOUT writing.
|
|
1770
|
+
- The toggle fails loudly (409) on a settings load error instead of reporting success.
|
|
1771
|
+
|
|
1772
|
+
Only newly-started sessions see a change: `PackageManager.resolve()` runs at session start. `/api/resources/reload` reloads affected sessions. See change: project-scope-disable-global-resources.
|
|
1773
|
+
|
|
927
1774
|
### Settings → Packages tab
|
|
928
1775
|
|
|
929
1776
|
- Settings tab renders single `<UnifiedPackagesSection>`.
|
|
@@ -1094,6 +1941,60 @@ Optional OAuth2 authentication protects the dashboard when accessed remotely.
|
|
|
1094
1941
|
8. WebSocket upgrade requests are also validated — external connections without valid cookie or trusted network get 401
|
|
1095
1942
|
9. Supported providers: GitHub (hardcoded endpoints), Google/Keycloak/OIDC (via OIDC discovery)
|
|
1096
1943
|
|
|
1944
|
+
#### `auth.redirectBaseUrl` — reverse-proxy OAuth base
|
|
1945
|
+
|
|
1946
|
+
Optional string field in `~/.pi/dashboard/config.json`.
|
|
1947
|
+
No default.
|
|
1948
|
+
Absent = previous behaviour unchanged.
|
|
1949
|
+
Change: `config-override-oauth-redirect-base`.
|
|
1950
|
+
|
|
1951
|
+
**Purpose.** Dashboard behind reverse proxy on stable custom domain: `https://pi.example.com` → nginx → `:8000`.
|
|
1952
|
+
No dashboard-managed tunnel.
|
|
1953
|
+
Without field `buildRedirectUri()` emits `http://localhost:8000/auth/callback/github`.
|
|
1954
|
+
Provider rejects with `redirect_uri_mismatch`.
|
|
1955
|
+
|
|
1956
|
+
**Base precedence** (`buildRedirectUri(provider, port, baseOverride?)`, `packages/server/src/auth/auth.ts`):
|
|
1957
|
+
1. `auth.redirectBaseUrl` — highest
|
|
1958
|
+
2. `getTunnelUrl()` — active tunnel
|
|
1959
|
+
3. `http://localhost:<port>` — fallback
|
|
1960
|
+
|
|
1961
|
+
Trailing slashes stripped from winning base.
|
|
1962
|
+
Empty string treated as absent — falls through.
|
|
1963
|
+
|
|
1964
|
+
**Path prefix supported.** `https://pi.example.com/pi` → `https://pi.example.com/pi/auth/callback/github`.
|
|
1965
|
+
|
|
1966
|
+
**Call sites** (`packages/server/src/auth/auth-plugin.ts`):
|
|
1967
|
+
- `/auth/login` — single-provider auto-redirect
|
|
1968
|
+
- `/auth/start/:provider` — authorize redirect
|
|
1969
|
+
- `/auth/callback/:provider` — token exchange
|
|
1970
|
+
|
|
1971
|
+
OAuth2 requires token-endpoint `redirect_uri` byte-identical to authorize-endpoint one.
|
|
1972
|
+
|
|
1973
|
+
**Operator MUST register same callback URL with provider too** (GitHub/Google/Keycloak app settings).
|
|
1974
|
+
Config field alone not enough.
|
|
1975
|
+
|
|
1976
|
+
**Hot reload.** `PUT /api/config` → `writeConfigPartial` → `loadConfig()` → `fastify._reloadAuth(newConfig)` → `authState.redirectBaseUrl` reassigned.
|
|
1977
|
+
No restart needed.
|
|
1978
|
+
|
|
1979
|
+
**Trap — boot-time empty provider registry.** `registerAuthPlugin` returns early on zero resolvable providers ("Auth configured but no providers resolved — auth disabled") BEFORE registering `/auth/*` routes and BEFORE installing `_reloadAuth`.
|
|
1980
|
+
Server booted with zero resolvable OAuth providers → any `auth.*` change via `PUT /api/config` inert until restart.
|
|
1981
|
+
|
|
1982
|
+
**Validation** (`warnOnInvalidRedirectBase()`, `packages/server/src/auth/auth.ts`).
|
|
1983
|
+
Warns at plugin registration + every auth reload when value not absolute `http`/`https` origin, or carries query string / fragment.
|
|
1984
|
+
Value still USED, never discarded.
|
|
1985
|
+
Typo = visible provider rejection + log line, not silent no-op.
|
|
1986
|
+
|
|
1987
|
+
**Scope — OAuth redirect URIs only.** Pairing QR codes, `GET /api/tunnel/endpoints`, "Accessible at" surfaces still derive from `getTunnelUrl()`.
|
|
1988
|
+
Dashboard with `redirectBaseUrl` set advertises tunnel host in those places.
|
|
1989
|
+
Known + accepted.
|
|
1990
|
+
Top-level `publicBaseUrls` stays separate — not an OAuth tier (D7).
|
|
1991
|
+
|
|
1992
|
+
**Settings UI field.** Settings ▸ Security carries the input — `packages/client/src/components/settings/SettingsPanel.tsx`, testid `redirect-base-url-input`.
|
|
1993
|
+
Writes `auth.redirectBaseUrl` through existing `PUT /api/config` path.
|
|
1994
|
+
Empty input sends `""` — clears override. Omitting key PRESERVES old value instead.
|
|
1995
|
+
Help text states provider-side registration requirement.
|
|
1996
|
+
Gateway action writes same key when oauth mode selected (see Gateway URL Management).
|
|
1997
|
+
|
|
1097
1998
|
### Server-Keypair Device Pairing
|
|
1098
1999
|
|
|
1099
2000
|
Second auth path beside OAuth. Pairs a device to a server via QR/copy-string. Mints long-lived bearer token. Change: `add-server-keypair-pairing`.
|
|
@@ -1108,7 +2009,7 @@ Server ensures persistent Ed25519 keypair at `~/.pi/dashboard/identity.key` (060
|
|
|
1108
2009
|
|
|
1109
2010
|
#### QR / copy-string pairing
|
|
1110
2011
|
|
|
1111
|
-
Two QR kinds (D1). **Pairing QR** = secure payload `{v,id,code,urls[]}` = protocol version, fingerprint, one-time ~60s code, TLS-only reachable URLs. `urls[]` holds https/wss only (D14) — never self-signed LAN; includes MagicDNS with provisioned `tailscale cert`; Gateway provider endpoints plus operator-configured `pairing.publicBaseUrls
|
|
2012
|
+
Two QR kinds (D1). **Pairing QR** = secure payload `{v,id,code,urls[]}` = protocol version, fingerprint, one-time ~60s code, TLS-only reachable URLs. `urls[]` holds https/wss only (D14) — never self-signed LAN; includes MagicDNS with provisioned `tailscale cert`; Gateway provider endpoints plus operator-configured `publicBaseUrls` (legacy `pairing.publicBaseUrls` fallback). Rendered as QR plus copyable base64url string. **Link QR** = per no-TLS http mesh/LAN endpoint. Encodes bare URL string only — no pairing payload, no crypto.subtle, no bearer. Link-QR arrival governed by `config.trustedNetworks`. Module `packages/server/src/pairing.ts`.
|
|
1112
2013
|
|
|
1113
2014
|
#### Compare-code approval — D12
|
|
1114
2015
|
|
|
@@ -1160,6 +2061,142 @@ Approval: operator types numeric confirm code shown on device → `POST /api/pai
|
|
|
1160
2061
|
|
|
1161
2062
|
Gate: `reachableUrls()` (`packages/server/src/pairing.ts`) read-time filter (D4/D14) advertises only secure `wss`/`https` endpoints. Keeps `urls[]` secure. `createPayload()` returns null when no reachable url → route returns `{success:false,error:"no_reachable_endpoint"}` (HTTP 200).
|
|
1162
2063
|
|
|
2064
|
+
### Gateway URL Management
|
|
2065
|
+
|
|
2066
|
+
Change: `config-override-oauth-redirect-base`.
|
|
2067
|
+
Operator declares reachable gateway URLs + auth posture in one statement.
|
|
2068
|
+
Server reads at runtime via mtime-gated config snapshot.
|
|
2069
|
+
|
|
2070
|
+
#### `publicBaseUrls` — promoted to top level
|
|
2071
|
+
|
|
2072
|
+
`pairing.publicBaseUrls` promoted to top-level `publicBaseUrls?: string[]`.
|
|
2073
|
+
Source: `packages/shared/src/config.ts`.
|
|
2074
|
+
Read through `resolvePublicBaseUrls(config)`.
|
|
2075
|
+
Top-level first.
|
|
2076
|
+
Legacy `pairing.publicBaseUrls` fallback.
|
|
2077
|
+
Else `[]`.
|
|
2078
|
+
NOT in `DEFAULTS`.
|
|
2079
|
+
Never seeded by `ensureConfig()`.
|
|
2080
|
+
Absence selects the legacy fallback.
|
|
2081
|
+
`[]` default would orphan existing entries.
|
|
2082
|
+
|
|
2083
|
+
Consumers:
|
|
2084
|
+
- `server.ts` `getReachableUrls`
|
|
2085
|
+
- `system-routes.ts` `GET /api/tunnel/endpoints`
|
|
2086
|
+
- client `gateway-config-ops.ts`
|
|
2087
|
+
|
|
2088
|
+
OAuth-isolation rule (D7): `publicBaseUrls` NOT an OAuth redirect-base tier, at any arity.
|
|
2089
|
+
Reason: list vs scalar arity.
|
|
2090
|
+
OAuth `redirect_uri` = one pre-registered origin.
|
|
2091
|
+
Operator states it in `auth.redirectBaseUrl`.
|
|
2092
|
+
|
|
2093
|
+
TLS gate unmoved (D8).
|
|
2094
|
+
Stays read-time in `PairingManager.reachableUrls()`.
|
|
2095
|
+
Non-loopback `http://` entry in promoted list never reaches a pairing QR.
|
|
2096
|
+
|
|
2097
|
+
Client writer `appendPublicBaseUrl(config, url, {allowInsecure})` = single writer.
|
|
2098
|
+
Seeds top-level from legacy on first write.
|
|
2099
|
+
|
|
2100
|
+
#### Gateway action — one statement, one write
|
|
2101
|
+
|
|
2102
|
+
One operator statement → ONE `PUT /api/config`.
|
|
2103
|
+
Writes:
|
|
2104
|
+
- `publicBaseUrls`
|
|
2105
|
+
- `cors.allowedOrigins`
|
|
2106
|
+
- `auth.redirectBaseUrl` (iff oauth mode)
|
|
2107
|
+
- `trustedNetworks` (iff trusted-network mode)
|
|
2108
|
+
- `gateways[]` provenance record
|
|
2109
|
+
|
|
2110
|
+
Code: pure algebra `packages/client/src/lib/gateway/gateway-action.ts`.
|
|
2111
|
+
Exports:
|
|
2112
|
+
- `validateGatewayDraft`
|
|
2113
|
+
- `buildGatewayAddPatch`
|
|
2114
|
+
- `buildGatewayRemovePatch`
|
|
2115
|
+
- `computeGatewayStatus`
|
|
2116
|
+
- `buildGatewayFixPatch`
|
|
2117
|
+
|
|
2118
|
+
UI: `packages/client/src/components/Gateway/GatewayUrlManager.tsx`.
|
|
2119
|
+
Rendered by BOTH `GatewayPage.tsx` and `GatewaySetupGuide.tsx`.
|
|
2120
|
+
One shared component — cannot drift.
|
|
2121
|
+
|
|
2122
|
+
Scheme rules:
|
|
2123
|
+
- `http://` → trusted network REQUIRED
|
|
2124
|
+
- `http://` → QR pairing ineligible
|
|
2125
|
+
- `http://` → OAuth ineligible
|
|
2126
|
+
- `https://` → trusted network optional
|
|
2127
|
+
- `https://` → both eligible
|
|
2128
|
+
- At least one auth mode mandatory either way
|
|
2129
|
+
|
|
2130
|
+
CIDR prefill reuses `suggestTrustEntries`.
|
|
2131
|
+
Exact `/32`.
|
|
2132
|
+
Never a subnet.
|
|
2133
|
+
|
|
2134
|
+
Provenance `wrote{}` = exact values.
|
|
2135
|
+
Remove deletes only recorded values STILL EQUAL in live config.
|
|
2136
|
+
Limit: identical-value authorship indistinguishable.
|
|
2137
|
+
Removing clears an operator's hand-set `auth.redirectBaseUrl`.
|
|
2138
|
+
Both dialogs say so.
|
|
2139
|
+
|
|
2140
|
+
Status computed on read, never persisted.
|
|
2141
|
+
States: OK / Incomplete / Conflicting / Ineligible.
|
|
2142
|
+
Fix = reconcile-to-record delta write.
|
|
2143
|
+
Never re-run add.
|
|
2144
|
+
|
|
2145
|
+
Status checks trusted networks against the EFFECTIVE merge.
|
|
2146
|
+
Merge = top-level `trustedNetworks` ∪ `auth.bypassHosts`.
|
|
2147
|
+
Settings writes the second key.
|
|
2148
|
+
|
|
2149
|
+
**D15 — persisting is not applying.** CORS `origin` callback + `networkGuard` read mtime-gated snapshot (`packages/server/src/config-snapshot.ts`).
|
|
2150
|
+
Exports: `getConfigSnapshot`, `liveCorsAllowedOrigins`, `liveTrustedNetworks`.
|
|
2151
|
+
Boot closure replaced.
|
|
2152
|
+
`statSync` ~1.9 µs steady state.
|
|
2153
|
+
Full read+parse ~24.5 µs.
|
|
2154
|
+
Cache MUST stay mtime-gated.
|
|
2155
|
+
Boot snapshot silently reinstates the bug.
|
|
2156
|
+
Hand-edited `config.json` never passes through the writer.
|
|
2157
|
+
|
|
2158
|
+
`_reloadAuth(newAuth, fullConfig)` now merges top-level `trustedNetworks` exactly as boot does.
|
|
2159
|
+
Fixes PRE-EXISTING bug.
|
|
2160
|
+
Any auth-carrying `PUT /api/config` dropped them until restart.
|
|
2161
|
+
|
|
2162
|
+
New route `DELETE /api/config/auth/providers/:id`.
|
|
2163
|
+
`deleteAuthProvider` in `config-api.ts`.
|
|
2164
|
+
Idempotent.
|
|
2165
|
+
Refuses last provider without `?force=true`.
|
|
2166
|
+
Lockout, not disable.
|
|
2167
|
+
|
|
2168
|
+
New route `GET /api/auth/diagnostics`.
|
|
2169
|
+
Returns `{redirectBase, source, authActive, providerCount}`.
|
|
2170
|
+
Guarded.
|
|
2171
|
+
Loopback-reachable.
|
|
2172
|
+
Same line mirrored to `server.log` at register/reload.
|
|
2173
|
+
|
|
2174
|
+
#### `trustProxy` stays off — D14
|
|
2175
|
+
|
|
2176
|
+
Fastify constructed WITHOUT `trustProxy`.
|
|
2177
|
+
Deliberate.
|
|
2178
|
+
`trustProxy` rewrites `request.ip` from `X-Forwarded-For`.
|
|
2179
|
+
`request.ip` = what BOTH authorization bypasses read:
|
|
2180
|
+
- `auth-plugin.ts` auth-gate bypass
|
|
2181
|
+
- `localhost-guard.ts` `networkGuard` bypass
|
|
2182
|
+
|
|
2183
|
+
Enabling makes both gates header-forgeable.
|
|
2184
|
+
Includes the gate on `PUT /api/config`.
|
|
2185
|
+
Also splits REST from the WS upgrade path.
|
|
2186
|
+
WS upgrade authorizes on `socket.remoteAddress`.
|
|
2187
|
+
|
|
2188
|
+
Instead: session cookie `Secure` derives from RESOLVED redirect base scheme.
|
|
2189
|
+
`resolveRedirectBase` in `auth/auth.ts`.
|
|
2190
|
+
Operator-stated config.
|
|
2191
|
+
No request header can influence.
|
|
2192
|
+
|
|
2193
|
+
Prerequisite if anyone ever wants `trustProxy`:
|
|
2194
|
+
Move BOTH bypass points to `request.socket.remoteAddress` FIRST.
|
|
2195
|
+
Only safe together.
|
|
2196
|
+
Only the first change looks harmless.
|
|
2197
|
+
|
|
2198
|
+
Regression test: `packages/server/src/__tests__/forwarded-ip-trust.test.ts`.
|
|
2199
|
+
|
|
1163
2200
|
### Settings Panel
|
|
1164
2201
|
The web client includes a Settings panel (gear icon in sidebar header → `/settings` route) that lets users view and edit all dashboard configuration. The panel:
|
|
1165
2202
|
1. Loads config via `GET /api/config` (secrets redacted as `***`)
|
|
@@ -1170,9 +2207,122 @@ The web client includes a Settings panel (gear icon in sidebar header → `/sett
|
|
|
1170
2207
|
|
|
1171
2208
|
### Reconnection Flow
|
|
1172
2209
|
1. Browser reconnects with `subscribe` message including `lastSeq`
|
|
1173
|
-
2. Server
|
|
2210
|
+
2. Server compacts the in-memory window via `compactEventsForReplay`, then replays missed events in async batches of 200 (`REPLAY_BATCH_SIZE`) with backpressure handling
|
|
1174
2211
|
3. Browser's event reducer processes replay, rebuilding state
|
|
1175
2212
|
|
|
2213
|
+
**Replay compaction** (change: `compact-warm-replay-stream`, issue #399): warm (in-memory) replay ships the raw live stream. Every assistant `message_update` carries a full content snapshot, not a delta. Reopening a large session replayed ~20k events; cold (on-disk) path `packages/shared/src/state-replay.ts` synthesizes ~1k. `sendEventBatches` (`packages/server/src/browser-handlers/subscription-handler.ts`) composes pure `compactEventsForReplay` (`packages/server/src/session/replay-compaction.ts`) with existing `truncateToolResultForReplay` map. REPLAY ONLY — store keeps full stream for live path, "Show full output", status extraction. Sibling precedent: `packages/server/src/session/replay-truncate.ts`.
|
|
2214
|
+
|
|
2215
|
+
Drop rule:
|
|
2216
|
+
- Drop every `message_update` before LAST `message_end` in window.
|
|
2217
|
+
- Two exemptions.
|
|
2218
|
+
|
|
2219
|
+
Exemption — thinking updates:
|
|
2220
|
+
- `data.assistantMessageEvent.type` starts with `thinking` (`thinking_start|thinking_delta|thinking_end`).
|
|
2221
|
+
- Client builds `role:"thinking"` rows from them, carrying `startedAt` + `duration`.
|
|
2222
|
+
- `message_end` reconstruction path (`reconstruct-reasoning-on-replay`) rebuilds without them.
|
|
2223
|
+
- Dropping NOT state-equivalent.
|
|
2224
|
+
|
|
2225
|
+
Exemption — last text update before tool start:
|
|
2226
|
+
- Last text `message_update` before each `tool_execution_start`.
|
|
2227
|
+
- At `tool_execution_start` reducer flushes `streamingText` into permanent row keyed `flush-<toolCallId>`.
|
|
2228
|
+
- No preceding update → `streamingText` empty → no flush → row lands at `message_end` with different id and position.
|
|
2229
|
+
- Snapshots cumulative; keeping only last reproduces `streamingText` exactly.
|
|
2230
|
+
|
|
2231
|
+
Invariants:
|
|
2232
|
+
- Everything after last `message_end` = still-streaming tail, kept verbatim.
|
|
2233
|
+
- Non-`message_update` events always pass through.
|
|
2234
|
+
- Seq values NEVER rewritten.
|
|
2235
|
+
- Client `getEvents` tolerates gaps; monotonicity preserved.
|
|
2236
|
+
- `sendEventBatches` returns PRE-compaction highest seq.
|
|
2237
|
+
- `clearReplaying` cannot re-send already-delivered events as catch-up.
|
|
2238
|
+
|
|
2239
|
+
Correctness = CLIENT reducer:
|
|
2240
|
+
- Acceptance gate `packages/server/src/__tests__/replay-compaction-equivalence.test.ts` imports `packages/client/src/lib/chat/event-reducer.ts`.
|
|
2241
|
+
- Asserts `deepEqual(reduceAll(raw), reduceAll(compacted))` across fixtures.
|
|
2242
|
+
- COUPLING: any change to how reducer consumes `streamingText` or thinking events invalidates rule.
|
|
2243
|
+
|
|
2244
|
+
Measured (synthetic #399-shaped window, 140 messages × ~150 snapshot updates):
|
|
2245
|
+
- Events 21420 → 420 (98.0%).
|
|
2246
|
+
- Wire bytes 6.26 MB → 0.10 MB (98.4%).
|
|
2247
|
+
- Batches 429 → 3 (99.3%).
|
|
2248
|
+
- Compaction wall time 2.2 ms, single O(n) pass.
|
|
2249
|
+
- Real persisted session: cold path emits 1428 events; compaction verified NO-OP (1428 → 1428).
|
|
2250
|
+
- Pass safe to apply uniformly to both replay paths.
|
|
2251
|
+
|
|
2252
|
+
See change: `compact-warm-replay-stream`.
|
|
2253
|
+
|
|
2254
|
+
**Replay windowing + gap backfill** (changes: `lazy-load-session-history`, `fix-lazy-history-backfill-ux`, `add-tail-only-replay-window`): full-stream replay can exceed the browser budget. `memoryLimits.maxReplayEvents` (default `2000`; explicit `0` = unlimited) caps it. Above `0`, `sendEventBatches` ships head + tail windows, then browser backfills the middle on demand. Second shape via `memoryLimits.replayWindowMode` (see Memory Limits): `"tail-only"` ships NO head — replay opens at the tail, browser walks down to the store floor.
|
|
2255
|
+
|
|
2256
|
+
#### Windowing (`packages/server/src/browser-handlers/subscription-handler.ts`)
|
|
2257
|
+
- `sendEventBatches(ws, sessionId, stored, sendTo, windowLimit?, mode = "head-tail")`.
|
|
2258
|
+
- Window applied AFTER `compactEventsForReplay`, never before. Compaction ~20:1.
|
|
2259
|
+
- Returned high-water seq stays the PRE-compaction max of the full input array. Windowing never lowers it. `clearReplaying` catch-up depends on this.
|
|
2260
|
+
- Keyed on CONTENT not call site: `lastSeq === 0 || lastSeq > maxSeq` = full stream → window. Genuine delta (`lastSeq > 0`) never windowed, never emits `history_window`.
|
|
2261
|
+
- `computeReplayWindow(compacted, windowLimit, mode)` returns `{headEnd, tailStart}` or `null`.
|
|
2262
|
+
- Tail-only → `headEnd: 0`. `HEAD_RATIO` / `HEAD_MIN` / `HEAD_CAP` never consulted.
|
|
2263
|
+
- `headMaxSeq` special-cased to `0` when `headEnd === 0`: `full[headEnd - 1]` would index `full[-1]` and throw. `0` = "nothing above the gap", NOT "no window".
|
|
2264
|
+
- `MIN_REPLAY_WINDOW` clamp mode-independent: tail-only limit below 100 still clamps up to 100.
|
|
2265
|
+
- Short-circuit: `compacted.length <= windowLimit` → no window, `gapCount` 0.
|
|
2266
|
+
- `HEAD_RATIO` 0.1, `HEAD_MIN` 20, `HEAD_CAP` 200. `head = clamp(floor(limit*0.1), 20, 200)`, `tail = limit - head`.
|
|
2267
|
+
- Default geometry at 2000: head 200 (at `HEAD_CAP`, protected chat head maximal), tail 1800. `compacted.length <= windowLimit` short-circuit → sessions compacting under the limit take the pre-change path exactly.
|
|
2268
|
+
- Tail leading edge snaps FORWARD to next `message_start`/`turn_start`. Head trailing edge snaps BACKWARD to a `message_end`. Both bounded by `SNAP_LOOKUP` 200. Both SHRINK the window, so budget stays a hard cap.
|
|
2269
|
+
- `session_state_reset` emitted INSIDE `sendEventBatches`, keyed on `replayWindow !== null`, immediately before `history_window`. Ordering: reset → `history_window` → `event_replay`. Call-site guards removed (change: `add-tail-only-replay-window`).
|
|
2270
|
+
- Fixes latent cold-hydration bug: the fan-out had no guard and relied on the reducer's `firstSeq === 1` rule. Tail-only breaks it — tail replay opens at `tailMinSeq > 1`, so prior client state would get the tail APPENDED onto stale rows.
|
|
2271
|
+
- Old call-site guard keyed on UNCOMPACTED `events.length` while the window is computed on the COMPACTED array — could reset a stream that then fit. Gone.
|
|
2272
|
+
- Stale-`lastSeq` reset (`lastSeq > maxSeq`) KEPT, NOT window-gated. Windowed → frame from `sendEventBatches`, exactly once. Unwindowed stale case → NO frame; batch starts at seq 1, `firstSeq === 1` rule wipes transcript on arrival.
|
|
2273
|
+
|
|
2274
|
+
#### Window protocol (`packages/shared/src/browser-protocol.ts`)
|
|
2275
|
+
- Server→browser `history_window { sessionId, headMaxSeq, tailMinSeq, gapCount, oldestGapSeq, windowShape? }`. Sent once per subscriber, before first `event_replay`, full-stream paths only.
|
|
2276
|
+
- `windowShape` OPTIONAL additive field: `"head-tail"` | `"tail-only"`. Absent → `head-tail` (backward compatible).
|
|
2277
|
+
- `headMaxSeq` invariant widened `>= 1` → `>= 0`. Exactly `0` in tail-only = nothing above the gap. Clients READ `windowShape`, NEVER infer from `headMaxSeq === 0`.
|
|
2278
|
+
- `gapCount` = gap events the store HOLDS. Never the seq distance. Middle-trimmed store reports fewer.
|
|
2279
|
+
- Browser→server `history_backfill { sessionId, fromSeq, toSeq }` (both inclusive).
|
|
2280
|
+
- Server→browser `history_backfill_result { sessionId, events, servedFrom, servedTo, remainingGapCount, error? }`. `error` ∈ `not_subscribed | in_flight | out_of_range | stale_generation`.
|
|
2281
|
+
- Exactly ONE result per request on every path, refusals included.
|
|
2282
|
+
|
|
2283
|
+
#### Backfill server (`handleHistoryBackfill`)
|
|
2284
|
+
- Serves in-memory store only. Never reads the session file.
|
|
2285
|
+
- `EventStore.getEventsRange(sessionId, minSeq, maxSeq)` — binary search both bounds + one slice, O(log n + k). `getRangeProbe()` is test-only instrumentation.
|
|
2286
|
+
- Span clamped to `BACKFILL_MAX_SPAN` 500 events. Range clamped into the disclosed gap.
|
|
2287
|
+
- Span clamp moves the NON-abutting bound: raises `from` on a tail-adjacent request, lowers `to` on a head-adjacent one. Oversized tail-adjacent slice keeps its tail adjacency (lowering `to` would break crediting and invert the next request → failure loop).
|
|
2288
|
+
- Single-flight per (socket, session) → second concurrent request refused `in_flight`.
|
|
2289
|
+
- Subscription generation bumped on every subscribe; completion at a stale generation replies `stale_generation`, never dropped.
|
|
2290
|
+
- Response compacted with `compactEventsForReplay(slice, slice.length)` — explicit supersession boundary, because the boundary is array-relative and a gap slice's `message_end` lives outside it.
|
|
2291
|
+
- Gap is SYMMETRIC: `tailMinSeq` mutable like `headMaxSeq`. Served range credited to whichever edge it abuts — tail-adjacent → `tailMinSeq = servedFrom`; head-adjacent → `headMaxSeq = servedTo`; a both-adjacent final request credits the TAIL (exclusive). `remainingGapCount` store read over both edges terminates the loop.
|
|
2292
|
+
- `GapState.hasHead` gates the head credit (change: `add-tail-only-replay-window`). Derived from the MODE that produced the window, never from the bound. Without it, `from === 1` against `headMaxSeq === 0` satisfies `from === headMaxSeq + 1` → credits a head that does not exist → sets `headMaxSeq = to` → poisons every later `remainingGapCount`.
|
|
2293
|
+
- Termination driven by whichever bound the served range abuts. Backfill tail-anchored → normally `tailMinSeq` RETREATING. `headMaxSeq` advances only in `head-tail`; in `tail-only` it never moves.
|
|
2294
|
+
- Slice snaps its GAP-FACING edge: lower for a tail-anchored request, upper for a head-anchored one, chosen by request ORIENTATION so a legacy head-first client stays correct. Snap only shrinks, never empties (empty `events` array = client termination signal). Credit edge from POST-SNAP served bounds.
|
|
2295
|
+
|
|
2296
|
+
#### Client gap UI
|
|
2297
|
+
- `packages/client/src/lib/chat/history-gap.ts` — `HistoryGapState`, `HISTORY_GAP_ROW_ID`, `nextBackfillRange`. `nextBackfillRange` walks DOWN from `tailMinSeq` (tail-anchored), so "Load earlier" delivers the events immediately preceding what the user reads. `HistoryGapState.tailMinSeq` mutable, updated from `servedFrom`; `headMaxSeq = servedTo` update dropped (two-edge move double-shrinks a gap credited once).
|
|
2298
|
+
- Head-free floor: `nextBackfillRange` floors at `oldestGapSeq` instead of `headMaxSeq + 1` (`isHeadFree(gap) ? gap.oldestGapSeq : gap.headMaxSeq + 1`).
|
|
2299
|
+
- `HistoryGapState.atFloor` = walk reached `oldestGapSeq`, nothing further to request. SUCCESS terminus, distinct from `unservable` (store cannot serve; walk continues).
|
|
2300
|
+
- `historyGapTerminus(gap)`: `null` for a two-sided gap (divider spliced out), `"session-start"` when `oldestGapSeq <= 1`, else `"not-retained"`. Wording names neither retention nor compaction — the floor answers "is anything below", never "why is it gone".
|
|
2301
|
+
- Synthetic `ChatMessage` role `historyGap`, spliced at the head→tail boundary during the `event_replay` fold. Never produced by `reduceEvent`.
|
|
2302
|
+
- `packages/client/src/components/chat/HistoryGapDivider.tsx` — click-to-load interstitial. States: idle / loading / refused / unavailable / removed-when-filled.
|
|
2303
|
+
- Backfill splice touches `messages[]` only: no `maxSeqMapRef` move, no `publishSessionEvents`, no `replayPersister` write.
|
|
2304
|
+
- Backfill segment stamped before merge: every still-running tool row → `elided` (`ChatMessage.toolStatus`, `ToolCall.status`). Terminal status, "result not loadable"; renders neutral "result not loaded", never spinner, never error styling. Also finalizes assistant rows the segment left `isStreaming`. Backfill segments ONLY, never the initial windowed replay (a live mid-tool run must stay on the supersede-heal path).
|
|
2305
|
+
- A windowed replay is NOT written to the client replay cache. Prevents caching a sparse array as contiguous, which would make the next reload a cache hit that delta-subscribes and hides the gap permanently.
|
|
2306
|
+
- Backfill armed only after the initial replay terminates (`isLast: true`).
|
|
2307
|
+
- Gap state cleared on `session_state_reset` and on re-subscribe.
|
|
2308
|
+
|
|
2309
|
+
#### Tail-only auto-load (change: `add-tail-only-replay-window`)
|
|
2310
|
+
- Pure `shouldAutoLoadHistory(t)` in `packages/client/src/lib/chat/history-gap.ts`; `SETTLE_MS = 120`. Tail-only only.
|
|
2311
|
+
- Keyed on INTENT, not position: `scrollTop` clamps at 0 so a delta rule stalls; a splice smaller than the proximity band yields no new rising edge.
|
|
2312
|
+
- ONE `programmaticScrollUntil` stamp (`Date.now() + SETTLE_MS`) shared by all nine `ChatView` scroll writers.
|
|
2313
|
+
- `handleScroll` only RECORDS; evaluation happens at settle-timer expiry — a momentum stream evaluates once.
|
|
2314
|
+
- Suppressed evaluation DEFERRED, not consumed: re-evaluated at expiry.
|
|
2315
|
+
- No `touchend` latch: WebKit fires `touchend` BEFORE inertia begins; a latch would evaluate mid-momentum.
|
|
2316
|
+
- A11y announcement lives in `ChatView`, OUTSIDE the virtualized list (`aria-live="polite"`, `data-testid="history-gap-live-region"`). `HistoryGapDivider` is a virtualized row the virtualizer unmounts after a splice — a live region there is not in the DOM when its text changes. Scoped to AUTOMATIC loads in tail-only.
|
|
2317
|
+
|
|
2318
|
+
Measured (docker harness, 4825-event session, median of 5): full-replay completion 715ms → 341ms (2.10x), wire bytes 1958KB → 834KB (-57%), delivered events 4825 → 1996. Time-to-first-rendered-row unchanged (340ms → 349ms): replay ships in `REPLAY_BATCH_SIZE` 200-event batches, so the first batch lands identically regardless of what follows.
|
|
2319
|
+
|
|
2320
|
+
#### Tail-only known limitations (measured)
|
|
2321
|
+
- Scroll-to-turn navigation UNAVAILABLE. `turnIndex` assigned in reducer `turnUsage` arm to the last USER message; tail-only reduces only the tail, so anchoring user messages sit in the gap unreduced. All turn bars get `turnIndex: -1`. Measured: 21 bars, 0 clickable.
|
|
2322
|
+
- `unservable` is a RACE, not a config. Retention BELOW the window → retained stream smaller than the window → `computeReplayWindow` short-circuits → NO gap announced. Retention ABOVE the window → `gapCount` is store-read → servable by construction.
|
|
2323
|
+
|
|
2324
|
+
See change: `lazy-load-session-history`, `add-tail-only-replay-window`.
|
|
2325
|
+
|
|
1176
2326
|
### Bridge Reconnection (State Reset)
|
|
1177
2327
|
When a bridge extension reconnects (e.g., after `pnpm run reload` or network recovery):
|
|
1178
2328
|
1. Bridge sends `session_register` with `eventCount` to re-register the session
|
|
@@ -1191,6 +2341,46 @@ Without the `session_state_reset` message (full replay path), replayed events wo
|
|
|
1191
2341
|
|
|
1192
2342
|
**Agent streaming state recovery**: The bridge tracks `isAgentStreaming` in process-level `BridgeState` (survives reload). Set `true` on `agent_start`, `false` on `agent_end`/`session_shutdown`. Since the replay doesn't include `agent_start`/`agent_end` events, the session status would otherwise stay "active" (displayed as "Waiting for input") when the agent is mid-turn during reconnect.
|
|
1193
2343
|
|
|
2344
|
+
### ask_user Tool-State Restoration (bridge reconnect)
|
|
2345
|
+
|
|
2346
|
+
Change: `restore-ask-user-tool-state-on-reconnect`. `ask_user` `tool_execution_start` is NOT a transcript entry, so never replayed. Bridge reconnect ends with synthetic `agent_start` that cleared `currentTool`. Prompt-blocked session rendered "Thinking…" forever. Two registries + derived-field fold fix it.
|
|
2347
|
+
|
|
2348
|
+
#### Two prompt registries (NOT the same map)
|
|
2349
|
+
- `pendingUiRequests` — extension UI RPC prompts. Written by `trackUiRequest`; read by `hasPendingUiRequest()`.
|
|
2350
|
+
- `pendingPromptRequests` — PromptBus prompts. Written by `trackPromptRequest`; read by `hasPendingPromptRequests()`.
|
|
2351
|
+
- Both live in `packages/server/src/pairing/browser-gateway.ts`. Accessors return ids / booleans, never prompt payloads.
|
|
2352
|
+
- `onUnregister` clears BOTH via `clearPendingRequestsForSession(sessionId)`.
|
|
2353
|
+
- Leak ⇒ permanent `hasPendingAsk: true` ⇒ session never reapable.
|
|
2354
|
+
- Notify log separate (change: `split-notify-from-prompt-request`): `ctx.ui.notify` moved off PromptBus onto dedicated `notify` message. Never writes `pendingPromptRequests`, never feeds `hasPendingAsk` union or `currentTool` fold. NOT cleared by `clearPendingRequestsForSession` — ended session keeps rows; reapability by exclusion, not deletion. See Notify Flow.
|
|
2355
|
+
|
|
2356
|
+
#### `currentTool` derived-field contract
|
|
2357
|
+
- `DashboardSession.currentTool` derived from live pi events by `extractSessionUpdates()` in `packages/server/src/session/event-status-extraction.ts`.
|
|
2358
|
+
- `tool_execution_start` → toolName. `tool_execution_end` → null. `agent_start` → null + streaming. `agent_end` → null + idle.
|
|
2359
|
+
- Two code paths → two mechanisms:
|
|
2360
|
+
- M1 fold — `extractSessionUpdates(event, hasPendingPrompt)`. Event-derived update would leave `currentTool` empty + prompt pending ⇒ writes `"ask_user"`. LIVE events only, never replay. Function stays pure.
|
|
2361
|
+
- M2 direct writes — `prompt_request` / `prompt_dismiss` / `prompt_cancel` branches in `packages/server/src/event-wiring.ts` sit OUTSIDE the `event_forward` block; never reach extractor. Write for themselves.
|
|
2362
|
+
- Precedence: live tool always wins. `tool_execution_start{bash}` → `bash`; registry not consulted.
|
|
2363
|
+
- `hasPendingPrompt: false` output byte-identical to pre-change.
|
|
2364
|
+
- `prompt_request` branch trigger-complete: evaluates unread trigger + `questionFirst` reorder itself. Correctness independent of race vs `tool_execution_start`.
|
|
2365
|
+
- New legal field pair: `status: "idle"` + `currentTool: "ask_user"` (agent_end while prompt pending).
|
|
2366
|
+
|
|
2367
|
+
#### Replay exit reconcile
|
|
2368
|
+
- Both exits — `replay_complete` and 5s safety timeout — run reconcile → recompute → drain, fixed order.
|
|
2369
|
+
- `reconcilePromptRequests(sessionId, promptIds)` treats bridge re-sent `prompt_request` burst as authoritative snapshot; drops tracked entries absent. Recovers `prompt_dismiss` lost across socket drop.
|
|
2370
|
+
- Recompute one-directional: registry non-empty ⇒ `"ask_user"`; registry empty ⇒ leave event-derived value untouched.
|
|
2371
|
+
- Drain applies to ephemeral per-replay set (`replayPromptIds`), NEVER durable registry. Durable one backs browser-refresh dialog replay.
|
|
2372
|
+
- `replay_complete` guarded by `if (replayingSessions.delete(sessionId))` — only FIRST exit acts. OpenSpec-state cleanup OUTSIDE guard (idempotent); replay slower than 5s does not lose it.
|
|
2373
|
+
|
|
2374
|
+
#### Reaper pending-ask union
|
|
2375
|
+
- `embed-lifecycle-controller.ts` wires `hasPendingAsk: (id) => hasPendingUiRequest(id) || hasPendingPromptRequests(id)`.
|
|
2376
|
+
- Explicit, not `currentTool` accident: `currentTool` vetoes only idle gear; `streamingGearVerdict` reads `hasPendingAsk`, never `currentTool`.
|
|
2377
|
+
|
|
2378
|
+
#### Restart preserves gateway port
|
|
2379
|
+
- `packages/server/src/spawn-process/restart-helper.ts` propagates `--pi-port` alongside `--port`.
|
|
2380
|
+
- Without it: restarted server re-resolves `piPort` from file config (usually absent) ⇒ fallback 9999. Live pi bridges still dial old port; fail to re-register. Sessions vanish after restart.
|
|
2381
|
+
|
|
2382
|
+
See change: `restore-ask-user-tool-state-on-reconnect`.
|
|
2383
|
+
|
|
1194
2384
|
### Session File Deduplication
|
|
1195
2385
|
When pi continues a session via `--session <file>`, it reuses the same JSONL file but may create a new session ID. The server detects this: when a new session registers with a `sessionFile` already associated with another session, the old session's `sessionFile` is cleared. This prevents the Resume button from loading the wrong conversation.
|
|
1196
2386
|
|
|
@@ -1199,12 +2389,178 @@ When the bridge extension is loaded multiple times (e.g., local project + global
|
|
|
1199
2389
|
- **Pi gateway**: When a `session_register` changes the connection's session ID, the old session is cleaned up if it has `source: "unknown"` or no `sessionFile`
|
|
1200
2390
|
- **Event wiring**: When `session_register` arrives, any active sessions in the same cwd that have no sessionFile, no events, aren't connected, and were created within 30s are removed as ghosts
|
|
1201
2391
|
|
|
2392
|
+
### Bridge Connection Contention (one live bridge per session id)
|
|
2393
|
+
|
|
2394
|
+
Change: `fix-duplicate-bridge-registration`. Two live bridges once claimed one
|
|
2395
|
+
`sessionId`; gateway map resolved last-writer-wins. Newcomer silently displaced
|
|
2396
|
+
incumbent. Every server→extension message — prompts included — delivered to the
|
|
2397
|
+
displaced socket. Session looked healthy everywhere; prompts vanished. Fix:
|
|
2398
|
+
gateway now enforces **one live bridge per session id** as an invariant.
|
|
2399
|
+
|
|
2400
|
+
Decision logic in `packages/server/src/pi/bridge-contention.ts`. Kept out of
|
|
2401
|
+
`pi-gateway.ts` so the two-factor rule tests against synthetic sockets — the
|
|
2402
|
+
decisive "OPEN but not writable" state is not constructible from a real client
|
|
2403
|
+
socket. See change: `fix-duplicate-bridge-registration` (D1, D2, D4, D6).
|
|
2404
|
+
|
|
2405
|
+
#### Claim point (D0)
|
|
2406
|
+
|
|
2407
|
+
Real claim is the first-message identity block in `pi-gateway.ts` — NOT the
|
|
2408
|
+
`session_register` dispatch. `session_register` is itself that first message.
|
|
2409
|
+
`session_register` branch keeps `connections.set` as a no-op re-assert for the
|
|
2410
|
+
socket that already owns the id, and as the id-change path claim.
|
|
2411
|
+
|
|
2412
|
+
Contention decision runs BEFORE every register side effect: watchdog clear,
|
|
2413
|
+
placeholder cleanup, `resetHeartbeat`, callbacks, `onEvent`. Refused newcomer
|
|
2414
|
+
reaching any would strip the incumbent's `sessionFile`, consume its spawn token,
|
|
2415
|
+
or reset its reconnect-grace timer. Refusal path short-circuits before all.
|
|
2416
|
+
|
|
2417
|
+
Ownership gate after register. `session_heartbeat` and `model_update` name
|
|
2418
|
+
`msg.sessionId`. Without a gate, in-flight frames from a refused socket reset
|
|
2419
|
+
the incumbent's heartbeat or overwrite its `processMetrics`. Gate drops every
|
|
2420
|
+
message whose named id is not held by that socket (`connections.get(id) !==
|
|
2421
|
+
ws`).
|
|
2422
|
+
|
|
2423
|
+
Id-change contention decision hoisted above the watchdog clear. `clearByCwd`
|
|
2424
|
+
would disarm a pending spawn watchdog before the register is refused.
|
|
2425
|
+
|
|
2426
|
+
#### Two-factor contention rule (D1)
|
|
2427
|
+
|
|
2428
|
+
On `session_register` for an id whose entry holds a different `OPEN` socket, the
|
|
2429
|
+
gateway probes the incumbent (WebSocket ping) and waits a bounded window
|
|
2430
|
+
(`CONTENTION_PROBE_WINDOW` = 5 s). Same two-factor rule the ping reaper already
|
|
2431
|
+
encodes:
|
|
2432
|
+
|
|
2433
|
+
- **pong** → alive and serving → incumbent keeps; newcomer refused.
|
|
2434
|
+
- **no pong but TCP socket writable** → busy, not dead → incumbent keeps;
|
|
2435
|
+
newcomer refused.
|
|
2436
|
+
- **neither** → dead → gateway terminates incumbent, clears entry, accepts
|
|
2437
|
+
newcomer.
|
|
2438
|
+
|
|
2439
|
+
Pong-only rule would be wrong. Pongs processed on same event loop the bridge
|
|
2440
|
+
blocks while running a tool; a busy bridge does not answer. Pong-only rule
|
|
2441
|
+
terminates the live working incumbent. Both factors demanded, not observed —
|
|
2442
|
+
rule deterministic, testable.
|
|
2443
|
+
|
|
2444
|
+
**Same-pid reconnect exemption**: registering socket reporting same pid gateway
|
|
2445
|
+
recorded for incumbent = same pi reconnecting (previous close frame lost or in
|
|
2446
|
+
flight), not a duplicate. Gateway replaces the entry, never refuses. Self-reported
|
|
2447
|
+
pid used ONLY to AVOID a permanent refusal, never to justify one.
|
|
2448
|
+
|
|
2449
|
+
**Placeholder incumbent** (`source: "unknown"`) never carries a recorded pid, so
|
|
2450
|
+
never satisfies same-pid exemption. Never a protected incumbent: a real register
|
|
2451
|
+
always displaces one. Closes the window.
|
|
2452
|
+
|
|
2453
|
+
**Accepted residual — half-open incumbent undetectable.** Peer dead without a FIN
|
|
2454
|
+
leaves socket `OPEN` and writable, reads identical to busy, keeps the id.
|
|
2455
|
+
Neither reaper clears it (ping reaper keeps on `socketAlive`; heartbeat
|
|
2456
|
+
reschedules while `OPEN`). Id stranded until OS TCP timeout. Recovery: kill the
|
|
2457
|
+
losing keeper by verified pid, let survivor re-register. TCP keepalive on bridge
|
|
2458
|
+
sockets is the named follow-up. Known cost of never sacrificing a
|
|
2459
|
+
busy-but-live session, chosen deliberately.
|
|
2460
|
+
|
|
2461
|
+
#### Terminal refusal (D2)
|
|
2462
|
+
|
|
2463
|
+
Closing a refused socket is not enough. Bridge treats any close as transient and
|
|
2464
|
+
reconnects with backoff. No rejection message existed. Refused duplicate would
|
|
2465
|
+
loop forever, pi process alive writing into the same `.jsonl` as incumbent.
|
|
2466
|
+
|
|
2467
|
+
New server→extension message `register_rejected` in
|
|
2468
|
+
`packages/shared/src/protocol.ts`. Sent BEFORE the close. Bridge stops retrying
|
|
2469
|
+
for that session id on receipt; surfaces the reason instead of dying silently.
|
|
2470
|
+
|
|
2471
|
+
Refused register leaves the spawn-register watchdog armed. Watchdog reclaims the
|
|
2472
|
+
refused duplicate's pi by server-minted spawn token (`findPidsBySpawnToken`) —
|
|
2473
|
+
only processes this server spawned. Stops refused duplicate's pi writing into
|
|
2474
|
+
incumbent's `.jsonl`. `armSpawnWatchdog` arms EVERY spawn entry point (REST
|
|
2475
|
+
resume, WebSocket drag-to-resume, zombie reopen, headless reload), not just the
|
|
2476
|
+
WebSocket one. Browser transport optional — absent browser must not block the
|
|
2477
|
+
reclaim.
|
|
2478
|
+
|
|
2479
|
+
Killing the refused newcomer by the pid it reports on the register message is
|
|
2480
|
+
rejected: server executing a kill on the word of an untrusted socket message.
|
|
2481
|
+
|
|
2482
|
+
#### Identity-scoped teardown (D3)
|
|
2483
|
+
|
|
2484
|
+
Every id-keyed cleanup fired by a closing socket — map delete, `onDisconnect`,
|
|
2485
|
+
`sessionManager.unregister`, automation finalize, `heartbeatTimers`/
|
|
2486
|
+
`heartbeatMeta` deletes — first confirms `connections.get(id) === ws`. Displaced
|
|
2487
|
+
or refused socket closing cannot raise a spurious disconnect on a live session,
|
|
2488
|
+
clear the incumbent's reconnect-grace timer, or finalize an automation run
|
|
2489
|
+
another socket serves.
|
|
2490
|
+
|
|
2491
|
+
`stop()` terminates `wss.clients`, NOT `connections.values()`. `wss.close()` does
|
|
2492
|
+
not terminate clients; a socket outside the map would survive teardown and
|
|
2493
|
+
re-register against the fresh server. This is the half that made the incident
|
|
2494
|
+
survive two restarts.
|
|
2495
|
+
|
|
2496
|
+
#### Prompt reporting (D4)
|
|
2497
|
+
|
|
2498
|
+
With D0/D1 the map cannot hold a usurper; at prompt time exactly one owner, send
|
|
2499
|
+
is honest. "Contended" is a recorded event, not a live routing state. Record
|
|
2500
|
+
has explicit lifecycle, cleared by whichever comes first: refused spawn
|
|
2501
|
+
reclaimed, TTL expiry, incumbent disconnect, or session end. Incumbent alone
|
|
2502
|
+
insufficient trigger — healthy, may never disconnect, and D3 makes the refused
|
|
2503
|
+
socket's close a no-op for that id.
|
|
2504
|
+
|
|
2505
|
+
`POST /api/session/:id/prompt` SHALL NOT return plain success while a contention
|
|
2506
|
+
record is live. Annotates the reason, distinguishable from the existing "no
|
|
2507
|
+
bridge" failure. Reports `delivered: true` — contended-but-delivered is the
|
|
2508
|
+
normal case. Annotates, does not fail.
|
|
2509
|
+
|
|
2510
|
+
`sendToSession` returns `true` only for the socket the map holds for that id.
|
|
2511
|
+
|
|
2512
|
+
#### Resume session-file guard (D5)
|
|
2513
|
+
|
|
2514
|
+
Existing 409 (`session-api.ts`) keyed on session id only; did not prevent the
|
|
2515
|
+
incident — second keeper resumed the same session *file* under a different id.
|
|
2516
|
+
|
|
2517
|
+
Both guard sites refuse a `continue` whose target `sessionFile` a live bridge
|
|
2518
|
+
already serves under ANY session id:
|
|
2519
|
+
- `packages/server/src/session/session-api.ts` (REST)
|
|
2520
|
+
- `packages/server/src/browser-handlers/session-action-handler.ts` (WebSocket
|
|
2521
|
+
drag-to-resume)
|
|
2522
|
+
|
|
2523
|
+
Third site: `handleSendPrompt`'s zombie-reopen branch in
|
|
2524
|
+
`session-action-handler.ts` also spawns `mode:"continue"`, so it carries the
|
|
2525
|
+
same guard.
|
|
2526
|
+
|
|
2527
|
+
All three call `piGateway.findLiveSessionBySessionFile`. Liveness is D1's
|
|
2528
|
+
two-factor definition (`isSocketAlive`), NOT raw `readyState`: a socket the
|
|
2529
|
+
gateway has not yet reaped, but whose transport is gone, does not block a
|
|
2530
|
+
resume. A TRUE half-open incumbent (`readyState OPEN`, transport still
|
|
2531
|
+
writable) reads as alive and DOES block the resume — the same accepted residual
|
|
2532
|
+
as D1, recovered by killing the losing keeper by pid.
|
|
2533
|
+
|
|
2534
|
+
Fork exempt. Sessions with no `sessionFile` never match (placeholders store
|
|
2535
|
+
`undefined`). Lookup runs before the register-time `sessionFile` mutation
|
|
2536
|
+
(`event-wiring.ts`), which would already have nulled the key.
|
|
2537
|
+
|
|
2538
|
+
#### Observability (D6)
|
|
2539
|
+
|
|
2540
|
+
`/api/health` exposes:
|
|
2541
|
+
- `bridgeContentionCount` — cumulative, process lifetime; never reset by expiry.
|
|
2542
|
+
- `contendedSessionIds` — record lifecycle: reclaim / 60 s expiry / incumbent
|
|
2543
|
+
disconnect / session end.
|
|
2544
|
+
- `piGatewayPort`.
|
|
2545
|
+
|
|
2546
|
+
Refusal log line `[gateway] contention refused: <id> incumbentPid=…
|
|
2547
|
+
newcomerPid=…`. Distinct from `[gateway] session registered:` so it is greppable
|
|
2548
|
+
as its own signal. Unknown pid renders `unknown`, never omitted.
|
|
2549
|
+
|
|
2550
|
+
Refusal log line + health entry rate-limited to 1 per session id per 5 s
|
|
2551
|
+
(`CONTENTION_RATE_LIMIT`). Older bridge that ignores `register_rejected` keeps
|
|
2552
|
+
reconnecting; rate limit stops either surface flooding.
|
|
2553
|
+
|
|
2554
|
+
Constants: probe window 5 s (`CONTENTION_PROBE_WINDOW`), contention record
|
|
2555
|
+
expiry 60 s (`CONTENTION_RECORD_TTL`), refusal rate limit 1/id/5 s
|
|
2556
|
+
(`CONTENTION_RATE_LIMIT`).
|
|
2557
|
+
|
|
1202
2558
|
### On-Demand Session Loading (Server-Side)
|
|
1203
2559
|
When a browser subscribes to a session whose events have been evicted from memory:
|
|
1204
2560
|
1. Server sends empty `event_replay` with `isLast: false` to indicate loading
|
|
1205
2561
|
2. Server's DirectoryService loads the session file directly via `SessionManager.open(sessionFile).getBranch()`
|
|
1206
2562
|
3. Entries are converted via `replayEntriesAsEvents()` and stored in the event buffer (truncated, capped at 5000/session)
|
|
1207
|
-
4. Server sends `event_replay` in async batches with backpressure to all waiting browsers
|
|
2563
|
+
4. Server sends `event_replay` via `sendEventBatches` in async batches with backpressure to all waiting browsers (compaction applied; verified no-op on this path — see Reconnection Flow)
|
|
1208
2564
|
5. If the session file is missing or corrupt, server sends `dataUnavailable: true`
|
|
1209
2565
|
6. Concurrent loads for the same session are deduplicated
|
|
1210
2566
|
|
|
@@ -1233,6 +2589,8 @@ The per-message ⤘ Fork button needs each chat bubble to carry the entry id of
|
|
|
1233
2589
|
| Events | In-memory Map | LRU eviction, max 100 sessions. Pinned if active bridge or browser subscribers. |
|
|
1234
2590
|
| Sessions | In-memory Map + `.meta.json` | In-memory registry. Each session's state cached in per-session `.meta.json` sidecar next to `.jsonl`. On startup, `session-scanner.ts` scans `~/.pi/agent/sessions/*/` to restore all sessions from cached meta. |
|
|
1235
2591
|
| Session meta | `~/.pi/agent/sessions/…/<id>.meta.json` | Per-session sidecar: dashboard-owned state (name, attachedProposal, hidden, source) + cached stats (tokens, cost, model, status). Debounced per-session writes (max 1/sec). Stale cache detected via `cachedAt` vs `.jsonl` mtime. |
|
|
2592
|
+
| Namer stop state | `~/.pi/agent/sessions/…/<id>.meta.json` (`autoNamerState`) | Auto-naming permanent stop + counters (attemptsUsed, starvedCount, waitingCount, stoppedModelRef, stopCause). Survives process restart; restored via `auto_name_state_restore` at register. Cleared on naming re-resolution or blocking-cause resolution. See change: fix-auto-naming-reasoning-model. |
|
|
2593
|
+
| Notify log | `~/.pi/agent/sessions/…/<id>.meta.json` (`SessionMeta.notifyLog`) | Bounded per-session notify history (cap 50, oldest-first). Not a `DashboardEvent` — `event_replay` cannot restore. Mirrored by `sessionToMeta` (full-overwrite save), restored by `sessionFromMeta` cold start, carried across bridge reattach by `memory-session-manager.register()`. See Notify Flow. |
|
|
1236
2594
|
| Pinned directories | `~/.pi/dashboard/preferences.json` | Ordered array of cwd paths. Pinned dirs always visible in sidebar. |
|
|
1237
2595
|
| Session order | `~/.pi/dashboard/preferences.json` | Per-cwd ordering managed by `session-order-manager.ts`. |
|
|
1238
2596
|
| Server PID | `~/.pi/dashboard/server.pid` | Tracks running server process for daemon management. |
|
|
@@ -1260,6 +2618,38 @@ Precedence: CLI flags → environment variables → config file (`~/.pi/dashboar
|
|
|
1260
2618
|
| `tunnel.tailscale` | — | `{authKey}`. tailscale sub-config |
|
|
1261
2619
|
| `tunnel.zerotier` | — | `{networkId}`. zerotier sub-config |
|
|
1262
2620
|
| `tunnel.reservedToken` | _(auto)_ | Legacy bare zrok token. Read-time shim resolves to `{provider:"zrok", mode:"public", zrok:{reservedToken}}` in loadConfig. No disk rewrite until next save. Explicit `provider` wins on conflict |
|
|
2621
|
+
| `auth.redirectBaseUrl` | — | Optional OAuth redirect base for reverse-proxy deployments (`https://host[/prefix]`). Overrides tunnel/localhost base in `buildRedirectUri`. No default; absent = previous behaviour |
|
|
2622
|
+
| `publicBaseUrls` | — | Top-level reachable base URLs. Pairing QR + `GET /api/tunnel/endpoints` surfaces. `resolvePublicBaseUrls` reads top-level first, legacy `pairing.publicBaseUrls` fallback, else `[]`. No default; absent = legacy. Not an OAuth tier (D7) |
|
|
2623
|
+
| `memoryLimits.maxReplayEvents` | 2000 | Max events in full-stream replay window. Default `2000`; explicit `0` = unlimited (rollback lever). Absent/negative/non-numeric → `2000`; explicit `0` → `0`. Requires server restart. UI: Settings → Server → Memory Limits |
|
|
2624
|
+
| `memoryLimits.replayWindowMode` | `head-tail` | Replay window shape: `"head-tail"` default or `"tail-only"`. Unknown value coerced to default, never throws. Requires server restart. UI: Settings → Server → Memory Limits |
|
|
2625
|
+
|
|
2626
|
+
### Memory Limits
|
|
2627
|
+
|
|
2628
|
+
`memoryLimits.maxReplayEvents` bounds full-stream replay. Default `2000`. Explicit `0` = unlimited, the documented rollback lever.
|
|
2629
|
+
|
|
2630
|
+
Parsing (`parseMaxReplayEvents`, `packages/shared/src/config.ts`):
|
|
2631
|
+
- Absent / non-numeric / negative / NaN / Infinity → default `2000`.
|
|
2632
|
+
- Explicit `0` → `0` (presence detected; never clamped).
|
|
2633
|
+
- Positive below `MIN_REPLAY_WINDOW` (100) clamps up to 100.
|
|
2634
|
+
- Fractional floored.
|
|
2635
|
+
|
|
2636
|
+
`memoryLimits.replayWindowMode` picks the window shape. `"head-tail"` (default) ships head + tail, gap backfilled between. `"tail-only"` ships tail only, browser walks to the store floor. Server-scoped: one mode reshapes the transcript for EVERY client of that server. Inert when `maxReplayEvents: 0` — no window forms, mode irrelevant.
|
|
2637
|
+
|
|
2638
|
+
Parsing (`parseReplayWindowMode`, `packages/shared/src/config.ts`):
|
|
2639
|
+
- Accepts exactly `"tail-only"` and `"head-tail"`.
|
|
2640
|
+
- Anything else → default `"head-tail"`. COERCES, never throws.
|
|
2641
|
+
|
|
2642
|
+
Defaults + types live in `packages/shared/src/memory-limits.ts`, a BROWSER-SAFE module re-exported by `config.ts`. Reason: `config.ts` imports `node:fs`/`node:os`/`node:path` at module scope, so a VALUE import from `packages/client` ships node built-ins to the browser and the SPA dies at boot with `uv.homedir is not a function` (blank page; tsc/vitest/build all stay green). `import type` is safe. Guarded by `packages/client/src/__tests__/no-node-only-shared-imports.test.ts`.
|
|
2643
|
+
|
|
2644
|
+
Requires server restart. Surfaced in Settings → Server → Memory Limits.
|
|
2645
|
+
|
|
2646
|
+
Threading:
|
|
2647
|
+
- `cli.ts` → `server.ts` (`ServerConfig.maxReplayEvents`)
|
|
2648
|
+
- → `createBrowserGateway(..., maxReplayEvents)` → `BrowserHandlerContext.maxReplayEvents`.
|
|
2649
|
+
- `cli.ts` → `server.ts` (`ServerConfig.replayWindowMode`) → `createBrowserGateway(..., replayWindowMode)` → `BrowserHandlerContext.replayWindowMode`.
|
|
2650
|
+
- Programmatic server falls back to shared DEFAULT, not `0`; stays unlimited only when threaded explicitly.
|
|
2651
|
+
|
|
2652
|
+
See change: `lazy-load-session-history`, `fix-lazy-history-backfill-ux`, `add-tail-only-replay-window`.
|
|
1263
2653
|
|
|
1264
2654
|
### Tunnel Lifecycle
|
|
1265
2655
|
|
|
@@ -1292,9 +2682,9 @@ Idempotent control commands against long-lived daemon (`tailscaled` / `zerotier-
|
|
|
1292
2682
|
|
|
1293
2683
|
#### Endpoints
|
|
1294
2684
|
|
|
1295
|
-
`GET /api/tunnel/endpoints` returns tagged `{kind, url, tls}`, kind ∈ `public`|`mesh`|`magicdns`|`lan`|`local`. Multi-sourced: active provider endpoints +
|
|
2685
|
+
`GET /api/tunnel/endpoints` returns tagged `{kind, url, tls}`, kind ∈ `public`|`mesh`|`magicdns`|`lan`|`local`. Multi-sourced: active provider endpoints + top-level `publicBaseUrls` (legacy `pairing.publicBaseUrls` fallback) + LAN/local. "Accessible at" UI surface.
|
|
1296
2686
|
|
|
1297
|
-
Manual HTTPS entry: UI "Add HTTPS URL" appends to `
|
|
2687
|
+
Manual HTTPS entry: UI "Add HTTPS URL" appends to top-level `publicBaseUrls` via `appendPublicBaseUrl` (auth-gated `PUT /api/config`; no new route). Legacy `pairing.publicBaseUrls` seeded into top-level on first write. https/wss gate authoritative server-side at read time in `reachableUrls()`; plain-http dropped before advertisement.
|
|
1298
2688
|
|
|
1299
2689
|
#### Trusted-network block events
|
|
1300
2690
|
|
|
@@ -1608,29 +2998,16 @@ Both `pi-dashboard start` (CLI) and the bridge extension's `launchServer` write
|
|
|
1608
2998
|
|
|
1609
2999
|
When `autoStart` is `true` (default), the bridge extension automatically starts the dashboard server:
|
|
1610
3000
|
|
|
1611
|
-
```
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
┌────┴────┐
|
|
1622
|
-
│ open │ closed & autoStart=true
|
|
1623
|
-
│ │
|
|
1624
|
-
▼ ▼
|
|
1625
|
-
connect spawn server (detached)
|
|
1626
|
-
silently pass --port & --pi-port
|
|
1627
|
-
│
|
|
1628
|
-
▼
|
|
1629
|
-
notify user:
|
|
1630
|
-
"🌐 Dashboard started at http://localhost:{port}"
|
|
1631
|
-
│
|
|
1632
|
-
▼
|
|
1633
|
-
connect
|
|
3001
|
+
```mermaid
|
|
3002
|
+
flowchart TD
|
|
3003
|
+
Start["pi session_start"] --> Config["ensureConfig() → create ~/.pi/dashboard/config.json if missing"]
|
|
3004
|
+
Config --> Load["loadConfig() → read piPort, port, autoStart"]
|
|
3005
|
+
Load --> Probe['TCP probe localhost:{piPort}']
|
|
3006
|
+
Probe --> Open{port open?}
|
|
3007
|
+
Open -->|"open"| Connect["connect (silently)"]
|
|
3008
|
+
Open -->|"closed & autoStart=true"| Spawn["spawn server (detached), pass --port & --pi-port"]
|
|
3009
|
+
Spawn --> Notify['notify user: "🌐 Dashboard started at http://localhost:{port}"']
|
|
3010
|
+
Notify --> Connect2["connect"]
|
|
1634
3011
|
```
|
|
1635
3012
|
|
|
1636
3013
|
The server is spawned detached (`child_process.spawn` with `detached: true`, stdout/stderr redirected to `~/.pi/dashboard/server.log`), so it outlives the pi session. If multiple pi sessions start simultaneously, duplicate spawn attempts fail harmlessly with EADDRINUSE. After a failed launch, the bridge re-probes the port — if another agent started the server concurrently, the warning is suppressed. The auto-start logic is extracted into `server-auto-start.ts` for testability.
|
|
@@ -1686,6 +3063,141 @@ An `inFlightSwitchKey` ref guards against duplicate clicks; the clicked dropdown
|
|
|
1686
3063
|
- Already-known servers show "Already added" badge in discovery results
|
|
1687
3064
|
- Electron loading page shows known servers as fallback when primary server is unreachable
|
|
1688
3065
|
|
|
3066
|
+
## Bridge↔Server Connection — transport & identity (designed)
|
|
3067
|
+
|
|
3068
|
+
> **Status:** designed, not implemented — openspec change `add-pi-gateway-transport-identity`. Source of truth: `openspec/changes/add-pi-gateway-transport-identity/design.md`. Prior research: `docs/research/bridge-transport-and-identity.md`.
|
|
3069
|
+
|
|
3070
|
+
> Forward-looking. Sections above describe today's TCP + mDNS path (`pi-gateway.ts`, `mdns-discovery.ts`) and stay authoritative. This section documents the planned model only; today's content untouched.
|
|
3071
|
+
|
|
3072
|
+
### A. Endpoint resolution ladder (planned)
|
|
3073
|
+
|
|
3074
|
+
Explicit beats discovered. Always. Precedence, highest first:
|
|
3075
|
+
|
|
3076
|
+
1. `PI_DASHBOARD_SOCKET` — explicit local socket path — **PINNED**
|
|
3077
|
+
2. `PI_DASHBOARD_URL` — explicit remote endpoint — **PINNED**
|
|
3078
|
+
3. config: pinned instance identity — **PINNED**
|
|
3079
|
+
4. HOME-derived rendezvous record (default local)
|
|
3080
|
+
5. paired remote dashboards (remote-join)
|
|
3081
|
+
6. mDNS — MAY SUGGEST, MAY NEVER OVERRIDE 1–5
|
|
3082
|
+
|
|
3083
|
+
PINNED = explicit human choice. Nothing automatic replaces it. Pinned + unreachable = visible retrying failure, not silent migration. This inverts the hijack: today explicit `PI_DASHBOARD_URL` can be silently overridden; only defence is remembering `PI_DASHBOARD_NO_MDNS`.
|
|
3084
|
+
|
|
3085
|
+
Absent rendezvous record ⇒ report no local dashboard. Does NOT fall through to discovery. Deletes the stale-advertisement failure class: today a stale mDNS answer resolves to a real, live, wrong server.
|
|
3086
|
+
|
|
3087
|
+
**Rendezvous record** = `home-lock.ts` metadata sidecar, HOME-derived path. `LockMetadata { httpPort, piPort, identity, pid, ppid, startedAt, version, url, hostname }`. `piPort` = where to dial. `identity` = who it must be.
|
|
3088
|
+
|
|
3089
|
+
No selection algorithm. Selector exists: `home-lock.ts` asserts one dashboard instance per `<canonicalHomedir>/.pi/`; a pi process inherits HOME. Coexisting instances use distinct HOMEs (isolated-verification precedent: temp HOME, non-8000 ports, `PI_DASHBOARD_NO_MDNS=1`).
|
|
3090
|
+
|
|
3091
|
+
```mermaid
|
|
3092
|
+
flowchart TD
|
|
3093
|
+
A["1 · PI_DASHBOARD_SOCKET"] -->|"PINNED"| D["dial"]
|
|
3094
|
+
B["2 · PI_DASHBOARD_URL"] -->|"PINNED"| D
|
|
3095
|
+
C["3 · config pinned instance identity"] -->|"PINNED"| D
|
|
3096
|
+
R["4 · HOME-derived rendezvous record<br/>(default local)"] --> D
|
|
3097
|
+
P["5 · paired remote dashboard<br/>(remote-join)"] --> D
|
|
3098
|
+
M["6 · mDNS / discovery"] -.->|"MAY SUGGEST<br/>MAY NEVER OVERRIDE 1–5"| H["suggests to a human"]
|
|
3099
|
+
D --> V{"identity verifies?"}
|
|
3100
|
+
V -->|"✓"| REG["register"]
|
|
3101
|
+
V -->|"✗"| REF["refuse"]
|
|
3102
|
+
```
|
|
3103
|
+
|
|
3104
|
+
### B. Per-platform dial table (planned)
|
|
3105
|
+
|
|
3106
|
+
| | POSIX | Windows | Remote |
|
|
3107
|
+
|---|---|---|---|
|
|
3108
|
+
| address | `ws+unix:///<HOME>/.pi/dashboard/gateway.sock:/` | `ws://127.0.0.1:<piPort>` | `wss://host/…` |
|
|
3109
|
+
| address source | HOME path | HOME sidecar → `piPort` | pairing record |
|
|
3110
|
+
| who may connect | socket mode `0600` (kernel) | `X-Pi-Local-Token` (`auth/local-token.ts`) | ws-ticket from device bearer |
|
|
3111
|
+
| server proves self | own socket | `identity` from sidecar | Ed25519 fingerprint challenge |
|
|
3112
|
+
| network-reachable | impossible, nothing listens | no, loopback-pinned | yes, by design |
|
|
3113
|
+
| protocol above | identical WebSocket | identical | identical |
|
|
3114
|
+
|
|
3115
|
+
Protocol identical on all three. `session_register`, `ping`/`pong`, contention, send ring, every `ExtensionToServerMessage` — unchanged. Only dial destination differs. The change is an address, not a protocol.
|
|
3116
|
+
|
|
3117
|
+
Verified experimentally before adopting: `ws+unix://` preserves `ping`/`pong`, `terminate()`, `wss.clients`, `readyState`. `bridge-contention.ts` uses WebSocket ping/pong frames as its liveness oracle for the duplicate-registration probe — survives unmodified. A ping-less transport (QUIC, raw stream) would force re-founding that subsystem.
|
|
3118
|
+
|
|
3119
|
+
- **POSIX auth** = socket ownership. Mode `0600` in `0700` directory. Kernel enforces. No token to mint, leak, rotate, replay. Matches `0600` convention of `paired-devices.json` + `identity.key`. `--host 0.0.0.0` exposure becomes unrepresentable — nothing listens.
|
|
3120
|
+
- **Windows auth** = `local-token.ts`. 32-byte secret at `~/.pi/dashboard/local/token`, header `X-Pi-Local-Token`, verify `crypto.timingSafeEqual`. Loopback bind pinned to `127.0.0.1` regardless of `--host`. Known pre-existing gap: `chmod` is a no-op on Windows; owner-only property rests on inherited NTFS ACLs. Must be verified on a real Windows host, not reasoned about.
|
|
3121
|
+
- **Remote auth** = paired device. Reuses `pairing/pairing.ts` (one-time code, 8-digit confirm), `paired-devices.ts` (hash-only bearer registry, revocable, `0600`), `bearer-auth.ts`, `ws-ticket.ts` (single-use, ~15s, scoped upgrade ticket — durable bearer never rides the WebSocket). New `bridge` value in `WsRouteScope` (today `"browser" | "terminal" | "live"`, `packages/server/src/auth/ws-ticket.ts:22`). Remote bridge pins server Ed25519 fingerprint at pairing; refuses any endpoint that cannot answer the nonce challenge. Makes the hijack class unrepresentable, not merely guarded.
|
|
3122
|
+
|
|
3123
|
+
Stale sockets fail closed. Bind unlinks pre-existing socket file. Client dialing a leftover path gets `ENOENT`/`ECONNREFUSED` immediately, definitively.
|
|
3124
|
+
|
|
3125
|
+
Server may listen on both transports. `WebSocketServer({ noServer: true })`, one upgrade handler shared by a UDS listener + optional TCP listener. Transport = per-bridge property, not per-server mode. TCP listener does not bind by default.
|
|
3126
|
+
|
|
3127
|
+
### C. Stickiness (planned)
|
|
3128
|
+
|
|
3129
|
+
Three separate pieces of state. Separateness matters:
|
|
3130
|
+
|
|
3131
|
+
- `pinned` — endpoint was explicit human choice; nothing automatic may replace it
|
|
3132
|
+
- `boundTo` — `identity` actually registered with; reconnect always targets this
|
|
3133
|
+
- `verify` — candidate must prove that identity before becoming `boundTo`
|
|
3134
|
+
|
|
3135
|
+
Today none exist. `connection.ts:334` `updateUrl(newUrl)` mutates `this.url` ambiently. That ambient mutation IS the hijack — see `openspec/changes/fix-bridge-mdns-migration-hijack`.
|
|
3136
|
+
|
|
3137
|
+
Re-target requires ALL of: current endpoint unpinned, current endpoint failed, candidate identity verifies. Otherwise bridge keeps retrying `X` and surfaces the failure.
|
|
3138
|
+
|
|
3139
|
+
```mermaid
|
|
3140
|
+
stateDiagram-v2
|
|
3141
|
+
[*] --> Resolving
|
|
3142
|
+
Resolving --> Connecting
|
|
3143
|
+
Connecting --> Registered
|
|
3144
|
+
Registered --> Dropped
|
|
3145
|
+
Dropped --> Connecting: same instance always
|
|
3146
|
+
Registered --> Registered: discovered candidate, REFUSED + logged
|
|
3147
|
+
Dropped --> Evaluating: unpinned AND repeated failure
|
|
3148
|
+
Evaluating --> Connecting: verify ✓ → rebind
|
|
3149
|
+
Evaluating --> Registered: verify ✗ → keep current
|
|
3150
|
+
Registered --> Moving: explicit move command
|
|
3151
|
+
Moving --> Registered: pinned = true
|
|
3152
|
+
```
|
|
3153
|
+
|
|
3154
|
+
### D. Explicit session move (planned)
|
|
3155
|
+
|
|
3156
|
+
Commands:
|
|
3157
|
+
- `/dashboard connect <instance>` — instance = socket path | port | identity | `default`
|
|
3158
|
+
- `/dashboard connect --list` — rendezvous records visible under this HOME
|
|
3159
|
+
- `/dashboard where` — current endpoint, identity, pinned?
|
|
3160
|
+
|
|
3161
|
+
Stickiness (C) makes automatic re-targeting hard. Move command is the escape valve — the only manual recovery for a bridge attached to the wrong instance (the 23-hour hijack has none today).
|
|
3162
|
+
|
|
3163
|
+
Order matters: register with target BEFORE closing origin. Session never orphaned mid-move. Then `session_moved` to origin — the ONLY new protocol message — origin card reads *moved*, not *crashed*. Move sets `pinned = true`; explicit choice must survive the next reconnect.
|
|
3164
|
+
|
|
3165
|
+
Primitives exist, no parallel path:
|
|
3166
|
+
- `ConnectionManager.updateUrl()` (`connection.ts:334`) — re-target
|
|
3167
|
+
- `pi.registerCommand("__dashboard_reload", …)` (`bridge.ts:1367`) — command template
|
|
3168
|
+
|
|
3169
|
+
```mermaid
|
|
3170
|
+
sequenceDiagram
|
|
3171
|
+
participant U as user
|
|
3172
|
+
participant B as bridge
|
|
3173
|
+
participant T as target instance
|
|
3174
|
+
participant O as origin instance
|
|
3175
|
+
U->>B: /dashboard connect <target>
|
|
3176
|
+
B->>T: session_register
|
|
3177
|
+
T-->>B: registered
|
|
3178
|
+
B->>O: session_moved
|
|
3179
|
+
O-->>B: ack
|
|
3180
|
+
B->>B: pinned = true
|
|
3181
|
+
```
|
|
3182
|
+
|
|
3183
|
+
### E. Two session sources — scope limit (planned)
|
|
3184
|
+
|
|
3185
|
+
Dashboard learns about a session from two places:
|
|
3186
|
+
|
|
3187
|
+
| Source | Mechanism | Travels with a move? |
|
|
3188
|
+
|---|---|---|
|
|
3189
|
+
| LIVE | bridge WebSocket events | yes |
|
|
3190
|
+
| HISTORY / card metadata / resume | `session/session-scanner.ts` reads `~/.pi/agent/sessions/**/*.jsonl` via `resolvePiSessionsDir()` — LOCAL filesystem | only within one HOME |
|
|
3191
|
+
|
|
3192
|
+
Consequence table:
|
|
3193
|
+
|
|
3194
|
+
| Move | live | history | outcome |
|
|
3195
|
+
|---|---|---|---|
|
|
3196
|
+
| same-HOME (worktree ↔ main, isolated ↔ live) | follows | follows — both scan same files | complete |
|
|
3197
|
+
| cross-host / remote-join | follows | does NOT — remote cannot read local `.jsonl`; `/api/session/:id/resume` cannot respawn a pi on another machine | live-only |
|
|
3198
|
+
|
|
3199
|
+
Bounds the remote-join feature. OPEN QUESTION, not solved by this change. Directions — stream history over the bridge at register, proxy from origin dashboard, accept live-only remote sessions — differ enough in cost to need their own change.
|
|
3200
|
+
|
|
1689
3201
|
## Provider Authentication
|
|
1690
3202
|
|
|
1691
3203
|
The dashboard supports browser-based authentication with pi's LLM providers, enabling login from phones, tablets, or remote tunnel access without needing terminal access.
|
|
@@ -1744,14 +3256,25 @@ The dashboard includes a browser-based terminal emulator for direct shell access
|
|
|
1744
3256
|
|
|
1745
3257
|
### Architecture
|
|
1746
3258
|
|
|
1747
|
-
```
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
3259
|
+
```mermaid
|
|
3260
|
+
flowchart LR
|
|
3261
|
+
subgraph Browser["Browser"]
|
|
3262
|
+
X["xterm.js (per terminal)"]
|
|
3263
|
+
Fit["FitAddon"]
|
|
3264
|
+
Att["AttachAddon"]
|
|
3265
|
+
end
|
|
3266
|
+
subgraph ServerSide["Server"]
|
|
3267
|
+
TM["TerminalManager"]
|
|
3268
|
+
PTY["node-pty"]
|
|
3269
|
+
RB["RingBuffer"]
|
|
3270
|
+
CS["clients Set"]
|
|
3271
|
+
end
|
|
3272
|
+
X --- Fit
|
|
3273
|
+
X --- Att
|
|
3274
|
+
TM --- PTY
|
|
3275
|
+
TM --- RB
|
|
3276
|
+
TM --- CS
|
|
3277
|
+
X <-->|"binary WS"| TM
|
|
1755
3278
|
```
|
|
1756
3279
|
|
|
1757
3280
|
### WebSocket Protocol
|
|
@@ -1778,6 +3301,19 @@ This is separate from the main JSON dashboard WebSocket (`/ws`).
|
|
|
1778
3301
|
|
|
1779
3302
|
Package operations all flow through `package-manager-wrapper.ts`'s single-flight `busy` lock. The route layer (`/api/packages/install` / `/remove` / `/update` / `/move`) returns `202 { operationId | moveId }` synchronously and progress streams over the existing `package_progress` + `package_operation_complete` WebSocket channels.
|
|
1780
3303
|
|
|
3304
|
+
**Client-side single-flight queue** (added in change `unify-pi-core-into-package-queue`):
|
|
3305
|
+
|
|
3306
|
+
Client mirrors server busy lock with FIFO singleton `packageQueue` (`packages/client/src/lib/package/package-queue.ts`). Single-flight across ALL op kinds — second enqueue returns `queued` status, not 409. `kind: "extension" | "pi-core"` discriminates dispatch path; `EnqueueRequest.kind` optional, defaults `"extension"`.
|
|
3307
|
+
|
|
3308
|
+
- `kind: "extension"` → POST `/api/packages/{install,remove,update}` → 202 + `operationId`. Completion arrives via `package_operation_complete` WS frame.
|
|
3309
|
+
- `kind: "pi-core"` → POST `/api/pi-core/update` with single-name batch `{packages:[name]}`. Blocks server-side until npm finishes. Completion read from response body `body.data.results[0]`.
|
|
3310
|
+
|
|
3311
|
+
Pi-core source key convention: `pi-core:<scoped-npm-name>` via exported `piCoreSource(name)` — convention only, `kind` is dispatch key, not prefix. Queue subscribes both window channels: `pi-package-event` + `pi-core-event`. `pi_core_update_progress` updates `running.message`. `pi_core_update_complete` deliberate NO-OP for queue — `packages/server/src/routes/pi-core-routes.ts` calls `onUpdateComplete(out)` BEFORE returning HTTP response, so WS frame reaches client FIRST; acting on it would complete early.
|
|
3312
|
+
|
|
3313
|
+
409 retry-once (500 ms backoff) applies to both arms via shared `scheduleRetry`. Queue browser-module singleton — survives component unmount, does NOT survive page reload, not shared across clients (two tabs still 409 each other). `moveTracker` (`move` + `reset-to-npm`) stays OUTSIDE queue — `moveId`-keyed identity, partial-success semantics. `packageQueue.isAnyRunning()` exists for future cross-domain UI lock; no consumer yet.
|
|
3314
|
+
|
|
3315
|
+
See change: `unify-pi-core-into-package-queue`.
|
|
3316
|
+
|
|
1781
3317
|
**Move semantics** (added in change `unify-package-management-ui`):
|
|
1782
3318
|
|
|
1783
3319
|
Moving a package between scopes (global ↔ local) is a hybrid operation, keyed on the source kind:
|
|
@@ -2041,27 +3577,14 @@ MSYS exists for legitimate reasons (porting GCC, Autotools, git itself — softw
|
|
|
2041
3577
|
|
|
2042
3578
|
### The four-cell failure-mode matrix
|
|
2043
3579
|
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
EMBEDDED │ works │ ❌ broken │
|
|
2053
|
-
in JS source │ │ MSYS can't │
|
|
2054
|
-
passed via │ │ see inside │
|
|
2055
|
-
node -e "..." │ │ string │
|
|
2056
|
-
───────────────┼─────────────┼─────────────────┤
|
|
2057
|
-
--import URL │ works │ ❌ broken │
|
|
2058
|
-
as raw path │ │ Node parses B: │
|
|
2059
|
-
(no file://) │ │ as URL scheme │
|
|
2060
|
-
───────────────┼─────────────┼─────────────────┤
|
|
2061
|
-
inside .mjs │ works │ works │
|
|
2062
|
-
path.resolve │ │ │
|
|
2063
|
-
───────────────┴─────────────┴─────────────────┘
|
|
2064
|
-
```
|
|
3580
|
+
Host OS across, path form down.
|
|
3581
|
+
|
|
3582
|
+
| Path form | POSIX | Windows |
|
|
3583
|
+
|---|---|---|
|
|
3584
|
+
| argv-position path | works | works (MSYS converts) |
|
|
3585
|
+
| EMBEDDED in JS source, passed via `node -e "..."` | works | ❌ broken — MSYS can't see inside string |
|
|
3586
|
+
| `--import` URL as raw path (no `file://`) | works | ❌ broken — Node parses `B:` as URL scheme |
|
|
3587
|
+
| inside `.mjs`, `path.resolve` | works | works |
|
|
2065
3588
|
|
|
2066
3589
|
The two broken cells map to existing repo invariants:
|
|
2067
3590
|
|
|
@@ -2084,6 +3607,28 @@ The two broken cells map to existing repo invariants:
|
|
|
2084
3607
|
|
|
2085
3608
|
See change: `eliminate-bash-on-windows-runners`.
|
|
2086
3609
|
|
|
3610
|
+
## OpenSpec main-spec integrity
|
|
3611
|
+
|
|
3612
|
+
Main specs live at `openspec/specs/<capability>/spec.md`.
|
|
3613
|
+
|
|
3614
|
+
Parse contract: needs h2 `## Purpose` + h2 `## Requirements`. `MarkdownParser.parseSpec` throws otherwise.
|
|
3615
|
+
|
|
3616
|
+
`findSection` matches title exactly, case-insensitive. `## ADDED Requirements` != `## Requirements`.
|
|
3617
|
+
|
|
3618
|
+
Delta headers (`## ADDED|MODIFIED|REMOVED|RENAMED Requirements`) valid ONLY in `openspec/changes/<name>/specs/<cap>/spec.md`. Never in main specs.
|
|
3619
|
+
|
|
3620
|
+
Archive path once copied delta specs to main verbatim. Result: 80 of 546 specs unparseable, 384 requirement blocks invisible to validate/list/show/archive.
|
|
3621
|
+
|
|
3622
|
+
Fix tool: `node scripts/repair-main-specs.mjs` (`--dry-run`, `--specs-dir <path>`). Idempotent. Refuses `## REMOVED Requirements` — retired requirements never promote; handle manually (delete, tombstone, or restore).
|
|
3623
|
+
|
|
3624
|
+
Gate: `npm run spec:validate` = `openspec validate --specs --no-interactive`. Runs as step "Validate OpenSpec main specs" in `ci` job in `.github/workflows/ci.yml`. Exit non-zero on any invalid spec.
|
|
3625
|
+
|
|
3626
|
+
Before pushing an archive: run `npm run spec:validate` locally. Corrupt archive blocks `develop` otherwise.
|
|
3627
|
+
|
|
3628
|
+
Retired capability with zero current requirements: tombstone (keep spec, one requirement naming successor) when it carries an authored `**DEPRECATED**` pointer, else delete. Zero-requirement spec does NOT validate.
|
|
3629
|
+
|
|
3630
|
+
See change: repair-corrupted-main-specs.
|
|
3631
|
+
|
|
2087
3632
|
## Electron Server Lifecycle
|
|
2088
3633
|
|
|
2089
3634
|
### Power-user-mode managed install (Defect 1 fix)
|
|
@@ -2206,23 +3751,18 @@ History source is **derived**, not stored: `extractUserPromptHistory(state.messa
|
|
|
2206
3751
|
|
|
2207
3752
|
Inside `CommandInput`, history navigation uses a small state machine:
|
|
2208
3753
|
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
any text edit while historyIndex != null
|
|
2222
|
-
k ─────────────────────────────────────────▶ null (user now editing; no restore)
|
|
2223
|
-
sessionId change
|
|
2224
|
-
null, savedDraftRef = ""
|
|
2225
|
-
```
|
|
3754
|
+
`historyIndex: number | null` — `null` = not in history mode.
|
|
3755
|
+
`savedDraftRef: useRef<string>` — in-progress draft captured when history mode first entered.
|
|
3756
|
+
|
|
3757
|
+
| Event (guard) | From | To | Note |
|
|
3758
|
+
|---|---|---|---|
|
|
3759
|
+
| ArrowUp (caret on first line, no dropdown, no pending, `history.length > 0`) | `null` | `0` | save current text first |
|
|
3760
|
+
| ArrowUp (same guard) | `k` | `min(k+1, len-1)` | |
|
|
3761
|
+
| ArrowDown (caret on last line, no dropdown, `historyIndex != null`) | `k > 0` | `k - 1` | |
|
|
3762
|
+
| ArrowDown (same guard) | `0` | `null` | restore `savedDraftRef` |
|
|
3763
|
+
| Escape (`historyIndex != null`) | `k` | `null` | restore `savedDraftRef` |
|
|
3764
|
+
| any text edit while `historyIndex != null` | `k` | `null` | user now editing; no restore |
|
|
3765
|
+
| sessionId change | any | `null` | `savedDraftRef = ""` |
|
|
2226
3766
|
|
|
2227
3767
|
**Bash-style caret gating** is critical: `ArrowUp` only triggers history when `selectionStart` is at or before the first `\n` (the textarea's native "ArrowUp" would have nowhere to go); `ArrowDown` only when `selectionStart` is at or after the last `\n`. Non-empty selections are excluded. This guarantees multiline editing (moving between rows with arrow keys) is never broken.
|
|
2228
3768
|
|
|
@@ -2584,3 +4124,178 @@ Caps (caps.ts): `maxActiveEmbedSessionsPerVisitor` + `maxActiveEmbedSessionsGlob
|
|
|
2584
4124
|
`createEmbedLifecycleController` (embed-lifecycle-controller.ts) constructed in server.ts. Reaper `start()`/`stop()` tied to server lifecycle. Dormant when `enabled: false`.
|
|
2585
4125
|
|
|
2586
4126
|
See change: add-embed-session-lifecycle.
|
|
4127
|
+
|
|
4128
|
+
## Knowledge Base (KB)
|
|
4129
|
+
|
|
4130
|
+
Markdown knowledge base backed by a single FTS5 table (`chunks`) over `node:sqlite`. Zero network, zero LLM — all ranking is mechanical. Backend `SqliteFtsStore` (`packages/kb/src/sqlite-store.ts`). Config layered project → global → defaults (`packages/kb/src/config.ts`).
|
|
4131
|
+
|
|
4132
|
+
### KB retrieval pipeline
|
|
4133
|
+
|
|
4134
|
+
`store.search()` post-processes one FTS5 BM25 pass with a staged pipeline. Stage order:
|
|
4135
|
+
|
|
4136
|
+
1. **Body-hash collapse** (exact-content dedup) — byte-identical chunks collapse to one `KbHit`; alternate locations become `akaPaths`. Runs FIRST so `akaPaths` computes against the full candidate set.
|
|
4137
|
+
2. **Source dedup** — one hit per `(root, path)`; representative = best (lowest) BM25 score; suppressed remainder counted in `KbHit.suppressedSections`.
|
|
4138
|
+
3. **MMR** (`diversity`, lexical over bodies, config-gated, default on).
|
|
4139
|
+
4. **Coverage rerank** — opt-in, default off.
|
|
4140
|
+
5. **Lane interleave** — `agents` lane blended into the page.
|
|
4141
|
+
6. **Limit slice**.
|
|
4142
|
+
7. **Parent expand** (`expandParent`, default on) — attaches parent `headingPath` to each hit.
|
|
4143
|
+
|
|
4144
|
+
Source dedup differs from body-hash dedup: body-hash answers "same content, two places"; source dedup answers "already showed this file". A file vendored under two roots collapses across roots first, then dedups by source.
|
|
4145
|
+
|
|
4146
|
+
#### `limit` = distinct sources (BREAKING)
|
|
4147
|
+
|
|
4148
|
+
`limit` bounds **distinct sources**, not chunks. Contract change for `kb_search`, `kb search`, `store.search()`. `store.search()` still returns `KbHit[]`; only cardinality semantics change.
|
|
4149
|
+
|
|
4150
|
+
Source dedup shrinks one source to one slot, so a pool sized at `limit` starves the page. Fetch depth = `limit × 6` when source dedup on (`limit × 4` body-hash only), capped at 4000.
|
|
4151
|
+
|
|
4152
|
+
#### Lane quota (`ranking.laneQuota`)
|
|
4153
|
+
|
|
4154
|
+
`agents` chunks are 3.2% of the index and ~3× longer than `doc`, so BM25 length normalisation buries the per-file record layer ~30:1. Fix is engine-side: second FTS pass restricted to `doc_type='agents'` with a shallow pool, interleaved at `ranking.laneQuota` (default 0.5). Explicit `docType` bypasses the quota. Starved lane yields its slots to the other; a source taken by one lane is never repeated (when source dedup on).
|
|
4155
|
+
|
|
4156
|
+
Swept over bundled fixtures; 0.5 = largest reserved share with no markdown-intent regression. See `measurements.md` sweep table.
|
|
4157
|
+
|
|
4158
|
+
#### Coverage rerank + PRF — off by default
|
|
4159
|
+
|
|
4160
|
+
Coverage rerank (`ranking.coverageRerank`) + RM3-style PRF (`queryExpansion.mode: "prf"`) implemented, tested, config-gated, **default off**. Measured a net regression on bundled fixtures (markdown-intent R@10 0.630 → 0.491; combined 0.566 → 0.524; latency ~4×). PRF applies only with coverage rerank on; expanding an OR-query deepens the dilution the rerank exists to cure. Do not present as active. See `measurements.md` D4.
|
|
4161
|
+
|
|
4162
|
+
#### Condensed render
|
|
4163
|
+
|
|
4164
|
+
Result render emits leaf heading, not breadcrumb, plus `(+N more sections)`. Full `headingPath` retained in `KbHit` and the JSON format, so `kb_get(path, section)` still addresses a section.
|
|
4165
|
+
|
|
4166
|
+
#### `kb_get` path-only fetch
|
|
4167
|
+
|
|
4168
|
+
Path-only fetch (`getChunk` without `headingPath`) returns first chunk plus `suppressedSections` count. Never a silent 1-of-N slice.
|
|
4169
|
+
|
|
4170
|
+
#### Measured outcome (31,121-chunk index, K=10)
|
|
4171
|
+
|
|
4172
|
+
| metric | baseline | shipped |
|
|
4173
|
+
|---|---|---|
|
|
4174
|
+
| combined R@10 | 0.363 | 0.566 (+56%) |
|
|
4175
|
+
| duplicate-slot share | 0.48 | 0.00 |
|
|
4176
|
+
| distinct sources/page | 5.2 | 10.0 |
|
|
4177
|
+
| render tokens/page | — | −32.8% |
|
|
4178
|
+
|
|
4179
|
+
Reproduce + full variant table: `packages/kb/eval/` (`run-fixtures.ts`, `measure-render.ts`).
|
|
4180
|
+
|
|
4181
|
+
#### Latency — budget met at median, not p95
|
|
4182
|
+
|
|
4183
|
+
| config | median | p95 |
|
|
4184
|
+
|---|---|---|
|
|
4185
|
+
| baseline | 20.6 ms | 34.8 ms |
|
|
4186
|
+
| + source dedup | 25.5 ms | 38.2 ms |
|
|
4187
|
+
| + lane quota 0.5 | 53.2 ms | 84.8 ms |
|
|
4188
|
+
|
|
4189
|
+
Lane quota is the cost: its `agents` lane is a second FTS query, and `doc_type` is an UNINDEXED FTS5 column — cannot be answered by an index, scans the full match set. Scaled 31,121 → ~22,000 chunks: ≈38 ms median (passes 50 ms budget), ≈60 ms p95 (fails).
|
|
4190
|
+
|
|
4191
|
+
See change: fix-kb-search-retrieval-quality.
|
|
4192
|
+
|
|
4193
|
+
## Pi Gateway Transport & Identity
|
|
4194
|
+
|
|
4195
|
+
Bridge↔server gateway transport + identity. Ground truth: `openspec/changes/add-pi-gateway-transport-identity/design.md` (decisions D0–D16), `packages/extension/src/endpoint-resolution.ts`, `packages/server/src/pi/gateway-transport-policy.ts`, `gateway-socket-bind.ts`, `bridge-upgrade-auth.ts`, `provisional-registration.ts`.
|
|
4196
|
+
|
|
4197
|
+
See change: add-pi-gateway-transport-identity.
|
|
4198
|
+
|
|
4199
|
+
### Transport: unix socket default, TCP by opt-in
|
|
4200
|
+
|
|
4201
|
+
- Default listener = unix socket `<dashboardConfigDir>/gateway-<piPort>.sock` (`~/.pi/dashboard/gateway-<piPort>.sock`).
|
|
4202
|
+
- Socket mode `0600`, directory `0700`. Kernel enforces ownership; no token to mint, leak, rotate, replay (D5).
|
|
4203
|
+
- Socket path per instance, keyed by `piPort`. Same-HOME instances collide structurally never (D2).
|
|
4204
|
+
- Bridge dials `ws+unix://<path>:/`. Same WS protocol over the socket (D1) — `ws.ping()`/`pong` liveness oracle intact.
|
|
4205
|
+
- `ConnectionManager` constructed with `ws` package as `WebSocketImpl`. Global WebSocket rejects `ws+unix://` and cannot set upgrade headers.
|
|
4206
|
+
- TCP = opt-in only. `PI_GATEWAY_TCP` truthy (`1`/`true`/`yes`/`on`) binds listener; absent → no TCP listener (`decideGatewayListeners`, `packages/server/src/pi/gateway-transport-policy.ts`).
|
|
4207
|
+
- Opt-in TCP widens to configured bind host. No-socket fallback listener pins `127.0.0.1` regardless of `--host`.
|
|
4208
|
+
- Docker container sets `PI_GATEWAY_TCP: "${PI_GATEWAY_TCP:-1}"` (`docker/compose.yml`) — external pi sessions cannot reach the in-container socket; TCP kept with bridge auth mandatory (D10b).
|
|
4209
|
+
- Windows = always loopback. No unix socket. `ws://127.0.0.1:<piPort>`, authorised by `X-Pi-Local-Token` (D6).
|
|
4210
|
+
- sun_path fallback: path length checked at construction, never at `bind`. `SUN_PATH_MAX` = 104 macOS/BSD, 108 Linux. Over limit → loopback + local token, reason in log (D15).
|
|
4211
|
+
- Stale-socket fail-closed (D9, defect B3): probe/unlink/bind serialized under exclusive companion lock `gateway-<piPort>.sock.lock` (`proper-lockfile`). Probe `live` → `GatewaySocketConflictError`, never unlink. Reclaim only on `ENOENT`, or `refused` + `<socketPath>.pid` records a provably dead owner (`isProcessAlive`). Timeout fails closed — saturated live backlog looks exactly like it.
|
|
4212
|
+
- On unbind: socket path + `.pid` + `.lock` sentinels removed. Idempotent (task 2.5).
|
|
4213
|
+
|
|
4214
|
+
### Endpoint resolution: precedence ladder (D3)
|
|
4215
|
+
|
|
4216
|
+
`resolveEndpoint` (`packages/extension/src/endpoint-resolution.ts`) — pure decision table. Every input passed in; the ladder is enumerable, not emergent from I/O order. Highest first:
|
|
4217
|
+
|
|
4218
|
+
| # | source | input | class |
|
|
4219
|
+
|---|---|---|---|
|
|
4220
|
+
| 1 | `PI_DASHBOARD_SOCKET` | explicit local socket path | **PINNED** |
|
|
4221
|
+
| 2 | `PI_DASHBOARD_URL` | explicit endpoint | **PINNED** |
|
|
4222
|
+
| 3 | pinned instance | operator config | **PINNED** |
|
|
4223
|
+
| 4 | rendezvous record | `~/.pi/dashboard/server.lock.meta.json` (HOME-derived) | default |
|
|
4224
|
+
| 5 | paired remote | remote-join feature | — |
|
|
4225
|
+
| 6 | mDNS / discovery | suggestion only | **never overrides** |
|
|
4226
|
+
|
|
4227
|
+
- mDNS never wins. Discovered candidate surfaces as `suggestion` only, informational, for deliberate operator action.
|
|
4228
|
+
- Absence = unavailable, never discovery (D0). Resolution `available:false` + reason. No silent substitute.
|
|
4229
|
+
- Rendezvous record written by the lock holder only (D2). Truncated / partially-written record = absent, never partially trusted (D15).
|
|
4230
|
+
- Stickiness (D4): once registered with instance X, bridge reconnects only to X. Re-target requires all of: current endpoint unpinned, current endpoint failed, candidate identity verified (`decideRetarget`).
|
|
4231
|
+
- Pinned endpoint unreachable → visible, retrying failure — never silent migration to something else.
|
|
4232
|
+
|
|
4233
|
+
```mermaid
|
|
4234
|
+
flowchart TD
|
|
4235
|
+
A["bridge starts"] --> B["resolveEndpoint"]
|
|
4236
|
+
B --> C1{"PI_DASHBOARD_SOCKET set?"}
|
|
4237
|
+
C1 -- "yes" --> P1["dial socket — pinned"]
|
|
4238
|
+
C1 -- "no" --> C2{"PI_DASHBOARD_URL set?"}
|
|
4239
|
+
C2 -- "yes" --> P2["dial endpoint — pinned"]
|
|
4240
|
+
C2 -- "no" --> C3{"pinned instance configured?"}
|
|
4241
|
+
C3 -- "yes" --> P3["dial pinned instance — pinned"]
|
|
4242
|
+
C3 -- "no" --> C4{"rendezvous record?"}
|
|
4243
|
+
C4 -- "yes" --> P4["dial record endpoint — not pinned"]
|
|
4244
|
+
C4 -- "no" --> C5{"paired remote?"}
|
|
4245
|
+
C5 -- "yes" --> P5["dial paired remote — not pinned"]
|
|
4246
|
+
C5 -- "no" --> U["unavailable + reason; mDNS = suggestion only"]
|
|
4247
|
+
P1 --> D["dial, verify instance id, register"]
|
|
4248
|
+
P2 --> D
|
|
4249
|
+
P3 --> D
|
|
4250
|
+
P4 --> D
|
|
4251
|
+
P5 --> D
|
|
4252
|
+
D --> R{"current endpoint failed?"}
|
|
4253
|
+
R -- "no" --> SERVE["serve"]
|
|
4254
|
+
R -- "yes" --> G["decideRetarget"]
|
|
4255
|
+
G -- "pinned / not failed / identity unverified" --> STAY["keep retrying current endpoint"]
|
|
4256
|
+
G -- "unpinned + failed + identity verified" --> B
|
|
4257
|
+
```
|
|
4258
|
+
|
|
4259
|
+
### Auth model
|
|
4260
|
+
|
|
4261
|
+
`decideBridgeUpgrade` (`packages/server/src/pi/bridge-upgrade-auth.ts`) — pure per-transport gate. Asymmetry is the point:
|
|
4262
|
+
|
|
4263
|
+
| transport | credential | mechanism |
|
|
4264
|
+
|---|---|---|
|
|
4265
|
+
| unix socket | none | kernel via `0600` socket in `0700` dir (D5) |
|
|
4266
|
+
| loopback TCP | `X-Pi-Local-Token` | 32-byte secret `~/.pi/dashboard/local/token`, verified with `crypto.timingSafeEqual` (D6) |
|
|
4267
|
+
| remote TCP | single-use bridge-scoped ws ticket | minted from paired-device bearer or genuinely-local caller; rides upgrade only |
|
|
4268
|
+
|
|
4269
|
+
- Loopback = `127.0.0.1`/`::1` AND absence of proxy-forwarding headers (`hasProxyForwardingHeaders`). `ssh -L`, zrok, host nginx present as loopback → not genuinely local.
|
|
4270
|
+
- Ticket scope `bridge` added to `WsRouteScope` (`packages/server/src/auth/ws-ticket.ts`). Single-use, ~15 s TTL, path `/ws/bridge`. Carried in `?ticket=` query or `sec-websocket-protocol` `pi-ticket.` entry. Durable bearer never rides the WebSocket.
|
|
4271
|
+
- Remote TCP requires a valid ticket always. No grace, ever.
|
|
4272
|
+
- Tokenless loopback accepted during deprecation window, logged `deprecated: true`; refused after horizon (1.0.0).
|
|
4273
|
+
- Refusal causes distinct — no-credential ≠ bad-credential: `local-token-missing`, `local-token-invalid`, `no-ticket`.
|
|
4274
|
+
- Server identity = Ed25519 fingerprint (`auth/identity.ts` → `~/.pi/dashboard/identity.key`), per-HOME, stable across restarts. Stored at pairing; verified by nonce challenge before registering (D8). Stale or hostile server cannot impersonate a pinned identity.
|
|
4275
|
+
- Rendezvous instance id = separate concept (D14, defect B1): `<dashboardConfigDir>/instances/<piPort>.id`, `0600`, per-instance, stable across restarts. Identifier, never a capability — `/api/health` publishes it unauthenticated. Answers "which instance answered"; never proof of entitlement.
|
|
4276
|
+
- Local token (or socket ownership) proves entitlement; instance id only names the instance (D14).
|
|
4277
|
+
|
|
4278
|
+
### Move command (D11)
|
|
4279
|
+
|
|
4280
|
+
- `/dashboard-connect <target>` — move the live session to another dashboard. Target: exact `instanceId` | port | unambiguous id prefix (git-short-sha style) | explicit socket path / `ws://` URL | `default` (D11b).
|
|
4281
|
+
- Ambiguous id prefix refused, never resolved — silently choosing moves the session wrong and still looks like it worked.
|
|
4282
|
+
- `/dashboard-list` — every gateway instance under this HOME, default first (display-only scan, `packages/shared/src/instance-directory.ts`). Never auto-picks an endpoint.
|
|
4283
|
+
- `/dashboard-where` — current endpoint, identity, pinned? for this session.
|
|
4284
|
+
- Sequence: connect target → provisional registration → verify instance id → commit. Origin keeps serving until commit succeeds (D11).
|
|
4285
|
+
- Provisional registration (`provisional-registration.ts`) claims NO routing entry, no contention slot, no heartbeat. Returns target `instanceId` + token. TTL 30 s (`PROVISIONAL_TTL`). Refusal = `provisional_rejected`, cause never on the wire — no session-enumeration oracle.
|
|
4286
|
+
- Routing transfers only on `session_move_commit`. Send-ring ownership: exactly one owner at every instant; origin owns until target acknowledges, then single swap instant.
|
|
4287
|
+
- `session_moved` → server sets `movedTo` + `status: "ended"` + `endedAt` (`packages/server/src/event-wiring.ts`). Card reads *moved*, never *crashed*.
|
|
4288
|
+
- Every failure — refusal, identity mismatch, timeout (30 s), transport error — drops the target and keeps the origin. Move that cannot complete = no-op, never an outage.
|
|
4289
|
+
- Move pin in-memory, process-lifetime only (D11a). Nothing on disk. Restarted pi re-resolves through the D3 ladder. Feeds existing `decideRetarget({ pinned })` stickiness gate.
|
|
4290
|
+
- Cross-host target: transcript stays on origin host — history and resume do not follow (`assessTranscriptFollow`, locality decided from endpoint, never path sent on wire). Warning surfaced before move.
|
|
4291
|
+
|
|
4292
|
+
### Remote transcripts + read-only boundary (D12, D13)
|
|
4293
|
+
|
|
4294
|
+
- Sessions addressed by id ONLY. `decideTranscriptRequest` (`packages/extension/src/transcript-request-guard.ts`) refuses any path-bearing field: `path`, `file`, `filePath`, `filepath`, `sessionFile`, `sessionDir`, `dir`, `cwd`. Refusal on field presence, never value validation — validating values is a traversal-parsing contest.
|
|
4295
|
+
- Shape checked before subject: two refusals cannot be differenced into an existence check. Foreign `sessionId` refused — bridge serves only its own session.
|
|
4296
|
+
- Backfill: lazy, interruptible, background after registration. Live events forward eagerly. Cursor = offset + length + hash of last consumed line; mismatch → re-read from start, never resume (append-only is measured, not provable over time).
|
|
4297
|
+
- Retention: `<dashboardConfigDir>/remote-transcripts/<sessionId>.jsonl` (`~/.pi/dashboard/remote-transcripts/`). File `0600`, dir `0700`. `sessionId` validated `^[A-Za-z0-9_-]{1,64}$` — rejected, never sanitised (write-anywhere guard).
|
|
4298
|
+
- Restarted read REPLACES, never appends — duplicated second pass corrupts the retained copy. `.complete` sidecar marker; transcript byte-identical to origin.
|
|
4299
|
+
- Origin derived from the authenticated bridge credential, never bridge-claimed (`attributeOrigin`, `packages/server/src/session/session-origin.ts`). unix / loopback → local. Remote + `deviceId` → remote. Unattributable remote → remote, fail closed. Claimed fields (`claimedDeviceId`, `claimedLocal`, …) ignored.
|
|
4300
|
+
- Remote-origin sessions refuse local file reads (`mayReadLocalSessionFile`: `remote-origin` | `no-session-file`) — same-username path collision would serve an unrelated host's transcript.
|
|
4301
|
+
- Remote-origin sessions refuse resume (`decideResume`: `remote-origin-ended` | `remote-origin-live`) — local resume would attach a writer to another host's transcript. Read-only after bridge ends (D13).
|