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

refactor: one formatHourOfDay helper replaces five hand-rolled hour formatters (#5701)

[._.]/ Adam Eivy0c35163b826a
diff --git a/client/src/components/calendar/DayView.jsx b/client/src/components/calendar/DayView.jsx
index a1bef7d7f6..4d85de4571 100644
--- a/client/src/components/calendar/DayView.jsx
+++ b/client/src/components/calendar/DayView.jsx
@@ -5,7 +5,7 @@ import socket from '../../services/socket';
import EventDetail from './EventDetail';
import ChronotypeOverlay from './ChronotypeOverlay';
import { buildSubcalendarColorMap, eventChipStyle } from './calendarUtils';
-import { formatDateFull } from '../../utils/formatters';
+import { formatDateFull, formatHourOfDay } from '../../utils/formatters';
import BrailleSpinner from '../BrailleSpinner';
import { useThemeContext } from '../ThemeContext';
import useUrlParams from '../../hooks/useUrlParams';
@@ -17,13 +17,6 @@ const PX_PER_HOUR = 80;
const PX_PER_15MIN = PX_PER_HOUR / 4; // 20px per 15-min block
const START_MINUTES = START_HOUR * 60;
-function formatHour(hour) {
- if (hour === 0) return '12 AM';
- if (hour < 12) return `${hour} AM`;
- if (hour === 12) return '12 PM';
- return `${hour - 12} PM`;
-}
-
function getEventMinutes(event) {
const start = new Date(event.startTime);
const end = new Date(event.endTime);
@@ -207,7 +200,7 @@ export default function DayView({ accounts }) {
<div key={hour} className="border-b border-port-border last:border-b-0" style={{ height: PX_PER_HOUR }}>
<div className="flex h-full">
<div className="w-16 shrink-0 text-xs text-gray-500 text-right pr-2 pt-1">
- {formatHour(hour)}
+ {formatHourOfDay(hour)}
</div>
<div className="flex-1 border-l border-port-border flex flex-col">
{[0, 1, 2, 3].map(q => (
diff --git a/client/src/components/calendar/WeekView.jsx b/client/src/components/calendar/WeekView.jsx
index ab902b70be..2ebe76bd19 100644
--- a/client/src/components/calendar/WeekView.jsx
+++ b/client/src/components/calendar/WeekView.jsx
@@ -7,7 +7,7 @@ import ChronotypeOverlay from './ChronotypeOverlay';
import { buildSubcalendarColorMap, eventChipStyle } from './calendarUtils';
import BrailleSpinner from '../BrailleSpinner';
import { useThemeContext } from '../ThemeContext';
-import { formatMonthDay, formatWeekdayShort, formatDateShort } from '../../utils/formatters';
+import { formatMonthDay, formatWeekdayShort, formatDateShort, formatHourOfDay } from '../../utils/formatters';
import useUrlParams from '../../hooks/useUrlParams';
const START_HOUR = 6;
@@ -17,13 +17,6 @@ const PX_PER_HOUR = 80;
const PX_PER_15MIN = PX_PER_HOUR / 4; // 20px per 15-min block
const START_MINUTES = START_HOUR * 60;
-function formatHour(hour) {
- if (hour === 0) return '12 AM';
- if (hour < 12) return `${hour} AM`;
- if (hour === 12) return '12 PM';
- return `${hour - 12} PM`;
-}
-
function getWeekStart(date) {
const d = new Date(date);
d.setDate(d.getDate() - d.getDay());
@@ -253,7 +246,7 @@ export default function WeekView({ accounts }) {
{HOURS.map(hour => (
<div key={hour} className="flex border-b border-port-border/50 last:border-b-0" style={{ height: PX_PER_HOUR }}>
<div className="w-14 shrink-0 text-[10px] text-gray-500 text-right pr-1 -mt-1.5">
- {formatHour(hour)}
+ {formatHourOfDay(hour)}
</div>
{weekDays.map((_, i) => (
<div key={i} className="flex-1 border-l border-port-border/50 flex flex-col">
diff --git a/client/src/components/cos/tabs/ProductivityTab.jsx b/client/src/components/cos/tabs/ProductivityTab.jsx
index cec6200856..d955ea7c8d 100644
--- a/client/src/components/cos/tabs/ProductivityTab.jsx
+++ b/client/src/components/cos/tabs/ProductivityTab.jsx
@@ -15,7 +15,7 @@ import {
Award
} from 'lucide-react';
import BrailleSpinner from '../../BrailleSpinner';
-import { formatDateTime, formatDateNumeric } from '../../../utils/formatters';
+import { formatDateTime, formatDateNumeric, formatHourOfDay } from '../../../utils/formatters';
import * as api from '../../../services/api';
import DailyTrendsChart from '../DailyTrendsChart';
@@ -61,13 +61,6 @@ export default function ProductivityTab() {
setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
}, []);
- const formatHour = useCallback((hour) => {
- const h = parseInt(hour, 10);
- if (h === 0) return '12AM';
- if (h === 12) return '12PM';
- return h < 12 ? `${h}AM` : `${h - 12}PM`;
- }, []);
-
const getSuccessRateColor = useCallback((rate) => {
if (rate >= 80) return 'text-port-success';
if (rate >= 60) return 'text-port-warning';
@@ -200,7 +193,7 @@ export default function ProductivityTab() {
<div className="space-y-2 max-h-48 overflow-y-auto">
{sortedHourlyPatterns.map((p) => (
<div key={p.hour} className="flex items-center justify-between text-sm">
- <span className="text-gray-400 w-12">{formatHour(p.hour)}</span>
+ <span className="text-gray-400 w-12">{formatHourOfDay(p.hour, { style: 'compact' })}</span>
<div className="flex-1 mx-2">
<div className="h-2 bg-port-border rounded-full overflow-hidden">
<div
@@ -268,7 +261,7 @@ export default function ProductivityTab() {
<div>
<div className="text-xs text-gray-500">Best Hour</div>
<div className="text-lg font-semibold text-port-accent">
- {formatHour(data.bestHour.hour)}
+ {formatHourOfDay(data.bestHour.hour, { style: 'compact' })}
</div>
<div className="text-xs text-gray-400">
{data.bestHour.successRate}% success ({data.bestHour.tasks} tasks)
diff --git a/client/src/components/dashboard/builtins/HourlyActivityWidget.jsx b/client/src/components/dashboard/builtins/HourlyActivityWidget.jsx
index f3788640f1..c3f87bd374 100644
--- a/client/src/components/dashboard/builtins/HourlyActivityWidget.jsx
+++ b/client/src/components/dashboard/builtins/HourlyActivityWidget.jsx
@@ -1,3 +1,5 @@
+import { formatHourOfDay } from '../../../utils/formatters';
+
export default function HourlyActivityWidget({ dashboardState }) {
const hourlyActivity = dashboardState.usage?.hourlyActivity;
if (!hourlyActivity) return null;
@@ -9,12 +11,6 @@ export default function HourlyActivityWidget({ dashboardState }) {
.filter((h) => h.count === peakValue && h.count > 0);
const totalSessions = hourlyActivity.reduce((sum, val) => sum + val, 0);
- const formatHour = (hour) => {
- if (hour === 0) return '12a';
- if (hour === 12) return '12p';
- return hour < 12 ? `${hour}a` : `${hour - 12}p`;
- };
-
const getIntensityClass = (count) => {
if (count === 0) return 'bg-port-border/30';
const intensity = count / maxActivity;
@@ -27,8 +23,8 @@ export default function HourlyActivityWidget({ dashboardState }) {
const peakDescription = peakHours.length === 0 || peakValue === 0
? null
: peakHours.length === 1
- ? `Peak: ${formatHour(peakHours[0].hour)} (${peakValue} sessions)`
- : `Peak hours: ${peakHours.slice(0, 3).map((h) => formatHour(h.hour)).join(', ')} (${peakValue} sessions each)`;
+ ? `Peak: ${formatHourOfDay(peakHours[0].hour, { style: 'tiny' })} (${peakValue} sessions)`
+ : `Peak hours: ${peakHours.slice(0, 3).map((h) => formatHourOfDay(h.hour, { style: 'tiny' })).join(', ')} (${peakValue} sessions each)`;
if (totalSessions === 0) return null;
@@ -50,8 +46,8 @@ export default function HourlyActivityWidget({ dashboardState }) {
<div
key={hour}
className={`aspect-square rounded-xs ${getIntensityClass(count)} transition-colors cursor-default min-w-[20px] min-h-[20px]`}
- title={`${formatHour(hour)}: ${count} session${count !== 1 ? 's' : ''}`}
- aria-label={`${formatHour(hour)}: ${count} sessions`}
+ title={`${formatHourOfDay(hour, { style: 'tiny' })}: ${count} session${count !== 1 ? 's' : ''}`}
+ aria-label={`${formatHourOfDay(hour, { style: 'tiny' })}: ${count} sessions`}
/>
))}
</div>
@@ -59,8 +55,8 @@ export default function HourlyActivityWidget({ dashboardState }) {
<div className="mt-2 grid grid-cols-6 sm:grid-cols-12 gap-1.5 sm:gap-1 text-xs text-gray-500">
{hourlyActivity.map((_, hour) => (
<div key={hour} className="text-center">
- <span className="hidden sm:inline">{hour % 3 === 0 ? formatHour(hour) : ''}</span>
- <span className="sm:hidden">{hour % 4 === 0 ? formatHour(hour) : ''}</span>
+ <span className="hidden sm:inline">{hour % 3 === 0 ? formatHourOfDay(hour, { style: 'tiny' }) : ''}</span>
+ <span className="sm:hidden">{hour % 4 === 0 ? formatHourOfDay(hour, { style: 'tiny' }) : ''}</span>
</div>
))}
</div>
diff --git a/client/src/components/digital-twin/ObservedTasteEvidence.jsx b/client/src/components/digital-twin/ObservedTasteEvidence.jsx
index e606de09c1..87a5868648 100644
--- a/client/src/components/digital-twin/ObservedTasteEvidence.jsx
+++ b/client/src/components/digital-twin/ObservedTasteEvidence.jsx
@@ -4,7 +4,7 @@ import * as api from '../../services/api';
import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
import MarkdownOutput from '../cos/MarkdownOutput';
-import { formatDateTime } from '../../utils/formatters';
+import { formatDateTime, formatHourOfDay } from '../../utils/formatters';
// Divergence badge: divergence is SIGNAL, not error — stated and observed
// chronotypes differing is a legitimate insight, so we frame it neutrally.
@@ -44,13 +44,6 @@ function TopList({ title, items }) {
);
}
-function fmtHour(h) {
- if (h == null) return '—';
- const suffix = h < 12 ? 'am' : 'pm';
- const hr = h % 12 === 0 ? 12 : h % 12;
- return `${hr}${suffix}`;
-}
-
function fmtNovelty(nv) {
if (!nv || nv.noveltyRatio == null) return null;
return `${Math.round(nv.noveltyRatio * 100)}% novel · ${nv.distinct}/${nv.total} distinct`;
@@ -66,7 +59,7 @@ function HourBars({ histogram }) {
{histogram.map((s) => (
<div
key={s.hour}
- title={`${fmtHour(s.hour)}: ${s.total} event(s)`}
+ title={`${formatHourOfDay(s.hour, { style: 'lower' })}: ${s.total} event(s)`}
className="flex-1 bg-port-accent-2/60 rounded-t"
style={{ height: `${Math.max(3, ((s.total || 0) / max) * 100)}%` }}
/>
@@ -218,9 +211,9 @@ export default function ObservedTasteEvidence() {
<HourBars histogram={chronotype.histogram} />
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs text-gray-400">
<div>Observed: <span className="text-white">{chronotype.observedType || '—'}</span></div>
- <div>Peak messages: <span className="text-white">{fmtHour(chronotype.peakHours?.messages)}</span></div>
- <div>Peak media: <span className="text-white">{fmtHour(chronotype.peakHours?.media)}</span></div>
- <div>Peak overall: <span className="text-white">{fmtHour(chronotype.peakHours?.overall)}</span></div>
+ <div>Peak messages: <span className="text-white">{formatHourOfDay(chronotype.peakHours?.messages, { style: 'lower' })}</span></div>
+ <div>Peak media: <span className="text-white">{formatHourOfDay(chronotype.peakHours?.media, { style: 'lower' })}</span></div>
+ <div>Peak overall: <span className="text-white">{formatHourOfDay(chronotype.peakHours?.overall, { style: 'lower' })}</span></div>
</div>
{evidence?.statedChronotype?.type && (
<div className="text-xs text-gray-500">
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index fc60714ba3..97adaec8fb 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -22,7 +22,7 @@ grep -i "what you want to do" client/src/utils/README.md
| Module | Purpose |
|---|---|
-| `formatters` | Date/time/duration/byte/word formatters (`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`. 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/word 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". |
| `cronHelpers` | Cron preset list, friendly cron parsing/building, anchored recurrence parsing/building/description, `isCronExpression` detection, `describeCron` human-readable rendering, and `JOB_INTERVAL_OPTIONS` — the interval-mode cadences for autonomous jobs, mirroring the server's `INTERVAL_OPTIONS`. 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 2f5feed712..f820ce85f6 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -222,6 +222,34 @@ export function formatClockTime(date, { timeZone, seconds = true, hour12 } = {})
}, '');
}
+const HOUR_MERIDIEM = {
+ long: [' AM', ' PM'],
+ compact: ['AM', 'PM'],
+ tiny: ['a', 'p'],
+ lower: ['am', 'pm'],
+};
+
+/**
+ * Format a bare hour-of-day number (0-23) as a 12-hour clock label.
+ * The canonical home for what five components each hand-rolled, which is why
+ * the same 3pm used to render as "3 PM", "3PM", "3p" and "3pm" on four screens.
+ * One helper with a `style` option rather than four helpers: every caller wants
+ * the same noon/midnight arithmetic and differs only in separator and case.
+ * @param {number|string|null} hour - Hour of day, 0-23 (numeric strings accepted)
+ * @param {object} [options]
+ * @param {'long'|'compact'|'tiny'|'lower'} [options.style='long'] - `3 PM` / `3PM` / `3p` / `3pm`
+ * @param {string} [options.fallback='—'] - Rendered for missing/non-numeric input
+ * @returns {string} Formatted hour, or the fallback
+ */
+export function formatHourOfDay(hour, { style = 'long', fallback = '—' } = {}) {
+ if (hour === null || hour === undefined || hour === '') return fallback;
+ const h = Number(hour);
+ if (!Number.isFinite(h)) return fallback;
+ const [am, pm] = HOUR_MERIDIEM[style] || HOUR_MERIDIEM.long;
+ const hr = h % 12 === 0 ? 12 : h % 12;
+ return `${hr}${h < 12 ? am : pm}`;
+}
+
/**
* Format a duration in milliseconds as a human-readable string
* @param {number} ms - Duration in milliseconds
diff --git a/client/src/utils/formatters.test.js b/client/src/utils/formatters.test.js
index f14c0aae86..8fcf7499f9 100644
--- a/client/src/utils/formatters.test.js
+++ b/client/src/utils/formatters.test.js
@@ -3,7 +3,7 @@ import {
clamp, formatContextLength, formatDurationMin, formatDurationMs, formatEventDateTime, timeAgo, formatAgeDays,
formatCooldown, formatCountdown, recommendedRamGb, parseTimeoutMs, formatDurationSec, middleTruncate,
formatWeight, formatPercent, formatUsd, formatBytes,
- formatDateNumeric, formatTimeOfDaySeconds, formatClockTime, formatWeekdayDate,
+ formatDateNumeric, formatTimeOfDaySeconds, formatClockTime, formatHourOfDay, formatWeekdayDate,
formatMonthDay, formatMonthYear, formatWeekdayShort, formatWeekdayTime, formatDateFull, formatDateShort, formatDateTime,
localDateKey, shiftISODate,
} from './formatters.js';
@@ -528,6 +528,40 @@ describe('canonical date/time formatters (#3870)', () => {
});
});
+ describe('formatHourOfDay', () => {
+ // Each of the five components this replaced re-derived the noon/midnight
+ // wrap by hand; the table pins 0 → 12 AM and 12 → 12 PM for every style.
+ const cases = [
+ [0, '12 AM', '12AM', '12a', '12am'],
+ [1, '1 AM', '1AM', '1a', '1am'],
+ [11, '11 AM', '11AM', '11a', '11am'],
+ [12, '12 PM', '12PM', '12p', '12pm'],
+ [13, '1 PM', '1PM', '1p', '1pm'],
+ [23, '11 PM', '11PM', '11p', '11pm'],
+ ];
+
+ it.each(cases)('renders hour %i in every style', (hour, long, compact, tiny, lower) => {
+ expect(formatHourOfDay(hour)).toBe(long);
+ expect(formatHourOfDay(hour, { style: 'long' })).toBe(long);
+ expect(formatHourOfDay(hour, { style: 'compact' })).toBe(compact);
+ expect(formatHourOfDay(hour, { style: 'tiny' })).toBe(tiny);
+ expect(formatHourOfDay(hour, { style: 'lower' })).toBe(lower);
+ });
+
+ it('accepts a numeric string, as hour-keyed stats records supply', () => {
+ expect(formatHourOfDay('9', { style: 'compact' })).toBe('9AM');
+ expect(formatHourOfDay('15', { style: 'compact' })).toBe('3PM');
+ });
+
+ it('renders the fallback for missing or non-numeric input', () => {
+ expect(formatHourOfDay(null)).toBe('—');
+ expect(formatHourOfDay(undefined)).toBe('—');
+ expect(formatHourOfDay('')).toBe('—');
+ expect(formatHourOfDay('abc')).toBe('—');
+ expect(formatHourOfDay(null, { fallback: 'n/a' })).toBe('n/a');
+ });
+ });
+
describe('formatWeekdayDate', () => {
const day = new Date(2026, 2, 5);