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

converge client toLocaleString() number/date renders on formatCount/formatDateTime

[._.]/ Adam Eivyf6ec8b0963c5
diff --git a/AGENTS.md b/AGENTS.md
index 152f2855db..07b9cb09ac 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -136,7 +136,7 @@ If a close match exists, **extend it or use it**. Only add a new module when non
- `useLockToggle` (`client/src/hooks/useLockToggle.js`) — optimistic-PATCH lock toggle for any new lock button.
- `useSseProgress` (`client/src/hooks/useSseProgress.js`) — generic JSON-frame EventSource subscriber; build new progress hooks on it.
- `formatBytes` / `formatTimecode` / `formatDateShort` / `formatDurationMs` / `timeAgo` (`client/src/utils/formatters.js`) — never re-define formatters inside components.
-- `formatCount` / `formatUsd` (`client/src/utils/formatters.js`) — thousands-grouped, en-US-pinned (`2,762`, `$4,610.09`). Reach for these rather than rendering a raw integer or a bare `.toLocaleString()` for a user-facing count or amount — an unseparated `4610` is read at the wrong order of magnitude, and the browser locale 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. Converging the ~80 remaining `.toLocaleString()` renders and adding the guard that enforces this is tracked in #7433, so expect to still find both spellings in the tree.
+- `formatCount` / `formatUsd` (`client/src/utils/formatters.js`) — thousands-grouped, en-US-pinned (`2,762`, `$4,610.09`). Reach for these rather than rendering a raw integer or a bare `.toLocaleString()` for a user-facing count or amount — an unseparated `4610` is read at the wrong order of magnitude, and the browser locale 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. `client/src/numberFormattingConventions.test.js` enforces this tree-wide — a new bare `.toLocaleString(` call under `components/`, `pages/`, or `lib/` fails CI.
### Maintenance rule (WHEN adding a public module)
diff --git a/client/src/components/brain/tabs/ImportTab.jsx b/client/src/components/brain/tabs/ImportTab.jsx
index 624c20c899..297c22908f 100644
--- a/client/src/components/brain/tabs/ImportTab.jsx
+++ b/client/src/components/brain/tabs/ImportTab.jsx
@@ -14,7 +14,7 @@ import * as api from '../../../services/api';
import toast from '../../ui/Toast';
import Banner from '../../ui/Banner';
import BrailleSpinner from '../../BrailleSpinner';
-import { formatBytes, formatDateShort } from '../../../utils/formatters';
+import { formatBytes, formatCount, formatDateShort } from '../../../utils/formatters';
import FilePickerButton from '../../ui/FilePickerButton';
// Sources we plan to support. Only `available` ones are clickable.
@@ -465,9 +465,9 @@ function StepReview({ preview, isZip, fileMeta, tagsInput, setTagsInput, skipEmp
</p>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
- <Stat label="Conversations" value={summary.totalConversations.toLocaleString()} />
- <Stat label="Messages" value={summary.totalMessages.toLocaleString()} />
- <Stat label="Total chars" value={summary.totalChars.toLocaleString()} />
+ <Stat label="Conversations" value={formatCount(summary.totalConversations)} />
+ <Stat label="Messages" value={formatCount(summary.totalMessages)} />
+ <Stat label="Total chars" value={formatCount(summary.totalChars)} />
<Stat label="Custom GPTs" value={summary.gizmoCount.toString()} />
<Stat label="Earliest" value={formatDateShort(summary.earliest)} />
<Stat label="Latest" value={formatDateShort(summary.latest)} />
@@ -488,7 +488,7 @@ function StepReview({ preview, isZip, fileMeta, tagsInput, setTagsInput, skipEmp
))}
{remaining > 0 && (
<li className="px-3 py-2 text-xs text-gray-500">
- …and {remaining.toLocaleString()} more
+ …and {formatCount(remaining)} more
</li>
)}
</ul>
diff --git a/client/src/components/digital-twin/tabs/AvatarBioTab.jsx b/client/src/components/digital-twin/tabs/AvatarBioTab.jsx
index 4249fb1d05..e003665117 100644
--- a/client/src/components/digital-twin/tabs/AvatarBioTab.jsx
+++ b/client/src/components/digital-twin/tabs/AvatarBioTab.jsx
@@ -13,6 +13,7 @@ import {
} from 'lucide-react';
import * as api from '../../../services/api';
import toast from '../../ui/Toast';
+import { formatCount } from '../../../utils/formatters';
import BrailleSpinner from '../../BrailleSpinner';
import useProviderModels from '../../../hooks/useProviderModels';
import ProviderModelSelector from '../../ProviderModelSelector';
@@ -160,7 +161,7 @@ export default function AvatarBioTab() {
</button>
))}
{bio && (
- <span className="text-xs text-gray-500 ml-auto">~{bio.tokenEstimate?.toLocaleString()} tokens</span>
+ <span className="text-xs text-gray-500 ml-auto">~{formatCount(bio.tokenEstimate)} tokens</span>
)}
</div>
</div>
@@ -259,7 +260,7 @@ export default function AvatarBioTab() {
<div className="flex items-center justify-between">
<h4 className="text-sm font-semibold text-port-success">Refined bio</h4>
<div className="flex items-center gap-3">
- <span className="text-xs text-gray-500">~{polished.tokenEstimate?.toLocaleString()} tokens</span>
+ <span className="text-xs text-gray-500">~{formatCount(polished.tokenEstimate)} tokens</span>
<CopyButton getText={() => polished.content} />
</div>
</div>
diff --git a/client/src/components/digital-twin/tabs/ExportTab.jsx b/client/src/components/digital-twin/tabs/ExportTab.jsx
index 16391c8aca..c1289f70d7 100644
--- a/client/src/components/digital-twin/tabs/ExportTab.jsx
+++ b/client/src/components/digital-twin/tabs/ExportTab.jsx
@@ -13,6 +13,7 @@ import * as api from '../../../services/api';
import toast from '../../ui/Toast';
import { copyToClipboard } from '../../../lib/clipboard';
import { downloadBlob } from '../../../lib/downloadBlob';
+import { formatCount } from '../../../utils/formatters';
import { DOCUMENT_CATEGORIES } from '../constants';
@@ -258,7 +259,7 @@ export default function ExportTab({ onRefresh: _onRefresh }) {
{exportResult && (
<div className="flex items-center gap-2">
<span className="text-sm text-gray-500 hidden sm:inline">
- ~{exportResult.tokenEstimate?.toLocaleString()} tokens
+ ~{formatCount(exportResult.tokenEstimate)} tokens
</span>
<button
onClick={handleCopyExport}
diff --git a/client/src/components/goals/GoalDetailPanel.jsx b/client/src/components/goals/GoalDetailPanel.jsx
index 4e49796a13..04c6032b4c 100644
--- a/client/src/components/goals/GoalDetailPanel.jsx
+++ b/client/src/components/goals/GoalDetailPanel.jsx
@@ -16,7 +16,7 @@ import GoalCheckIns from './GoalCheckIns';
import GoalProgressLog from './GoalProgressLog';
import GoalLinkedActivities from './GoalLinkedActivities';
import GoalLinkedCalendars from './GoalLinkedCalendars';
-import { formatDateNumeric } from '../../utils/formatters';
+import { formatCount, formatDateNumeric } from '../../utils/formatters';
// Re-exported for backward compatibility — GoalsListView/GoalsTreeView/GoalProgressWidget
// import these from GoalDetailPanel. Source of truth is ./goalConstants.
@@ -155,11 +155,11 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })
</div>
{goal.feasibility.links.map(l => (
<div key={l.activityName} className="text-gray-500">
- {l.activityName}: {l.perWeek}/wk ({l.totalOverHorizon.toLocaleString()} total)
+ {l.activityName}: {l.perWeek}/wk ({formatCount(l.totalOverHorizon)} total)
</div>
))}
<div className="text-gray-500">
- {goal.feasibility.weeksAvailable.toLocaleString()} weeks available
+ {formatCount(goal.feasibility.weeksAvailable)} weeks available
</div>
</div>
</div>
diff --git a/client/src/components/imageGen/ImageGenControls.jsx b/client/src/components/imageGen/ImageGenControls.jsx
index 19bbcf4094..20dd2bbfad 100644
--- a/client/src/components/imageGen/ImageGenControls.jsx
+++ b/client/src/components/imageGen/ImageGenControls.jsx
@@ -13,6 +13,7 @@ import { filterResolutions, MAX_IMAGE_EDGE, MAX_IMAGE_PIXELS } from '../../lib/i
import { randomSeed } from '../../lib/genUtils';
import { RUNNER_FAMILIES } from '../../lib/runnerFamilies';
import { IMAGE_GEN_MODE, isCloudCliMode } from '../../lib/imageGenBackends';
+import { formatCount } from '../../utils/formatters';
import ModelDownloadBadge, { deriveSizeEstimate } from '../media/ModelDownloadBadge';
import ResolutionField from '../media/ResolutionField';
import { FormField } from '../ui/FormField';
@@ -140,7 +141,7 @@ export default function ImageGenControls({
maxPixels={MAX_IMAGE_PIXELS}
disabled={disabled}
inputClassName={inputCls}
- note={`Each edge 64–${MAX_IMAGE_EDGE}px, total ≤ ${MAX_IMAGE_PIXELS.toLocaleString()} px. Multiples of 8 render best on local models.`}
+ note={`Each edge 64–${MAX_IMAGE_EDGE}px, total ≤ ${formatCount(MAX_IMAGE_PIXELS)} px. Multiples of 8 render best on local models.`}
/>
{/* Codex's image_gen tool ignores seed/steps/guidance — only resolution
diff --git a/client/src/components/meatspace/ActivityBloodCorrelation.jsx b/client/src/components/meatspace/ActivityBloodCorrelation.jsx
index 37ead66df5..91e27b9bff 100644
--- a/client/src/components/meatspace/ActivityBloodCorrelation.jsx
+++ b/client/src/components/meatspace/ActivityBloodCorrelation.jsx
@@ -3,6 +3,7 @@ import {
} from 'recharts';
import useChartColors from '../../hooks/useChartColors.js';
import { pluralize } from '../../lib/textUtils';
+import { formatCount } from '../../utils/formatters';
// Blood markers to chart — prefer common ones if available in the test results
const PREFERRED_MARKERS = ['cholesterol', 'glucose', 'ldl', 'hdl', 'triglycerides'];
@@ -36,7 +37,7 @@ const CustomTooltip = ({ active, payload, label, colors }) => {
<p style={{ color: colors.axis, marginBottom: 4 }}>{label}</p>
{payload.map((entry) => (
<p key={entry.dataKey} style={{ color: entry.color ?? entry.fill, margin: '2px 0' }}>
- {entry.name}: {entry.value != null ? Math.round(entry.value).toLocaleString() : '—'}
+ {entry.name}: {entry.value != null ? formatCount(entry.value) : '—'}
{entry.dataKey === 'steps' ? ' steps/day' : ''}
</p>
))}
@@ -90,7 +91,7 @@ export default function ActivityBloodCorrelation({ data, range }) {
const summaries = bloodTests.map(test => {
const avg = compute30DayRollingAvg(dailyData, test.date);
if (avg == null) return null;
- return `Average ${avg.toLocaleString()} steps/day in the 30 days before your ${test.date} blood test`;
+ return `Average ${formatCount(avg)} steps/day in the 30 days before your ${test.date} blood test`;
}).filter(Boolean);
return (
@@ -109,7 +110,7 @@ export default function ActivityBloodCorrelation({ data, range }) {
orientation="left"
tick={{ fill: chartColors.axis, fontSize: 11 }}
width={60}
- tickFormatter={v => v.toLocaleString()}
+ tickFormatter={v => formatCount(v)}
label={{ value: 'Steps (30d avg)', angle: -90, position: 'insideLeft', fill: chartColors.axis, fontSize: 10 }}
/>
{markers.length > 0 && (
diff --git a/client/src/components/meatspace/GenomeCategoryCard.jsx b/client/src/components/meatspace/GenomeCategoryCard.jsx
index 678b9d0dfb..422ae62fec 100644
--- a/client/src/components/meatspace/GenomeCategoryCard.jsx
+++ b/client/src/components/meatspace/GenomeCategoryCard.jsx
@@ -3,6 +3,7 @@ import { ChevronDown, ChevronRight } from 'lucide-react';
import InlineConfirmRow from '../ui/InlineConfirmRow';
import { FormField } from '../ui/FormField';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
+import { formatCount } from '../../utils/formatters';
const STATUS_DOT = {
beneficial: 'bg-port-success',
@@ -167,7 +168,7 @@ export default function GenomeCategoryCard({ category: _category, label, emoji,
{/* Location */}
<div className="flex gap-4 text-xs text-gray-500">
{marker.chromosome && <span>Chr {marker.chromosome}</span>}
- {marker.position && <span>Pos {marker.position?.toLocaleString()}</span>}
+ {marker.position && <span>Pos {formatCount(marker.position)}</span>}
</div>
{/* Notes */}
diff --git a/client/src/components/meatspace/MetricCard.jsx b/client/src/components/meatspace/MetricCard.jsx
index 858eaff37b..d5435859f3 100644
--- a/client/src/components/meatspace/MetricCard.jsx
+++ b/client/src/components/meatspace/MetricCard.jsx
@@ -3,6 +3,7 @@ import {
} from 'recharts';
import BrailleSpinner from '../BrailleSpinner';
import useChartColors from '../../hooks/useChartColors.js';
+import { formatCount } from '../../utils/formatters';
export default function MetricCard({ data = [], loading = false, config, latestValue }) {
const { label, unit, color, aggregation, formatValue } = config;
@@ -16,7 +17,7 @@ export default function MetricCard({ data = [], loading = false, config, latestV
: null;
const displayValue = summary != null
- ? (formatValue ? formatValue(summary) : (Number.isInteger(summary) ? summary.toLocaleString() : summary))
+ ? (formatValue ? formatValue(summary) : (Number.isInteger(summary) ? formatCount(summary) : summary))
: null;
const chartData = data.map(d => ({
@@ -56,11 +57,11 @@ export default function MetricCard({ data = [], loading = false, config, latestV
<CartesianGrid strokeDasharray="3 3" stroke={chartColors.grid} />
<XAxis dataKey="date" tick={{ fill: chartColors.axis, fontSize: 11 }} interval="preserveStartEnd" />
<YAxis tick={{ fill: chartColors.axis, fontSize: 11 }} width={55} domain={['auto', 'auto']}
- tickFormatter={v => typeof v === 'number' && v >= 1000 ? v.toLocaleString() : v} />
+ tickFormatter={v => typeof v === 'number' && v >= 1000 ? formatCount(v) : v} />
<Tooltip content={({ active, payload, label: tipLabel }) => {
if (!active || !payload?.length) return null;
const val = payload[0].value;
- const formatted = formatValue ? formatValue(val) : (typeof val === 'number' && val >= 1000 ? val.toLocaleString() : Math.round(val * 100) / 100);
+ const formatted = formatValue ? formatValue(val) : (typeof val === 'number' && val >= 1000 ? formatCount(val) : Math.round(val * 100) / 100);
return (
<div style={{ background: chartColors.tooltipBg, border: `1px solid ${chartColors.tooltipBorder}`, color: chartColors.text, padding: '8px', borderRadius: '6px', fontSize: '12px' }}>
<p style={{ color: chartColors.axis, marginBottom: 2 }}>{tipLabel}</p>
diff --git a/client/src/components/meatspace/healthMetrics.js b/client/src/components/meatspace/healthMetrics.js
index 7cc848be6d..813f6174d8 100644
--- a/client/src/components/meatspace/healthMetrics.js
+++ b/client/src/components/meatspace/healthMetrics.js
@@ -6,6 +6,8 @@
* Each category contains metrics with their label, unit, color, and aggregation type.
*/
+import { formatCount } from '../../utils/formatters';
+
export const SUM_METRICS = new Set([
'step_count', 'active_energy', 'basal_energy_burned', 'flights_climbed',
'apple_exercise_time', 'apple_stand_time', 'walking_running_distance',
@@ -32,15 +34,15 @@ export const METRIC_CATEGORIES = [
id: 'activity',
label: 'Activity',
metrics: [
- { key: 'step_count', label: 'Steps', unit: 'steps', color: '#3b82f6', aggregation: 'sum', formatValue: v => Math.round(v).toLocaleString() },
- { key: 'active_energy', label: 'Active Energy', unit: 'Cal', color: '#f59e0b', aggregation: 'sum', formatValue: v => Math.round(v).toLocaleString() },
- { key: 'basal_energy_burned', label: 'Basal Energy', unit: 'Cal', color: '#d97706', aggregation: 'sum', formatValue: v => Math.round(v).toLocaleString() },
+ { key: 'step_count', label: 'Steps', unit: 'steps', color: '#3b82f6', aggregation: 'sum', formatValue: v => formatCount(v) },
+ { key: 'active_energy', label: 'Active Energy', unit: 'Cal', color: '#f59e0b', aggregation: 'sum', formatValue: v => formatCount(v) },
+ { key: 'basal_energy_burned', label: 'Basal Energy', unit: 'Cal', color: '#d97706', aggregation: 'sum', formatValue: v => formatCount(v) },
{ key: 'walking_running_distance', label: 'Walk/Run Distance', unit: 'mi', color: '#10b981', aggregation: 'sum', formatValue: v => v.toFixed(2) },
- { key: 'apple_exercise_time', label: 'Exercise Time', unit: 'min', color: '#22c55e', aggregation: 'sum', formatValue: v => Math.round(v).toLocaleString() },
+ { key: 'apple_exercise_time', label: 'Exercise Time', unit: 'min', color: '#22c55e', aggregation: 'sum', formatValue: v => formatCount(v) },
{ key: 'flights_climbed', label: 'Flights Climbed', unit: 'flights', color: '#6366f1', aggregation: 'sum' },
{ key: 'physical_effort', label: 'Physical Effort', unit: 'kJ/hr/kg', color: '#ec4899', aggregation: 'avg' },
- { key: 'time_in_daylight', label: 'Time in Daylight', unit: 'min', color: '#fbbf24', aggregation: 'sum', formatValue: v => Math.round(v).toLocaleString() },
- { key: 'apple_stand_time', label: 'Stand Time', unit: 'min', color: '#14b8a6', aggregation: 'sum', formatValue: v => Math.round(v).toLocaleString() },
+ { key: 'time_in_daylight', label: 'Time in Daylight', unit: 'min', color: '#fbbf24', aggregation: 'sum', formatValue: v => formatCount(v) },
+ { key: 'apple_stand_time', label: 'Stand Time', unit: 'min', color: '#14b8a6', aggregation: 'sum', formatValue: v => formatCount(v) },
]
},
{
@@ -72,7 +74,7 @@ export const METRIC_CATEGORIES = [
{ key: 'walking_steadiness', label: 'Steadiness', unit: '%', color: '#22c55e', aggregation: 'avg', formatValue: v => (v * 100).toFixed(0) },
{ key: 'stair_speed_up', label: 'Stair Speed (Up)', unit: 'ft/s', color: '#8b5cf6', aggregation: 'avg', formatValue: v => v.toFixed(2) },
{ key: 'stair_speed_down', label: 'Stair Speed (Down)', unit: 'ft/s', color: '#6366f1', aggregation: 'avg', formatValue: v => v.toFixed(2) },
- { key: 'six_minute_walk_test', label: '6-Min Walk Test', unit: 'm', color: '#10b981', aggregation: 'avg', formatValue: v => Math.round(v).toLocaleString() },
+ { key: 'six_minute_walk_test', label: '6-Min Walk Test', unit: 'm', color: '#10b981', aggregation: 'avg', formatValue: v => formatCount(v) },
{ key: 'walking_heart_rate_average', label: 'Walking Heart Rate', unit: 'bpm', color: '#ef4444', aggregation: 'avg' },
]
},
@@ -82,9 +84,9 @@ export const METRIC_CATEGORIES = [
metrics: [
{ key: 'distance_cycling', label: 'Cycling Distance', unit: 'mi', color: '#3b82f6', aggregation: 'sum', formatValue: v => v.toFixed(2) },
{ key: 'cycling_speed', label: 'Cycling Speed', unit: 'mi/hr', color: '#06b6d4', aggregation: 'avg', formatValue: v => v.toFixed(1) },
- { key: 'cycling_cadence', label: 'Cadence', unit: 'rpm', color: '#f59e0b', aggregation: 'avg', formatValue: v => Math.round(v).toLocaleString() },
- { key: 'cycling_power', label: 'Power', unit: 'W', color: '#ef4444', aggregation: 'avg', formatValue: v => Math.round(v).toLocaleString() },
- { key: 'cycling_ftp', label: 'FTP', unit: 'W', color: '#8b5cf6', aggregation: 'avg', formatValue: v => Math.round(v).toLocaleString() },
+ { key: 'cycling_cadence', label: 'Cadence', unit: 'rpm', color: '#f59e0b', aggregation: 'avg', formatValue: v => formatCount(v) },
+ { key: 'cycling_power', label: 'Power', unit: 'W', color: '#ef4444', aggregation: 'avg', formatValue: v => formatCount(v) },
+ { key: 'cycling_ftp', label: 'FTP', unit: 'W', color: '#8b5cf6', aggregation: 'avg', formatValue: v => formatCount(v) },
]
},
{
@@ -92,10 +94,10 @@ export const METRIC_CATEGORIES = [
label: 'Running',
metrics: [
{ key: 'running_speed', label: 'Running Speed', unit: 'mi/hr', color: '#3b82f6', aggregation: 'avg', formatValue: v => v.toFixed(1) },
- { key: 'running_power', label: 'Running Power', unit: 'W', color: '#ef4444', aggregation: 'avg', formatValue: v => Math.round(v).toLocaleString() },
+ { key: 'running_power', label: 'Running Power', unit: 'W', color: '#ef4444', aggregation: 'avg', formatValue: v => formatCount(v) },
{ key: 'running_stride_length', label: 'Stride Length', unit: 'm', color: '#06b6d4', aggregation: 'avg', formatValue: v => v.toFixed(2) },
{ key: 'running_vertical_oscillation', label: 'Vertical Oscillation', unit: 'cm', color: '#f59e0b', aggregation: 'avg', formatValue: v => v.toFixed(1) },
- { key: 'running_ground_contact_time', label: 'Ground Contact', unit: 'ms', color: '#8b5cf6', aggregation: 'avg', formatValue: v => Math.round(v).toLocaleString() },
+ { key: 'running_ground_contact_time', label: 'Ground Contact', unit: 'ms', color: '#8b5cf6', aggregation: 'avg', formatValue: v => formatCount(v) },
]
},
{
diff --git a/client/src/components/meatspace/tabs/CalendarTab.jsx b/client/src/components/meatspace/tabs/CalendarTab.jsx
index c258da06fd..185e737b89 100644
--- a/client/src/components/meatspace/tabs/CalendarTab.jsx
+++ b/client/src/components/meatspace/tabs/CalendarTab.jsx
@@ -10,6 +10,7 @@ import LifeGrid from './calendar/LifeGrid';
import TimeStats from './calendar/TimeStats';
import AddActivityForm from './calendar/AddActivityForm';
import LifeEventsPanel from './calendar/LifeEventsPanel';
+import { formatCount } from '../../../utils/formatters';
export default function CalendarTab() {
const [data, setData] = useState(null);
@@ -136,15 +137,15 @@ export default function CalendarTab() {
<div className="text-[10px] text-gray-500">years left</div>
</div>
<div className="text-center">
- <div className="font-bold text-port-success">{stats.remaining.months.toLocaleString()}</div>
+ <div className="font-bold text-port-success">{formatCount(stats.remaining.months)}</div>
<div className="text-[10px] text-gray-500">months</div>
</div>
<div className="text-center">
- <div className="font-bold text-port-success">{stats.remaining.weeks.toLocaleString()}</div>
+ <div className="font-bold text-port-success">{formatCount(stats.remaining.weeks)}</div>
<div className="text-[10px] text-gray-500">weeks</div>
</div>
<div className="text-center">
- <div className="font-bold text-port-success">{stats.remaining.days.toLocaleString()}</div>
+ <div className="font-bold text-port-success">{formatCount(stats.remaining.days)}</div>
<div className="text-[10px] text-gray-500">days</div>
</div>
</div>
@@ -193,7 +194,7 @@ export default function CalendarTab() {
<div className="text-[10px] text-gray-500">{b.frequency}{CADENCE_LABELS[b.cadence]}</div>
</div>
<div className="text-right shrink-0">
- <div className="text-base font-bold text-white">{b.remaining.toLocaleString()}</div>
+ <div className="text-base font-bold text-white">{formatCount(b.remaining)}</div>
</div>
<button
onClick={() => handleRemoveActivity(i)}
diff --git a/client/src/components/meatspace/tabs/OverviewTab.jsx b/client/src/components/meatspace/tabs/OverviewTab.jsx
index fd18211a1b..8f218d59ca 100644
--- a/client/src/components/meatspace/tabs/OverviewTab.jsx
+++ b/client/src/components/meatspace/tabs/OverviewTab.jsx
@@ -7,7 +7,7 @@ import DeathClockCountdown from '../../DeathClockCountdown';
import ProvenanceChip from '../../ui/ProvenanceChip';
import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
import { clickableProps } from '../../../lib/a11yKeyboard.js';
-import { formatWeight, formatPercent, formatDateShort } from '../../../utils/formatters';
+import { formatWeight, formatPercent, formatDateShort, formatCount } from '../../../utils/formatters';
function HealthTile({ icon: Icon, iconColor, label, metrics, onClick }) {
return (
@@ -329,9 +329,9 @@ export default function OverviewTab() {
label="Life Calendar"
onClick={() => navigate('/meatspace/calendar')}
metrics={[
- { label: 'Saturdays left', value: calendar.stats.remaining.saturdays.toLocaleString() },
- { label: 'Weeks left', value: calendar.stats.remaining.weeks.toLocaleString() },
- { label: 'Awake days', value: calendar.stats.remaining.awakeDays.toLocaleString() },
+ { label: 'Saturdays left', value: formatCount(calendar.stats.remaining.saturdays) },
+ { label: 'Weeks left', value: formatCount(calendar.stats.remaining.weeks) },
+ { label: 'Awake days', value: formatCount(calendar.stats.remaining.awakeDays) },
]}
/>
)}
diff --git a/client/src/components/meatspace/tabs/SettingsTab.jsx b/client/src/components/meatspace/tabs/SettingsTab.jsx
index 739f8bf039..a030004b85 100644
--- a/client/src/components/meatspace/tabs/SettingsTab.jsx
+++ b/client/src/components/meatspace/tabs/SettingsTab.jsx
@@ -5,6 +5,7 @@ import socket from '../../../services/socket';
import BrailleSpinner from '../../BrailleSpinner';
import Banner from '../../ui/Banner';
import FilePickerButton from '../../ui/FilePickerButton';
+import { formatCount } from '../../../utils/formatters';
export default function SettingsTab({ onRefresh }) {
// JSON import state
@@ -177,19 +178,19 @@ export default function SettingsTab({ onRefresh }) {
<div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm mt-2">
<div>
<span className="text-gray-500">Metrics processed</span>
- <p className="text-white font-semibold">{jsonResult.metricsProcessed?.toLocaleString()}</p>
+ <p className="text-white font-semibold">{formatCount(jsonResult.metricsProcessed)}</p>
</div>
<div>
<span className="text-gray-500">Records ingested</span>
- <p className="text-white font-semibold">{jsonResult.recordsIngested?.toLocaleString()}</p>
+ <p className="text-white font-semibold">{formatCount(jsonResult.recordsIngested)}</p>
</div>
<div>
<span className="text-gray-500">Records skipped</span>
- <p className="text-white font-semibold">{jsonResult.recordsSkipped?.toLocaleString()}</p>
+ <p className="text-white font-semibold">{formatCount(jsonResult.recordsSkipped)}</p>
</div>
<div>
<span className="text-gray-500">Days affected</span>
- <p className="text-white font-semibold">{jsonResult.daysAffected?.toLocaleString()}</p>
+ <p className="text-white font-semibold">{formatCount(jsonResult.daysAffected)}</p>
</div>
</div>
</Banner>
@@ -248,7 +249,7 @@ export default function SettingsTab({ onRefresh }) {
<div className="mt-4">
<div className="flex items-center justify-between text-xs text-gray-400 mb-1">
<span>Processing records...</span>
- <span>{xmlProgress.toLocaleString()} records processed</span>
+ <span>{formatCount(xmlProgress)} records processed</span>
</div>
<div className="h-2 bg-port-border rounded-full overflow-hidden">
<div className="h-full bg-port-accent rounded-full animate-pulse w-full" />
@@ -262,11 +263,11 @@ export default function SettingsTab({ onRefresh }) {
<div className="grid grid-cols-2 gap-3 text-sm mt-2">
<div>
<span className="text-gray-500">Records imported</span>
- <p className="text-white font-semibold">{xmlResult.records?.toLocaleString()}</p>
+ <p className="text-white font-semibold">{formatCount(xmlResult.records)}</p>
</div>
<div>
<span className="text-gray-500">Days affected</span>
- <p className="text-white font-semibold">{xmlResult.days?.toLocaleString()}</p>
+ <p className="text-white font-semibold">{formatCount(xmlResult.days)}</p>
</div>
</div>
</Banner>
diff --git a/client/src/components/meatspace/tabs/calendar/LifeGrid.jsx b/client/src/components/meatspace/tabs/calendar/LifeGrid.jsx
index 3ce0c33cd2..d3426df762 100644
--- a/client/src/components/meatspace/tabs/calendar/LifeGrid.jsx
+++ b/client/src/components/meatspace/tabs/calendar/LifeGrid.jsx
@@ -7,6 +7,7 @@ import {
EVENT_TYPE_STYLES, cellClasses, computeYearGrid, computeMonthGrid,
computeMonthCalendars, computeEventWeeks,
} from './lifeGridMath';
+import { formatCount } from '../../../../utils/formatters';
// === Year Grid ===
@@ -377,8 +378,8 @@ export default function LifeGrid({ grid, stats, birthDate, deathDate, lifeEvents
const unitLabel = {
years: `Year ${Math.floor(stats.age.years)} of ${Math.ceil(stats.remaining.years + stats.age.years)}`,
months: `Month ${Math.floor(stats.age.years * 12)} of ${Math.floor((stats.remaining.years + stats.age.years) * 12)}`,
- weeks: `Week ${stats.age.weeks.toLocaleString()} of ${stats.total.weeks.toLocaleString()}`,
- days: `Day ${stats.age.days.toLocaleString()} of ${Math.floor((stats.remaining.days || 0) + stats.age.days).toLocaleString()}`,
+ weeks: `Week ${formatCount(stats.age.weeks)} of ${formatCount(stats.total.weeks)}`,
+ days: `Day ${formatCount(stats.age.days)} of ${formatCount(Math.floor((stats.remaining.days || 0) + stats.age.days))}`,
};
return (
diff --git a/client/src/components/meatspace/tabs/calendar/TimeStats.jsx b/client/src/components/meatspace/tabs/calendar/TimeStats.jsx
index 2d97311468..7791f2121b 100644
--- a/client/src/components/meatspace/tabs/calendar/TimeStats.jsx
+++ b/client/src/components/meatspace/tabs/calendar/TimeStats.jsx
@@ -1,4 +1,5 @@
import { Calendar, Sun, Moon, TreePine, Snowflake, Flower2, CloudSun, Cake } from 'lucide-react';
+import { formatCount } from '../../../../utils/formatters';
function CompactStat({ icon: Icon, iconColor, label, value, sub }) {
return (
@@ -8,7 +9,7 @@ function CompactStat({ icon: Icon, iconColor, label, value, sub }) {
<div className="text-xs text-gray-400">{label}</div>
</div>
<div className="text-right">
- <div className="text-sm font-bold text-white">{typeof value === 'number' ? value.toLocaleString() : value}</div>
+ <div className="text-sm font-bold text-white">{typeof value === 'number' ? formatCount(value) : value}</div>
{sub && <div className="text-[9px] text-gray-600">{sub}</div>}
</div>
</div>
@@ -24,7 +25,7 @@ export default function TimeStats({ stats }) {
<CompactStat icon={Sun} iconColor="text-yellow-400" label="Saturdays" value={r.saturdays} sub={`${Math.round(r.saturdays / 52)}y`} />
<CompactStat icon={Sun} iconColor="text-orange-400" label="Sundays" value={r.sundays} sub={`${Math.round(r.sundays / 52)}y`} />
<CompactStat icon={CloudSun} iconColor="text-blue-400" label="Weekends" value={r.weekends} sub={`${Math.round(r.weekends * 2)} days`} />
- <CompactStat icon={Moon} iconColor="text-indigo-400" label="Sleep" value={`${Math.round(r.sleepHours / 24 / 365.25)}y`} sub={`${r.sleepHours.toLocaleString()}h`} />
+ <CompactStat icon={Moon} iconColor="text-indigo-400" label="Sleep" value={`${Math.round(r.sleepHours / 24 / 365.25)}y`} sub={`${formatCount(r.sleepHours)}h`} />
<CompactStat icon={Sun} iconColor="text-green-400" label="Awake Days" value={r.awakeDays} sub={`${Math.round(r.awakeDays / 365.25)}y`} />
<CompactStat icon={Calendar} iconColor="text-purple-400" label="Months" value={r.months} />
<CompactStat icon={Calendar} iconColor="text-teal-400" label="Weeks" value={r.weeks} />
diff --git a/client/src/components/media/ArExportPanel.jsx b/client/src/components/media/ArExportPanel.jsx
index 9c5ce9dbd1..05b1bf9886 100644
--- a/client/src/components/media/ArExportPanel.jsx
+++ b/client/src/components/media/ArExportPanel.jsx
@@ -9,7 +9,7 @@ import {
} from '../../lib/usdzExport.js';
import { generateQrCodeSvg } from '../../lib/qrCode';
import useMounted from '../../hooks/useMounted';
-import { formatBytes } from '../../utils/formatters';
+import { formatBytes, formatCount } from '../../utils/formatters';
import toast from '../ui/Toast';
/**
@@ -61,8 +61,8 @@ export default function ArExportPanel({ record, scene, onRecordChange }) {
// refusal — the export still runs — but the count and the remedy are named,
// because the only real fix is a lighter render, not a lighter export.
toast(
- `This mesh is ${triangles.toLocaleString()} triangles — above the `
- + `${AR_TRIANGLE_BUDGET.toLocaleString()} that opens comfortably in AR. `
+ `This mesh is ${formatCount(triangles)} triangles — above the `
+ + `${formatCount(AR_TRIANGLE_BUDGET)} that opens comfortably in AR. `
+ 'Re-render at a lower Quality tier for a lighter AR file.',
{ icon: '⚠️' },
);
diff --git a/client/src/components/media/ResolutionField.jsx b/client/src/components/media/ResolutionField.jsx
index ae90ecfa1d..908ff7f49b 100644
--- a/client/src/components/media/ResolutionField.jsx
+++ b/client/src/components/media/ResolutionField.jsx
@@ -18,6 +18,7 @@ import { FormField } from '../ui/FormField';
import {
resolveResolutionLabel, clampImageEdge, CUSTOM_RESOLUTION_VALUE, MAX_IMAGE_EDGE,
} from '../../lib/imageGenResolutions';
+import { formatCount } from '../../utils/formatters';
const DEFAULT_INPUT_CLS = 'w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50';
@@ -79,7 +80,7 @@ export default function ResolutionField({
const pixelCount = (width || 0) * (height || 0);
const overPixelCap = maxPixels != null && pixelCount > maxPixels;
const stepClause = step > 1 ? ` Multiples of ${step} render best on local models.` : '';
- const defaultNote = `Each edge ${min}–${max}px${maxPixels != null ? `, total ≤ ${maxPixels.toLocaleString()} px` : ''}.${stepClause}`;
+ const defaultNote = `Each edge ${min}–${max}px${maxPixels != null ? `, total ≤ ${formatCount(maxPixels)} px` : ''}.${stepClause}`;
return (
<>
@@ -119,7 +120,7 @@ export default function ResolutionField({
</FormField>
<p className={`col-span-full text-[10px] -mt-1 ${overPixelCap ? 'text-port-error' : 'text-gray-500'}`}>
{overPixelCap
- ? `Too large — ${pixelCount.toLocaleString()} px exceeds the ${maxPixels.toLocaleString()} px cap. Reduce width or height.`
+ ? `Too large — ${formatCount(pixelCount)} px exceeds the ${formatCount(maxPixels)} px cap. Reduce width or height.`
: (note || defaultNote)}
</p>
</>
diff --git a/client/src/components/media/RigPanel.jsx b/client/src/components/media/RigPanel.jsx
index 1698b62239..c5aa75a214 100644
--- a/client/src/components/media/RigPanel.jsx
+++ b/client/src/components/media/RigPanel.jsx
@@ -4,7 +4,7 @@ import { getRiggingReadiness, rigImageTo3dModel, listRiggingClips, retargetImage
import { riggingReasonLabel } from '../../lib/riggingReasons.js';
import useMounted from '../../hooks/useMounted';
import { useInstanceFeatures } from '../../hooks/useInstanceFeatures';
-import { formatBytes } from '../../utils/formatters';
+import { formatBytes, formatCount } from '../../utils/formatters';
import toast from '../ui/Toast';
/**
@@ -152,7 +152,7 @@ export default function RigPanel({ record, onRecordChange }) {
<div className="mt-2 space-y-1 text-xs text-gray-400">
<p className="text-port-success">
Rigged against {rig.summary?.bones ?? 0} bones
- {rig.summary?.vertices ? ` · ${rig.summary.vertices.toLocaleString()} vertices` : ''}
+ {rig.summary?.vertices ? ` · ${formatCount(rig.summary.vertices)} vertices` : ''}
{rig.bytes ? ` · ${formatBytes(rig.bytes)}` : ''}
</p>
<p>
diff --git a/client/src/components/pipeline/stages/TextStagePanel.jsx b/client/src/components/pipeline/stages/TextStagePanel.jsx
index 2eb4c2987f..fa66db77b5 100644
--- a/client/src/components/pipeline/stages/TextStagePanel.jsx
+++ b/client/src/components/pipeline/stages/TextStagePanel.jsx
@@ -21,7 +21,7 @@ import {
} from '../../../services/api';
import { useAsyncAction } from '../../../hooks/useAsyncAction';
import { useSseProgress, isTerminalSseFrame } from '../../../hooks/useSseProgress';
-import { formatDurationMs } from '../../../utils/formatters';
+import { formatCount, formatDurationMs } from '../../../utils/formatters';
import StageHistoryModal from './StageHistoryModal';
const stageHasContent = (stage) => Boolean(stage?.input?.trim() || stage?.output?.trim());
@@ -433,7 +433,7 @@ export default function TextStagePanel({
)
) : null}
<span className="text-gray-600 text-[10px] tabular-nums ml-auto">
- {Number.isFinite(f.outputLength) ? `${f.outputLength.toLocaleString()} chars · ` : ''}
+ {Number.isFinite(f.outputLength) ? `${formatCount(f.outputLength)} chars · ` : ''}
{formatDurationMs(f.ms)}
</span>
</li>
diff --git a/client/src/components/providers/ProviderCard.jsx b/client/src/components/providers/ProviderCard.jsx
index 68cc284216..67b7b821aa 100644
--- a/client/src/components/providers/ProviderCard.jsx
+++ b/client/src/components/providers/ProviderCard.jsx
@@ -34,7 +34,7 @@ import {
resolveModelContextWindow,
supportsModelRefresh,
} from '../../utils/providers';
-import { formatContextLength } from '../../utils/formatters';
+import { formatContextLength, formatDateTime } from '../../utils/formatters';
import { isHttpsUrl } from '../../utils/urlNormalize';
import ProviderRuntimeStatus from './ProviderRuntimeStatus';
import ProviderReadiness from './ProviderReadiness';
@@ -653,7 +653,7 @@ function CodexSubscriptionPanel({
runs on this provider may not be counted here.
</p>
)}
- {typeof account?.checkedAt === 'number' && <p className="text-gray-500">Last usage refresh: {new Date(account.checkedAt).toLocaleString()}</p>}
+ {typeof account?.checkedAt === 'number' && <p className="text-gray-500">Last usage refresh: {formatDateTime(account.checkedAt)}</p>}
{catalogCount !== null && <p className="text-gray-500">Subscription catalog: {catalogCount} model{catalogCount === 1 ? '' : 's'} available.</p>}
{modelError && <p role="status" className="text-port-warning">Using the last known model catalog while a refresh is unavailable.</p>}
{verificationUrl && (
diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsx
index 86bb9ae676..b943015265 100644
--- a/client/src/components/providers/ProviderForm.jsx
+++ b/client/src/components/providers/ProviderForm.jsx
@@ -8,6 +8,7 @@ import Banner from '../ui/Banner';
import {
formatDurationMs,
formatContextLength,
+ formatCount,
parseTimeoutMs,
TIMEOUT_INPUT_MIN_MS,
TIMEOUT_INPUT_MAX_MS,
@@ -45,7 +46,7 @@ const PROVIDER_FIELD_RANGES = {
};
const rangeMessage = (label, { min, max }, unit = '') =>
- `${label} must be between ${min.toLocaleString()} and ${max.toLocaleString()}${unit ? ` ${unit}` : ''}`;
+ `${label} must be between ${formatCount(min)} and ${formatCount(max)}${unit ? ` ${unit}` : ''}`;
export default function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders = [], localModels = { ollama: [], lmstudio: [], ctxById: {}, hardwareCompatibilityByBackend: {} }, runnerAllowedCommands = null }) {
const [formData, setFormData] = useState({
@@ -266,7 +267,7 @@ export default function ProviderForm({ provider, onClose, onSave, onEditProvider
if (text(formData.timeout) !== '' && parseTimeoutMs(formData.timeout) == null) {
return {
tab: 'generation',
- message: `Timeout must be a whole number of ms between ${TIMEOUT_INPUT_MIN_MS.toLocaleString()} and ${TIMEOUT_INPUT_MAX_MS.toLocaleString()}`,
+ message: `Timeout must be a whole number of ms between ${formatCount(TIMEOUT_INPUT_MIN_MS)} and ${formatCount(TIMEOUT_INPUT_MAX_MS)}`,
};
}
if (outOfRange(formData.contextWindow, PROVIDER_FIELD_RANGES.contextWindow)) {
@@ -934,7 +935,7 @@ export default function ProviderForm({ provider, onClose, onSave, onEditProvider
const ms = parseTimeoutMs(formData.timeout);
return ms != null
? `≈ ${formatDurationMs(ms)} per run`
- : `Per-call cap. Server max: ${TIMEOUT_INPUT_MAX_MS.toLocaleString()} ms (${formatDurationMs(TIMEOUT_INPUT_MAX_MS)}).`;
+ : `Per-call cap. Server max: ${formatCount(TIMEOUT_INPUT_MAX_MS)} ms (${formatDurationMs(TIMEOUT_INPUT_MAX_MS)}).`;
})()}
</p>
</FormField>
diff --git a/client/src/components/settings/DatabaseTab.jsx b/client/src/components/settings/DatabaseTab.jsx
index a8e1346485..77e658b23c 100644
--- a/client/src/components/settings/DatabaseTab.jsx
+++ b/client/src/components/settings/DatabaseTab.jsx
@@ -2,7 +2,7 @@ import { useState, useEffect, useRef, useCallback } from 'react';
import { Container, HardDrive, Download, ArrowRightLeft, Wrench, RefreshCw, Square, RotateCw, Play, Trash2 } from 'lucide-react';
import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
-import { formatBytes } from '../../utils/formatters';
+import { formatBytes, formatCount } from '../../utils/formatters';
import {
getDatabaseStatus, switchDatabase, setupNativeDatabase, exportDatabase, fixDatabase,
syncDatabase, startDatabase, stopDatabase, destroyDatabase
@@ -239,7 +239,7 @@ export function DatabaseTab() {
<span className={`w-2 h-2 rounded-full ${dbStatus?.connected ? 'bg-port-success' : 'bg-port-error'}`} />
<span className="text-sm text-gray-300">
{dbStatus?.connected ? 'Connected' : dbStatus ? 'Disconnected' : ''}
- {dbStatus?.memoryCount != null && ` \u2014 ${dbStatus.memoryCount.toLocaleString()} memories`}
+ {dbStatus?.memoryCount != null && ` \u2014 ${formatCount(dbStatus.memoryCount)} memories`}
{dbStatus?.dbBytes != null && ` \u2014 ${formatBytes(dbStatus.dbBytes)}`}
{dbStatus?.tableCount != null && ` (${dbStatus.tableCount} tables)`}
</span>
diff --git a/client/src/components/settings/LocalLlmLibraryView.jsx b/client/src/components/settings/LocalLlmLibraryView.jsx
index 5d1ff32818..e766cf67d1 100644
--- a/client/src/components/settings/LocalLlmLibraryView.jsx
+++ b/client/src/components/settings/LocalLlmLibraryView.jsx
@@ -4,7 +4,7 @@ import { Download, RefreshCw, Search, Plus, ExternalLink, Star, Play, AlertTrian
import toast from '../ui/Toast';
import FormField from '../ui/FormField';
import BrailleSpinner from '../BrailleSpinner';
-import { formatAgeDays, formatContextLength, timeAgo, recommendedRamGb, formatDateNumeric } from '../../utils/formatters';
+import { formatAgeDays, formatContextLength, formatCount, timeAgo, recommendedRamGb, formatDateNumeric } from '../../utils/formatters';
import { localLlmTargetKey } from '../../lib/localLlmTargetKey';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
import useDownloadPreflightConfirm from '../../hooks/useDownloadPreflightConfirm';
@@ -634,7 +634,7 @@ export default function LocalLlmLibraryView() {
)}
{m.provenance && (
<p className="text-[11px] text-gray-400 mt-1">
- Reviewed {m.provenance.checkedAt}: {m.provenance.likes.toLocaleString()} likes · {m.provenance.downloads.toLocaleString()} monthly downloads · {m.provenance.followers.toLocaleString()} publisher followers.{' '}
+ Reviewed {m.provenance.checkedAt}: {formatCount(m.provenance.likes)} likes · {formatCount(m.provenance.downloads)} monthly downloads · {formatCount(m.provenance.followers)} publisher followers.{' '}
<a className="text-port-accent hover:underline" href={`https://huggingface.co/${m.provenance.repository}/tree/${m.provenance.revision}`} target="_blank" rel="noopener noreferrer">Reviewed revision</a>
{' · Installer uses the publisher’s current release; this is a dated review, not an immutable install pin.'}
</p>
diff --git a/client/src/components/settings/MtplxCheckpoints.jsx b/client/src/components/settings/MtplxCheckpoints.jsx
index d08f6c6939..c5d11d0b49 100644
--- a/client/src/components/settings/MtplxCheckpoints.jsx
+++ b/client/src/components/settings/MtplxCheckpoints.jsx
@@ -4,7 +4,7 @@ import BrailleSpinner from '../BrailleSpinner';
import ConfirmButtonPair from '../ui/ConfirmButtonPair';
import ProgressBar from '../ui/ProgressBar';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
-import { formatAgeDays, formatBytes, formatDateNumeric } from '../../utils/formatters';
+import { formatAgeDays, formatBytes, formatCount, formatDateNumeric } from '../../utils/formatters';
/**
* MTPLX checkpoint manager — search, download, and remove MTP model weights.
@@ -222,7 +222,7 @@ export default function MtplxCheckpoints({
<p className="text-xs text-white truncate">{row.name}</p>
<p className="text-[11px] text-gray-500 truncate">
{row.repo}
- {Number.isFinite(row.downloads) ? ` · ${row.downloads.toLocaleString()} downloads` : ''}
+ {Number.isFinite(row.downloads) ? ` · ${formatCount(row.downloads)} downloads` : ''}
{/* Age in days, not a "3mo ago" bucket: a checkpoint's release
date is what says whether it is worth a multi-gigabyte pull. */}
{age && <span title={`Published ${formatDateNumeric(row.publishedAt)}`}>{` · published ${age}`}</span>}
diff --git a/client/src/components/writers-room/AnalysisHistory.jsx b/client/src/components/writers-room/AnalysisHistory.jsx
index b68c1f5e5c..01bebb3534 100644
--- a/client/src/components/writers-room/AnalysisHistory.jsx
+++ b/client/src/components/writers-room/AnalysisHistory.jsx
@@ -3,7 +3,7 @@ import { AlertTriangle, Check, Clapperboard, FileSignature, MapPin, RotateCcw, S
import BrailleSpinner from '../BrailleSpinner';
import toast from '../ui/Toast';
import { listWritersRoomAnalyses, getWritersRoomAnalysis } from '../../services/apiWritersRoom';
-import { timeAgo } from '../../utils/formatters';
+import { timeAgo, formatCount } from '../../utils/formatters';
import useMounted from '../../hooks/useMounted';
// Icon + label maps must include every kind from `ANALYSIS_KINDS`. Adding a
@@ -188,7 +188,7 @@ function FormatResult({ result, onApply }) {
return (
<div className="space-y-2 text-[11px]">
<div className="flex items-center justify-between">
- <span className="uppercase text-[9px] text-gray-500">Cleaned prose ({text.length.toLocaleString()} chars)</span>
+ <span className="uppercase text-[9px] text-gray-500">Cleaned prose ({formatCount(text.length)} chars)</span>
{onApply && (
<button
onClick={() => onApply(text)}
diff --git a/client/src/components/writers-room/PolishPanel.jsx b/client/src/components/writers-room/PolishPanel.jsx
index e83e695b06..6be489fdfa 100644
--- a/client/src/components/writers-room/PolishPanel.jsx
+++ b/client/src/components/writers-room/PolishPanel.jsx
@@ -3,7 +3,7 @@ import { Sparkles, StopCircle, RotateCcw, Check, X, ArrowRight, Loader2 } from '
import toast from '../ui/Toast';
import useMounted from '../../hooks/useMounted';
import { useSseProgress, isTerminalSseFrame } from '../../hooks/useSseProgress';
-import { timeAgo } from '../../utils/formatters';
+import { timeAgo, formatCount } from '../../utils/formatters';
import {
startWritersRoomPolish,
cancelWritersRoomPolish,
@@ -190,7 +190,7 @@ export default function PolishPanel({ work, dirty, onBodyChanged }) {
</div>
{baseline && (
<div className="text-[12px] text-gray-400">
- Baseline score <ScoreBadge value={baseline.score} /> · {baseline.wordCount?.toLocaleString()} words
+ Baseline score <ScoreBadge value={baseline.score} /> · {formatCount(baseline.wordCount)} words
</div>
)}
<ul className="space-y-1.5">
@@ -206,7 +206,7 @@ export default function PolishPanel({ work, dirty, onBodyChanged }) {
<span className="flex items-center gap-1 text-gray-500 text-[11px]"><X size={11} /> reverted</span>
)}
<span className="text-gray-600 text-[10px] tabular-nums ml-auto">
- {f.wordCountBefore?.toLocaleString()}→{f.wordCountAfter?.toLocaleString()}w · {f.cutsApplied} cut{f.cutsApplied === 1 ? '' : 's'}
+ {formatCount(f.wordCountBefore)}→{formatCount(f.wordCountAfter)}w · {f.cutsApplied} cut{f.cutsApplied === 1 ? '' : 's'}
</span>
</li>
))}
@@ -232,7 +232,7 @@ export default function PolishPanel({ work, dirty, onBodyChanged }) {
{s.label || `Cycle ${s.cycle}`}
{typeof s.qualityScore === 'number' && <span className="text-gray-500"> · <ScoreBadge value={s.qualityScore} inline /></span>}
</span>
- <span className="text-gray-600 text-[10px] shrink-0">{s.wordCount?.toLocaleString()}w · {timeAgo(s.createdAt, '')}</span>
+ <span className="text-gray-600 text-[10px] shrink-0">{formatCount(s.wordCount)}w · {timeAgo(s.createdAt, '')}</span>
{/* 44px tap target; -my-1.5/-mr-2 bleed into the row's own
padding so the snapshot list keeps its density. */}
<button
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsx
index afc9a86f24..7042b3bf2b 100644
--- a/client/src/components/writers-room/WorkEditor.jsx
+++ b/client/src/components/writers-room/WorkEditor.jsx
@@ -47,7 +47,7 @@ import {
} from '../../services/apiWritersRoom';
import { safeReadStorage, safeWriteStorage } from '../../lib/safeStorage';
import { STATUS_LABELS } from './labels';
-import { formatDurationSec } from '../../utils/formatters';
+import { formatCount, formatDurationSec } from '../../utils/formatters';
import { countWords } from '../../lib/textUtils';
import StoryboardPanel, { STORYBOARD_TAB, STORYBOARD_TAB_VALUES } from './StoryboardPanel';
import LiveContinuationPanel from './LiveContinuationPanel';
@@ -959,7 +959,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
readingTheme === 'light' ? 'text-gray-700 bg-[var(--wr-reading-paper)]/85' : 'text-gray-500 bg-port-bg/80'
}`}
>
- <span>{wordCount.toLocaleString()} words</span>
+ <span>{formatCount(wordCount)} words</span>
{dirty && <span className="text-port-warning">● unsaved</span>}
</div>
)}
diff --git a/client/src/lib/mindThinkingPresets.js b/client/src/lib/mindThinkingPresets.js
index f4ecd0bbcb..d3155a200a 100644
--- a/client/src/lib/mindThinkingPresets.js
+++ b/client/src/lib/mindThinkingPresets.js
@@ -12,7 +12,7 @@
* READ of the already-loaded provider record, not a capability call.
*/
-import { formatRuntime } from '../utils/formatters.js';
+import { formatCount, formatRuntime } from '../utils/formatters.js';
import {
credentialSource,
isApiProvider,
@@ -165,9 +165,9 @@ export function formatMindCallUsage(usage) {
if (usage?.state !== 'reported') return 'Usage unknown';
const parts = [];
if (usage.totalTokens !== null && usage.totalTokens !== undefined) {
- parts.push(`${usage.totalTokens.toLocaleString()} tokens`);
+ parts.push(`${formatCount(usage.totalTokens)} tokens`);
} else if (usage.inputTokens !== null && usage.inputTokens !== undefined) {
- parts.push(`${usage.inputTokens.toLocaleString()} in`);
+ parts.push(`${formatCount(usage.inputTokens)} in`);
}
if (usage.costUsd !== null && usage.costUsd !== undefined) {
parts.push(`$${usage.costUsd.toFixed(4)}`);
diff --git a/client/src/lib/powersBreakdown.js b/client/src/lib/powersBreakdown.js
index c549f78a0b..638ee036a2 100644
--- a/client/src/lib/powersBreakdown.js
+++ b/client/src/lib/powersBreakdown.js
@@ -1,4 +1,6 @@
-const value = (base, exponent) => Math.pow(base, exponent).toLocaleString('en-US');
+import { formatCount } from '../utils/formatters';
+
+const value = (base, exponent) => formatCount(Math.pow(base, exponent));
const recalled = (base, exponent, technique, label) => ({
technique,
diff --git a/client/src/numberFormattingConventions.test.js b/client/src/numberFormattingConventions.test.js
new file mode 100644
index 0000000000..0a6a5ac36a
--- /dev/null
+++ b/client/src/numberFormattingConventions.test.js
@@ -0,0 +1,141 @@
+// @vitest-environment node
+
+/**
+ * Repo-wide guard: `formatCount` (`utils/formatters.js`) is the canonical
+ * grouped-integer renderer; a bare `.toLocaleString()` on a number is not.
+ *
+ * The two disagree in a user-visible way, not just stylistically (#7433):
+ *
+ * - Locale. `formatCount` pins `en-US` so a grouped count matches the `$`
+ * beside it (`formatUsd` also pins `en-US`). A bare `.toLocaleString()`
+ * follows the BROWSER locale, so on a non-`en` browser the same screen
+ * renders "1.234" in one span and "1,234" in the next.
+ * - Fractions. `.toLocaleString()` defaults to up to 3 fraction digits;
+ * `formatCount` rounds to 0.
+ * - Missing vs. zero. `formatCount(x)` renders '—' for an unmeasured count
+ * and takes `{ fallback: '0' }` where a measured zero is meant. The
+ * `.toLocaleString()` call sites each hand-rolled their own `?? 0` / `|| 0`
+ * coalesce, inconsistently.
+ *
+ * `new Date(x).toLocaleString()` is the same anti-pattern for a date/time
+ * render — root `AGENTS.md` forbids the inline form; route it through
+ * `formatDateTime` or the date helper matching the shape wanted.
+ *
+ * The rule is therefore structural rather than per-site: any `.toLocaleString(`
+ * call outside the allowlist fails this suite.
+ *
+ * ## Allowlist
+ *
+ * - `src/utils/formatters.js` — it IS the canonical implementation (`formatCount`
+ * grouping numbers; `formatDateTime`/`formatWeekdayTime`/`formatEventDateTime`
+ * rendering dates through the browser locale on purpose).
+ * - `src/components/usage/UsageMeter.jsx` — `formatResetsAt` renders a quota
+ * reset as a compact "Sep 16, 1:30 AM" (month + day + time, no year, no
+ * weekday). No existing helper matches that shape, and it has exactly one
+ * caller — same reasoning `storageConventions.test.js` uses to allowlist
+ * `timeWindow.js` rather than add a single-caller helper. Move it off this
+ * allowlist (into a named `utils/formatters.js` helper) the day a second
+ * caller wants the same shape.
+ *
+ * ## What this guard CANNOT see
+ *
+ * It is a source grep, not an AST pass. Comments are stripped (both forms,
+ * with a `:` lookbehind so a `https://` URL is not read as a line comment) so
+ * prose mentioning "toLocaleString" does not trip the guard; string literals
+ * are NOT stripped. Aliasing (`const f = n.toLocaleString`), a computed
+ * member (`n['toLocaleString']()`), or a call funneled through a helper in
+ * another file all slip through. Those are unusual enough here that the grep
+ * earns its keep; closing them means moving to an AST pass.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { trackedSourceFiles } from './test/trackedFiles.js';
+
+const CLIENT_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+
+const WRAPPER_FILE = 'src/utils/formatters.js';
+const ALLOWED = [
+ WRAPPER_FILE,
+ 'src/components/usage/UsageMeter.jsx',
+];
+
+const isAllowed = (file) => ALLOWED.includes(file);
+
+/**
+ * Block and line comments removed, the same way `storageConventions.test.js`
+ * does it — see that file for why the `[^:]` guard before `//` matters.
+ */
+const stripComments = (src) => src
+ .replace(/\/\*[\s\S]*?\*\//g, ' ')
+ .replace(/(^|[^:\\])\/\/[^\n]*/g, '$1');
+
+/**
+ * `.toLocaleString(` preceded by a member-access dot or `?.`. Matches with or
+ * without call arguments — a locale-pinned `.toLocaleString('en-US')` is the
+ * same anti-pattern as a bare `.toLocaleString()`, just already half-fixed.
+ */
+const RAW_TO_LOCALE_STRING = /\??\.\s*toLocaleString\s*\(/g;
+
+/** Raw `.toLocaleString(` calls in `src`, as matched snippets. */
+export function findRawToLocaleString(src) {
+ return [...stripComments(src).matchAll(RAW_TO_LOCALE_STRING)].map((m) => m[0].trim());
+}
+
+describe('Number/date formatting goes through utils/formatters', () => {
+ it('has no raw .toLocaleString( calls outside the wrapper and its allowlist', () => {
+ const files = trackedSourceFiles(CLIENT_ROOT);
+ // A broken `git ls-files` (wrong cwd, detached checkout) would otherwise make
+ // this guard pass by scanning nothing at all.
+ expect(files.length).toBeGreaterThan(100);
+
+ const violations = [];
+ for (const file of files) {
+ if (isAllowed(file)) continue;
+ const src = readFileSync(join(CLIENT_ROOT, file), 'utf8');
+ for (const hit of findRawToLocaleString(src)) violations.push(`${file}: ${hit}`);
+ }
+
+ expect(
+ violations,
+ 'These files call `.toLocaleString(` directly. A NUMBER should render through '
+ + '`formatCount` (thousands-grouped, en-US-pinned, matches the `$` beside it) — '
+ + 'pass `{ fallback: \'0\' }` only where an ABSENT count should read as zero. A '
+ + 'DATE should render through `formatDateTime` or the helper matching the shape '
+ + 'wanted (see the exports list in `utils/formatters.js`).\n'
+ + `Offenders:\n ${violations.join('\n ')}`,
+ ).toEqual([]);
+ });
+
+ // Guards the guard: if the detector stops recognizing the call, the scan
+ // above goes vacuously green and the bug class walks straight back in.
+ it('flags every call shape and ignores prose that merely names the method', () => {
+ expect(findRawToLocaleString('n.toLocaleString()')).toEqual(['.toLocaleString(']);
+ expect(findRawToLocaleString("n.toLocaleString('en-US')")).toEqual(['.toLocaleString(']);
+ expect(findRawToLocaleString('count?.toLocaleString()')).toEqual(['?.toLocaleString(']);
+ expect(findRawToLocaleString('d.toLocaleString(undefined, { month: "short" })')).toEqual(['.toLocaleString(']);
+
+ expect(findRawToLocaleString('formatCount(n)')).toEqual([]);
+ expect(findRawToLocaleString('formatDateTime(d)')).toEqual([]);
+ // A comment naming the method is not a call.
+ expect(findRawToLocaleString(
+ '// prefer formatCount over toLocaleString() for a user-facing count\nconst x = 1;',
+ )).toEqual([]);
+ });
+
+ // The allowlist must keep naming files that really exist and really carry the
+ // shape — otherwise a rename turns an exemption into silent dead config.
+ it('allowlists only files that exist and still call toLocaleString directly', () => {
+ const tracked = trackedSourceFiles(CLIENT_ROOT);
+ for (const file of ALLOWED) {
+ expect(tracked, `${file} is allowlisted but no longer tracked`).toContain(file);
+ const src = readFileSync(join(CLIENT_ROOT, file), 'utf8');
+ expect(
+ findRawToLocaleString(src).length,
+ `${file} no longer calls toLocaleString directly — drop it from the allowlist`,
+ ).toBeGreaterThan(0);
+ }
+ });
+});
diff --git a/client/src/pages/AgentsPage.jsx b/client/src/pages/AgentsPage.jsx
index 736902da84..24b92c4929 100644
--- a/client/src/pages/AgentsPage.jsx
+++ b/client/src/pages/AgentsPage.jsx
@@ -2,7 +2,7 @@ import { useState, useCallback, Fragment } from 'react';
import { RefreshCw, Activity, XCircle, Cpu, MemoryStick, Terminal } from 'lucide-react';
import * as api from '../services/api';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
-import { formatDateTime } from '../utils/formatters';
+import { formatCount, formatDateTime } from '../utils/formatters';
import PageSkeleton from '../components/ui/PageSkeleton';
export function AgentsPage() {
@@ -251,7 +251,7 @@ export function AgentsPage() {
</div>
<div>
<div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Runtime (ms)</div>
- <div className="text-sm text-gray-300 font-mono">{agent.runtime?.toLocaleString()}</div>
+ <div className="text-sm text-gray-300 font-mono">{formatCount(agent.runtime)}</div>
</div>
{agent.model && (
<div>
diff --git a/client/src/pages/ApiExplorer.jsx b/client/src/pages/ApiExplorer.jsx
index 19fac01248..d907632597 100644
--- a/client/src/pages/ApiExplorer.jsx
+++ b/client/src/pages/ApiExplorer.jsx
@@ -8,6 +8,7 @@ import RouteTabsHeader from '../components/ui/RouteTabsHeader';
import BrailleSpinner from '../components/BrailleSpinner';
import { copyToClipboard } from '../lib/clipboard';
import * as api from '../services/api';
+import { formatCount } from '../utils/formatters';
const HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD', 'TRACE'];
const HTTP_METHOD_SET = new Set(HTTP_METHODS);
@@ -131,7 +132,7 @@ function CatalogView() {
</label>
</div>
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-gray-500">
- <span>{filtered.length.toLocaleString()} matching operations</span>
+ <span>{formatCount(filtered.length)} matching operations</span>
<div className="flex items-center gap-3">
<Link to="/settings/api-access" className="text-port-accent hover:underline">Configure external access</Link>
<a href="/api/api-docs/internal/openapi.json" target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-port-accent hover:underline">
@@ -254,7 +255,7 @@ function RestReferenceView() {
</label>
</div>
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-gray-500">
- <span>{filtered.length.toLocaleString()} matching operations</span>
+ <span>{formatCount(filtered.length)} matching operations</span>
<a href={specPath} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-port-accent hover:underline">
Open JSON <ExternalLink size={11} />
</a>
@@ -365,7 +366,7 @@ function EventCatalogView() {
</label>
</div>
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-gray-500">
- <span>{events.length.toLocaleString()} matching events</span>
+ <span>{formatCount(events.length)} matching events</span>
<a href="/api/api-docs/asyncapi.json" target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-port-accent hover:underline">Open AsyncAPI JSON <ExternalLink size={11} /></a>
</div>
</div>
diff --git a/client/src/pages/CatalogIngest.jsx b/client/src/pages/CatalogIngest.jsx
index a445a90d06..0322904ac8 100644
--- a/client/src/pages/CatalogIngest.jsx
+++ b/client/src/pages/CatalogIngest.jsx
@@ -8,6 +8,7 @@
import { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router';
import { Sparkles, Loader2, CheckCircle2, AlertCircle, ArrowLeft, RotateCcw, Circle, Upload, Link2, FileText, Mic, Square } from 'lucide-react';
+import { formatCount } from '../utils/formatters';
import useProviderModels from '../hooks/useProviderModels';
import ProviderModelSelector from '../components/ProviderModelSelector';
import toast from '../components/ui/Toast';
@@ -523,7 +524,7 @@ export default function CatalogIngest() {
? '[\n { "type": "character", "name": "Alice", "description": "A curious sleuth", "tags": ["noir"] }\n]'
: '## Character: Alice\nA curious sleuth.\ntags: noir, gritty\n\n## Place: The Hollow\nAbandoned subway tunnel.\n'}
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm font-mono focus:outline-none focus:border-port-accent" />
- <p className="text-xs text-gray-500 mt-1">{bulkText.length.toLocaleString()} {bulkText.length === 1 ? 'character' : 'characters'}</p>
+ <p className="text-xs text-gray-500 mt-1">{formatCount(bulkText.length)} {bulkText.length === 1 ? 'character' : 'characters'}</p>
</div>
<div className="flex items-center justify-end gap-2">
<button type="button" onClick={() => setBulkOpen(false)} disabled={bulkSubmitting}
@@ -605,7 +606,7 @@ export default function CatalogIngest() {
<textarea id="ingest-text" maxLength={babble ? 30000 : undefined} rows={12} value={rawText} onChange={(e) => setRawText(e.target.value)}
placeholder="Paste prose, scene notes, character sketches — anything you want catalogued."
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm font-mono focus:outline-none focus:border-port-accent" />
- <p className="text-xs text-gray-500 mt-1">{rawText.length.toLocaleString()}{babble ? ' / 30,000 chars' : ' chars'}</p>
+ <p className="text-xs text-gray-500 mt-1">{formatCount(rawText.length)}{babble ? ' / 30,000 chars' : ' chars'}</p>
</div>
{babble && <>
<p className="text-sm text-gray-400">One AI pass refines your brainstorm into distinct suggestions: story ideas, character journeys, alternate realities, scenes, dialogue, and concepts. Review and edit before saving. Your original text is preserved as a scrap.</p>
diff --git a/client/src/pages/DataManager.jsx b/client/src/pages/DataManager.jsx
index 62386cffb2..7d96b28fff 100644
--- a/client/src/pages/DataManager.jsx
+++ b/client/src/pages/DataManager.jsx
@@ -1,7 +1,7 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { HardDrive, RefreshCw, Archive, Trash2, ChevronDown, ChevronRight, FolderOpen, File, Package } from 'lucide-react';
import * as api from '../services/api';
-import { formatBytes, formatDateNumeric } from '../utils/formatters';
+import { formatBytes, formatCount, formatDateNumeric } from '../utils/formatters';
import PageSkeleton from '../components/ui/PageSkeleton';
import { SkeletonRegion, SkeletonRows } from '../components/ui/Skeleton';
import toast from '../components/ui/Toast';
@@ -168,7 +168,7 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu
</div>
<div className="text-right shrink-0 ml-2">
<div className="text-sm font-mono text-white">{formatBytes(cat.size)}</div>
- <div className="text-xs text-gray-500">{cat.fileCount.toLocaleString()} files</div>
+ <div className="text-xs text-gray-500">{formatCount(cat.fileCount)} files</div>
</div>
</button>
@@ -178,7 +178,7 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu
{confirmingPurge && !busy ? (
<InlineConfirmRow
variant="separator"
- question={`Purge all ${cat.fileCount.toLocaleString()} files (${formatBytes(cat.size)}) in ${cat.label}? This permanently deletes the data and cannot be undone.`}
+ question={`Purge all ${formatCount(cat.fileCount)} files (${formatBytes(cat.size)}) in ${cat.label}? This permanently deletes the data and cannot be undone.`}
confirmText="Purge"
confirmTitle="Confirm purge"
cancelTitle="Cancel purge"
@@ -247,7 +247,7 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu
<span className="truncate">{item.name}</span>
</td>
<td className="p-2 text-right text-gray-400 font-mono">{formatBytes(item.size)}</td>
- <td className="p-2 pr-3 text-right text-gray-500">{item.type === 'directory' ? item.fileCount?.toLocaleString() : '—'}</td>
+ <td className="p-2 pr-3 text-right text-gray-500">{item.type === 'directory' ? formatCount(item.fileCount) : '—'}</td>
{itemScoped && (
<td className="p-2 pr-3 text-right">
{item.type === 'directory' ? (
diff --git a/client/src/pages/Importer.jsx b/client/src/pages/Importer.jsx
index 7f436eee5e..50340edf0f 100644
--- a/client/src/pages/Importer.jsx
+++ b/client/src/pages/Importer.jsx
@@ -22,6 +22,7 @@ import {
IMPORTER_SOURCE_CHAR_LIMIT_FALLBACK,
CLASSIFY_SOURCE_HEAD_CHARS,
} from '../services/apiImporter';
+import { formatCount } from '../utils/formatters';
const CONTENT_TYPE_LABELS = {
'short-story': 'Short Story',
@@ -680,7 +681,7 @@ function IntakeForm({
Source Text
</label>
<span className={`text-xs ${sourceOver ? 'text-port-error' : 'text-port-text-muted'}`}>
- {sourceLen.toLocaleString()} / {sourceCharLimit.toLocaleString()} chars
+ {formatCount(sourceLen)} / {formatCount(sourceCharLimit)} chars
</span>
</div>
<textarea
@@ -693,7 +694,7 @@ function IntakeForm({
{sourceOver && (
<p className="text-xs text-port-error mt-1 flex items-center gap-1">
<AlertTriangle className="w-3 h-3" />
- Source exceeds the {sourceCharLimit.toLocaleString()}-char ceiling. Trim it or wait for chunked-extraction support.
+ Source exceeds the {formatCount(sourceCharLimit)}-char ceiling. Trim it or wait for chunked-extraction support.
</p>
)}
</div>
@@ -1241,7 +1242,7 @@ const IssueCard = memo(function IssueCard({ idx, issue, onPatch, arcRoles, seaso
aria-controls={`iss-${idx}-prose`}
>
{proseExpanded ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
- {excerptLabel}: {proseLen.toLocaleString()} chars
+ {excerptLabel}: {formatCount(proseLen)} chars
<span className="text-port-text-muted/70">— {proseExpanded ? 'click to collapse' : 'click to edit (verbatim from source)'}</span>
</button>
{proseExpanded && (
diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsx
index bbfca83715..a0be00f1ea 100644
--- a/client/src/pages/Loras.jsx
+++ b/client/src/pages/Loras.jsx
@@ -23,7 +23,7 @@ import ProgressBar from '../components/ui/ProgressBar';
import { FormField } from '../components/ui/FormField';
import { useConfirmDelete } from '../hooks/useConfirmDelete';
import useDownloadPreflightConfirm from '../hooks/useDownloadPreflightConfirm';
-import { formatBytes } from '../utils/formatters';
+import { formatBytes, formatCount } from '../utils/formatters';
import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, isVideoLoraFamily } from '../lib/runnerFamilies';
import { LORA_EFFECT_STATUSES, loraEffectDetail, loraEffectBadge } from '../lib/loraEffect';
import {
@@ -1126,7 +1126,7 @@ function VideoSuggestionCard({ card, installedHfKeys, installingVideoKey, instal
</div>
{card.note && <p className="text-[11px] text-gray-400 italic break-words">{card.note}</p>}
{typeof card.downloads === 'number' && (
- <div className="text-[10px] text-gray-600">↓ {card.downloads.toLocaleString()}</div>
+ <div className="text-[10px] text-gray-600">↓ {formatCount(card.downloads)}</div>
)}
{card.description && (
<details className="text-[11px] text-gray-500">
@@ -1372,7 +1372,7 @@ function SuggestionCard({ card, installedFilenames, installingSuggestionKey, onI
)}
<div className="text-[10px] text-gray-600 flex items-center gap-3 mt-auto">
{card.creator && <span className="truncate" title={card.creator}>by {card.creator}</span>}
- {typeof card.downloads === 'number' && <span>↓ {card.downloads.toLocaleString()}</span>}
+ {typeof card.downloads === 'number' && <span>↓ {formatCount(card.downloads)}</span>}
</div>
{installs ? (
<div className="flex flex-col gap-1">
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsx
index 98248bbbb9..0652664580 100644
--- a/client/src/pages/StoryBuilder.jsx
+++ b/client/src/pages/StoryBuilder.jsx
@@ -38,6 +38,7 @@ import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';
import useDrawerTab from '../hooks/useDrawerTab';
import useStoryImportIntake from '../hooks/useStoryImportIntake';
import TabPills from '../components/ui/TabPills';
+import { formatCount } from '../utils/formatters';
// Bible fields the embedded arc step flushes before an ArcCanvas generate/verify.
// The Story Builder edits these on their own steps (not inside the arc step), so
@@ -420,7 +421,7 @@ function ImportPanel({ intake }) {
</div>
<div>
<label htmlFor="imp-src" className="block text-sm text-gray-400 mb-1">
- Source text <span className="text-gray-600">({source.length.toLocaleString()} chars)</span>
+ Source text <span className="text-gray-600">({formatCount(source.length)} chars)</span>
</label>
<textarea id="imp-src" value={source} onChange={(e) => patch({ source: e.target.value })} rows={8}
placeholder="Paste the full script / manuscript here…"
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.js
index 1a5199f1b3..f58f3559d5 100644
--- a/scripts/ci-test-plan.js
+++ b/scripts/ci-test-plan.js
@@ -404,6 +404,7 @@ const structuralTestsFor = (changedFiles, trackedSet) => {
add('client/src/globalShadowConventions.test.js');
add('client/src/headingTruncationConventions.test.js');
add('client/src/hooks/mountedRefConventions.test.js');
+ add('client/src/numberFormattingConventions.test.js');
add('client/src/pollingConventions.test.js');
add('client/src/popoverClampConventions.test.js');
add('client/src/preWrapClasses.test.js');
diff --git a/scripts/repo-scan-guards.test.js b/scripts/repo-scan-guards.test.js
index c7ba24a4bc..fc8c69d1ca 100644
--- a/scripts/repo-scan-guards.test.js
+++ b/scripts/repo-scan-guards.test.js
@@ -58,6 +58,7 @@ const STRUCTURALLY_SELECTED = new Map([
['client/src/globalShadowConventions.test.js', 'structuralTestsFor: client/src/**.js(x)'],
['client/src/headingTruncationConventions.test.js', 'structuralTestsFor: client/src/**.js(x)'],
['client/src/hooks/mountedRefConventions.test.js', 'structuralTestsFor: client/src/**.js(x)'],
+ ['client/src/numberFormattingConventions.test.js', 'structuralTestsFor: client/src/**.js(x)'],
['client/src/pollingConventions.test.js', 'structuralTestsFor: client/src/**.js(x)'],
['client/src/popoverClampConventions.test.js', 'structuralTestsFor: client/src/**.js(x)'],
['client/src/preWrapClasses.test.js', 'structuralTestsFor: client/src/**.js(x)'],