Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Merge pull request #231 from atomantic/shell-uuid-routes
[._.]/ Adam Eivy978cf2f9590a
diff --cc CLAUDE.mdindex fc34f1af70,1812b7c720..a365e501f8--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -157,9 -157,13 +157,15 @@@ When working **directly in the Claude C- Arrays/objects: gate on `Array.isArray(parsed?.field)` / `typeof parsed?.field === 'object'` before deciding to fall back to the original.- Keep server-side merges and the client's `pick` helpers mirrored — a one-sided change breaks the round-trip.- **Schema parity when adding fields.** When you add a field to a sanitizer, `createXxx`, or a payload shape, update the corresponding Zod schema (`server/lib/aiToolkit/validation.js` for toolkit shapes, `server/lib/validation.js` for PortOS routes) in the same change. Wire validation into POST and PUT (PUT can use `schema.partial()`); the PortOS convention is *all* inputs validated. Tolerate UI sentinels (`endpoint: ''` for CLI providers) with `z.preprocess(v => v === '' ? undefined : v, …)`. When a service migrates legacy keys on read, the schema must still accept the legacy shape so older clients don't 400 before the migration runs.+- **Silent vs. toasting API requests.** The `request()` helper in `client/src/services/apiCore.js` toasts errors by default. When a caller already owns its own error UI — either via `useAsyncAction` (which toasts on throw) or a `.catch(() => fallback)` that intentionally swallows the failure — pass `{ silent: true }` to the API helper so the toast only fires from one layer. Add an `options` parameter to new API wrappers so callers can opt into silent mode.+- **"Run Now" actions must gate on saved state, not the form input.** When a settings page has a companion "Run this now" button that triggers a server action reading server-side settings (not the local form values), the button must be gated on the *saved* value, not the in-memory input. Track a parallel `saved*` state for each setting the action depends on, update it on successful save, and use it for the action's enabled gate. Disable the action while the form is dirty *or* a save is in flight — a tooltip-only warning is missed on touch and produces surprising "I edited X and ran, but X didn't apply" bugs.- **High-frequency state writes must batch.** Per-line state mutations that round-trip through `withStateLock → loadState → saveState` (e.g. `appendAgentOutput` in `cosAgents.js`) are fine for human-pace events but catastrophic when called from a hot loop — PTY output streams, AI tool-call streams, or any producer that can emit dozens of events per second. When wiring a new streaming producer, add a batched variant that takes an array (see `appendAgentOutputLines` for the pattern) and flush from the caller on a ~250ms debounce. Always drain the pending buffer in the producer's `finish`/`cleanup` path before the final state write so completion events don't beat the last output batch to disk.+ - **Socket event-driven state — don't pre-clear before the server confirms.** When swapping which entity a socket-driven UI is showing (shell session, agent run, etc.), wait for the server's success event to drive the swap atomically; the error event is the recovery point. Pre-clearing the local `*Ref` / visible state up front leaves the UI stranded on a dead URL when the success event never arrives (target died mid-request, server rejected the switch). Pair every `socket.on('X:error')` that follows a stateful request with a recovery branch that restores the previously-displayed state or falls back to a live alternative.+ - **Single-subscriber socket resources need notify + recipient-relative advertise + filter + claim.** Some server-side resources (PTY shell sessions, etc.) intentionally store one attached socket and fan output to it. The contract: (1) emit `<resource>:detached` on the previous socket when a new socket takes over so the displaced client can drop its local view; (2) include an `attached: boolean` field on each list-entry payload, computed *relative to the recipient socket* (true only when bound to a different socket) — a globally-truthy `attached` makes a client's own sessions look unavailable to itself; (3) broadcast list updates from both attach AND detach paths; (4) auto-pick paths send `claim: true` and the server refuses to displace a different socket. Manual paths (tab click, deep-link URL) default to `claim: false` so explicit intent still wins. See `server/services/shell.js` for the canonical implementation.+ - **Pending socket-request tracking — `{ target, generation }` ref.** When a stateful socket operation is in flight, track it as `{ target, generation }` and increment `generation` on every change. Response handlers gate on strict equality with `target` — null/stale/cancelled all fall through, so a cancelled-mid-flight response can't re-activate after the user moved on. Deferred work (`setTimeout` fallbacks) captures `generation` and aborts if it advanced. Pair every cancellation path with explicit `cancelPendingAttach()`-style helpers rather than overloading a `clearActiveSession()` helper — clearing the displayed entity and cancelling an in-flight request are *separate* concerns, and conflating them cancels user-initiated switches when an unrelated session dies. See `client/src/pages/Shell.jsx` `pendingAttachRef` for the pattern.+ - **Server-correlate every async response, then filter display.** When the server emits `<resource>:error` in response to a client request, include the original `sessionId` / request id in the payload so the client can match against its pending state. Drop stale errors silently and gate the red-error display on correlation — rendering before classification flashes noise in the UI for requests the user has already moved past (rapid tab clicks, expected `claim:true` race rejections). Passive errors against the currently-displayed resource (e.g. `shell:input` to a now-dead session) should still display, but must not mutate pending state.+ - **Distinguish intentional idle from passive idle.** A "no entity displayed" state can come from a user action (Stop / dismiss) or from passive circumstance (initial load found everything in-use elsewhere). Recovery branches that auto-adopt the next free entity must gate on a `userIdle*Ref` flag set by explicit user-clear paths and cleared by every user-initiated start/attach. The gate needs to cover every reconnect-triggered re-init path, not just the initial-load branch — a transient disconnect resets initialization flags, and an empty-list auto-start or survivor adoption can otherwise undo an explicit Stop on reconnect.+ - **Deferred work must respect both staleness and unmount.** Any `setTimeout`-scheduled side effect that emits to the network or mutates shared state needs two guards: (1) a generation counter check so user actions during the delay window abort it, and (2) a `mountedRef` so a navigation-away unmount stops it from firing into the void. Pattern: `const mountedRef = useRef(true); useEffect(() => () => { mountedRef.current = false; }, []);` — never reset to `true` (handles dev-mode double-mount cleanly). Without the unmount guard, a deferred socket emit can claim a resource (e.g. shell session) with no listener left to render it.## Tailwind Design Tokens