Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: finish the formatter consolidation — one weekday-date helper, one fallback rule (#3870)
[._.]/ Adam Eivy5f707ac751a3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 412f366922..d65ea46e07 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -47,4 +47,4 @@- The Pipeline's Reverse Outline map now keeps the selected scene in the URL (`?scene=<id>`) instead of component state, so the open scene detail survives a reload and can be linked to or shared. A stale id — after regenerating the outline, say — falls back to the "click a marker" placeholder rather than a blank card, and regenerating clears the selection outright.- The six "file too large" toasts — album covers, artist portraits, tracks, author headshots, reference audio and OpenClaw attachments — now render their size cap through the shared `formatBytes` helper instead of each dividing by 1024 twice and gluing on "MB". The rendered text gains a space before the unit (`12 MB` rather than `12MB`), which is what the rest of PortOS already shows and what the reference-audio toast already read. The OpenClaw combined-attachment message picked up the same treatment for its decoded-size estimate, so the two limits it can report no longer print their units two different ways.- The post-restart agent-recovery path is now its own function instead of a 65-line branch inlined at the top of `handleAgentCompletion`, so a change to either it or the live in-memory completion path no longer means reading past the other. The pause guard that path sits behind — the one keeping a stray completion event from cleaning the worktree out from under a later resume — is now pinned by tests that call the real function rather than by a source-text assertion that broke the moment the code moved.-- Every inline `new Date(x).toLocaleDateString()` / `.toLocaleTimeString()` in the client — roughly seventy across fifty components, from the calendar views and CyberCity HUD to the CoS tabs, goals, media queue and app-update panels — now routes through `client/src/utils/formatters.js`, so a change to how PortOS renders a date is one edit rather than fifty. The helper set grew to cover the shapes that were being spelled out by hand (`formatDateNumeric`, `formatTimeOfDaySeconds`, `formatMonthDay`, `formatMonthYear`, `formatWeekdayShort`, `formatWeekdayDate`, `formatWeekdayTime`), and `formatClockTime` gained `seconds` / `hour12` options instead of a second copy of itself. Two long-standing paper cuts go with it: a bare `YYYY-MM-DD` is now anchored at local midnight everywhere (a plain `new Date('2026-03-05')` is UTC midnight and renders as the 4th anywhere west of Greenwich — call sites used to fix this by hand, and the ones that forgot showed the wrong day), and a missing or malformed timestamp renders a caller-chosen fallback instead of the literal text "Invalid Date".+- Every inline `new Date(x).toLocaleDateString()` / `.toLocaleTimeString()` in the client — roughly seventy across fifty components, from the calendar views and CyberCity HUD to the CoS tabs, goals, media queue and app-update panels — now routes through `client/src/utils/formatters.js`, so a change to how PortOS renders a date is one edit rather than fifty. The helper set grew to cover the shapes that were being spelled out by hand (`formatDateNumeric`, `formatTimeOfDaySeconds`, `formatMonthDay`, `formatMonthYear`, `formatWeekdayShort`, `formatWeekdayDate`, `formatWeekdayTime`), and `formatClockTime` gained `seconds` / `hour12` options instead of a second copy of itself. Two long-standing paper cuts go with it: a bare `YYYY-MM-DD` is now anchored at local midnight everywhere (a plain `new Date('2026-03-05')` is UTC midnight and renders as the 4th anywhere west of Greenwich — call sites used to fix this by hand, and the ones that forgot showed the wrong day), and a missing or malformed timestamp renders a caller-chosen fallback instead of the literal text "Invalid Date" — including the calendar event-detail formatter, which had ended up guarding its all-day branch but not its timed one.diff --git a/client/src/components/CosDashboardWidget.jsx b/client/src/components/CosDashboardWidget.jsxindex 635f6cc136..21abcdef13 100644--- a/client/src/components/CosDashboardWidget.jsx+++ b/client/src/components/CosDashboardWidget.jsx@@ -17,7 +17,7 @@ import {import * as api from '../services/api';import { useAutoRefetch } from '../hooks/useAutoRefetch';import { useTimeTick } from '../hooks/useTimeTick';-import { timeAgo, formatDateWeekday } from '../utils/formatters';+import { timeAgo, formatWeekdayDate } from '../utils/formatters';/*** CosDashboardWidget - Compact CoS status widget for the main Dashboard@@ -431,7 +431,7 @@ function ActivityCalendar({ data }) {${day.isToday ? 'ring-1 ring-port-accent' : ''}${day.isFuture ? 'opacity-30' : ''}`}- title={day.isFuture ? '' : `${formatDateWeekday(day.date)}: ${day.tasks} task${day.tasks !== 1 ? 's' : ''} (${day.successRate}% success)`}+ title={day.isFuture ? '' : `${formatWeekdayDate(day.date, { weekday: 'short' })}: ${day.tasks} task${day.tasks !== 1 ? 's' : ''} (${day.successRate}% success)`}/>))}</div>diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 5a1f3876d4..ceb52044a4 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -22,7 +22,7 @@ grep -i "what you want to do" client/src/utils/README.md| Module | Purpose ||---|---|-| `formatters` | Date/time/duration/byte/word formatters (`formatBytes`, `formatCompactCount`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `parseTimeoutMs`, `formatCooldown`, `parseSizeGb`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price) — `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. **Never write `new Date(x).toLocaleDateString()` inline** — pick the helper for the shape you want: `formatDateNumeric` ("3/5/2026", compact cells), `formatDateShort` ("Mar 5, 2026"), `formatDate` ("March 5, 2026"), `formatDateFull` ("Saturday, March 5, 2026"), `formatWeekdayDate` ("Monday, Mar 5", `{ weekday, year }`), `formatMonthDay` ("Mar 5"), `formatMonthYear` ("March 2026"), `formatWeekdayShort` ("Mon"), `formatWeekdayTime` ("Mon, 7:00 AM"), `formatDateWeekday` (noon-anchored heatmap tooltips), `formatTimeOfDay` ("1:30 PM"), `formatTimeOfDaySeconds` ("1:30:45 PM", log/queue rows), `formatClockTime` ("02:30:45 PM"; `{ seconds, hour12, timeZone }`), `formatDateTime`. All of them anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new Date('2026-03-05')` is UTC midnight and renders as the previous day west of Greenwich) and take a fallback instead of rendering the literal "Invalid Date". |+| `formatters` | Date/time/duration/byte/word formatters (`formatBytes`, `formatCompactCount`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `parseTimeoutMs`, `formatCooldown`, `parseSizeGb`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price) — `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. **Never write `new Date(x).toLocaleDateString()` inline** — pick the helper for the shape you want: `formatDateNumeric` ("3/5/2026", compact cells), `formatDateShort` ("Mar 5, 2026"), `formatDate` ("March 5, 2026"), `formatDateFull` ("Saturday, March 5, 2026"), `formatWeekdayDate` ("Monday, Mar 5", `{ weekday, year }`), `formatMonthDay` ("Mar 5"), `formatMonthYear` ("March 2026"), `formatWeekdayShort` ("Mon"), `formatWeekdayTime` ("Mon, 7:00 AM"), `formatTimeOfDay` ("1:30 PM"), `formatTimeOfDaySeconds` ("1:30:45 PM", log/queue rows), `formatClockTime` ("02:30:45 PM"; `{ seconds, hour12, timeZone }`), `formatDateTime`. All of them anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new Date('2026-03-05')` is UTC midnight and renders as the previous day west of Greenwich) and take a fallback instead of rendering the literal "Invalid Date". || `cronHelpers` | Cron preset list, `isCronExpression` detection, and `describeCron` human-readable rendering. || `markdownText` | `markdownToPlainText(md)` — flatten markdown source to one plain-text string for a clamped preview: strips heading/list/blockquote/fence markers, unwraps emphasis, inline code and links, images → `[alt]`, collapses blank-line runs. Use whenever a card previews arbitrary agent-authored markdown — `line-clamp-N` does not clamp a subtree of block elements, and foreign `##` headings would otherwise join the page's heading outline. Underscore emphasis is word-boundary gated and `__…__` needs interior whitespace, so stack frames and user-agent strings (`10_15_7`, `__init__`) are never silently rewritten. `dropsMarkupWhenFlattened(md)` — did the flatten lose actual markup, as opposed to only normalizing whitespace? Gates a "Show more" disclosure so a short-but-lossy body stays reachable without putting a toggle on every body that merely lost a trailing newline. || `timeWindow` | Time-of-day window math (`isInTimeWindow`, `timeStringToMinutes`) and morning-layout auto-switch helpers (`pickActiveLayoutId`, `recordManualLayoutPick`). |diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.jsindex 9381c0b4b4..11a7ef13d5 100644--- a/client/src/utils/formatters.js+++ b/client/src/utils/formatters.js@@ -156,8 +156,7 @@ export function formatWeekdayShort(value, { timeZone } = {}) {/*** Format a weekday-led date with a short month (e.g., "Monday, Mar 5", or* "Mon, Mar 5, 2026" with `{ weekday: 'short', year: true }`). Distinct from- * `formatDateFull` (long month, always with year) and `formatDateWeekday`- * (noon-anchored heatmap tooltips).+ * `formatDateFull` (long month, always with year).* @param {string|number|Date|null} value* @param {object} [options]* @param {'long'|'short'} [options.weekday='long'] - Weekday width@@ -535,11 +534,11 @@ export function formatDurationMin(minutes, options = {}) {* time (e.g. "Sat, Apr 1, 1:30 PM"); all-day events show a full weekday and* year (e.g. "Saturday, April 1, 2026"). Kept separate from `formatDateTime`* because the weekday-led shape is event-specific.- * Behavior-identical to the local formatter it replaced: any input is passed- * straight to `new Date(...)`, so malformed/empty values render the same- * `Invalid Date` / epoch string the original did. The two call sites always- * pass a real event time, so this degenerate path is never exercised — kept- * faithful so the migration introduces zero visual change.+ * Missing/unparseable input renders '' — the same fallback contract every+ * other helper here follows. (It used to pass the raw `Invalid Date` string+ * through "for migration fidelity"; once the all-day branch started routing+ * through `formatDateFull`'s guard, that left one branch guarded and one not.+ * Both call sites pass a real event time, so nothing visible changes.)* @param {string|Date|null} dateStr - ISO timestamp or Date object* @param {object} [options]* @param {boolean} [options.allDay=false] - Render date-only (all-day event).@@ -547,27 +546,14 @@ export function formatDurationMin(minutes, options = {}) {*/export function formatEventDateTime(dateStr, options = {}) {const { allDay = false } = options ?? {};- const date = new Date(dateStr);// All-day events render exactly like `formatDateFull` (full weekday + year).- if (allDay) return formatDateFull(date);+ if (allDay) return formatDateFull(dateStr);+ if (dateStr == null || dateStr === '') return '';+ const date = toDisplayDate(dateStr);+ if (Number.isNaN(date.getTime())) return '';return date.toLocaleString([], { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });}-/**- * Format a date string as a short weekday + month + day string- * (e.g., "Sat, Mar 5"). Used for activity-heatmap tooltips where compact- * output with a leading weekday abbreviation is important.- * The input is treated as a calendar date (anchored at local noon to avoid- * day-boundary drift), not as a precise timestamp.- * @param {string} dateStr - Date-only string ("YYYY-MM-DD"); a full ISO- * timestamp is NOT supported (the noon-anchor suffix would make it invalid)- * @returns {string} Formatted date (e.g., "Sat, Mar 5")- */-export function formatDateWeekday(dateStr) {- const date = new Date(dateStr + 'T12:00:00');- return date.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' });-}-/*** Get app name from app ID by looking up in apps array* @param {string|null} appId - The app ID to look updiff --git a/client/src/utils/formatters.test.js b/client/src/utils/formatters.test.jsindex e61d513109..f70f4fa143 100644--- a/client/src/utils/formatters.test.js+++ b/client/src/utils/formatters.test.js@@ -207,14 +207,15 @@ describe('formatEventDateTime', () => {expect(formatEventDateTime(sample, null)).toBe(formatEventDateTime(sample));});- it('passes malformed input straight through, like the original local formatter (no guard, by design)', () => {- // The migration is deliberately behavior-identical: unparseable input- // yields the raw toLocaleString result ("Invalid Date"), not an empty- // string. Locks the no-guard decision so a future change does not re-add- // a guard and silently alter the (unreachable) degenerate path.- expect(formatEventDateTime('not-a-date')).toBe(- new Date('not-a-date').toLocaleString([], { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })- );+ it("renders an empty string for malformed/missing input on BOTH branches (#3870)", () => {+ // Used to pass the raw "Invalid Date" string through for migration+ // fidelity. Once the all-day branch started routing through formatDateFull's+ // guard, one branch was guarded and one was not; both now follow the+ // module-wide fallback contract.+ expect(formatEventDateTime('not-a-date')).toBe('');+ expect(formatEventDateTime('not-a-date', { allDay: true })).toBe('');+ expect(formatEventDateTime(null)).toBe('');+ expect(formatEventDateTime('')).toBe('');});});