Skip to content

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

24.9 KB
Raw Blame

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/id pairing - when adding a settings/config form field, wire <label htmlFor="..."> to an id="..." on the input — screen readers and click-to-focus both depend on the association. The visual block/mb-1 styling 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-N with 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 by client/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-flex must yield it to a caller's own display utility. Tailwind v4 emits display utilities in alphabetical order, so .inline-flex lands AFTER .hidden in 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. Pill handles this (see OWN_DISPLAY in components/ui/Pill.jsx); InfoTooltip, CopyableId, and ProvenanceChip still interpolate className after a hardcoded inline-flex and need the same treatment the first time one of them is given a hidden md: call site. Primitives baking flex/grid are not exposed — those sort BEFORE .hidden and 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-64 and up, or the same size as an arbitrary w-[19rem]) must also carry max-w-[calc(100vw-1rem)]. Layout's root shell is overflow-x-hidden, so anything wider than the viewport is clipped away, not made scrollable: a w-96 filter panel anchored right-3 on a 360px phone puts its whole left column of controls permanently off-screen with nothing to scroll to. The calc(100vw-1rem) form (not 90vw) 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 by client/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. Pass mobileCompact to TabPills and it renders the same tab buttons icon-only below sm (label kept as max-sm:sr-only, so the accessible name never changes) with a chevron at whichever edge is still scrollable. RouteTabsHeader decides whether to collapse (past MOBILE_COMPACT_THRESHOLD tabs); TabPills decides 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 via buildSectionNavTabs(getSectionNavTabs(s), NAV_PRESENTATION, s), which throws on a missing one; client/src/lib/navPresentation.test.js pins 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 in pages/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 a border-b-2 tab strip outside TabPills and allowlists the few underlines that are not section sub-navs (comment-anchored manuscript prose). Reuse TabPills; never roll a new tab bar.
  • 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.hostname for 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-strong for a small label directly on photography; .port-media-overlay-item for its buttons, .port-media-overlay-divider for its separators — all defined in index.css, which carries the mechanism and the rule for picking between this, .always-dark, and the OpenWorld HUD remap). Don't write bg-black/NN + text-white/text-gray-N00 for 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.jsx are 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 are utils/openWorld*.js, its hooks are useOpenWorld*.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 persisted portos-city-settings key 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 shared shouldIgnoreGlobalKey(event, opts) predicate in lib/a11yKeyboard.js, so a new guard goes THERE, never at one caller (that drift is what let useKeyCapture swallow button activation, #4748). The corollary: a surface that OWNS a key spreads noPointerFocusSurfaceProps on 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, not disabled — disabled drops focus) and filter e.repeat in its handler, or put Enter-to-advance in a window handler gated on shouldIgnoreGlobalKey (which drops auto-repeat for you) and leave the button unfocused. MorseTrainer.jsx takes the first shape, PostDrillRunner.jsx the 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/sessionStorage throw 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, so typeof sessionStorage === 'undefined' is not a guard and neither is ?. (it only covers a null base, not a throwing getItem). Use safeReadStorage / safeWriteStorage / safeRemoveStorage and their Json and *Session variants. 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 by client/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 in server/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 uses useAutoRefetch(fetchFn, intervalMs, { enabled, pollOnly: true }) (hooks/useAutoRefetch.js), never a hand-rolled useEffect + setInterval. The hook skips its tick while document.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 as enabled rather than an early return, and pass immediate: false when another effect already owns the first fetch. Enforced tree-wide by client/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 - a useState pair, useCallback, or const named setInterval / setTimeout / clearInterval / clearTimeout / requestAnimationFrame / cancelAnimationFrame / fetch shadows 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 by client/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, every set* 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, so WorkEditor enriched 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 by client/src/asyncEffectDisposalConventions.test.js, which allowlists the few deps that cannot select a different record (a drawer open flag, 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 unseparated 4610 is 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 renders 0; formatCount gives — 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 by client/src/numberFormattingConventions.test.js — any new bare .toLocaleString( call under client/src fails CI. Other formatters (formatBytes, timeAgo, …) live beside them — see the helper catalog in the root AGENTS.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 with preventScroll. 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 in client/src/services/apiCore.js toasts errors by default. When a caller already owns its error UI — via useAsyncAction (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 an options parameter so callers can opt in. Custom catch ⇒ silent: true, or the user sees two toasts back to back; no custom toast ⇒ omit silent and 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>Saving boolean, set it before the PATCH, clear it in .finally(). Canonical example: lengthProfileSaving in client/src/pages/PipelineIssue.jsx.

Routing and deep linking

  • Linkable routes for all views - tabbed pages use URL params, not local state (e.g., /devtools/history not /devtools with 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 local useState/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 handlers navigate() to the id'd route; deletes/clears navigate() back to the index; render a "not found" fallback for stale/deleted ids. Add both the bare index route and the :id detail route in App.jsx, and keep the base path registered in NAV_COMMANDS.
  • New page → pick the right Layout scroll mode. layoutRoutes.js classifies the full-width routes used by Layout.jsx. Normal title/nav pages should use PageLayout: pass a PageHeader as header, optional TabPills/RouteTabsHeader as navigation, 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 override bodyClassName only when their panes own scrolling (CoS is the example). Intentional document/form routes such as /apps/create may 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. See docs/PAGE_LAYOUT_AUDIT.md for 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 Drawer convention. Slide-in "settings over a feature page" surfaces use the shared client/src/components/Drawer.jsx primitive — never a hand-rolled fixed inset-y-0 right-0 clone. Follow this convention instead of dumping another page-length flat scroll into a narrow panel (the epic #1966 redesign):
    • Size. Pass size (sm 520px · md 640px · lg 720→880px · xl up to 1100px). Widen for genuinely large forms so they can lay out in columns on desktop; keep small dialogs at sm. Mobile is always w-full (full-screen sheet) regardless of size — mobile-responsive is non-negotiable. widthClass is a back-compat escape hatch that overrides size.
    • 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 / onTabChange and render only the active tab's fields as children — 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's grouped prop 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 (see EditAppDrawer.jsx's state-hoisting comment). Validate fields on tabs that may be unmounted at Save time explicitly, and setActiveTab() to the offending tab to surface the error.
    • Mobile collapse + TabPills. The tab bar is client/src/components/ui/TabPills.jsx (mobileCompact collapses it under sm) — reuse it, never roll a new tab bar. The Drawer tabs layout wires TabPills for you; a surface hosted in both a drawer and a page (like ImageGenTab) renders its own internal <TabPills variant="pills" mobileCompact> instead so the same grouping works in either host. See the sub-nav rule below for what mobileCompact renders.
    • Deep-linkable active tab. Drive activeTab from a URL search param via useDrawerTab(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 to defaultTab instead 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 both position:fixed, and a filter / backdrop-filter / transform ancestor becomes their containing block; on the "glass" themes index.css gives every bordered/rounded .bg-port-card a backdrop-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-themed in index.css): a caller inside one must pass that class as portalClassName (the prop is documented on Drawer.jsx). Same trap, same fix, for any new hand-rolled fixed inset-0 overlay — portal it (Modal's usePortal, GalleryImagePicker.jsx).
    • Worked examples: client/src/components/apps/EditAppDrawer.jsx (built-in tabs layout, size="lg", useDrawerTab('appTab', …)) and client/src/components/settings/ImageGenTab.jsx (internal TabPills variant="pills" sub-tabs, useDrawerTab('mediaTab', …)). The primitive is Drawer.jsx; the design record is docs/plans/2026-07-01-drawer-ux-redesign.md.

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.