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

group thousands in every user-facing count and dollar amount

[._.]/ Adam Eivy906520e0068c
diff --git a/AGENTS.md b/AGENTS.md
index b715041d75..0decb2ac29 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -136,6 +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`). **Never render 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. `formatCount` gives `—` for a count that was never measured; pass `{ fallback: '0' }` where a measured zero is meant.
### Maintenance rule (WHEN adding a public module)
diff --git a/client/src/components/RapidReader.jsx b/client/src/components/RapidReader.jsx
index 92d220fe50..2166fd96d7 100644
--- a/client/src/components/RapidReader.jsx
+++ b/client/src/components/RapidReader.jsx
@@ -4,7 +4,7 @@ import Modal from './ui/Modal';
import useKeyCapture from '../hooks/useKeyCapture';
import { noPointerFocusSurfaceProps } from '../lib/a11yKeyboard';
import { rapidReaderWords } from '../lib/rapidReaderPosition';
-import { formatCountdown } from '../utils/formatters';
+import { formatCount, formatCountdown } from '../utils/formatters';
// Optimal Recognition Point — the focal letter the eye lands on. Spritz-style:
// shorter words use a left-shifted ORP, longer words shift right. Punctuation
@@ -321,7 +321,7 @@ export default function RapidReader({
</button>
</div>
<span className="font-mono text-gray-500">
- {Math.min(wordIndex + 1, totalWords)}{current.wordCount > 1 ? `–${Math.min(wordIndex + current.wordCount, totalWords)}` : ''}/{totalWords} words · {formatCountdown(remainingSec)} left
+ {formatCount(Math.min(wordIndex + 1, totalWords))}{current.wordCount > 1 ? `–${formatCount(Math.min(wordIndex + current.wordCount, totalWords))}` : ''}/{formatCount(totalWords)} words · {formatCountdown(remainingSec)} left
</span>
</div>
</div>
diff --git a/client/src/components/apps/tabs/ProcessesTab.jsx b/client/src/components/apps/tabs/ProcessesTab.jsx
index 70bdc49725..7c753e0fcb 100644
--- a/client/src/components/apps/tabs/ProcessesTab.jsx
+++ b/client/src/components/apps/tabs/ProcessesTab.jsx
@@ -9,7 +9,7 @@ import ProcessLogLines from '../../ui/ProcessLogLines';
import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
import { useProcessLogs } from '../../../hooks/useProcessLogs';
import { copyToClipboard } from '../../../lib/clipboard';
-import { formatBytes, formatDurationMs, formatTimeOfDaySeconds } from '../../../utils/formatters';
+import { formatBytes, formatCount, formatDurationMs, formatTimeOfDaySeconds } from '../../../utils/formatters';
const getStatusClasses = (status) => {
switch (status) {
@@ -196,7 +196,7 @@ export default function ProcessesTab({ appId, pm2ProcessNames, filterFn }) {
<option value={2000}>2000</option>
</select>
</FormField>
- <span className="text-xs text-gray-600">{logs.length} lines</span>
+ <span className="text-xs text-gray-600">{formatCount(logs.length)} lines</span>
<button
onClick={clearLogs}
className="min-h-[44px] min-w-[44px] px-1 text-xs text-gray-500 hover:text-white"
@@ -279,7 +279,7 @@ export default function ProcessesTab({ appId, pm2ProcessNames, filterFn }) {
<option value={2000}>2000</option>
</select>
</FormField>
- <span className="text-sm text-gray-600">{logs.length} lines</span>
+ <span className="text-sm text-gray-600">{formatCount(logs.length)} lines</span>
<button
onClick={clearLogs}
className="min-h-[44px] min-w-[44px] px-1 text-sm text-gray-500 hover:text-white"
diff --git a/client/src/components/apps/tabs/ProcessesTab.test.jsx b/client/src/components/apps/tabs/ProcessesTab.test.jsx
index 578817cc67..0ae95ad158 100644
--- a/client/src/components/apps/tabs/ProcessesTab.test.jsx
+++ b/client/src/components/apps/tabs/ProcessesTab.test.jsx
@@ -22,7 +22,10 @@ vi.mock('../../../lib/clipboard', () => ({ copyToClipboard: vi.fn() }));
vi.mock('../../BrailleSpinner', () => ({ default: () => null }));
vi.mock('../../ui/FormField', () => ({ FormField: ({ children }) => children }));
vi.mock('../../ui/ProcessLogLines', () => ({ default: () => null }));
-vi.mock('../../../utils/formatters', () => ({
+// `formatCount` is deliberately NOT stubbed — a stub that returns the raw
+// number would make the "N lines" assertions blind to a grouping regression.
+vi.mock('../../../utils/formatters', async (importOriginal) => ({
+ ...(await importOriginal()),
formatBytes: vi.fn(() => '0 B'),
formatDurationMs: vi.fn(),
formatTimeOfDaySeconds: vi.fn((timestamp) => `time-${timestamp}`),
diff --git a/client/src/components/brain/tabs/NotesTab.jsx b/client/src/components/brain/tabs/NotesTab.jsx
index ee2c188f46..fee940af97 100644
--- a/client/src/components/brain/tabs/NotesTab.jsx
+++ b/client/src/components/brain/tabs/NotesTab.jsx
@@ -22,7 +22,7 @@ import BrailleSpinner from '../../BrailleSpinner';
import toast from '../../ui/Toast';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
import FolderPicker from '../../FolderPicker';
-import { timeAgo, formatBytes } from '../../../utils/formatters';
+import { timeAgo, formatBytes, formatCount } from '../../../utils/formatters';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
import { useNoteSave } from '../../../hooks/useNoteSave.js';
import { clickableProps } from '../../../lib/a11yKeyboard.js';
@@ -424,7 +424,7 @@ export default function NotesTab() {
{/* Stats bar */}
<div className="px-3 py-1.5 border-b border-port-border flex items-center gap-3 text-xs text-gray-500">
- <span>{totalNotes} notes</span>
+ <span>{formatCount(totalNotes)} notes</span>
{folderFilter && (
<button
onClick={() => setFolderFilter('')}
@@ -435,7 +435,7 @@ export default function NotesTab() {
</button>
)}
{searchResults && (
- <span className="text-port-accent">{searchResults.total} results</span>
+ <span className="text-port-accent">{formatCount(searchResults.total)} results</span>
)}
<button
onClick={() => { loadTags(); setShowTags(!showTags); }}
@@ -871,7 +871,7 @@ function FolderItem({ folder, notes, expanded, onToggle, onSelectNote, onFilterF
onClick={onFilterFolder}
className="w-full px-3 py-1 text-xs text-port-accent hover:text-white"
>
- Show all {notes.length} notes...
+ Show all {formatCount(notes.length)} notes...
</button>
)}
</div>
diff --git a/client/src/components/calendar/AgendaTab.jsx b/client/src/components/calendar/AgendaTab.jsx
index 536e0ca84d..1b35d28fc3 100644
--- a/client/src/components/calendar/AgendaTab.jsx
+++ b/client/src/components/calendar/AgendaTab.jsx
@@ -4,7 +4,7 @@ import toast from '../ui/Toast';
import * as api from '../../services/api';
import socket from '../../services/socket';
import EventDetail from './EventDetail';
-import { formatTimeOfDay as formatTime, formatWeekdayDate, localDateKey } from '../../utils/formatters';
+import { formatCount, formatTimeOfDay as formatTime, formatWeekdayDate, localDateKey } from '../../utils/formatters';
import BrailleSpinner from '../BrailleSpinner';
import EmptyState from '../EmptyState';
import useUrlParams from '../../hooks/useUrlParams';
@@ -282,7 +282,7 @@ export default function AgendaTab({ accounts }) {
{!loading && events.length > 0 && (
<div className="flex flex-wrap items-center justify-center gap-3">
- <p role="status" className="text-sm text-gray-400">{events.length} of {total} events loaded</p>
+ <p role="status" className="text-sm text-gray-400">{formatCount(events.length)} of {formatCount(total)} events loaded</p>
{nextOffset.current < total && (
<button
onClick={() => fetchEvents(true)}
diff --git a/client/src/components/calendar/ReviewTab.jsx b/client/src/components/calendar/ReviewTab.jsx
index ed03c59b4c..42c1901fa5 100644
--- a/client/src/components/calendar/ReviewTab.jsx
+++ b/client/src/components/calendar/ReviewTab.jsx
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback } from 'react';
import {Check, X, ChevronLeft, ChevronRight, Clock, Target, AlertTriangle, CalendarDays} from 'lucide-react';
import toast from '../ui/Toast';
import * as api from '../../services/api';
-import { formatDurationMin, formatTimeOfDay } from '../../utils/formatters';
+import { formatCount, formatDurationMin, formatTimeOfDay } from '../../utils/formatters';
import BrailleSpinner from '../BrailleSpinner';
import EmptyState from '../EmptyState';
import { localDateStr } from '../meatspace/constants';
@@ -145,19 +145,19 @@ export default function ReviewTab({ accounts = [] }) {
{/* Summary */}
{review && (
<div className="flex gap-4 text-xs">
- <span className="text-gray-500">{review.summary.totalEvents} events</span>
+ <span className="text-gray-500">{formatCount(review.summary.totalEvents)} events</span>
{review.summary.confirmed > 0 && (
- <span className="text-port-success">{review.summary.confirmed} confirmed</span>
+ <span className="text-port-success">{formatCount(review.summary.confirmed)} confirmed</span>
)}
{review.summary.skipped > 0 && (
- <span className="text-gray-500">{review.summary.skipped} skipped</span>
+ <span className="text-gray-500">{formatCount(review.summary.skipped)} skipped</span>
)}
{review.summary.unreviewed > 0 && (
- <span className="text-port-accent">{review.summary.unreviewed} to review</span>
+ <span className="text-port-accent">{formatCount(review.summary.unreviewed)} to review</span>
)}
{review.progressEntries?.length > 0 && (
<span className="text-port-accent">
- {review.progressEntries.reduce((sum, e) => sum + (e.durationMinutes || 0), 0)}min logged
+ {formatCount(review.progressEntries.reduce((sum, e) => sum + (e.durationMinutes || 0), 0))}min logged
</span>
)}
</div>
diff --git a/client/src/components/cos/PersistentMindContextPanel.jsx b/client/src/components/cos/PersistentMindContextPanel.jsx
index 60e2d87f72..73153368ec 100644
--- a/client/src/components/cos/PersistentMindContextPanel.jsx
+++ b/client/src/components/cos/PersistentMindContextPanel.jsx
@@ -3,6 +3,7 @@ import { Brain, Database, Eye, Plus, RefreshCw, Save } from 'lucide-react';
import * as api from '../../services/api';
import BrailleSpinner from '../BrailleSpinner';
import Banner from '../ui/Banner';
+import { formatCount } from '../../utils/formatters';
const EMPTY_MEMORY = {
content: '', summary: '', type: 'observation', category: 'other', tags: [], importance: 0.5, protection: 'standard',
@@ -193,7 +194,7 @@ export default function PersistentMindContextPanel({ view = 'all', refreshKey =
{view !== 'memories' && <section className="rounded border border-port-border bg-port-card p-4" aria-labelledby="mind-preview-heading">
<h3 id="mind-preview-heading" className="flex items-center gap-2 text-sm font-semibold text-port-text"><Eye size={16} aria-hidden="true" /> Effective context preview</h3>
<p className="mt-1 text-xs text-port-text-muted">
- This is the actual bounded text projection used on the next wake: {data?.preview?.chars || 0} characters, about {data?.preview?.approximateTokens || 0} tokens, summary cache {data?.preview?.summaryState || 'unknown'}.
+ This is the actual bounded text projection used on the next wake: {formatCount(data?.preview?.chars)} characters, about {formatCount(data?.preview?.approximateTokens)} tokens, summary cache {data?.preview?.summaryState || 'unknown'}.
</p>
<pre className="mt-3 max-h-[34rem] overflow-auto whitespace-pre-wrap break-words rounded border border-port-border bg-port-bg p-3 text-xs text-port-text">{data?.preview?.text || 'No context available.'}</pre>
<details className="mt-3 rounded border border-port-border p-3">
diff --git a/client/src/components/cos/PersistentMindRuntimePanel.jsx b/client/src/components/cos/PersistentMindRuntimePanel.jsx
index b5047366d5..67878fc37f 100644
--- a/client/src/components/cos/PersistentMindRuntimePanel.jsx
+++ b/client/src/components/cos/PersistentMindRuntimePanel.jsx
@@ -1,8 +1,7 @@
import { AlertTriangle, Brain, Cpu, Gauge } from 'lucide-react';
import { describeMindTurnProgress, mindTurnHeadline } from '../../lib/mindTurnProgress.js';
-import { formatBytes, timeUntil } from '../../utils/formatters.js';
+import { formatBytes, formatCount, timeUntil } from '../../utils/formatters.js';
-const number = (value) => Number.isFinite(value) ? value.toLocaleString() : '—';
const RESIDENCY_STATES = {
loaded: 'Loaded in memory',
@@ -86,9 +85,9 @@ export default function PersistentMindRuntimePanel({ runtime, error, loading, on
<section aria-label="Persistent mind runtime" className="grid gap-3 md:grid-cols-3">
<ContextSurface {...(onOpenContext ? { type: 'button', onClick: onOpenContext } : {})} className={`rounded border border-port-border bg-port-card p-3 text-left ${onOpenContext ? 'hover:bg-port-border/20' : ''}`}>
<span className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-port-accent"><Brain size={15} aria-hidden="true" /> Effective context</span>
- <span className="mt-2 block text-lg font-semibold text-port-text">~{number(context?.approximateTokens)} tokens</span>
+ <span className="mt-2 block text-lg font-semibold text-port-text">~{formatCount(context?.approximateTokens)} tokens</span>
<span className="mt-1 block text-xs text-port-text-muted">
- {number(context?.chars)} / {number(context?.maxChars)} characters · {number(context?.memoryCount)} curated memories · summary {context?.summaryState || 'unknown'}
+ {formatCount(context?.chars)} / {formatCount(context?.maxChars)} characters · {formatCount(context?.memoryCount)} curated memories · summary {context?.summaryState || 'unknown'}
</span>
</ContextSurface>
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index 3050a72e71..c2ad8a14cb 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -34,7 +34,7 @@ import { extractCosTaskType } from '../../../lib/cosTaskType';
import { isAgentHandoff } from '../../../lib/agentOutcome';
import AgentResultLine from '../AgentResultLine';
import { DEFAULT_REVIEWER, normalizeReviewers } from '../constants';
-import { formatBytes, formatDurationMs, formatDateTime, formatTimeOfDay } from '../../../utils/formatters';
+import { formatBytes, formatCount, formatDurationMs, formatDateTime, formatTimeOfDay } from '../../../utils/formatters';
import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
import ConfirmButtonPair from '../../ui/ConfirmButtonPair';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
@@ -111,7 +111,7 @@ function TranscriptTruncationNotice({ transcript }) {
<AlertTriangle size={12} aria-hidden="true" className="shrink-0" />
<span>
{count > 0
- ? `Showing the last ${count.toLocaleString()} ${count === 1 ? 'line' : 'lines'} — the full transcript${size} is on disk in the agent's output.txt.`
+ ? `Showing the last ${formatCount(count)} ${count === 1 ? 'line' : 'lines'} — the full transcript${size} is on disk in the agent's output.txt.`
: `The tail of this transcript held no readable lines — the full transcript${size} is on disk in the agent's output.txt.`}
</span>
</div>
@@ -481,7 +481,7 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
: null;
const prefillLabel = prefillBudget ? formatDurationMs(prefillBudget.prefillMs) : null;
const prefillReason = prefillBudget
- ? `Large prompt (~${(prefillBudget.promptTokens ?? 0).toLocaleString()} tokens) on a local model server — expect roughly ${prefillLabel} of silent prefill before the first line of output. The run is working, not wedged.${
+ ? `Large prompt (~${formatCount(prefillBudget.promptTokens, { fallback: '0' })} tokens) on a local model server — expect roughly ${prefillLabel} of silent prefill before the first line of output. The run is working, not wedged.${
prefillBudget.expectedDurationMs
? ` Its duration estimate was raised to ~${formatDurationMs(prefillBudget.expectedDurationMs)} to cover it.`
: ''}`
@@ -1183,7 +1183,7 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
<span className="text-sm text-gray-300">Agent prompt</span>
{promptContent && (
<span className="text-xs text-gray-500 font-mono">
- {promptContent.length.toLocaleString()} chars · {promptContent.split('\n').length} lines
+ {formatCount(promptContent.length)} chars · {formatCount(promptContent.split('\n').length)} lines
</span>
)}
</div>
diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsx
index 9f7a72f087..62c4b3d1e5 100644
--- a/client/src/components/cos/tabs/AgentsTab.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.jsx
@@ -10,6 +10,7 @@ import BrailleSpinner from '../../BrailleSpinner';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
import { agentResumeMessage } from '../../../lib/agentResumeOutcome';
import { isAgentHandoff } from '../../../lib/agentOutcome';
+import { formatCount } from '../../../utils/formatters';
// What each `resumeAgent` outcome actually did (server modes, agentManagement.js).
// `already-active` and `superseded` deliberately queue NOTHING — the task is already
@@ -334,7 +335,7 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
<h3 className="text-lg font-semibold text-white">
Completed Agents
<span className="text-sm text-gray-500 font-normal ml-2">
- ({totalCount} total)
+ ({formatCount(totalCount)} total)
</span>
</h3>
<button
@@ -350,7 +351,7 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
<InlineConfirmRow
className="mb-3"
question={totalCount > 0
- ? `Clear ALL completed agents? This removes ${totalCount} agent record${totalCount === 1 ? '' : 's'} and cannot be undone.`
+ ? `Clear ALL completed agents? This removes ${formatCount(totalCount)} agent record${totalCount === 1 ? '' : 's'} and cannot be undone.`
: 'Clear ALL completed agents? This cannot be undone.'}
confirmText="Clear all"
confirmTitle="Confirm clear all completed agents"
@@ -431,7 +432,7 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
: `No loaded agents match "${searchQuery}"`}
{hasMoreDates && (
<div className="mt-2 text-xs">
- {remainingCount} agents in older dates not yet loaded
+ {formatCount(remainingCount)} agents in older dates not yet loaded
</div>
)}
</div>
diff --git a/client/src/components/cos/tabs/JobsTab.jsx b/client/src/components/cos/tabs/JobsTab.jsx
index 33ebb4bfec..c77a5a22ac 100644
--- a/client/src/components/cos/tabs/JobsTab.jsx
+++ b/client/src/components/cos/tabs/JobsTab.jsx
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback, useMemo } from 'react';
import { Plus, RefreshCw } from 'lucide-react';
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
-import { formatDateTime } from '../../../utils/formatters';
+import { formatCount, formatDateTime } from '../../../utils/formatters';
import AgentJobProviderFields, { hasRunnableAgentProvider } from '../AgentJobProviderFields';
import { filterRunnableProviders } from '../../../utils/providers';
import FormField from '../../ui/FormField';
@@ -203,8 +203,8 @@ export default function JobsTab() {
{stats && (
<div className="flex gap-4 text-xs text-gray-500">
- <span>{stats.enabled} enabled / {stats.total} total</span>
- <span>{stats.totalRuns} total runs</span>
+ <span>{formatCount(stats.enabled)} enabled / {formatCount(stats.total)} total</span>
+ <span>{formatCount(stats.totalRuns)} total runs</span>
{stats.nextDue && (
<span className={stats.nextDue.isDue ? 'text-port-warning' : ''}>
Next: {stats.nextDue.jobName} ({stats.nextDue.isDue ? 'due now' : formatDateTime(stats.nextDue.nextDueAt)})
diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsx
index 76f827fd0c..12bcd962d2 100644
--- a/client/src/components/cos/tabs/MindTab.jsx
+++ b/client/src/components/cos/tabs/MindTab.jsx
@@ -8,7 +8,7 @@ import useProviderModels from '../../../hooks/useProviderModels';
import { useSocket } from '../../../hooks/useSocket';
import { uuidv4 } from '../../../lib/uuid.js';
import * as api from '../../../services/api';
-import { formatDateTime, timeUntil } from '../../../utils/formatters';
+import { formatCount, formatDateTime, timeUntil } from '../../../utils/formatters';
import BrailleSpinner from '../../BrailleSpinner';
import Drawer from '../../Drawer';
import AutoSizeTextarea from '../../ui/AutoSizeTextarea';
@@ -941,8 +941,8 @@ export default function MindTab() {
/>
<div className="grid grid-cols-2 gap-2">
- <MindStateButton icon={Brain} label="Context" value={runtime?.context?.approximateTokens == null ? 'Unavailable' : `~${runtime.context.approximateTokens.toLocaleString()} tokens`} detail={`${runtime?.context?.chars?.toLocaleString() || '—'} characters`} onClick={() => openPanel('context')} />
- <MindStateButton icon={Database} label="Memories" value={runtime?.context?.memoryCount == null ? 'Unavailable' : `${runtime.context.memoryCount} accessible`} detail="Created and curated" onClick={() => openPanel('memories')} />
+ <MindStateButton icon={Brain} label="Context" value={runtime?.context?.approximateTokens == null ? 'Unavailable' : `~${formatCount(runtime.context.approximateTokens)} tokens`} detail={`${formatCount(runtime?.context?.chars)} characters`} onClick={() => openPanel('context')} />
+ <MindStateButton icon={Database} label="Memories" value={runtime?.context?.memoryCount == null ? 'Unavailable' : `${formatCount(runtime.context.memoryCount)} accessible`} detail="Created and curated" onClick={() => openPanel('memories')} />
<MindStateButton icon={Eraser} label="Cleanup" value={mind?.capabilities?.manageMind ? 'Self-maintenance on' : 'User controlled'} detail="Memories, history, and context" onClick={() => openPanel('maintenance')} />
<MindStateButton icon={Wrench} label="Tools" value={grantedCapabilityCount > 0 ? `${grantedCapabilityCount} grant${grantedCapabilityCount === 1 ? '' : 's'} enabled` : 'No grants'} detail="Narrow, typed authority" onClick={() => openPanel('tools')} />
diff --git a/client/src/components/cos/tabs/RunEventsTab.jsx b/client/src/components/cos/tabs/RunEventsTab.jsx
index e03d5b52df..c8d32a1fc9 100644
--- a/client/src/components/cos/tabs/RunEventsTab.jsx
+++ b/client/src/components/cos/tabs/RunEventsTab.jsx
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback } from 'react';
import { useSearchParams } from 'react-router';
import { RefreshCw, ScrollText, Wrench } from 'lucide-react';
import * as api from '../../../services/api';
-import { formatDateTime, formatRuntime, formatBytes, timeAgo } from '../../../utils/formatters';
+import { formatCount, formatDateTime, formatRuntime, formatBytes, timeAgo } from '../../../utils/formatters';
import BrailleSpinner from '../../BrailleSpinner';
import Banner from '../../ui/Banner';
import ConfirmButtonPair from '../../ui/ConfirmButtonPair';
@@ -210,9 +210,9 @@ export default function RunEventsTab() {
{stats && (
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
- <LedgerStat label="Active generation" value={`${stats.activeEvents} / ${stats.maxActiveEvents}`} />
- <LedgerStat label="Archived" value={String(stats.archivedEvents)} />
- <LedgerStat label="Retention" value={`${stats.maxRetainedEvents} events · ${stats.maxEventAgeDays}d`} />
+ <LedgerStat label="Active generation" value={`${formatCount(stats.activeEvents)} / ${formatCount(stats.maxActiveEvents)}`} />
+ <LedgerStat label="Archived" value={formatCount(stats.archivedEvents)} />
+ <LedgerStat label="Retention" value={`${formatCount(stats.maxRetainedEvents)} events · ${stats.maxEventAgeDays}d`} />
<LedgerStat label="Oldest event" value={stats.oldestEventAt ? timeAgo(stats.oldestEventAt) : '—'} />
</div>
)}
@@ -253,7 +253,7 @@ export default function RunEventsTab() {
</span>
</div>
<div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-port-text-muted">
- <span>{projection.eventCount} events</span>
+ <span>{formatCount(projection.eventCount)} events</span>
<span>{timeAgo(projection.lastEventAt)}</span>
{projectionAnnotations(projection).map((note) => (
<span key={note} className="rounded bg-port-border/40 px-1.5 py-0.5">{note}</span>
diff --git a/client/src/components/cos/tabs/RunEventsTab.test.jsx b/client/src/components/cos/tabs/RunEventsTab.test.jsx
index 6096e5804e..42d74fdd06 100644
--- a/client/src/components/cos/tabs/RunEventsTab.test.jsx
+++ b/client/src/components/cos/tabs/RunEventsTab.test.jsx
@@ -94,8 +94,8 @@ describe('RunEventsTab', () => {
it('renders the ledger bound so "why is this run missing" has an answer', async () => {
renderTab();
- expect(await screen.findByText('12 / 5000')).toBeInTheDocument();
- expect(screen.getByText('10000 events · 30d')).toBeInTheDocument();
+ expect(await screen.findByText('12 / 5,000')).toBeInTheDocument();
+ expect(screen.getByText('10,000 events · 30d')).toBeInTheDocument();
});
it('replays the run named by ?run= without the user clicking anything', async () => {
diff --git a/client/src/components/dashboard/builtins/HourlyActivityWidget.jsx b/client/src/components/dashboard/builtins/HourlyActivityWidget.jsx
index c3f87bd374..3337d9141e 100644
--- a/client/src/components/dashboard/builtins/HourlyActivityWidget.jsx
+++ b/client/src/components/dashboard/builtins/HourlyActivityWidget.jsx
@@ -1,4 +1,4 @@
-import { formatHourOfDay } from '../../../utils/formatters';
+import { formatCount, formatHourOfDay } from '../../../utils/formatters';
export default function HourlyActivityWidget({ dashboardState }) {
const hourlyActivity = dashboardState.usage?.hourlyActivity;
@@ -35,7 +35,7 @@ export default function HourlyActivityWidget({ dashboardState }) {
<div className="text-2xl" aria-hidden="true">⏰</div>
<div>
<h3 className="text-lg font-semibold text-white">Activity by Hour</h3>
- <p className="text-sm text-gray-500">{totalSessions} total sessions tracked</p>
+ <p className="text-sm text-gray-500">{formatCount(totalSessions)} total sessions tracked</p>
</div>
</div>
{peakDescription && <div className="text-sm text-port-success">{peakDescription}</div>}
diff --git a/client/src/components/digital-twin/tabs/AutobiographyTab.jsx b/client/src/components/digital-twin/tabs/AutobiographyTab.jsx
index f43b8f28b4..319a5908de 100644
--- a/client/src/components/digital-twin/tabs/AutobiographyTab.jsx
+++ b/client/src/components/digital-twin/tabs/AutobiographyTab.jsx
@@ -22,7 +22,7 @@ import { copyToClipboard } from '../../../lib/clipboard';
import { countWords } from '../../../lib/textUtils';
import toast from '../../ui/Toast';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
-import { formatDateTime, formatDateNumeric } from '../../../utils/formatters';
+import { formatCount, formatDateTime, formatDateNumeric } from '../../../utils/formatters';
export default function AutobiographyTab({ onRefresh }) {
const [searchParams, setSearchParams] = useSearchParams();
@@ -242,7 +242,7 @@ export default function AutobiographyTab({ onRefresh }) {
{stats && (
<div className="flex flex-wrap gap-3 text-sm text-gray-400">
<span>{stats.totalStories} stories</span>
- <span>{(stats.totalWords ?? 0).toLocaleString()} words</span>
+ <span>{formatCount(stats.totalWords, { fallback: '0' })} words</span>
<span>{stats.promptsRemaining} prompts remaining</span>
</div>
)}
@@ -392,7 +392,7 @@ export default function AutobiographyTab({ onRefresh }) {
<div className="flex items-center justify-between">
<div className="flex items-center gap-3 text-sm text-gray-400">
- <span>{wordCount} words</span>
+ <span>{formatCount(wordCount)} words</span>
<Clock size={14} />
<span>~{Math.max(1, Math.round(wordCount / 150))} min read</span>
</div>
@@ -479,7 +479,7 @@ export default function AutobiographyTab({ onRefresh }) {
follow-up
</span>
)}
- <span className="text-xs text-gray-500">{story.wordCount} words</span>
+ <span className="text-xs text-gray-500">{formatCount(story.wordCount)} words</span>
<span className="text-xs text-gray-600">
{formatDateNumeric(story.createdAt)}
</span>
diff --git a/client/src/components/digital-twin/tabs/EnrichTab.jsx b/client/src/components/digital-twin/tabs/EnrichTab.jsx
index 32f36867c3..44fc3d5910 100644
--- a/client/src/components/digital-twin/tabs/EnrichTab.jsx
+++ b/client/src/components/digital-twin/tabs/EnrichTab.jsx
@@ -18,7 +18,7 @@ import { FormField } from '../../ui/FormField';
import { ENRICHMENT_CATEGORIES } from '../constants';
import ListEnrichment from '../ListEnrichment';
import ScaleInput from '../ScaleInput';
-import { formatDateNumeric } from '../../../utils/formatters';
+import { formatCount, formatDateNumeric } from '../../../utils/formatters';
export default function EnrichTab({ onRefresh }) {
const [searchParams, setSearchParams] = useSearchParams();
@@ -589,7 +589,7 @@ export default function EnrichTab({ onRefresh }) {
</button>
)}
<div className="text-xs text-gray-500 mt-1">
- {sample.value.length} characters {sample.value.length < 50 && sample.value.length > 0 && '(need 50+)'}
+ {formatCount(sample.value.length)} characters {sample.value.length < 50 && sample.value.length > 0 && '(need 50+)'}
</div>
</div>
))}
diff --git a/client/src/components/digital-twin/tabs/InterviewTab.jsx b/client/src/components/digital-twin/tabs/InterviewTab.jsx
index de0769c991..7389b66cc5 100644
--- a/client/src/components/digital-twin/tabs/InterviewTab.jsx
+++ b/client/src/components/digital-twin/tabs/InterviewTab.jsx
@@ -15,6 +15,7 @@ import useProviderModels from '../../../hooks/useProviderModels';
import ProviderModelSelector from '../../ProviderModelSelector';
import InterviewAnalysisCard from '../InterviewAnalysisCard';
import { ENRICHMENT_CATEGORIES } from '../constants';
+import { formatCount } from '../../../utils/formatters';
export default function InterviewTab({ onRefresh }) {
const navigate = useNavigate();
@@ -122,7 +123,7 @@ export default function InterviewTab({ onRefresh }) {
<div className="flex items-center justify-between">
<span className="text-xs text-gray-500">
- {content.length} characters {content.length > 0 && content.length < 50 && '(need 50+)'}
+ {formatCount(content.length)} characters {content.length > 0 && content.length < 50 && '(need 50+)'}
</span>
<button
onClick={handleAnalyze}
diff --git a/client/src/components/digital-twin/tabs/VoiceStyleTab.jsx b/client/src/components/digital-twin/tabs/VoiceStyleTab.jsx
index cd21787a45..04a1a2f2c6 100644
--- a/client/src/components/digital-twin/tabs/VoiceStyleTab.jsx
+++ b/client/src/components/digital-twin/tabs/VoiceStyleTab.jsx
@@ -10,6 +10,7 @@ import * as api from '../../../services/api';
import toast from '../../ui/Toast';
import useProviderModels from '../../../hooks/useProviderModels';
import ProviderModelSelector from '../../ProviderModelSelector';
+import { formatCount } from '../../../utils/formatters';
const MIN_TRANSCRIPT = 100;
@@ -176,7 +177,7 @@ export default function VoiceStyleTab({ onRefresh }) {
disabled={comparing}
/>
<span className="text-xs text-gray-500">
- {transcript.length} characters {transcript.length > 0 && transcript.length < MIN_TRANSCRIPT && `(need ${MIN_TRANSCRIPT}+)`}
+ {formatCount(transcript.length)} characters {transcript.length > 0 && transcript.length < MIN_TRANSCRIPT && `(need ${MIN_TRANSCRIPT}+)`}
</span>
</div>
diff --git a/client/src/components/insights/GoalScorecardTab.jsx b/client/src/components/insights/GoalScorecardTab.jsx
index 6f56667ccf..601bfad877 100644
--- a/client/src/components/insights/GoalScorecardTab.jsx
+++ b/client/src/components/insights/GoalScorecardTab.jsx
@@ -10,7 +10,7 @@ import {
updateGoalScorecardSettings,
getProviders,
} from '../../services/api';
-import { timeAgo } from '../../utils/formatters';
+import { formatCount, timeAgo } from '../../utils/formatters';
const fmtHours = (h) => `${Number(h ?? 0).toFixed(1)}h`;
@@ -243,7 +243,7 @@ export default function GoalScorecardTab() {
<div className="bg-port-card border border-port-border rounded-lg p-4">
<div className="text-xs text-gray-500 mb-1">Unaligned time</div>
<div className="text-2xl font-bold text-port-warning">{fmtHours(totals?.unalignedHours)}</div>
- <div className="text-xs text-gray-600 mt-1">{totals?.eventCount ?? 0} events tracked</div>
+ <div className="text-xs text-gray-600 mt-1">{formatCount(totals?.eventCount, { fallback: '0' })} events tracked</div>
</div>
<div className="bg-port-card border border-port-border rounded-lg p-4">
<div className="flex items-center justify-between mb-1">
diff --git a/client/src/components/instances/BrainParityPanel.jsx b/client/src/components/instances/BrainParityPanel.jsx
index cca00037e4..c6ce9de6ae 100644
--- a/client/src/components/instances/BrainParityPanel.jsx
+++ b/client/src/components/instances/BrainParityPanel.jsx
@@ -16,7 +16,7 @@ import { useEffect, useState } from 'react';
import { ChevronDown, ChevronRight, ScanSearch, RefreshCw } from 'lucide-react';
import Pill from '../ui/Pill';
import { runBrainParityCheck } from '../../services/api';
-import { timeAgo } from '../../utils/formatters';
+import { formatCount, timeAgo } from '../../utils/formatters';
// Statuses in the order they're worth reading: what we hold and they don't,
// what they hold and we don't, then same-id-different-clock drift.
@@ -151,7 +151,7 @@ export default function BrainParityPanel({ peer, report: storedReport }) {
{report?.available && (
<>
<div className="flex flex-wrap items-center gap-1.5">
- <Pill tone="muted" size="xs" bordered={false}>{report.summary?.total ?? 0} records compared</Pill>
+ <Pill tone="muted" size="xs" bordered={false}>{formatCount(report.summary?.total, { fallback: '0' })} records compared</Pill>
{STATUS_META.map(({ key, label: statusLabel, tone: statusTone }) => (
report.summary?.[key] > 0 && (
<Pill key={key} tone={statusTone} size="xs" bordered={false}>
diff --git a/client/src/components/meatspace/tabs/GenomeTab.jsx b/client/src/components/meatspace/tabs/GenomeTab.jsx
index 58ee2c870d..41599c0da3 100644
--- a/client/src/components/meatspace/tabs/GenomeTab.jsx
+++ b/client/src/components/meatspace/tabs/GenomeTab.jsx
@@ -56,7 +56,7 @@ async function parseZipText(arrayBuffer, ext = '.txt') {
}
import * as api from '../../../services/api';
import { ATTACHMENT_MAX_FILE_SIZE } from '../../../utils/fileUpload';
-import { formatBytes, formatDateNumeric } from '../../../utils/formatters';
+import { formatBytes, formatCount, formatDateNumeric } from '../../../utils/formatters';
import GenomeCategoryCard from '../GenomeCategoryCard';
import EpigeneticTracker from '../EpigeneticTracker';
import ProvenanceChip from '../../ui/ProvenanceChip';
@@ -215,7 +215,7 @@ export default function GenomeTab() {
}
const result = await api.uploadGenomeFile(parsed.content, parsed.filename).catch(() => null);
if (result) {
- toast.success(`Genome uploaded: ${result.snpCount.toLocaleString()} SNPs found`);
+ toast.success(`Genome uploaded: ${formatCount(result.snpCount)} SNPs found`);
await fetchSummary();
}
setUploading(false);
@@ -228,7 +228,7 @@ export default function GenomeTab() {
const content = e.target.result;
const result = await api.uploadGenomeFile(content, file.name).catch(() => null);
if (result) {
- toast.success(`Genome uploaded: ${result.snpCount.toLocaleString()} SNPs found`);
+ toast.success(`Genome uploaded: ${formatCount(result.snpCount)} SNPs found`);
await fetchSummary();
}
setUploading(false);
@@ -325,7 +325,7 @@ export default function GenomeTab() {
return null;
});
if (result) {
- toast.success(`ClinVar synced: ${result.variantCount?.toLocaleString()} variants indexed`);
+ toast.success(`ClinVar synced: ${formatCount(result.variantCount)} variants indexed`);
setClinvarStatus(result);
}
setClinvarSyncing(false);
@@ -454,7 +454,7 @@ export default function GenomeTab() {
{/* Summary Dashboard */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
- <StatCard label="SNPs Loaded" value={summary.snpCount?.toLocaleString()} />
+ <StatCard label="SNPs Loaded" value={formatCount(summary.snpCount)} />
<StatCard label="Markers Found" value={markers.length} />
<StatCard label="Categories" value={Object.keys(grouped).length} />
<StatCard label="Build" value={summary.build} />
@@ -687,7 +687,7 @@ export default function GenomeTab() {
) : (
<>
<span className="text-xs text-gray-500">
- {clinvarStatus.variantCount?.toLocaleString()} variants indexed
+ {formatCount(clinvarStatus.variantCount)} variants indexed
{clinvarStatus.syncedAt && ` (synced ${formatDateNumeric(clinvarStatus.syncedAt)})`}
</span>
<button
@@ -723,7 +723,7 @@ export default function GenomeTab() {
{/* Summary badges */}
<div className="flex flex-wrap gap-2 text-sm">
<span className="px-2 py-1 rounded bg-port-card border border-port-border text-gray-300">
- {clinvarResults.totalMatched} total matches
+ {formatCount(clinvarResults.totalMatched)} total matches
</span>
{clinvarResults.bySeverity.pathogenic > 0 && (
<span className="px-2 py-1 rounded bg-red-500/10 text-red-400 border border-red-500/20">
diff --git a/client/src/components/messages/ContactsTab.jsx b/client/src/components/messages/ContactsTab.jsx
index 606c9eb443..bf0fa765d6 100644
--- a/client/src/components/messages/ContactsTab.jsx
+++ b/client/src/components/messages/ContactsTab.jsx
@@ -6,7 +6,7 @@ import {
} from 'lucide-react';
import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
-import { formatDateTime } from '../../utils/formatters';
+import { formatCount, formatDateTime } from '../../utils/formatters';
import {
getContactsStatus,
checkContactsSetup,
@@ -261,7 +261,7 @@ export default function ContactsTab() {
<div className="min-w-0">
<div className="font-medium text-gray-100 truncate">{s.displayName}</div>
<div className="text-xs text-gray-500 truncate">
- {[s.organization, s.phones?.[0], s.emails?.[0], s.eventCount ? `${s.eventCount} msgs` : null]
+ {[s.organization, s.phones?.[0], s.emails?.[0], s.eventCount ? `${formatCount(s.eventCount)} msgs` : null]
.filter(Boolean)
.join(' · ')}
</div>
diff --git a/client/src/components/messages/IMessageTab.jsx b/client/src/components/messages/IMessageTab.jsx
index 0d46952b6d..a24c999e1c 100644
--- a/client/src/components/messages/IMessageTab.jsx
+++ b/client/src/components/messages/IMessageTab.jsx
@@ -8,7 +8,7 @@ import BrailleSpinner from '../BrailleSpinner';
import Drawer from '../Drawer';
import toast from '../ui/Toast';
import * as api from '../../services/api';
-import { formatClockTime, timeAgo, formatDateNumeric } from '../../utils/formatters';
+import { formatClockTime, formatCount, timeAgo, formatDateNumeric } from '../../utils/formatters';
import useDrawerTab from '../../hooks/useDrawerTab';
import { IMessageSettingsPanel } from './IMessageSettingsPanel';
@@ -623,7 +623,7 @@ export default function IMessageTab() {
<div className="flex flex-wrap gap-2 text-xs text-gray-400 shrink-0">
<span className="rounded border border-port-border bg-port-card px-2 py-1">
- {stats?.eventCount ?? 0} events
+ {formatCount(stats?.eventCount, { fallback: '0' })} events
</span>
<span className="rounded border border-port-border bg-port-card px-2 py-1">
{stats?.conversationCount ?? 0} conversations
diff --git a/client/src/components/messages/MessageDetail.jsx b/client/src/components/messages/MessageDetail.jsx
index 4ff44b7f0e..38065aeb57 100644
--- a/client/src/components/messages/MessageDetail.jsx
+++ b/client/src/components/messages/MessageDetail.jsx
@@ -1,7 +1,7 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { ArrowLeft, Reply, Sparkles, Send, RefreshCw, Archive, Trash2, User } from 'lucide-react';
import toast from '../ui/Toast';
-import { formatDateTime } from '../../utils/formatters';
+import { formatCount, formatDateTime } from '../../utils/formatters';
import * as api from '../../services/api';
/**
@@ -187,7 +187,7 @@ export default function MessageDetail({ message, accounts, onBack }) {
<div className="flex-1 min-w-0">
<h2 className="text-sm font-medium text-white truncate">{displayedMessage.subject || '(no subject)'}</h2>
{hasThread && (
- <span className="text-xs text-gray-500">{threadMessages.length} messages</span>
+ <span className="text-xs text-gray-500">{formatCount(threadMessages.length)} messages</span>
)}
</div>
<div className="flex flex-wrap items-center justify-end gap-1">
diff --git a/client/src/components/songs/MidiVisualization.jsx b/client/src/components/songs/MidiVisualization.jsx
index 64ac5e7c57..fa9fbcd30f 100644
--- a/client/src/components/songs/MidiVisualization.jsx
+++ b/client/src/components/songs/MidiVisualization.jsx
@@ -5,7 +5,7 @@ import useMidiPlayer from '../../hooks/useMidiPlayer';
import { detectChordWindows } from '../../lib/midiChords';
import { midiNoteName } from '../../lib/pianoKeyboard';
import { layerColor, ROLL_BG } from '../../lib/canvasRoll.js';
-import { formatTimecode } from '../../utils/formatters';
+import { formatCount, formatTimecode } from '../../utils/formatters';
import MidiPianoRoll, { MIN_ZOOM, ZOOM_STEP, clampZoom } from './MidiPianoRoll.jsx';
// Chrome around <MidiPianoRoll>: loads + parses the .mid (useMidiNotes),
@@ -155,12 +155,12 @@ export default function MidiVisualization({ url, filename, model }) {
onTogglePlay={toggle}
/>
<p className="sr-only">
- MIDI transcription: {data.notes.length} notes across {data.tracks.length} track{data.tracks.length === 1 ? '' : 's'},
+ MIDI transcription: {formatCount(data.notes.length)} notes across {formatCount(data.tracks.length)} track{data.tracks.length === 1 ? '' : 's'},
pitch range {midiNoteName(data.minMidi)} to {midiNoteName(data.maxMidi)}, duration {formatTimecode(data.durationSec)}.
{chords.length > 0 && ` Detected chords include ${chords.slice(0, 8).map((c) => c.label).join(', ')}.`}
</p>
<div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[10px] text-port-text-muted">
- <span>{`${data.notes.length} notes · ${densityLabel}`}</span>
+ <span>{`${formatCount(data.notes.length)} notes · ${densityLabel}`}</span>
<span>{`${midiNoteName(data.minMidi)}–${midiNoteName(data.maxMidi)}`}</span>
<span>{formatTimecode(data.durationSec)}</span>
{data.tempos.length > 0 && <span>{`${data.tempos[0].bpm} BPM`}</span>}
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsx
index 928e24abef..0ab27c2a8e 100644
--- a/client/src/components/universe/UniverseCanonSection.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -48,6 +48,7 @@ import { universeStylePreset } from '../../lib/universeStylePreset';
import { descriptorForCanonEntry } from '../../lib/canonPrompt';
import { applySheetPointer } from '../../lib/sheetPointers';
import { BIBLE_LIMITS, capImageRefs } from '../../lib/bibleLimits';
+import { formatCount } from '../../utils/formatters';
// A universe's canon list for a kind is sometimes absent on a freshly-created
// record; normalize to [] so callers can spread/map without a guard each time.
@@ -1138,7 +1139,7 @@ function KindSection() {
const list = all.length === 0 ? (
filtered && totalCount > 0
- ? <p className="text-xs text-gray-500 italic">No {kind.label.toLowerCase()} in the selected series. {totalCount} total in this universe — clear the filter to see them all.</p>
+ ? <p className="text-xs text-gray-500 italic">No {kind.label.toLowerCase()} in the selected series. {formatCount(totalCount)} total in this universe — clear the filter to see them all.</p>
: <p className="text-xs text-gray-500 italic">No {kind.label.toLowerCase()} yet. Use <em>Add</em> or <em>Extract from prose</em> above to populate this list.</p>
) : (
<ul className="space-y-2">
diff --git a/client/src/components/wiki/tabs/LogTab.jsx b/client/src/components/wiki/tabs/LogTab.jsx
index 5a61a3e031..3ede7d61ea 100644
--- a/client/src/components/wiki/tabs/LogTab.jsx
+++ b/client/src/components/wiki/tabs/LogTab.jsx
@@ -1,7 +1,7 @@
import { useState, useEffect, useMemo } from 'react';
import * as api from '../../../services/api';
import { RefreshCw, Clock } from 'lucide-react';
-import { timeAgo } from '../../../utils/formatters';
+import { formatCount, timeAgo } from '../../../utils/formatters';
import BrailleSpinner from '../../BrailleSpinner';
export default function LogTab({ vaultId, allNotes }) {
@@ -80,7 +80,7 @@ export default function LogTab({ vaultId, allNotes }) {
<div className="flex items-center justify-between mb-4">
<h3 className="text-sm font-medium text-white">Activity Log</h3>
<div className="flex items-center gap-2 text-xs text-gray-500">
- <span>{entries.length} entries</span>
+ <span>{formatCount(entries.length)} entries</span>
{log.modifiedAt && <span>Updated {timeAgo(log.modifiedAt)}</span>}
<button onClick={loadLog} aria-label="Refresh" className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 rounded hover:bg-port-card text-gray-500 hover:text-white">
<RefreshCw size={12} />
diff --git a/client/src/components/writers-room/ExercisePanel.jsx b/client/src/components/writers-room/ExercisePanel.jsx
index 0c1102ea0c..e1b42cccd9 100644
--- a/client/src/components/writers-room/ExercisePanel.jsx
+++ b/client/src/components/writers-room/ExercisePanel.jsx
@@ -8,7 +8,7 @@ import {
discardWritersRoomExercise,
promoteWritersRoomExercise,
} from '../../services/apiWritersRoom';
-import { formatCountdown } from '../../utils/formatters';
+import { formatCount, formatCountdown } from '../../utils/formatters';
import { countWords } from '../../lib/textUtils';
import { FormField } from '../ui/FormField';
import useMounted from '../../hooks/useMounted';
@@ -185,7 +185,7 @@ export default function ExercisePanel({ activeWork, onClose, editorDirty = false
{formatCountdown(remaining)}
</div>
<div className="flex-1 text-xs text-gray-400">
- <div>{wordsAdded} words this session</div>
+ <div>{formatCount(wordsAdded)} words this session</div>
{prompt && <div className="text-gray-500 italic truncate">{prompt}</div>}
</div>
<button onClick={() => finishSession({ keep: true })}
@@ -225,7 +225,7 @@ export default function ExercisePanel({ activeWork, onClose, editorDirty = false
'bg-port-warning animate-pulse'
}`} />
<span className="text-gray-300">
- {ex.status === 'finished' ? `${ex.wordsAdded ?? 0} words` : ex.status}
+ {ex.status === 'finished' ? `${formatCount(ex.wordsAdded, { fallback: '0' })} words` : ex.status}
</span>
<span className="text-gray-600 truncate flex-1">{ex.prompt || '(free-write)'}</span>
<span className="text-gray-600">{Math.round((ex.durationSeconds || 0) / 60)}m</span>
diff --git a/client/src/pages/CharacterSheet.jsx b/client/src/pages/CharacterSheet.jsx
index 7741209522..e070d5fcc7 100644
--- a/client/src/pages/CharacterSheet.jsx
+++ b/client/src/pages/CharacterSheet.jsx
@@ -9,7 +9,7 @@ import BrailleSpinner from '../components/BrailleSpinner';
import PageSkeleton from '../components/ui/PageSkeleton';
import GoalsCard from '../components/character/GoalsCard';
import toast from '../components/ui/Toast';
-import { timeAgo, formatCompactCount } from '../utils/formatters';
+import { timeAgo, formatCompactCount, formatCount } from '../utils/formatters';
import api, { generateAvatar } from '../services/api';
import socket from '../services/socket';
import { clickableProps } from '../lib/a11yKeyboard.js';
@@ -846,7 +846,7 @@ export default function CharacterSheet() {
<div className="flex items-center gap-2 px-4 py-3 border-b border-port-border">
<ScrollText className="w-4 h-4 text-gray-400" />
<h3 className="text-sm font-medium text-gray-300">Event Log</h3>
- <span className="text-xs text-gray-500">({char.events?.length || 0} entries)</span>
+ <span className="text-xs text-gray-500">({formatCount(char.events?.length, { fallback: '0' })} entries)</span>
</div>
<div className="overflow-y-auto max-h-[400px] divide-y divide-port-border/50">
{(!char.events || char.events.length === 0) ? (
diff --git a/client/src/pages/FeatureAgents.jsx b/client/src/pages/FeatureAgents.jsx
index 730e361dbd..24fcb6e248 100644
--- a/client/src/pages/FeatureAgents.jsx
+++ b/client/src/pages/FeatureAgents.jsx
@@ -7,6 +7,7 @@ import socket from '../services/socket';
import FeatureAgentCard from '../components/feature-agents/FeatureAgentCard';
import PageSkeleton from '../components/ui/PageSkeleton';
import PageHeader from '../components/PageHeader';
+import { formatCount } from '../utils/formatters';
export default function FeatureAgents() {
const [agents, setAgents] = useState([]);
@@ -84,7 +85,7 @@ export default function FeatureAgents() {
<PageHeader
icon={Wand2}
title="Feature Agents"
- subtitle={`${agents.length} agent${agents.length !== 1 ? 's' : ''} · ${activeCount} active · ${totalRuns} total runs`}
+ subtitle={`${formatCount(agents.length)} agent${agents.length !== 1 ? 's' : ''} · ${formatCount(activeCount)} active · ${formatCount(totalRuns)} total runs`}
actions={
<>
<button
diff --git a/client/src/pages/Loops.jsx b/client/src/pages/Loops.jsx
index 2e4ebc55b0..62b20aeb54 100644
--- a/client/src/pages/Loops.jsx
+++ b/client/src/pages/Loops.jsx
@@ -8,7 +8,7 @@ import socket from '../services/socket';
import toast from '../components/ui/Toast';
import { FormField } from '../components/ui/FormField';
import { timeAgo } from '../components/feature-agents/constants';
-import { formatDurationMs } from '../utils/formatters';
+import { formatCount, formatDurationMs } from '../utils/formatters';
import BrailleSpinner from '../components/BrailleSpinner';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import { clickableProps } from '../lib/a11yKeyboard.js';
@@ -399,7 +399,7 @@ export default function Loops() {
</div>
<div className="flex items-center gap-3 text-xs text-gray-400">
{runningCount > 0 && <span className="text-port-success">{runningCount} active</span>}
- <span>{loops.length} total</span>
+ <span>{formatCount(loops.length)} total</span>
<button onClick={fetchLoops} className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 rounded hover:bg-port-border" title="Refresh" aria-label="Refresh">
<RefreshCw size={14} />
</button>
diff --git a/client/src/pages/OpenClaw.jsx b/client/src/pages/OpenClaw.jsx
index 58ce31d7bb..d58dc2d404 100644
--- a/client/src/pages/OpenClaw.jsx
+++ b/client/src/pages/OpenClaw.jsx
@@ -38,7 +38,7 @@ import SettingsTabsHeader from '../components/settings/SettingsTabsHeader';
import PageHeader from '../components/PageHeader';
import * as api from '../services/apiOpenClaw';
import * as coreApi from '../services/api';
-import { formatDateTime } from '../utils/formatters';
+import { formatCount, formatDateTime } from '../utils/formatters';
import { useOpenClawAttachments, OPENCLAW_ATTACHMENT_ACCEPT } from '../hooks/useOpenClawAttachments';
import { useOpenClawStream } from '../hooks/useOpenClawStream';
import { modKey } from '../utils/platform';
@@ -444,7 +444,7 @@ export default function OpenClaw() {
<div className="truncate text-sm font-medium">{session.title || session.label || session.id}</div>
<div className="mt-1 flex items-center justify-between gap-3 text-xs text-gray-500">
<span className="truncate">{session.id}</span>
- <span>{session.messageCount ?? 0} msgs</span>
+ <span>{formatCount(session.messageCount, { fallback: '0' })} msgs</span>
</div>
</button>
);
@@ -476,7 +476,7 @@ export default function OpenClaw() {
<div className="truncate text-sm font-medium">{session.title || session.label || session.id}</div>
<div className="mt-1 flex items-center justify-between gap-3 text-xs text-gray-500">
<span className="truncate">{session.id}</span>
- <span>{session.messageCount ?? 0} msgs</span>
+ <span>{formatCount(session.messageCount, { fallback: '0' })} msgs</span>
</div>
</button>
);
diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsx
index f8b2677a46..a055cd5721 100644
--- a/client/src/pages/PipelineIssue.jsx
+++ b/client/src/pages/PipelineIssue.jsx
@@ -38,6 +38,7 @@ import LengthProfilePicker from '../components/pipeline/LengthProfilePicker';
import ArcRolePicker from '../components/pipeline/ArcRolePicker';
import CatalogCastPanel from '../components/CatalogCastPanel';
import { VisualGenSettingsPanel } from '../components/pipeline/stages/VisualGenSettings';
+import { formatCount } from '../utils/formatters';
// Stages that surface a header-level settings gear. The Comic editor
// (`comicScript`) owns its own image-gen drawer inside ComicScriptStage,
@@ -438,7 +439,7 @@ export default function PipelineIssue() {
<div className="text-xs text-gray-400">
{latest.type === 'stage:start' && <>Generating <span className="text-white">{PIPELINE_STAGE_LABELS[latest.stage]}</span>…</>}
{latest.type === 'stage:complete' && latest.stage === 'episodeVideo' && <>{PIPELINE_STAGE_LABELS[latest.stage]} kicked off — {latest.scenes} scene{latest.scenes === 1 ? '' : 's'} queued in Creative Director</>}
- {latest.type === 'stage:complete' && latest.stage !== 'episodeVideo' && <>{PIPELINE_STAGE_LABELS[latest.stage]} ready ({latest.length} chars)</>}
+ {latest.type === 'stage:complete' && latest.stage !== 'episodeVideo' && <>{PIPELINE_STAGE_LABELS[latest.stage]} ready ({formatCount(latest.length)} chars)</>}
{latest.type === 'stage:error' && <>{PIPELINE_STAGE_LABELS[latest.stage]} error — {latest.error}</>}
{latest.type === 'skip' && <>{PIPELINE_STAGE_LABELS[latest.stage]} skipped — {latest.reason}</>}
{latest.type === 'start' && <>Starting auto-run…</>}
diff --git a/client/src/pages/Timeline.jsx b/client/src/pages/Timeline.jsx
index 72de0cfa69..28eb8a77fa 100644
--- a/client/src/pages/Timeline.jsx
+++ b/client/src/pages/Timeline.jsx
@@ -9,7 +9,7 @@ import PageHeader from '../components/PageHeader';
import TimelineImportPanels, { IMPORT_SOURCE_COUNT } from '../components/timeline/TimelineImportPanels';
import * as api from '../services/api';
import toast from '../components/ui/Toast';
-import { formatClockTime, formatDurationSec, formatWeekdayDate, localDateKey, shiftISODate } from '../utils/formatters';
+import { formatClockTime, formatCount, formatDurationSec, formatWeekdayDate, localDateKey, shiftISODate } from '../utils/formatters';
const SOURCE_ICON = {
gmail: Mail,
@@ -241,7 +241,7 @@ export default function Timeline() {
<Histogram histogram={histogram} />
<div className="flex flex-wrap gap-2 text-xs text-gray-400">
- <span className="rounded bg-port-card px-2 py-1 border border-port-border">{counts.total} events</span>
+ <span className="rounded bg-port-card px-2 py-1 border border-port-border">{formatCount(counts.total)} events</span>
{Object.entries(counts.bySource).map(([source, n]) => (
<span key={source} className="rounded bg-port-card px-2 py-1 border border-port-border">
{source}: {n}
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsx
index 29b487886e..dcac086274 100644
--- a/client/src/pages/UsagePage.jsx
+++ b/client/src/pages/UsagePage.jsx
@@ -5,7 +5,7 @@ import * as api from '../services/api';
import BrailleSpinner from '../components/BrailleSpinner';
import PageSkeleton from '../components/ui/PageSkeleton';
import Pill from '../components/ui/Pill';
-import { formatCompactCountOrDash as formatNumber, formatUsd, timeAgo } from '../utils/formatters';
+import { formatCompactCountOrDash as formatNumber, formatCount, formatUsd, timeAgo } from '../utils/formatters';
import { useAsyncAction } from '../hooks/useAsyncAction';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import SubscriptionSavingsCard from '../components/usage/SubscriptionSavingsCard';
@@ -352,7 +352,7 @@ function CostReportTable({ report }) {
// Cache token counts, with the hidden-on-mobile columns' values folded into a
// title so the numbers stay reachable when the columns collapse.
const cacheTitle = (row) =>
- `Cache read ${(row.cacheReadTokens ?? 0).toLocaleString()} · cache write ${(row.cacheWriteTokens ?? 0).toLocaleString()} tokens`;
+ `Cache read ${formatCount(row.cacheReadTokens, { fallback: '0' })} · cache write ${formatCount(row.cacheWriteTokens, { fallback: '0' })} tokens`;
function ProviderCostRows({ provider }) {
return (
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index a41ca46efe..dfa7c5bdd3 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -100,7 +100,7 @@ import { GROK_VIDEO_DURATIONS } from '../lib/grokVideoClip.js';
import { REACTOR_MAX_PROMPT_LENGTH } from '../lib/reactorVideoClip.js';
import { styledVideoPrompt } from '../lib/videoGenSubmission.js';
import ReactorPanel from '../components/videoGen/ReactorPanel';
-import { timeAgo } from '../utils/formatters';
+import { formatCount, timeAgo } from '../utils/formatters';
import ResolutionField from '../components/media/ResolutionField';
import { VIDEO_EDGE_BOUNDS, videoEdgeBoundsForModel, IC_LORA_MODES } from '../lib/videoGenParams.js';
import { finishTargetForRecord, isDeliveryVideoModel } from '../lib/videoFinish.js';
@@ -1310,8 +1310,8 @@ export default function VideoGen() {
here instead of surfacing as a 400 after Generate. */}
<p className={`mt-1 text-[11px] leading-snug ${promptOverLimit ? 'text-port-error' : 'text-gray-500'}`}>
{isReactor
- ? `${submittedPromptLength} / ${REACTOR_MAX_PROMPT_LENGTH} characters`
- : `${submittedPromptLength} characters`}
+ ? `${formatCount(submittedPromptLength)} / ${formatCount(REACTOR_MAX_PROMPT_LENGTH)} characters`
+ : `${formatCount(submittedPromptLength)} characters`}
</p>
{/* Only crossing the cap is worth announcing; the count itself
changes on every keystroke and would be pure noise. */}
diff --git a/client/src/pages/X.jsx b/client/src/pages/X.jsx
index 2b7f32dc78..3405f56fc2 100644
--- a/client/src/pages/X.jsx
+++ b/client/src/pages/X.jsx
@@ -7,7 +7,7 @@ import PageHeader from '../components/PageHeader';
import PageSkeleton from '../components/ui/PageSkeleton';
import TabPills from '../components/ui/TabPills';
import { useValidTab } from '../hooks/useValidTab';
-import { formatDateTime } from '../utils/formatters';
+import { formatCount, formatDateTime } from '../utils/formatters';
const TABS = [
{ id: 'health', label: 'Reach & health', icon: BarChart3 },
@@ -21,7 +21,6 @@ const buttonClass = 'rounded bg-port-accent px-3 py-2 text-sm font-medium text-w
const secondaryButton = 'rounded border border-port-border px-3 py-2 text-sm text-gray-200 disabled:cursor-not-allowed disabled:opacity-50';
const sameAccount = (left, right) => JSON.stringify(left) === JSON.stringify(right);
-const formatCount = (value) => Number.isInteger(value) ? value.toLocaleString() : '—';
const formatDate = (value) => formatDateTime(value, '—');
const stateLabel = (state) => ({ draft: 'Draft', pending_review: 'Awaiting review', approved: 'Approved', rejected: 'Rejected', opened: 'Opened in X' }[state] || state);
const normalizeHandle = (value) => String(value || '').trim().replace(/^@/, '');
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 939bc073f6..8b5dfa2244 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 formatters (`clamp`, `formatBytes`, `formatDownloadGb` (decimal-GB model download size, "~29 GB"), `formatCompactCount`, `formatCompactCountOrDash` (same, but an ABSENT count renders "—" rather than "0"), `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 (`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`. `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 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 formatters (`clamp`, `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 (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price; thousands are grouped, "$4,610.09") — `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`. `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 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, friendly cron parsing/building, anchored recurrence parsing/building/description, `isCronExpression` detection, `describeCron` human-readable rendering, `cronFromIntervalMs` numeric-interval → expression conversion (mirrors the server helper), 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`). |
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index 885e0e22e1..2e2b7ae577 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -306,7 +306,7 @@ export function formatAgeDays(value, fallback = '') {
const days = Math.floor((Date.now() - time) / 86400000);
// <= 0 covers a clock skew ahead of the publish date — never "-1 days ago".
if (days <= 0) return 'today';
- return `${days.toLocaleString()} day${days === 1 ? '' : 's'} ago`;
+ return `${GROUPED_INTEGER.format(days)} day${days === 1 ? '' : 's'} ago`;
}
/**
@@ -359,6 +359,30 @@ export function formatCompactCountOrDash(n) {
return n == null ? '—' : formatCompactCount(n);
}
+// Grouping is pinned to en-US rather than the browser locale. The UI is
+// English-only, and `$` is a US currency mark — rendering "$4.610,09" next to
+// English copy reads as a typo, not as localization. Counts use the same
+// separator so a total and its cost line up. The DATE helpers above stay on the
+// browser locale on purpose: a date carries no currency anchor, so there is
+// nothing for its separators to contradict.
+const GROUPED_INTEGER = new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 });
+const USD_CENTS = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
+
+/**
+ * Thousands-separated count for a number the user is meant to read exactly:
+ * 2762 → "2,762". Use this for a total, a record count, or a token count —
+ * anywhere `formatCompactCount`'s "2.8K" would lose the precision that is the
+ * point of showing the number at all.
+ * @param {number|string|null|undefined} n
+ * @param {object} [options]
+ * @param {string} [options.fallback='—'] - Rendered when the value is missing/unparseable
+ * @returns {string} e.g. "2,762"
+ */
+export function formatCount(n, { fallback = '—' } = {}) {
+ const value = roundForDisplay(n, 0);
+ return value === null ? fallback : GROUPED_INTEGER.format(value);
+}
+
/**
* Round a number to `decimals` places and drop trailing zeros
* (170.35000000000002 → 170.4, 170.0 → 170). Returns null for
@@ -412,12 +436,14 @@ export function formatPercent(value, { decimals = 1, fallback = '—' } = {}) {
}
/**
- * Format a USD amount for display: `$12.34`.
+ * Format a USD amount for display: `$12.34`, `$4,610.09`.
*
* `signed` keeps the minus sign OUTSIDE the dollar sign (`-$5.00`), so a
* negative saving reads as a loss rather than as a strange currency string.
* `trimWhole` drops the `.00` on a round figure — for a price the user typed
* ($200/mo), not for a computed total, where aligned cents are the point.
+ * Amounts past a thousand are grouped (`$4,610.09`) — an unseparated `$4610.09`
+ * is read as the wrong order of magnitude at a glance.
*
* @param {number} value - Dollar amount (nullish renders as $0.00; a non-nullish
* value that fails to parse as a finite number — NaN, a broken calc — renders
@@ -429,7 +455,9 @@ export function formatUsd(value, { signed = false, trimWhole = false, fallback =
const n = value === null || value === undefined ? 0 : Number(value);
if (!Number.isFinite(n)) return fallback;
const magnitude = signed ? Math.abs(n) : n;
- const body = trimWhole && Number.isInteger(magnitude) ? String(magnitude) : magnitude.toFixed(2);
+ const body = trimWhole && Number.isInteger(magnitude)
+ ? GROUPED_INTEGER.format(magnitude)
+ : USD_CENTS.format(magnitude);
return `${signed && n < 0 ? '-' : ''}$${body}`;
}
diff --git a/client/src/utils/formatters.test.js b/client/src/utils/formatters.test.js
index 8fcf7499f9..7eb63e9b64 100644
--- a/client/src/utils/formatters.test.js
+++ b/client/src/utils/formatters.test.js
@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';
import {
clamp, formatContextLength, formatDurationMin, formatDurationMs, formatEventDateTime, timeAgo, formatAgeDays,
formatCooldown, formatCountdown, recommendedRamGb, parseTimeoutMs, formatDurationSec, middleTruncate,
- formatWeight, formatPercent, formatUsd, formatBytes,
+ formatWeight, formatPercent, formatUsd, formatBytes, formatCount,
formatDateNumeric, formatTimeOfDaySeconds, formatClockTime, formatHourOfDay, formatWeekdayDate,
formatMonthDay, formatMonthYear, formatWeekdayShort, formatWeekdayTime, formatDateFull, formatDateShort, formatDateTime,
localDateKey, shiftISODate,
@@ -126,6 +126,38 @@ describe('formatUsd', () => {
expect(formatUsd(19.99, { trimWhole: true })).toBe('$19.99');
expect(formatUsd(200)).toBe('$200.00');
});
+
+ // $4610.09 is read as the wrong order of magnitude at a glance; the separator
+ // is what makes a four-figure spend legible.
+ it('groups thousands', () => {
+ expect(formatUsd(4610.09)).toBe('$4,610.09');
+ expect(formatUsd(1234567.5)).toBe('$1,234,567.50');
+ expect(formatUsd(-4610.09, { signed: true })).toBe('-$4,610.09');
+ expect(formatUsd(12000, { trimWhole: true })).toBe('$12,000');
+ });
+});
+
+describe('formatCount', () => {
+ it('groups thousands so a total reads at its true magnitude', () => {
+ expect(formatCount(2762)).toBe('2,762');
+ expect(formatCount(999)).toBe('999');
+ expect(formatCount(1234567)).toBe('1,234,567');
+ expect(formatCount(0)).toBe('0');
+ });
+
+ it('accepts a numeric string and rounds a stray fraction away', () => {
+ expect(formatCount('4610')).toBe('4,610');
+ expect(formatCount(1500.6)).toBe('1,501');
+ });
+
+ // A count that was never measured must not render as a confident 0.
+ it('renders the fallback for a missing or unparseable count', () => {
+ expect(formatCount(null)).toBe('—');
+ expect(formatCount(undefined)).toBe('—');
+ expect(formatCount('')).toBe('—');
+ expect(formatCount(NaN)).toBe('—');
+ expect(formatCount(null, { fallback: '0' })).toBe('0');
+ });
});
describe('formatPercent', () => {