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: read On This Day from brain projections and derive the Daily Log day from the URL

[._.]/ Adam Eivyd5719bb189d2
diff --git a/client/src/components/brain/tabs/DailyLogTab.jsx b/client/src/components/brain/tabs/DailyLogTab.jsx
index 34d112e545..c6a9787e2d 100644
--- a/client/src/components/brain/tabs/DailyLogTab.jsx
+++ b/client/src/components/brain/tabs/DailyLogTab.jsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { useSearchParams } from 'react-router';
+import useUrlParams from '../../../hooks/useUrlParams';
import {BookOpen, ChevronLeft, ChevronRight, Mic, MicOff, Save, Volume2, Settings,
Plus, Trash2, CloudUpload, Menu, X, Sparkles} from 'lucide-react';
import * as api from '../../../services/api';
@@ -80,17 +80,24 @@ const STALE_JOURNAL_MAX_ATTEMPTS = 3;
const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
export default function DailyLogTab() {
- const [searchParams, setSearchParams] = useSearchParams();
- // Deep-linkable date (?date=YYYY-MM-DD) — the On This Day widget and shared
- // links open a specific past day; without the param the tab opens on today.
- const [date, setDate] = useState(() => {
- const param = searchParams.get('date');
- return param && ISO_DATE_RE.test(param) ? param : localDateKey();
- });
+ // The URL is the source of truth for the open day (?date=YYYY-MM-DD) — the
+ // On This Day widget and shared links deep-link a specific past day; without
+ // the param the tab shows the server's today.
+ const [searchParams, updateParams] = useUrlParams();
// Backend today — resolved via GET /daily-log/today on mount so the
// "Today" button, disabled-forward-nav check, and isToday chip all match
// the server's timezone. Falls back to localDateKey() until fetched.
const [serverToday, setServerToday] = useState(localDateKey());
+ const dateParam = searchParams.get('date');
+ const date = dateParam && ISO_DATE_RE.test(dateParam) ? dateParam : serverToday;
+ // Navigating to today clears the param so the default view keeps a clean
+ // URL. Ref-read so the setter stays referentially stable for the voice-event
+ // handlers that capture it.
+ const serverTodayRef = useRef(serverToday);
+ serverTodayRef.current = serverToday;
+ const setDate = useCallback((next) => {
+ updateParams({ date: next === serverTodayRef.current ? null : next }, { replace: true });
+ }, [updateParams]);
const [entry, setEntry] = useState(null);
const [content, setContent] = useState('');
const [loading, setLoading] = useState(true);
@@ -178,18 +185,6 @@ export default function DailyLogTab() {
}, []);
useEffect(() => { loadEntry(date); }, [date, loadEntry]);
-
- // Reflect non-today dates back into ?date= so the open day stays shareable
- // and reload-safe. Replace, not push — prev/next taps shouldn't pile up
- // history entries.
- useEffect(() => {
- setSearchParams((prev) => {
- const next = new URLSearchParams(prev);
- if (date === serverToday) next.delete('date');
- else next.set('date', date);
- return next;
- }, { replace: true });
- }, [date, serverToday, setSearchParams]);
useEffect(() => { loadHistory(); loadSettings(); }, [loadHistory, loadSettings]);
// Keep the server's dictation target date aligned with the UI while
@@ -202,16 +197,15 @@ export default function DailyLogTab() {
// Ask the server for its canonical "today" so a user in a different timezone
// than the browser (remote/VPN access) doesn't open the tab on the wrong day.
+ // No explicit hop needed: with no ?date= param, `date` derives from
+ // serverToday and follows it the moment this resolves.
useEffect(() => {
let cancelled = false;
api.getDailyLog('today').then((res) => {
if (cancelled || !res?.date) return;
setServerToday(res.date);
- // If we initialized with a wrong local date, hop to the real one.
- if (date === localDateKey() && res.date !== date) setDate(res.date);
}).catch(() => null);
return () => { cancelled = true; };
- // Only on mount — we intentionally don't re-run when date changes.
}, []);
useEffect(() => {
diff --git a/client/src/components/brain/tabs/DailyLogTab.test.jsx b/client/src/components/brain/tabs/DailyLogTab.test.jsx
index 34894ed7db..2d5374c4cc 100644
--- a/client/src/components/brain/tabs/DailyLogTab.test.jsx
+++ b/client/src/components/brain/tabs/DailyLogTab.test.jsx
@@ -62,9 +62,9 @@ const entryFor = (date, content) => ({
let store;
-const renderTab = async () => {
- // Router context is required for the ?date= deep-link search param.
- const result = render(<MemoryRouter><DailyLogTab /></MemoryRouter>);
+const renderTab = async (initialEntries = ['/']) => {
+ // Router context is required: the open day derives from the ?date= param.
+ const result = render(<MemoryRouter initialEntries={initialEntries}><DailyLogTab /></MemoryRouter>);
// Flush the mount fetches (entry + server-today + history + settings).
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
return result;
@@ -126,6 +126,19 @@ const typeThenReceiveVoiceSegment = async (typed, spoken = 'spoken words') => {
});
};
+describe('DailyLogTab deep linking', () => {
+ it('opens the day named by a ?date= param instead of today', async () => {
+ await renderTab([`/?date=${YESTERDAY}`]);
+ expect(api.getDailyLog).toHaveBeenCalledWith(YESTERDAY);
+ expect(editor().value).toBe('old day');
+ });
+
+ it('ignores a malformed ?date= param and falls back to today', async () => {
+ await renderTab(['/?date=not-a-date']);
+ expect(editor().value).toBe('existing');
+ });
+});
+
describe('DailyLogTab autosave', () => {
it('saves after the user stops typing', async () => {
await renderTab();
diff --git a/client/src/components/dashboard/builtins/OnThisDayWidget.jsx b/client/src/components/dashboard/builtins/OnThisDayWidget.jsx
index c16a01fc35..af01ecc02e 100644
--- a/client/src/components/dashboard/builtins/OnThisDayWidget.jsx
+++ b/client/src/components/dashboard/builtins/OnThisDayWidget.jsx
@@ -5,8 +5,8 @@ import { History, Lightbulb, BookOpen, NotebookPen } from 'lucide-react';
// this calendar date in previous years. Reads the shared `brainOnThisDay`
// slice of dashboardState (populated from GET /api/brain/on-this-day — the
// server owns the timezone-correct date key, so this never re-derives it).
-// Gated off until there is at least one past-year item to show, so a young
-// install reserves no grid cell.
+// The registry gate (`total > 0`) keeps this off the grid on days with no
+// lookbacks, so a mounted widget always has rows — no empty state needed.
const ROW_META = {
journal: { icon: NotebookPen, label: 'Daily Log', link: (item) => `/brain/daily-log?date=${item.date}` },
memory: { icon: BookOpen, label: 'Memory', link: () => '/brain/memory' },
@@ -20,7 +20,6 @@ export default function OnThisDayWidget({ dashboardState }) {
if (!data) return null;
const items = Array.isArray(data.items) ? data.items : [];
- const total = data.total ?? items.length;
return (
<div className="bg-port-card border border-port-border rounded-xl p-4 h-full">
@@ -29,38 +28,32 @@ export default function OnThisDayWidget({ dashboardState }) {
<h3 className="text-sm font-semibold text-white">On This Day</h3>
</div>
- {items.length === 0 ? (
- <div className="text-xs text-gray-500">No captures from this day in past years.</div>
- ) : (
- <>
- <ul className="space-y-2">
- {items.map((item) => {
- const meta = ROW_META[item.type] || ROW_META.memory;
- const Icon = meta.icon;
- return (
- <li key={`${item.type}:${item.id}`}>
- <Link to={meta.link(item)} className="group flex items-start gap-2 text-xs">
- <Icon size={14} className="shrink-0 mt-0.5 text-gray-500" />
- <span className="min-w-0">
- <span className="block text-gray-500">
- {yearsAgoLabel(item.yearsAgo)} · {meta.label}
- </span>
- <span className="block truncate text-gray-300 group-hover:text-white" title={item.title || item.snippet}>
- {item.title || item.snippet}
- </span>
- {item.title && item.snippet && (
- <span className="block truncate text-gray-500">{item.snippet}</span>
- )}
- </span>
- </Link>
- </li>
- );
- })}
- </ul>
- {total > items.length && (
- <div className="text-xs text-gray-500 mt-2">+{total - items.length} more</div>
- )}
- </>
+ <ul className="space-y-2">
+ {items.map((item) => {
+ const meta = ROW_META[item.type] || ROW_META.memory;
+ const Icon = meta.icon;
+ return (
+ <li key={`${item.type}:${item.id}`}>
+ <Link to={meta.link(item)} className="group flex items-start gap-2 text-xs">
+ <Icon size={14} className="shrink-0 mt-0.5 text-gray-500" />
+ <span className="min-w-0">
+ <span className="block text-gray-500">
+ {yearsAgoLabel(item.yearsAgo)} · {meta.label}
+ </span>
+ <span className="block truncate text-gray-300 group-hover:text-white" title={item.title || item.snippet}>
+ {item.title || item.snippet}
+ </span>
+ {item.title && item.snippet && (
+ <span className="block truncate text-gray-500">{item.snippet}</span>
+ )}
+ </span>
+ </Link>
+ </li>
+ );
+ })}
+ </ul>
+ {data.total > items.length && (
+ <div className="text-xs text-gray-500 mt-2">+{data.total - items.length} more</div>
)}
</div>
);
diff --git a/client/src/components/dashboard/builtins/OnThisDayWidget.test.jsx b/client/src/components/dashboard/builtins/OnThisDayWidget.test.jsx
index 3b6496772f..b1b631abfa 100644
--- a/client/src/components/dashboard/builtins/OnThisDayWidget.test.jsx
+++ b/client/src/components/dashboard/builtins/OnThisDayWidget.test.jsx
@@ -16,11 +16,6 @@ describe('OnThisDayWidget', () => {
expect(container.firstChild).toBeNull();
});
- it('shows the empty state when nothing matched today', () => {
- renderWidget({ date: '2026-09-01', timezone: 'UTC', total: 0, items: [] });
- expect(screen.getByText(/No captures from this day/)).toBeTruthy();
- });
-
it('deep-links each row by type — journals to their exact past date', () => {
renderWidget({
date: '2026-09-01',
diff --git a/scripts/migrations/329-seed-on-this-day-widget.js b/scripts/migrations/329-seed-on-this-day-widget.js
index bc33992a2b..aa4c6c9cb7 100644
--- a/scripts/migrations/329-seed-on-this-day-widget.js
+++ b/scripts/migrations/329-seed-on-this-day-widget.js
@@ -1,46 +1,14 @@
/**
* Seed the On This Day brain widget into the built-in Everything and Morning
* Review layouts. The widget is gated on having past-year Brain captures for
- * today's date, so installs without history see no change. Custom/user layouts
- * are intentionally untouched: the layout editor is the user's source of truth
- * for those.
+ * today's date, so installs without history see no change.
*/
-import { readLayoutsDoc, writeLayoutsDoc } from './_lib.js';
+import { makeWidgetSeedMigration } from './_lib.js';
-const LABEL = 'migration 329';
-const TARGET_LAYOUTS = new Set(['default', 'morning-review']);
-const WIDGET_ID = 'on-this-day';
-
-function applyToLayout(layout) {
- if (!layout || !TARGET_LAYOUTS.has(layout.id) || !Array.isArray(layout.widgets)) return false;
- const hasWidget = layout.widgets.includes(WIDGET_ID);
- const hasGridEntry = Array.isArray(layout.grid) && layout.grid.some((item) => item?.id === WIDGET_ID);
- if (hasWidget && hasGridEntry) return false;
-
- if (!hasWidget) layout.widgets = [...layout.widgets, WIDGET_ID];
- if (!hasGridEntry) {
- // Append at the end of the packing sequence — the widget is gated, so a
- // trailing cell that gates off leaves only harmless trailing space.
- const grid = Array.isArray(layout.grid) ? layout.grid : [];
- const maxOrder = grid.reduce((max, item) => Math.max(max, Number.isFinite(item?.order) ? item.order : -1), -1);
- layout.grid = [...grid, { id: WIDGET_ID, x: 0, w: 4, order: maxOrder + 1, h: 4 }];
- }
- return true;
-}
-
-export default {
- async up({ rootDir }) {
- const result = await readLayoutsDoc({ rootDir, label: LABEL });
- if (!result.ok) return { updated: 0, reason: result.reason };
- const { doc, path } = result;
- let updated = 0;
- for (const layout of doc.layouts) {
- if (applyToLayout(layout)) updated += 1;
- }
- if (updated === 0) return { updated: 0, reason: 'already-applied' };
- await writeLayoutsDoc(path, doc);
- console.log(`🗓️ ${LABEL}: seeded On This Day widget in ${updated} built-in dashboard layout(s).`);
- return { updated };
- },
-};
+export default makeWidgetSeedMigration({
+ label: 'migration 329',
+ widgetId: 'on-this-day',
+ cell: { w: 4, h: 4 },
+ logLine: '🗓️ migration 329: seeded On This Day widget in',
+});
diff --git a/scripts/migrations/_lib.js b/scripts/migrations/_lib.js
index 5a5bd2bee1..1405d5c5a0 100644
--- a/scripts/migrations/_lib.js
+++ b/scripts/migrations/_lib.js
@@ -551,6 +551,61 @@ export async function writeLayoutsDoc(path, doc) {
await writeFile(path, JSON.stringify(doc, null, 2));
}
+/**
+ * Factory for the "seed a new dashboard widget into built-in layouts"
+ * migration family (327 seeded today-agenda by hand; 329 onward use this).
+ *
+ * Appends `widgetId` to each targeted built-in layout's `widgets` list and to
+ * the end of its `grid` packing sequence (`{ id, x: 0, w, order: max+1, h }`)
+ * — a gated widget that gates off leaves only harmless trailing space, so
+ * appending is always safe. Custom/user layouts are intentionally untouched:
+ * the layout editor is the user's source of truth for those. Idempotent —
+ * re-running heals whichever of the two arrays is missing the widget and
+ * reports `already-applied` when both carry it.
+ *
+ * @param {object} opts
+ * @param {string} opts.label Human tag, e.g. `'migration 329'`
+ * @param {string} opts.widgetId Registry id being seeded
+ * @param {string[]} [opts.layoutIds] Built-in layout ids to seed (defaults to
+ * the Everything + Morning Review pair every widget seed so far targets)
+ * @param {{ w: number, h: number }} opts.cell Grid cell size for the append
+ * @param {string} opts.logLine Success log line (count is appended)
+ */
+export function makeWidgetSeedMigration({ label, widgetId, layoutIds = ['default', 'morning-review'], cell, logLine }) {
+ const targets = new Set(layoutIds);
+
+ const applyToLayout = (layout) => {
+ if (!layout || !targets.has(layout.id) || !Array.isArray(layout.widgets)) return false;
+ const hasWidget = layout.widgets.includes(widgetId);
+ const hasGridEntry = Array.isArray(layout.grid) && layout.grid.some((item) => item?.id === widgetId);
+ if (hasWidget && hasGridEntry) return false;
+
+ if (!hasWidget) layout.widgets = [...layout.widgets, widgetId];
+ if (!hasGridEntry) {
+ const grid = Array.isArray(layout.grid) ? layout.grid : [];
+ const maxOrder = grid.reduce((max, item) => Math.max(max, Number.isFinite(item?.order) ? item.order : -1), -1);
+ layout.grid = [...grid, { id: widgetId, x: 0, w: cell.w, order: maxOrder + 1, h: cell.h }];
+ }
+ return true;
+ };
+
+ return {
+ async up({ rootDir }) {
+ const result = await readLayoutsDoc({ rootDir, label });
+ if (!result.ok) return { updated: 0, reason: result.reason };
+ const { doc, path } = result;
+ let updated = 0;
+ for (const layout of doc.layouts) {
+ if (applyToLayout(layout)) updated += 1;
+ }
+ if (updated === 0) return { updated: 0, reason: 'already-applied' };
+ await writeLayoutsDoc(path, doc);
+ console.log(`${logLine} ${updated} built-in dashboard layout(s).`);
+ return { updated };
+ },
+ };
+}
+
// ---- media-model-registry migration family ----
const MEDIA_MODELS_REL_PATH = 'data/media-models.json';
diff --git a/server/services/brainOnThisDay.js b/server/services/brainOnThisDay.js
index 2900bca860..6c82c059f1 100644
--- a/server/services/brainOnThisDay.js
+++ b/server/services/brainOnThisDay.js
@@ -10,7 +10,9 @@
*/
import * as brainStorage from './brainStorage.js';
+import { getBrainProjections } from './brainSearchIndex.js';
import { getUserTimezone } from './userTimezone.js';
+import { stripMarkdownEmphasis } from '../lib/markdownText.js';
import { todayInTimezone } from '../lib/timezone.js';
const SNIPPET_MAX = 160;
@@ -24,10 +26,10 @@ const TYPE_RANK = { journal: 0, memory: 1, idea: 2 };
*/
export function snippetOf(text, max = SNIPPET_MAX) {
if (typeof text !== 'string') return '';
- const flat = text
- .replace(/```[\s\S]*?```/g, ' ')
- .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
- .replace(/^[#>\-*\s]+/gm, ' ')
+ const flat = stripMarkdownEmphasis(
+ text.replace(/```[\s\S]*?```/g, ' ').replace(/!\[/g, '['),
+ )
+ .replace(/^[#>\-\s]+/gm, ' ')
.replace(/\s+/g, ' ')
.trim();
if (flat.length <= max) return flat;
@@ -36,13 +38,21 @@ export function snippetOf(text, max = SNIPPET_MAX) {
const yearOf = (isoDate) => Number(isoDate.slice(0, 4));
+/**
+ * Does this local YYYY-MM-DD share `today`'s month-day in a prior year?
+ */
+export const isPriorYearMonthDay = (isoDate, today) =>
+ typeof isoDate === 'string'
+ && isoDate.endsWith(today.slice(4))
+ && Number.isInteger(yearOf(isoDate))
+ && yearOf(isoDate) < yearOf(today);
+
/**
* Pure collector: match records to today's month-day in prior years.
* `today` is the local YYYY-MM-DD; `timezone` converts record timestamps to
* local dates. Exported for tests.
*/
export function collectOnThisDay({ today, timezone, journals = [], ideas = [], memories = [] }) {
- const monthDay = today.slice(5);
const currentYear = yearOf(today);
const items = [];
@@ -51,17 +61,14 @@ export function collectOnThisDay({ today, timezone, journals = [], ideas = [], m
const at = Date.parse(stamp ?? '');
if (!Number.isFinite(at)) return null;
const localDate = todayInTimezone(timezone, new Date(at));
- if (localDate.slice(5) !== monthDay || yearOf(localDate) >= currentYear) return null;
- return localDate;
+ return isPriorYearMonthDay(localDate, today) ? localDate : null;
};
for (const journal of journals) {
- if (typeof journal?.date !== 'string' || !journal.date.endsWith(`-${monthDay}`)) continue;
- const year = yearOf(journal.date);
- if (!Number.isInteger(year) || year >= currentYear) continue;
+ if (!isPriorYearMonthDay(journal?.date, today)) continue;
const snippet = snippetOf(journal.content);
if (!snippet) continue;
- items.push({ type: 'journal', id: journal.date, date: journal.date, yearsAgo: currentYear - year, title: null, snippet });
+ items.push({ type: 'journal', id: journal.date, date: journal.date, yearsAgo: currentYear - yearOf(journal.date), title: null, snippet });
}
for (const memory of memories) {
@@ -85,15 +92,25 @@ export function collectOnThisDay({ today, timezone, journals = [], ideas = [], m
/**
* The dashboard widget's read: today's lookbacks across journals, memories,
* and ideas, capped at `limit` rows (total reports the uncapped match count).
+ *
+ * Reads the brainSearchIndex projections rather than `brainStorage.getAll` —
+ * the projection cache is built once and kept fresh by brainEvents, so a
+ * steady-state dashboard load costs zero disk I/O against stores that can
+ * hold thousands of records. Journal projections deliberately carry no body,
+ * so only the handful of matched days are loaded for their snippet.
*/
export async function getOnThisDay({ limit = 8 } = {}) {
const timezone = await getUserTimezone();
const today = todayInTimezone(timezone);
- const [journals, ideas, memories] = await Promise.all([
- brainStorage.getAll('journals'),
- brainStorage.getAll('ideas'),
- brainStorage.getAll('memories'),
+ const [journalIndex, ideas, memories] = await Promise.all([
+ getBrainProjections('journals', { ranked: false }),
+ getBrainProjections('ideas', { ranked: false }),
+ getBrainProjections('memories', { ranked: false }),
]);
+ const journals = (await Promise.all(journalIndex
+ .filter((j) => j.hasBody && isPriorYearMonthDay(j.date, today))
+ .map((j) => brainStorage.getById('journals', j.date))
+ )).filter(Boolean);
const items = collectOnThisDay({ today, timezone, journals, ideas, memories });
return { date: today, timezone, total: items.length, items: items.slice(0, limit) };
}
diff --git a/server/services/brainOnThisDay.test.js b/server/services/brainOnThisDay.test.js
index 3bd435c2d5..689c922ed3 100644
--- a/server/services/brainOnThisDay.test.js
+++ b/server/services/brainOnThisDay.test.js
@@ -7,6 +7,7 @@ const TODAY = '2026-09-01';
describe('snippetOf', () => {
it('flattens markdown chrome and collapses whitespace', () => {
expect(snippetOf('# Heading\n\n- did a [thing](https://example.com)\n> quote')).toBe('Heading did a thing quote');
+ expect(snippetOf('**Big day** — shipped `it` with ![pic](img.png)')).toBe('Big day — shipped it with pic');
});
it('drops fenced code blocks and truncates with an ellipsis', () => {
diff --git a/server/services/brainSearchIndex.js b/server/services/brainSearchIndex.js
index e4ef0c7c5c..9721e29eee 100644
--- a/server/services/brainSearchIndex.js
+++ b/server/services/brainSearchIndex.js
@@ -64,9 +64,12 @@ const PROJECTED_FIELDS = Object.freeze({
inbox: Object.freeze(['capturedText']),
people: GRAPH_PROJECTION_FIELDS,
projects: GRAPH_PROJECTION_FIELDS,
- ideas: GRAPH_PROJECTION_FIELDS,
+ // `createdAt` (+ import-time `sourceCreatedAt` on memories) serves
+ // `getOnThisDay` (server/services/brainOnThisDay.js), which matches records
+ // to a calendar date without walking the stores.
+ ideas: Object.freeze([...GRAPH_PROJECTION_FIELDS, 'createdAt']),
admin: Object.freeze([...GRAPH_PROJECTION_FIELDS, 'nextAction']),
- memories: Object.freeze([...GRAPH_PROJECTION_FIELDS, 'mood']),
+ memories: Object.freeze([...GRAPH_PROJECTION_FIELDS, 'mood', 'createdAt', 'sourceCreatedAt']),
links: Object.freeze(['title', 'url', 'description']),
journals: Object.freeze(['date']),
songs: GRAPH_PROJECTION_FIELDS,