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

25.0 KB
Raw Blame

client/src/utils/ — pure formatting & compute helpers

Lightweight, mostly-pure helpers used by pages, components, and hooks: formatters, time math, small functional utilities, the OpenWorld scene-compute functions, and a few thin browser-storage / file-read / module-loading helpers. Before writing a helper here, grep this catalog first — many domain patterns already have one. When you add a new module, add it to index.js AND add a row here.

State + lifecycle hooks live in client/src/hooks/. Shared client helpers with prompt/canon logic (and server mirrors) live in client/src/lib/. HTTP/socket clients live in client/src/services/.

Discovery rule

grep -i "what you want to do" client/src/utils/README.md

Formatting & time

Module Purpose
trackOptionLabels trackOptionLabels(tracks) — ID-keyed library option labels with title, artist, duration, creation date, missing-audio status, and stable collision-resolving ID suffixes. Build before filtering selector eligibility.
formatters Date/time/duration/byte formatters (clamp, shortClaudeModelName (Claude model id → display name; strips claude- and only an 8-digit date suffix, so sonnet-5-5 survives), formatBytes, formatDownloadGb (decimal-GB model download size, "29 GB"), formatCompactCount, formatCompactCountOrDash (same, but an ABSENT count renders "—" rather than "0"), formatCount (thousands-separated EXACT count, "2,762" — for a total the user is meant to read as a number, where "2.8K" would throw away the precision that is the point of showing it), timeAgo, formatAgeDays (age in whole DAYS — "412 days ago" — where timeAgo would collapse to "1y ago"; model-download lists), localDateKey (browser-local YYYY-MM-DD), shiftISODate (DST-safe calendar-day shifts), formatTimecode, formatDurationMs, formatDateShort, formatContextTokens (suffix-less context length, "4K"), throughputLabel (a measured model's speed as one label — tok/s where the runtime reported token counts, `prefixed when frame-counted, else chars/s; never both),parseTimeoutMs, formatCooldown, recommendedRamGb, nameFromImageFilename, formatUsd — one USD renderer (signedputs the minus outside the$; trimWholedrops.00on a typed round price; thousands are grouped, "$4,610.09") —formatLoudness(a mastered render's measured audio as one line, "-14.1 LUFS, peak -1.6 dB (was -27.3 LUFS)"),formatWeight/formatPercent — round unit-converted floats (170.35000000000002→170.4 lbs) so raw binary precision never reaches a tile — middleTruncate— clip a long string from the MIDDLE so its distinguishing tail survives, where CSSline-clamp/text-overflowalways eats the end — …) plus timeout-input bounds andgetAppName. Do not re-define formatters inside components. **Never write new Date(x).toLocaleDateString()inline** — pick the helper for the shape you want:formatDateNumeric("3/5/2026", compact cells),formatDateShort("Mar 5, 2026"),formatDate("March 5, 2026"),formatDateFull("Saturday, March 5, 2026"),formatWeekdayDate("Monday, Mar 5",{ weekday, year }), formatMonthDay("Mar 5"),formatMonthYear("March 2026"),formatWeekdayShort("Mon"),formatWeekdayTime("Mon, 7:00 AM"),formatTimeOfDay("1:30 PM"),formatTimeOfDaySeconds("1:30:45 PM", log/queue rows),formatClockTime("02:30:45 PM";{ seconds, hour12, timeZone }), formatDateTime. formatHourOfDay renders a bare hour-of-day number (0-23) as a 12-hour label in one of four styles (long"3 PM",compact"3PM",tiny"3p",lower"3pm") — the canonical home for what five components each hand-rolled, so the same 3pm no longer renders four ways across screens. Date display helpers anchor a bareYYYY-MM-DDat LOCAL midnight (a naivenew Date('2026-03-05')` is UTC midnight and renders as the previous day west of Greenwich) and take a fallback instead of rendering the literal "Invalid Date".
cronHelpers Cron preset list, friendly cron parsing/building, anchored recurrence parsing/building/description, isCronExpression detection, describeCron human-readable rendering, cronFromIntervalMs numeric-interval → expression conversion (mirrors the server helper), summarizeAppSchedules rendering of the per-app cron cadences a task's global row cannot express, and JOB_INTERVAL_OPTIONS / ON_DEMAND_INTERVAL — the interval-mode cadences for autonomous jobs, derived from the server's INTERVAL_OPTIONS (on-demand = stays enabled and manually runnable, but arms no timer). Import it rather than re-declaring the list in a scheduling component.
markdownText markdownToPlainText(md) — flatten markdown source to one plain-text string for a clamped preview: strips heading/list/blockquote/fence markers, unwraps emphasis, inline code and links, images → [alt], collapses blank-line runs. Use whenever a card previews arbitrary agent-authored markdown — line-clamp-N does not clamp a subtree of block elements, and foreign ## headings would otherwise join the page's heading outline. Underscore emphasis is word-boundary gated and __…__ needs interior whitespace, so stack frames and user-agent strings (10_15_7, __init__) are never silently rewritten. dropsMarkupWhenFlattened(md) — did the flatten lose actual markup, as opposed to only normalizing whitespace? Gates a "Show more" disclosure so a short-but-lossy body stays reachable without putting a toggle on every body that merely lost a trailing newline.
timeWindow Time-of-day window math (isInTimeWindow, timeStringToMinutes) and morning-layout auto-switch helpers (pickActiveLayoutId, recordManualLayoutPick).
timezone Timezone day-key helpers (dayKeyInTimezone, todayKeyInTimezone) — browser mirror of the server's todayInTimezone, so date-scoped POST surfaces derive "today" in the user's configured timezone and agree with the server (#2681).

General pure helpers

Module Purpose
animationClips Treadmill helpers for rigged GLB clips: withInPlaceClips synthesizes root-translation-stripped ("in place") variants of root-motion walk/run clips so a fixed-frame avatar can't drift; inPlaceClipName routes a clip name to its variant. Framework-agnostic (caller passes the root-motion names + suffix).
coalesce Trailing-edge coalescer: wraps a function so rapid calls collapse into one deferred invocation.
easing Interpolation easing curves — linear, easeIn, easeOut, smoothstep (ease in/out), plus the EASING_CURVES map keyed by the declarative Three.js clip contract's easing enum. Extend here rather than re-defining an easing inline.
hashString Deterministic string → 32-bit hash (stable colors, keys, seeds).
modelFit fitModelToHeight(object, { targetHeight, feetOnGround, yOffset }) — normalize a loaded GLB to a fixed on-screen height and anchor it vertically, either by bounding-box center (portrait framing) or by its lowest point (a figure standing on a ground plane). Recenters x/z, guards a zero-height model against an infinite scale, leaves a geometry-less object or a non-finite targetHeight untouched rather than writing NaN/Infinity through the transform, and resets to identity before measuring so a repeat call (StrictMode's double mount effect) converges instead of blowing the model back up. Call from an effect, never during render — a skinned mesh measures wrong before useAnimations binds the skeleton.
renderBudget Pure adaptive render-quality state machine: capability-aware startup tier (recommendStartTier), p75 frame-time windows, hysteresis, cooldown, warm-up/gap rejection (createRenderBudget, recordFrame, restartWarmup, resetRenderBudget, getEffectiveTier, QUALITY_TIERS, DEFAULT_RENDER_BUDGET_CONFIG).
sleep sleep(ms) — promise-returning setTimeout for retry backoffs and race timeouts. Use instead of re-declaring a local delay.
urlNormalize isUrl detection, normalizeUrl (optional git/requireDot modes), isHttpUrl / isHttpsUrl (safe-href checks), and tiktokVideoId / tiktokEmbedSrc (host-anchored TikTok video-id extraction + its Embed Player URL, so a reference embeds without loading TikTok's embed.js).
platform isMac detection and modKey (⌘/Ctrl) for keyboard-shortcut display.
navWorkingSet Recent/pinned nav persistence (recordVisit, togglePin, isPinned) plus resolveRecentNavEntries for mapping stored deep links back to their longest matching nav-manifest entry. Also migrateLegacyNavPath(path, commands) — maps a stored path onto the CURRENT path of the page that used to answer to it, driven by each command's own previousPaths (declared in server/lib/navManifest.js beside the page that moved, shipped whole in the palette manifest). A pin is a stored route path, so without it a moved page's pin stops matching the manifest and the sidebar row silently vanishes on update.
systemCapabilities Server-annotated hardware compatibility helpers: preserve model/provider choices when compatibility is unknown, and hide only entries whose hardwareCompatibility.state is definitively unavailable.
layeredIntelligenceReasons Canonical gloss for the Layered Intelligence loop's run-outcome reason tokens, shared by the on-demand toast and the durable "Last run" line (formatLiReason, liReasonTone, LI_NEUTRAL_REASONS).

AI providers

Provider helpers are split by the question each answers; providers.js is the compatibility facade over all of them. Grep here for the question, then import the declaring module — that is where each shared table is re-exported from its server/lib leaf.

Module Purpose
providers Compatibility facade re-exporting every helper from the nine modules below, so existing ../utils/providers imports keep working. New code imports the declaring module.
providerTypes What KIND of provider a record is: PROVIDER_TYPES (re-exported from server/lib/aiToolkit/constants.js) with isCliProvider / isTuiProvider / isApiProvider / isProcessProvider and isClaudeHarnessProvider (re-exported from server/lib/providerTypes.js, with legacy alias isClaudeCommandProvider), isLaunchableTuiProvider (a TUI provider carrying the server-resolved tuiCommandLine, i.e. one a human can start at a shell prompt — shared by the Providers card's "Launch in Shell" button and the Shell page's launch menu so the two can't disagree), enabledApiProviderFilter, enabledProcessProviderFilter (the coding/CLI-TUI-only counterpart, for a manual Claim/Replan/Resolve/Review "Run with" picker), providerTypeClass; the vendor-harness predicates keyed on the shipped ids plus commandBasename so a path-configured or renamed binary still qualifies (isCodexProvider, isCodexSubscriptionProvider — subscription readiness is keyed on the codex command, never an editable id — isAntigravityProvider, isCursorProvider, isKimiProvider, isGrokProvider, isGrokBuildCli, isClaudeCommandProvider, isOpencodeLocalProvider); and the structural backend markers a wrapper carries (localRuntimeNamespace, isOllamaBackedProvider). Everything with a server twin is re-exported from the pure leaves server/lib/providerTypes.js, server/lib/providerModels.js, server/lib/aiToolkit/constants.js and server/lib/aiToolkit/internal/ollamaBacked.js, never copied — isGrokBuildCli moved there in #7339 so the shared reviewer→provider matcher table keys on the same predicate the browser does.
providerGateways PROVIDER_GATEWAYS / gatewayById / gatewayForProvider / isGatewayBackedProvider — the hosted OpenAI-compatible gateways (orcarouter, openrouter, nvidia-nim) an OpenCode CLI/TUI wrapper can front-end, inheriting its API key at spawn time from the sibling API provider whose id equals the gateway id. Reads the generic gatewayBacked marker and, forever, the legacy per-gateway boolean. Rows with a stable vendor key page also carry keyUrl, rendered as the card's "get a key" link while the key is missing. All four are re-exported from the pure leaf server/lib/providerGateways.js.
providerRef parseProviderRef(id) / isCompositeProviderId(id) / isPresetProviderId(id) / formatCompositeId(parts) / PRESET_ID_RE / COMPOSITE_ID_RE — the shared preset-vs-composite grammar (#7566): distinguishes a preset id from a <harness>.<method>@<service-slug>[+<bootstrap-slug>] composite so useProviderCatalog's resolveRef and ProviderComposePopover recognize the same strings the server does. Re-exported from the pure leaf server/lib/providerRef.js, never copied.
providerHarnesses harnessLabel(harnessId) — the display name for an agent program PortOS drives (Claude Code, OpenCode, Codex, …), used wherever a harness is named (the preset-first pickers, the composition catalog hook), where null means Direct API and an unknown id renders verbatim rather than disappearing. Read through harnessById from the pure leaf server/lib/providerHarnesses.js, so a harness added to the registry is named here without a second edit. Also providerHarnessId(provider) (a derived preset's own harnessId, else the server's harnessForProvider classification) and groupProvidersByHarness(providers) — the { harnessId, label, providers } buckets in registry order (Direct API after the agent harnesses, an Other bucket last) that the preset-first ProviderModelSelector renders as <optgroup>s (#7566) and the AI Providers page renders as its preset sections (#7567). presetEditPath(presetId) — the preset editor URL (/ai/presets/:id), falling back to the kept /ai/edit/:id alias for the one id (new) the static create route shadows.
providerEndpoints WHERE a provider's endpoint points. isLocalEndpoint (loopback), isPrivateNetworkEndpoint (RFC1918 / tailnet address, or a .local / .ts.net / single-label host — somewhere an unauthenticated OpenAI-compatible server is a normal setup rather than a missing API key), isLocalInstanceProvider (talks to a daemon on THIS machine; mirror of server/lib/localProviderRuntime.js#isLocalInstanceEndpoint — gate anything that explains a provider by inspecting the host PortOS runs on), isFleetProvider / isFleetHostConfigured (another machine inside the private network), and localBackendForProvider ('ollama' / 'lmstudio' / null by id, endpoint or name — it matches by NAME, so pair it with isLocalInstanceProvider before claiming this machine's install state).
providerModels Which MODEL and EFFORT a run resolves to, and what a picker may list. sortProviderModels alphabetizes display options by name/id without mutating the catalog. The configured-default sentinels (CODEX_CONFIGURED_DEFAULT …, isConfiguredDefaultModel, configuredDefaultIn — so a picker can render an option matching a sentinel-valued tier instead of a blank select) and filterSelectableModels; the per-CLI effort ladders, effortLevelsForProvider, resolveCliEffort (what a stored effort actually runs as, so the picker can name a clamped level), effortSurvivingModel and seedModelEffort; the Antigravity base-model ↔ effort-suffix split (splitAntigravityModel, antigravityBaseModels, antigravityModelEffortLevels, withStaleAntigravityPin); the account-aware option list (providerModelList, resolveProviderModelOptions, effortAwareModelOptions, MODEL_SOURCE — the one place a Codex-subscription account catalog enters a picker); effectiveModelFor; mergeModelLists / mergeProviderUpdate; and generationControlsFor (which temperature / top-p / thinking controls a provider forwards at all). The sentinels, effort ladders and the Antigravity split are re-exported from the pure leaf server/lib/providerModels.js; effortLevelsForProvider / resolveCliEffort delegate to the server's and add the ladder a sanitized provider inventory publishes, clamped through the server's clampEffortToLadder. The generation-control tables still mirror server/lib/opencodeConfig.js.
providerSelection Which providers and models a picker may OFFER on this install: isProviderHardwareCompatible / isProviderModelHardwareCompatible / filterHardwareCompatibleProviderModels (server-annotated, fail-open), selectableProviders (the single rule ProviderModelSelector renders from), filterRunnableProviders (agent jobs need a CLI/TUI harness), supportsToolFreeOneShot / toolFreeOneShotSelectionPolicy (API or server-verified tool-free CLI authoring; excludes TUI and unverified composite routes), supportsStrictToolFreeOneShot / strictToolFreeOneShotSelectionPolicy (the same without read-only-sandboxed authoring CLIs, mirroring the server's isToolFreeOneShotProvider), the fail-closed tool-free local policy (TOOL_FREE_LOCAL_PROVIDER_IDS, TOOL_FREE_LOCAL_TEXT_CAPABILITIES, isToolFreeLocalProvider, isToolFreeLocalModel, toolFreeLocalSelectionPolicy) used by security-sensitive pickers, and the pr-reviewer postures (PUBLIC_REVIEW_NO_TOOL_POSTURE / PUBLIC_REVIEW_ACTIONS_POSTURE, supportsPublicReviewPosture, enforcesPublicReviewPosture, publicReviewSelectionPolicy — mirror of server/lib/agentExecutionProfiles.js: a pipeline stage names a POSTURE, the server publishes each provider's publicReviewPostures and publicReviewEnforcedPostures on GET /api/providers, and the picker offers exactly the providers this install can run the stage on, so no vendor is named on either side). Also the caller EXECUTION-MODE picker rule (callerModeList, providerModeSelectionPolicy — whose modes also bound the selector's compose flow) and COMPOSE_OPTION_VALUE, the "Custom combination…" action sentinel outside both provider-id grammars (#7566), over server/lib/callerModePolicy.js — the server enforces the policy on the pin, on activeProvider inheritance and on every fallback candidate; this only lets a picker SHOW the rule, keeping an ineligible saved value visible-but-disabled instead of hidden or silently replaced — read off CALLER_MODE_POLICIES in that pure leaf, so it cannot drift).
localModelHeuristics What an untyped LOCAL model can do, judged from its id: isEmbeddingModel / isVisionModel / isToolUseModel (re-exported from the pure leaf server/lib/localModelHeuristics.js — one regex per family; a model card's explicit capability metadata outranks the id regex), isVisionCapableCliProvider, filterGenerationModels (sentinels and embedding-only models dropped), visionLocalModelFilter and localToolUseHint / withToolUseOptionLabel (unioned with the server's authoritative per-provider capability maps from useVisionModelIds / useToolUseModelIds; tool-use is an annotation plus warning, never a filter), and modelCapabilityInfo (capability badges for a selected model without over-sharing a local runtime's answer with another provider).
providerContextWindows How large a context window a provider/model gets for planning and where the number came from: the vendor constants and the KNOWN_MODEL_CONTEXT_WINDOWS ladder (knownModelContextWindow, knownProviderContextWindow), catalogModelContextWindow (the window the provider's own /models catalog reported), resolveModelContextWindow → { tokens, source } with CONTEXT_WINDOW_SOURCE (override / reported / assumed — the state a card has to label rather than print as fact), effectiveModelContextWindow, and modelOptionLabel ("id (32K ctx)"). The constants and the known-model / known-provider / catalog rungs are re-exported from the pure leaf server/lib/providerContextWindows.js, the same rungs the server's effectiveContextWindow budgets with — including mergeObservedContextWindows, which folds a local daemon's live window (off the readiness payload) onto the catalog rung so the card shows what the dispatch gate enforces, and holds every resolved window down to an Ollama daemon's launch num_ctx through clampToRuntimeContextWindow (applied internally, from server/lib/aiToolkit/internal/ollamaBacked.js — the same module the server's budgeter and pre-dispatch gate use), so the meter can't promise a budget a run would be refused for (#7466). withRuntimeContextWindow(provider, ceiling) stamps that ceiling's second rung — the ambient OLLAMA_CONTEXT_LENGTH the server launched the daemon with, which the browser cannot read and so takes off the readiness payload as runtimeContextWindow (#7472).
providerModelAccess Which of a provider's advertised catalog this install is entitled to run (free tier, plan, hand-picked allowlist). Re-exports the policy rules the browser consumes from the pure leaf server/lib/aiToolkit/internal/modelAccess.js — MODEL_ACCESS_MODES, MAX_MODEL_ACCESS_PATTERNS, CONFIGURED_MODEL_KEYS, normalizeModelAccess, modelMatchesAccessPatterns — so the editor's live preview and the server's own scoping cannot disagree. Adds providerModelCatalog(provider) (the FULL list, off modelCatalog when the payload was scoped — seed a model editor from this or a Save persists the narrowed list), previewModelAccess(catalog, policy, configuredModels) → { total, visibleCount, hidden, inert }, configuredModelsOf, NO_MODEL_ACCESS and MODEL_ACCESS_MODE_LABELS. applyModelAccess is deliberately NOT re-exported: a client payload is already scoped, and re-scoping would overwrite modelCatalog with the narrowed list.
providerReadiness Is a provider READY to run on this install, and why not. credentialSource (stored / inherited / env / subscription / none) and providerCardState(provider, { runtime, status, keySetFor, envVarSet, codexAccount }) + PROVIDER_CARD_STATE — ready, benched, blocked on a missing prerequisite (CLI not installed / API key absent / empty credential env var / signed-out ChatGPT account), unknown, or simply switched off. Reads the SERVER's missingPrerequisites (published per provider on GET /api/providers from server/lib/providerPrerequisites.js, the same computation getFallbackProvider routes on) and adds only what the browser can see; unknown lookup values mean "not probed", never "missing". Distinct from ProviderReadiness / GET /api/providers/readiness, which probes the local daemon behind a provider. Also isRunnerAllowedCommand(command, allowedCommands) — would the CoS Agent Runner accept this command? Mirrors only the normalization in server/cos-runner/allowedCommands.js (the list arrives as runnerAllowedCommands on GET /api/providers); returns null for "list not fetched" so a failed fetch never renders a warning; pinned by server/cos-runner/allowedCommands.parity.test.js. resolvesOutsidePortosPath / providerRuntimeKey (the key a CLI runtime is published under by GET /api/providers/runtimes), supportsModelRefresh (canRefreshModels === true, the server's own answer) and codexRoutingAdvisory (the non-blocking "your ~/.codex/config.toml re-points Codex" notice — server-only and machine-local, rendered in the UI and nowhere else).
providerAssignments Which provider/model a RECORD resolves to, and the option helpers the assignment editors share: resolveEffectiveProvider (its pin, else the active provider, plus whether it fell back so a "Default" option can name what it resolves to), resolveSeriesRunLlm (mirror of server/lib/seriesLlmOverride.js: per-run override → series.llm → active provider), getProviderTimeout, providerDisplayName and providerModelLabel (the one "Provider / model" phrasing), and assignmentProviderOptions / assignmentModelOptions / assignmentDefaultModel / assignmentToolUseState over the getAiAssignments payload shape — shared by the global AI Assignments table and every per-record override drawer so none of them derives the rule differently.

Module loading / resilience

Module Purpose
lazyWithReload React.lazy wrapper that retries transient import failures and reloads only when a failed chunk belongs to an older build; the route error screen can explicitly purge PortOS asset caches before retrying a runtime import failure.
staleChunkReload Detects stale import/runtime-export errors at import and render boundaries, confirms a newer served build before automatic reload, and purges PortOS caches for that recovery; an explicit route-error retry can also purge them when the live shell is reachable.

File handling

Module Purpose
fileUpload Pure screenshot/attachment upload helpers: base64 read (readFileAsBase64) and image validation (validateImageFile). Also the shared upload constants — JSON_UPLOAD_MAX_FILE_SIZE (max file size / wire limit, mirrors server/lib/uploadLimits.js), ATTACHMENT_MAX_FILE_SIZE, ALLOWED_ATTACHMENT_EXTENSIONS, and the accept strings ATTACHMENT_ACCEPT / IMAGE_ACCEPT / UPLOAD_IMAGE_ACCEPT. The actual upload orchestration (processScreenshotUploads / processAttachmentUploads and their single-file variants) does network I/O and lives in services/apiMedia.js — import those from there, not from here.

OpenWorld — character & avatar

Module Purpose
characterXp Character age and birthday-progress helpers: computeAgeView, diffXp, birthDateCta, and legacy levelFromXP.