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
Client conventions (client/src/)
These apply to React/Vite client code. Universal constraints (functional programming, no try/catch, single-line logging, Zod validation, the Security Model, and the Sensitive Data & Privacy rules) live in the root AGENTS.md and always apply.
UI conventions
- Display timestamps in browser-local time — use the shared date/time formatters in
utils/formatters.js; never render an ISO/UTC serialization as a display timestamp. Keep ISO timestamps for transport and persistence. Explicit schedule timezones and date-keyed reporting boundaries retain their domain semantics. - Admin workspace design — for new or redesigned admin pages, follow the workspace design guide: choose a page family, put useful work first, use desktop width for related work/evidence, and preserve icon-prefixed desktop navigation plus CoS-style compact mobile icon rows. Apply incrementally; the guide does not authorize unrelated behavior changes or a global CSS rewrite.
- No window.alert/confirm - use inline confirmations or toast notifications
- Form labels need
htmlFor/idpairing - when adding a settings/config form field, wire<label htmlFor="...">to anid="..."on the input — screen readers and click-to-focus both depend on the association. The visualblock/mb-1styling alone doesn't establish it. - Narrow containers on desktop — follow the narrow-container acceptance contract. Sidebar-reduced pages and dashboard tiles need container queries, shrinkable grid/flex children, wrapping actions and long-string handling. Verify child rectangles as well as scroll dimensions; hiding overflow is not a fix.
- Mobile responsive - all pages should be mobile responsive friendly. A
grid-cols-Nwith N > 3 and no…:grid-cols-*anywhere in the same class string is a bug, not a style nit: at 360px a four-up stat bar gives each card ~65px of outer width, so its label wraps to five lines and the whole above-the-fold region is unreadable. Give text-bearing cards a narrow phone default and let the viewport opt into the wide layout (grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-4); a widened gap (gap-4 sm:gap-6) is not a column breakpoint. A grid of square thumbnails or heatmap cells may stay four-plus wide on a phone, but it still needs a column breakpoint so the desktop isn't stuck at the phone count. Enforced tree-wide byclient/src/responsiveGridConventions.test.js, which carries the allowlist for the few grids that really are frozen N-across (a seven-day month grid, the fixed five-trait Big Five bars). - A shared primitive that bakes in
inline-flexmust yield it to a caller's own display utility. Tailwind v4 emits display utilities in alphabetical order, so.inline-flexlands AFTER.hiddenin the stylesheet and wins at equal specificity: a<Pill className="hidden sm:inline-flex">stayed visible at every width, and the responsive variant it was paired with did nothing.Pillhandles this (seeOWN_DISPLAYincomponents/ui/Pill.jsx);InfoTooltip,CopyableId, andProvenanceChipstill interpolateclassNameafter a hardcodedinline-flexand need the same treatment the first time one of them is given ahidden md:call site. Primitives bakingflex/gridare not exposed — those sort BEFORE.hiddenand lose to it correctly. - A fixed-width popover carries a viewport clamp - an absolutely-positioned panel whose width is fixed at 256px or more (
w-64and up, or the same size as an arbitraryw-[19rem]) must also carrymax-w-[calc(100vw-1rem)].Layout's root shell isoverflow-x-hidden, so anything wider than the viewport is clipped away, not made scrollable: aw-96filter panel anchoredright-3on a 360px phone puts its whole left column of controls permanently off-screen with nothing to scroll to. Thecalc(100vw-1rem)form (not90vw) is the standard because it holds an 8px gutter at every width instead of a proportional one that collapses on small screens. Enforced tree-wide byclient/src/popoverClampConventions.test.js. - Size form fields for their content. Short selects, numeric inputs, and related settings should share rows when the container has room, then stack on narrow screens or drawers. Prefer wrapping grids with bounded columns (for example
grid-cols-[repeat(auto-fit,minmax(min(100%,18rem),24rem))]) over full-page-width controls. Keep labels and help text with their fields, preserve DOM/tab order, and leave prose editors and long paths room to work. Avoid global input width limits; compact toolbars and narrow panels have different needs. - A sub-nav that doesn't fit a phone collapses to ICON LINKS, not a
<select>- this is a stated product preference, not a judgement call to re-make per page: a dropdown reads as a form control and hides where you are behind a tap, while an icon row still looks and behaves like navigation and keeps every destination one tap away. PassmobileCompacttoTabPillsand it renders the same tab buttons icon-only belowsm(label kept asmax-sm:sr-only, so the accessible name never changes) with a chevron at whichever edge is still scrollable.RouteTabsHeaderdecides whether to collapse (pastMOBILE_COMPACT_THRESHOLDtabs);TabPillsdecides how. #7283 made the<select>universal and was reverted — don't reintroduce it as "consistency". Corollaries:- Every tab in a fixed set of sections needs an icon, and no two in one bar may share one. One iconless tab drops the whole bar back to the
<select>, and on a phone the icon is all the user sees, so a repeated glyph is a repeated destination. Section tabs get theirs from the sidebar registry viabuildSectionNavTabs(getSectionNavTabs(s), NAV_PRESENTATION, s), which throws on a missing one;client/src/lib/navPresentation.test.jspins coverage and uniqueness for every section. - The
<select>fallback is for lists icons can't serve — an unbounded, data-driven one where every entry would draw the same glyph (FableLoomStory's episode list). Not for a fixed set of sections someone hasn't given icons yet. Unbounded record pickers that happen to be<select>s (the account switchers inpages/X.jsx,pages/StackerNews.jsx) are not sub-navs and are out of scope. - Enforced tree-wide by
client/src/subNavConventions.test.js, which flags aborder-b-2tab strip outsideTabPillsand allowlists the few underlines that are not section sub-navs (comment-anchored manuscript prose). ReuseTabPills; never roll a new tab bar.
- Every tab in a fixed set of sections needs an icon, and no two in one bar may share one. One iconless tab drops the whole bar back to the
- Above the fold - keep actionable content and info above the fold and design pages for maximum information and access without scrolling
- No hardcoded localhost - use
window.location.hostnamefor URLs; app accessed via Tailscale remotely - Chrome floating over media uses
.port-media-overlay- a label, status bar, badge, or control panel sitting on top of an image, a video, or a 3D canvas takes its surface and ink from the theme (.port-media-overlay, or.port-media-overlay-strongfor a small label directly on photography;.port-media-overlay-itemfor its buttons,.port-media-overlay-dividerfor its separators — all defined inindex.css, which carries the mechanism and the rule for picking between this,.always-dark, and the OpenWorld HUD remap). Don't writebg-black/NN+text-white/text-gray-N00for this — day mode remaps the text to the theme's dark ink while the black scrim stays black, so the label renders dark-on-black. Older overlays outside the 3D/Three.js pages still carry that idiom (migration tracked in #3796), so match the new convention rather than the nearest neighbor. - Alphabetical navigation - sidebar nav items in
Layout.jsxare alphabetically ordered after the Dashboard+OpenWorld top section and separator; children within collapsible sections are also alphabetical - OpenWorld's internal names match the user-facing area. The scene tree lives under
components/openworld/, its pure helpers areutils/openWorld*.js, its hooks areuseOpenWorld*.js, and its CSS scope is.openworld-themed. The legacy OpenWorld command ids remain deliberately frozen because they are opaque values persisted in ⌘K history. Keep the persistedportos-city-settingskey unchanged when adding settings migrations. - Space is an app-global hotkey - the voice widget binds Space for push-to-talk. A surface that owns Space itself (a timed drill, a keyer, a transport control) must claim it with
useKeyCapture(capture phase +stopImmediatePropagation), or the mic opens on every press. Conversely, a global single-key handler stands down when the browser is about to activate a focused button. All three global key paths —useKeyCapture,useKeyboardShortcuts, and the voice widget's own hotkey listener — decide that through the one sharedshouldIgnoreGlobalKey(event, opts)predicate inlib/a11yKeyboard.js, so a new guard goes THERE, never at one caller (that drift is what letuseKeyCaptureswallow button activation, #4748). The corollary: a surface that OWNS a key spreadsnoPointerFocusSurfacePropson its ROOT — a mouse click that parks focus on any button inside silently takes that key over, because the global handler correctly stands down for native activation. Put it on the root, not on each button, so controls added later are covered without anyone having to remember. - A control that appears in response to a key-submit is never
autoFocused - the Enter that submitted is still down when the new control mounts and takes focus, so the browser activates it off that same keystroke (its keypress/keyup, or the first auto-repeat) and the thing it was meant to reveal is gone in the tick it appeared. This is not a flicker nit: a Morse copy round showed a right/wrong verdict per question that no user ever saw, so a two-character drill stayed a coin flip. Keep the submitting element focused (readOnly, notdisabled— disabled drops focus) and filtere.repeatin its handler, or put Enter-to-advance in a window handler gated onshouldIgnoreGlobalKey(which drops auto-repeat for you) and leave the button unfocused.MorseTrainer.jsxtakes the first shape,PostDrillRunner.jsxthe second; a verdict gated behind a network round-trip is latent only, because Enter is long released by then. - Web Storage goes through
lib/safeStorage.js-localStorage/sessionStoragethrow rather than returning null in Safari private browsing, with cookies disabled, in a sandboxed iframe, and at quota — and in several of those the object still exists, sotypeof sessionStorage === 'undefined'is not a guard and neither is?.(it only covers a null base, not a throwinggetItem). UsesafeReadStorage/safeWriteStorage/safeRemoveStorageand theirJsonand*Sessionvariants. This is not a lost-preference nit: a raw read in a render body is a render-phase exception that unmounts the whole route, and a raw write in an effect kills the flow mid-session (#5689). Enforced tree-wide byclient/src/storageConventions.test.js. - API polling is an anti-pattern — push, don't poll. Fetch once, then update from Socket.IO events (
useSocketSubscription, the media-job hooks) and apply your own mutation's response to local state immediately; never re-fetch on a timer or spin waiting for one. A change with no event gets a server emit (declared inserver/lib/socketEventContracts.js), not a client poll. Contract and the narrow exceptions (hardware telemetry, external systems with no callback, PortOS self-restart): Realtime updates, not polling. - A sanctioned poll goes through
useAutoRefetch- a view that re-fetches on a timer usesuseAutoRefetch(fetchFn, intervalMs, { enabled, pollOnly: true })(hooks/useAutoRefetch.js), never a hand-rolleduseEffect+setInterval. The hook skips its tick whiledocument.visibilityState === 'hidden'and re-fires once on the way back; a raw interval keeps hammering the server from a background tab, and PortOS is routinely left open on a second machine over the tailnet (#5697). Keep the site's existing gate asenabledrather than an earlyreturn, and passimmediate: falsewhen another effect already owns the first fetch. Enforced tree-wide byclient/src/pollingConventions.test.js, which allowlists the local timers that are not polls (clock ticks, frame advances, a bounded self-cancelling poll). - No local binding shadows a timer or
fetch- auseStatepair,useCallback, orconstnamedsetInterval/setTimeout/clearInterval/clearTimeout/requestAnimationFrame/cancelAnimationFrame/fetchshadows that global for the whole component body, so a timer or fetch added to the same scope later silently calls the local instead — no throw, no lint error, just a state setter that stores a callback (#5728). Name the binding for what it holds (intervalPreset,timeoutMinutes,loadRefs). Enforced tree-wide byclient/src/globalShadowConventions.test.js, which has no allowlist; idiomatic React state like[open, setOpen]/[status, setStatus]is deliberately out of scope because nothing here calls those globals bare. - An async effect keyed to a switchable identity drops a superseded response - an effect that fetches on a dependency and writes the answer into state needs a disposal guard:
let active = true;at the top, everyset*gated on it,return () => { active = false; };. Without it, switching the record faster than the request resolves renders the previous record's data under the current one — and it does not self-correct where the value is passed down as a controlled prop, soWorkEditorenriched one work's persisted storyboard images with another's characters and places (#7242, after #6996–#7000 were each fixed as a single site).useMounted()does not cover this — the component never unmounted, only its subject changed. Where the response must be matched against the newest request rather than merely dropped — notably when the effect writes a state value that is itself in its own dependency array, so a lifetime-scoped flag would be flipped by its own cleanup — bump and compare a generation ref instead (IngredientPicker.jsx). Enforced tree-wide byclient/src/asyncEffectDisposalConventions.test.js, which allowlists the few deps that cannot select a different record (a draweropenflag, a once-only latch). - User-facing counts and amounts go through
formatCount/formatUsd(utils/formatters.js) — thousands-grouped and en-US-pinned (2,762,$4,610.09). An unseparated4610is read at the wrong order of magnitude, and a bare.toLocaleString()follows the browser locale, which then disagrees with the$beside it. A measured zero already renders0;formatCountgives—only for a value that is missing or unparseable, so pass{ fallback: '0' }just where an ABSENT count should still read as zero. Enforced tree-wide byclient/src/numberFormattingConventions.test.js— any new bare.toLocaleString(call underclient/srcfails CI. Other formatters (formatBytes,timeAgo, …) live beside them — see the helper catalog in the rootAGENTS.md. - List deletion preserves place — after the server confirms success, collapse the affected row and its spacing with
components/ui/CollapsibleListItem, then remove it from local state. Keep the list/scroll container mounted, retain filters and pagination, and refresh counts separately. Never replace populated content with a loading placeholder for a deletion. Keep failures visible, guard duplicate requests, honor reduced motion, and move focus to a surviving row/container withpreventScroll. Put spacing inside the collapsing wrapper rather than parent gaps. - Reactive UI updates - after mutations (delete, create, update), update local state directly instead of refetching the entire list from the server. Use
setState(prev => prev.filter(...))or similar patterns for immediate feedback
API errors and save gating
- Silent vs. toasting API requests. The
request()helper inclient/src/services/apiCore.jstoasts errors by default. When a caller already owns its error UI — viauseAsyncAction(which toasts on throw) or a.catch(() => fallback)that intentionally swallows the failure — pass{ silent: true }so the toast fires from one layer only. Give new API wrappers anoptionsparameter so callers can opt in. Custom catch ⇒silent: true, or the user sees two toasts back to back; no custom toast ⇒ omitsilentand let the helper handle it. - "Run Now" actions gate on saved state, not the form input. When a settings page has a companion "Run this now" button that triggers server work reading server-side settings, gate the button on the saved value: track a parallel
saved*state per dependent setting, update it on successful save, and disable the action while the form is dirty or a save is in flight. A tooltip-only warning is missed on touch and produces "I edited X and ran, but X didn't apply" bugs. - In-flight saves gate dependent actions, not just the form. When a field's PATCH is async and a button triggers server work that reads that field (auto-run, regenerate), disable the button while the PATCH is in flight — not merely while the input is dirty. Otherwise the user picks a value, the input clears, and they click before the server has persisted it. Track a
<field>Savingboolean, set it before the PATCH, clear it in.finally(). Canonical example:lengthProfileSavinginclient/src/pages/PipelineIssue.jsx.
Routing and deep linking
- Linkable routes for all views - tabbed pages use URL params, not local state (e.g.,
/devtools/historynot/devtoolswith tab state) - ID-based deep linking for every selectable UI element - any view that opens/selects a specific record (a project, item, scene, detail, editor, or master-detail selection) MUST encode that selection in the URL via a route param (
/music-video/:projectId,/media/timeline/:projectId,/media/creative-director/:id/:tab) — never in localuseState/selectedId. The URL is the single source of truth for "what is open," so every element is directly shareable, bookmarkable, and reachable from ⌘K, voice nav, and media job-completion hooks. Selection handlersnavigate()to the id'd route; deletes/clearsnavigate()back to the index; render a "not found" fallback for stale/deleted ids. Add both the bare index route and the:iddetail route inApp.jsx, and keep the base path registered inNAV_COMMANDS. - New page → pick the right Layout scroll mode.
layoutRoutes.jsclassifies the full-width routes used byLayout.jsx. Normal title/nav pages should usePageLayout: pass aPageHeaderasheader, optionalTabPills/RouteTabsHeaderasnavigation, and keep content inside the padded, internally scrolling body. Register the route as full-width so Layout does not add a second gutter/scroller. Chrome has no outer margin or padding; its own label/button padding stays intact. Keep bounded reading widths inside the body. Editors may overridebodyClassNameonly when their panes own scrolling (CoS is the example). Intentional document/form routes such as/apps/createmay keep Layout's default padded scroller; do not classify them full-width without an internal scroll owner. Match path boundaries when adding rules so an index change does not silently change a different detail component. Seedocs/PAGE_LAYOUT_AUDIT.mdfor the audited exceptions.
For the full "adding a new page" checklist (nav manifest entry shape, palette actions, voice aliases), invoke the portos-add-page skill.
Config drawers
- Config drawers → the shared tabbed
Drawerconvention. Slide-in "settings over a feature page" surfaces use the sharedclient/src/components/Drawer.jsxprimitive — never a hand-rolledfixed inset-y-0 right-0clone. Follow this convention instead of dumping another page-length flat scroll into a narrow panel (the epic #1966 redesign):- Size. Pass
size(sm520px ·md640px ·lg720→880px ·xlup to 1100px). Widen for genuinely large forms so they can lay out in columns on desktop; keep small dialogs atsm. Mobile is alwaysw-full(full-screen sheet) regardless ofsize— mobile-responsive is non-negotiable.widthClassis a back-compat escape hatch that overridessize. - When to tab. A large config surface (many fields / logical groups, e.g. Edit App's ~25 fields) should group its fields into
tabs={[{ id, label, icon?, count? }]}+activeTab/onTabChangeand render only the active tab's fields aschildren— not one page-length scroll. A medium form that should stay fully visible above the fold uses the child's own labeled sections instead (e.g.ImageGenSettingsForm'sgroupedprop in the pipeline image-gen drawers), because tabs hide inactive fields behind a click. - Per-tab scroll. The drawer gives each tab its own scroll region that resets on switch (
key={currentTab}remounts the panel) — so no single tab is ever page-length. Because the body remounts per tab, all mutable form state must live above the Drawer body in the parent component, never in an uncontrolled input inside the form, or it resets on tab switch (seeEditAppDrawer.jsx's state-hoisting comment). Validate fields on tabs that may be unmounted at Save time explicitly, andsetActiveTab()to the offending tab to surface the error. - Mobile collapse +
TabPills. The tab bar isclient/src/components/ui/TabPills.jsx(mobileCompactcollapses it undersm) — reuse it, never roll a new tab bar. TheDrawer tabslayout wires TabPills for you; a surface hosted in both a drawer and a page (likeImageGenTab) renders its own internal<TabPills variant="pills" mobileCompact>instead so the same grouping works in either host. See the sub-nav rule below for whatmobileCompactrenders. - Deep-linkable active tab. Drive
activeTabfrom a URL search param viauseDrawerTab(paramName, defaultTab, tabIds)(client/src/hooks/useDrawerTab.js) so the open section is shareable/bookmarkable/reload-safe — the same "URL is the source of truth for what's open" rule as routed views. The caller owns the param name (appTab,mediaTab, …) so a page can host more than one drawer; pass the id list so a stale deep link degrades todefaultTabinstead of a blank panel. - Long-lived forms opt out of accidental dismissal with
closeOnEsc={false}/closeOnBackdrop={false}so an Esc keystroke mid-edit doesn't discard the form. - The overlay is always portaled to
<body>— never re-nest it. The backdrop and panel are bothposition:fixed, and afilter/backdrop-filter/transformancestor becomes their containing block; on the "glass" themesindex.cssgives every bordered/rounded.bg-port-cardabackdrop-filter, so an inline drawer nested under a card was sized to the card, not the viewport (issue #4150). Portaling is unconditional rather than an opt-in flag, so no call site has to remember it — React still routes events and context through the React tree. The one thing the portal leaves behind is a page-scoped CSS theming root written as descendant selectors (.openworld-themedinindex.css): a caller inside one must pass that class asportalClassName(the prop is documented onDrawer.jsx). Same trap, same fix, for any new hand-rolledfixed inset-0overlay — portal it (Modal'susePortal,GalleryImagePicker.jsx). - Worked examples:
client/src/components/apps/EditAppDrawer.jsx(built-intabslayout,size="lg",useDrawerTab('appTab', …)) andclient/src/components/settings/ImageGenTab.jsx(internalTabPills variant="pills"sub-tabs,useDrawerTab('mediaTab', …)). The primitive isDrawer.jsx; the design record isdocs/plans/2026-07-01-drawer-ux-redesign.md.
- Size. Pass
Large collections and incremental loading
Follow the collection-loading contract for every potentially growing list (including Brain inbox/memory, agent history, and image history). Fetch only the active route's data, start with a bounded server page, and hydrate large details on demand. Use usePagedCollection and InfiniteScrollFooter for new infinite lists; do not copy observer/request/race logic into each feature. Client-side slicing of an unbounded response is not pagination. Stable collections (apps, providers, histories) load on demand and refresh through targeted websocket invalidations and reconnect recovery, not recurring whole-list polls. Any telemetry polling must be justified, bounded, visibility-gated, and limited to an open consumer. Keep query-wide search/counts and selection URLs correct; do not silently search only loaded rows. Existing exceptions are migrated incrementally with tracker coverage.
Socket-driven UI
Socket lifecycle conventions (event-driven state swaps, single-subscriber resources, pending-request tracking, deferred-work guards) are in the portos-socket-ui skill — invoke it before wiring a new socket-driven view.