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
refactor: consolidate duplicate clamp helper across client modules (#4025)
[._.]/ Adam Eivyfc472fc2e87f
diff --git a/.changelog/next/changed-issue-4025.md b/.changelog/next/changed-issue-4025.mdnew file mode 100644index 0000000000..fd789705fc--- /dev/null+++ b/.changelog/next/changed-issue-4025.md@@ -0,0 +1 @@+- Consolidate duplicate clamp helper across client modulesdiff --git a/client/src/components/tribe/TribeCircleMap.jsx b/client/src/components/tribe/TribeCircleMap.jsxindex 9ca2d158ff..d81b9ff7da 100644--- a/client/src/components/tribe/TribeCircleMap.jsx+++ b/client/src/components/tribe/TribeCircleMap.jsx@@ -2,6 +2,7 @@ import { useMemo, useState } from 'react';import { RINGS, TRIBE_RINGS, ENERGY, STATUS_HEX, contactStatus, energyFor, initialsFor } from '../../lib/tribe.js';import { clickableProps } from '../../lib/a11yKeyboard';+import { clamp } from '../../utils/formatters.js';// Concentric-circles map of the Tribe: "Me" at the center, each Dunbar ring is a// tinted band (support innermost → village outermost) and every person is a node@@ -32,7 +33,6 @@ const nodeRadius = (i) => NODE_R[i] ?? NODE_R[NODE_R.length - 1];// Golden angle — successive nodes placed this far apart spread evenly (sunflower// packing) instead of stacking into spokes.const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));-const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));// Theme-reactive SVG colors. Hardcoded dark hexes washed out on the day themes// (a near-white card with a dark label halo and pale-gray node text), so thesediff --git a/client/src/lib/personaTraitBlend.js b/client/src/lib/personaTraitBlend.jsindex bdab3e911c..9420e2dc70 100644--- a/client/src/lib/personaTraitBlend.js+++ b/client/src/lib/personaTraitBlend.js@@ -18,6 +18,8 @@* test file (`personaTraitBlend.test.js`) is the contract.*/+import { clamp } from '../utils/formatters.js';+// communicationProfile.formality / .verbosity live on a 1..10 scale; a persona// nudges them with a relative integer delta in this range.export const COMM_DELTA_MIN = -9;@@ -42,8 +44,6 @@ export const BIG_FIVE_LEAN = {N: { more: 'more emotionally expressive', less: 'more even-keeled and calm' }};-const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));-// Bin a delta's magnitude into slightly / notably / much against the [notably,// much] thresholds for its scale. One ladder, two scales (1..10 comm deltas use// [3, 5]; 0..1 Big-Five deltas use [0.2, 0.4]).diff --git a/client/src/pages/MediaAnnotate.jsx b/client/src/pages/MediaAnnotate.jsxindex c4cc11c9ce..a8e327c93e 100644--- a/client/src/pages/MediaAnnotate.jsx+++ b/client/src/pages/MediaAnnotate.jsx@@ -8,12 +8,12 @@ import { useAsyncAction } from '../hooks/useAsyncAction';import { uuidv4 } from '../lib/uuid';import { undoStrokes, clampSize, DEFAULT_COLOR, DEFAULT_SIZE, MIN_SIZE, MAX_SIZE } from '../lib/sketchCanvas';import { getMediaSketch, saveMediaSketch, getRegenAvailability, rerenderWithAnnotations } from '../services/api';+import { clamp } from '../utils/formatters.js';// Default denoise for an annotation re-render — high enough that the drawn marks// actually reshape the image (mirrors the server's REGEN_ANNOTATED_STRENGTH_DEFAULT).// Clamped into the backend's advertised [min, max] bounds at render time.const DEFAULT_ANNOTATED_STRENGTH = 0.5;-const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));// Blank-canvas defaults (phase 3). A storyboard sketch opens at a square 1:1// unless the caller passes ?w=&h= (e.g. matching the scene's aspect ratio).diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 5b519b76d9..f5e6880cd7 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -22,7 +22,7 @@ grep -i "what you want to do" client/src/utils/README.md| Module | Purpose ||---|---|-| `formatters` | Date/time/duration/byte/word formatters (`formatBytes`, `formatCompactCount`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `parseTimeoutMs`, `formatCooldown`, `parseSizeGb`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price) — `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 CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. 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`. All of them anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new 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". |+| `formatters` | Date/time/duration/byte/word formatters (`clamp`, `formatBytes`, `formatCompactCount`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `parseTimeoutMs`, `formatCooldown`, `parseSizeGb`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price) — `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 CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. 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`. All of them anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new 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, `isCronExpression` detection, and `describeCron` human-readable rendering. || `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`). |diff --git a/client/src/utils/cityChronotype.js b/client/src/utils/cityChronotype.jsindex 534abe4329..aa722a3ca8 100644--- a/client/src/utils/cityChronotype.js+++ b/client/src/utils/cityChronotype.js@@ -13,6 +13,8 @@// `client/src/utils/index.js` barrel free of generic names like `parseHour` that// would collide with a future module.+import { clamp } from './formatters.js';+// Sentinel energy for "no usable profile" — distinct from any real curve value so a// missing profile is recognizable. It maps to NEUTRAL_MODIFIERS (no visible change),// NOT to peak brightness, so an unconfigured city looks untouched rather than washed out.@@ -33,8 +35,6 @@ const ENERGY_RANGE = {// overlay. Keeps "unconfigured / failed to fetch" visually distinct from "low energy."const NEUTRAL_MODIFIERS = { energy: NEUTRAL_ENERGY, brightness: 1.0, tempo: 1.0 };-const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));-// Parse "HH:MM" → fractional hours in [0,24). Returns NaN for unparseable input.// Hours past midnight that belong to "today's" late night (e.g. a 00:30 sleep time)// are returned as-is (0.5); callers that need a continuous timeline normalize.diff --git a/client/src/utils/cityDataHarbor.js b/client/src/utils/cityDataHarbor.jsindex edd6a56d20..681766ae53 100644--- a/client/src/utils/cityDataHarbor.js+++ b/client/src/utils/cityDataHarbor.js@@ -10,7 +10,7 @@// component from the live theme palette (deterministic per name via getAccentColor). No// three.js / React imports so the topology is unit-testable (mirrors cityMemoryDistrict.js).-import { formatBytes, formatCompactCount } from './formatters';+import { clamp, formatBytes, formatCompactCount } from './formatters';import { scaleMetricToHeight } from './cityDistrictLayout';import { PARCELS } from './cityPlan';@@ -36,8 +36,6 @@ export const DATA_HARBOR = {rackSlats: 8, // emissive slat rows per rack; lit count tracks the fill ratio};-const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));-// log2-scale `value` into [0, 1] against `max`. Delegates the curve to the shared// scaleMetricToHeight so every district's log scaling stays one implementation.const logRatio = (value, max) => {diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.jsindex d47f3650f8..b334e65d0d 100644--- a/client/src/utils/formatters.js+++ b/client/src/utils/formatters.js@@ -654,3 +654,15 @@ export function recommendedRamGb(sizeBytes, sizeStr) {if (!gb || gb <= 0) return null;return Math.max(1, Math.ceil(gb * 1.2));}++/**+ * Clamp a numeric value `n` into the inclusive range `[min, max]`.+ * @param {number} n - Value to clamp+ * @param {number} min - Lower bound+ * @param {number} max - Upper bound+ * @returns {number} Clamped value+ */+export function clamp(n, min, max) {+ return Math.min(max, Math.max(min, n));+}+diff --git a/client/src/utils/formatters.test.js b/client/src/utils/formatters.test.jsindex f70f4fa143..f6d80cdb35 100644--- a/client/src/utils/formatters.test.js+++ b/client/src/utils/formatters.test.js@@ -1,12 +1,42 @@import { describe, it, expect } from 'vitest';import {- formatContextLength, formatDurationMin, formatDurationMs, formatEventDateTime, timeAgo,+ clamp, formatContextLength, formatDurationMin, formatDurationMs, formatEventDateTime, timeAgo,formatCooldown, parseSizeGb, recommendedRamGb, parseTimeoutMs, formatDurationSec, middleTruncate,formatWeight, formatPercent, formatUsd, formatBytes,formatDateNumeric, formatTimeOfDaySeconds, formatClockTime, formatWeekdayDate,formatMonthDay, formatMonthYear, formatWeekdayShort, formatWeekdayTime, formatDateFull, formatDateShort, formatDateTime,} from './formatters.js';+describe('clamp', () => {+ it('returns value unchanged when within [min, max]', () => {+ expect(clamp(5, 0, 10)).toBe(5);+ expect(clamp(0, 0, 10)).toBe(0);+ expect(clamp(10, 0, 10)).toBe(10);+ expect(clamp(0.5, 0, 1)).toBe(0.5);+ });++ it('clamps values below min to min', () => {+ expect(clamp(-5, 0, 10)).toBe(0);+ expect(clamp(-0.1, 0, 1)).toBe(0);+ });++ it('clamps values above max to max', () => {+ expect(clamp(15, 0, 10)).toBe(10);+ expect(clamp(1.5, 0, 1)).toBe(1);+ });++ it('handles negative ranges correctly', () => {+ expect(clamp(-15, -10, -5)).toBe(-10);+ expect(clamp(0, -10, -5)).toBe(-5);+ expect(clamp(-7, -10, -5)).toBe(-7);+ });++ it('handles min equal to max', () => {+ expect(clamp(5, 10, 10)).toBe(10);+ expect(clamp(15, 10, 10)).toBe(10);+ });+});+describe('formatBytes', () => {it('renders whole-MB file-size caps with no decimals at decimals=0', () => {// The shape the "file too large" toasts depend on (issue #3869).diff --git a/server/lib/personaTraitBlend.js b/server/lib/personaTraitBlend.jsindex bdab3e911c..201737d49f 100644--- a/server/lib/personaTraitBlend.js+++ b/server/lib/personaTraitBlend.js@@ -18,6 +18,8 @@* test file (`personaTraitBlend.test.js`) is the contract.*/+import { clamp } from '../../client/src/utils/formatters.js';+// communicationProfile.formality / .verbosity live on a 1..10 scale; a persona// nudges them with a relative integer delta in this range.export const COMM_DELTA_MIN = -9;@@ -42,8 +44,6 @@ export const BIG_FIVE_LEAN = {N: { more: 'more emotionally expressive', less: 'more even-keeled and calm' }};-const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));-// Bin a delta's magnitude into slightly / notably / much against the [notably,// much] thresholds for its scale. One ladder, two scales (1..10 comm deltas use// [3, 5]; 0..1 Big-Five deltas use [0.2, 0.4]).diff --git a/server/lib/personaTraitBlend.parity.test.js b/server/lib/personaTraitBlend.parity.test.jsindex 972831d43d..aba98c685b 100644--- a/server/lib/personaTraitBlend.parity.test.js+++ b/server/lib/personaTraitBlend.parity.test.js@@ -25,6 +25,7 @@ describe('personaTraitBlend — server↔client byte parity', () => {it('keeps the client mirror byte-for-byte identical to the server source', () => {const server = readFileSync(SERVER_COPY, 'utf-8');const client = readFileSync(CLIENT_COPY, 'utf-8');- expect(client).toBe(server);+ const normalizedServer = server.replace('../../client/src/utils/formatters.js', '../utils/formatters.js');+ expect(client).toBe(normalizedServer);});});