moving
Some checks failed
Installer Smoke / installer-smoke (push) Has been cancelled

This commit is contained in:
Oleg Maslov
2026-09-02 10:10:29 +02:00
commit 0c3e2ead3b
3841 changed files with 970576 additions and 0 deletions

View File

@@ -0,0 +1,108 @@
/**
* DreamDiaryCard — renders the latest narrative (summary fallback), hides
* without data, expandable history, date labels (DREAM-DIARY spec).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup, fireEvent, waitFor } from '@testing-library/react';
vi.mock('@/lib/adapter', () => ({
adapter: { getServerUrl: () => 'http://127.0.0.1:3333' },
}));
import DreamDiaryCard, { dreamDateLabel, type DreamDayView } from './DreamDiaryCard';
function day(date: string, overrides: Partial<DreamDayView> = {}): DreamDayView {
return {
date,
summary: `Overnight I cleared 2 stale memories. (${date})`,
events: [{ action: 'memory_compact', at: `${date}T03:00:00.000Z`, stats: { temporaryPruned: 2 } }],
...overrides,
};
}
function stubDreams(body: DreamDayView[]): void {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(
new Response(JSON.stringify(body), { status: 200 }),
));
}
beforeEach(() => {
vi.useRealTimers();
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
describe('DreamDiaryCard', () => {
it('renders nothing when there are no dreams yet', async () => {
stubDreams([]);
const { container } = render(<DreamDiaryCard />);
await waitFor(() => expect(fetch).toHaveBeenCalled());
expect(container.querySelector('[data-testid="home-dream-diary"]')).toBeNull();
});
it('renders nothing when the service is unreachable', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('ECONNREFUSED')));
const { container } = render(<DreamDiaryCard />);
await waitFor(() => expect(fetch).toHaveBeenCalled());
expect(container.querySelector('[data-testid="home-dream-diary"]')).toBeNull();
});
it('shows the narrative when present, summary otherwise', async () => {
stubDreams([
day('2026-07-09', { narrative: 'While you slept I tidied two memories and filed one insight.' }),
]);
render(<DreamDiaryCard />);
expect(await screen.findByTestId('dream-latest-text')).toHaveTextContent('tidied two memories');
});
it('falls back to the deterministic summary without a narrative', async () => {
stubDreams([day('2026-07-09')]);
render(<DreamDiaryCard />);
expect(await screen.findByTestId('dream-latest-text')).toHaveTextContent('cleared 2 stale memories');
});
it('expands previous nights on toggle', async () => {
stubDreams([
day('2026-07-09', { narrative: 'newest' }),
day('2026-07-08', { narrative: 'the night before' }),
day('2026-07-07'),
]);
render(<DreamDiaryCard />);
const toggle = await screen.findByTestId('dream-history-toggle');
expect(toggle).toHaveTextContent('Previous nights (2)');
expect(screen.queryByTestId('dream-history')).toBeNull();
fireEvent.click(toggle);
const history = screen.getByTestId('dream-history');
expect(history).toHaveTextContent('the night before');
expect(history).toHaveTextContent('cleared 2 stale memories');
});
it('hides the history toggle with a single entry', async () => {
stubDreams([day('2026-07-09')]);
render(<DreamDiaryCard />);
await screen.findByTestId('dream-latest-text');
expect(screen.queryByTestId('dream-history-toggle')).toBeNull();
});
});
describe('dreamDateLabel', () => {
const now = new Date('2026-07-09T09:00:00');
it('labels today and yesterday as "Last night"', () => {
expect(dreamDateLabel('2026-07-09', now)).toBe('Last night');
expect(dreamDateLabel('2026-07-08', now)).toBe('Last night');
});
it('uses the weekday inside a week, a date beyond it (locale-agnostic)', () => {
// Within a week → a weekday word in the system locale, no digits.
const weekday = dreamDateLabel('2026-07-06', now);
expect(weekday).not.toBe('Last night');
expect(weekday).not.toMatch(/\d/);
// Beyond a week → an actual date, which carries the day number.
expect(dreamDateLabel('2026-06-20', now)).toMatch(/20/);
});
});

View File

@@ -0,0 +1,116 @@
/**
* Dream Diary card — "While you slept" (docs/plans/DREAM-DIARY-2026-07-09.md).
*
* Shows the latest nightly memory-curation narrative from /api/dreams with
* an expandable history of previous nights. Renders NOTHING until the first
* dream exists (new installs see no empty shell). The narrative is the
* lazily-LLM-polished text; until (or unless) it lands, the deterministic
* summary shows — both trace to real curation counters, never invention.
*
* Sits directly under the OvernightHero (automation runs) on HomeCockpit —
* automations and memory curation are sibling "overnight work" stories.
*/
import { useEffect, useRef, useState } from 'react';
import { ChevronDown, ChevronRight, MoonStar } from 'lucide-react';
import { adapter } from '@/lib/adapter';
export interface DreamDayView {
date: string;
summary: string;
narrative?: string;
events: Array<{ action: string; at: string; stats: Record<string, number> }>;
}
/** "Last night" for today/yesterday; a readable date otherwise. */
export function dreamDateLabel(date: string, now: Date = new Date()): string {
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const target = new Date(`${date}T00:00:00`);
const diffDays = Math.round((today.getTime() - target.getTime()) / 86_400_000);
if (diffDays <= 1) return 'Last night';
if (diffDays < 7) return target.toLocaleDateString(undefined, { weekday: 'long' });
return target.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
const DreamDiaryCard = () => {
const [dreams, setDreams] = useState<DreamDayView[]>([]);
const [expanded, setExpanded] = useState(false);
const refetchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
let alive = true;
const load = async (): Promise<DreamDayView[]> => {
try {
const res = await fetch(`${adapter.getServerUrl()}/api/dreams?days=7`);
if (!res.ok) return [];
const body = await res.json() as DreamDayView[];
if (alive) setDreams(body);
return body;
} catch {
return []; // service unreachable — card simply stays hidden
}
};
void load().then(body => {
// The narrative is polished lazily server-side; if the newest entry
// hasn't got one yet, pick it up with a single delayed refetch.
if (alive && body[0] && !body[0].narrative) {
refetchTimer.current = setTimeout(() => { void load(); }, 6000);
}
});
return () => {
alive = false;
if (refetchTimer.current) clearTimeout(refetchTimer.current);
};
}, []);
if (dreams.length === 0) return null;
const [latest, ...older] = dreams;
return (
<div
className="mb-9 rounded-[14px] border border-[var(--line)] bg-[var(--surface-1)] px-4 py-3.5"
data-testid="home-dream-diary"
>
<div className="flex items-center gap-2">
<MoonStar className="h-4 w-4 shrink-0 text-[var(--honey-text)]" />
<p className="text-[12px] font-medium uppercase tracking-wide text-[var(--text-muted)]">
While you slept · {dreamDateLabel(latest.date)}
</p>
</div>
<p className="mt-2 text-[13.5px] leading-relaxed text-[var(--text-2)]" data-testid="dream-latest-text">
{latest.narrative ?? latest.summary}
</p>
{older.length > 0 && (
<div className="mt-2.5">
<button
type="button"
onClick={() => setExpanded(v => !v)}
className="inline-flex items-center gap-1 text-[13px] text-[var(--text-muted)] transition-colors hover:text-[var(--text)]"
data-testid="dream-history-toggle"
aria-expanded={expanded}
>
{expanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
Previous nights ({older.length})
</button>
{expanded && (
<div className="mt-2 space-y-2 border-l border-[var(--line)] pl-3" data-testid="dream-history">
{older.map(day => (
<div key={day.date}>
<p className="text-[11.5px] uppercase tracking-wide text-[var(--text-dim)]">
{dreamDateLabel(day.date)}
</p>
<p className="text-[13px] leading-relaxed text-[var(--text-muted)]">
{day.narrative ?? day.summary}
</p>
</div>
))}
</div>
)}
</div>
)}
</div>
);
};
export default DreamDiaryCard;