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

fix: page Calendar daily review so days over 200 events are fully reviewable (#10873)

Adam Eivyde909139ea3c
diff --git a/client/src/components/calendar/ReviewTab.jsx b/client/src/components/calendar/ReviewTab.jsx
index 403e0b5514..f27f13c93a 100644
--- a/client/src/components/calendar/ReviewTab.jsx
+++ b/client/src/components/calendar/ReviewTab.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback } from 'react';
+import { useState, useEffect, useCallback, useMemo } 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';
@@ -6,25 +6,49 @@ import { formatCount, formatDurationMin, formatTimeOfDay } from '../../utils/for
import BrailleSpinner from '../BrailleSpinner';
import EmptyState from '../EmptyState';
import { localDateStr } from '../meatspace/constants';
+import { usePagedCollection } from '../../hooks/usePagedCollection';
+
+const PAGE_SIZE = 200;
+
+const reviewEventId = event => event.id || event.externalId;
export default function ReviewTab({ accounts = [] }) {
const [date, setDate] = useState(localDateStr());
- const [review, setReview] = useState(null);
- const [loading, setLoading] = useState(true);
const [confirming, setConfirming] = useState(null);
const [editingEvent, setEditingEvent] = useState(null);
const [editForm, setEditForm] = useState({ durationMinutes: '', note: '', goalId: '' });
- const fetchReview = useCallback(async () => {
- setLoading(true);
- const data = await api.getDailyReview(date).catch(() => null);
- setReview(data);
- setLoading(false);
+ // The server pages the day's events but summarizes the whole day on every
+ // page, so each page's response replaces `meta` while rows accumulate.
+ const fetchPage = useCallback(async ({ cursor, signal }) => {
+ const offset = cursor ?? 0;
+ const data = await api.getDailyReview(date, { limit: PAGE_SIZE, offset }, { signal, silent: true });
+ const nextOffset = data?.nextOffset ?? null;
+ if (!Array.isArray(data?.events) || !Number.isSafeInteger(data.total) || data.total < 0
+ || data.events.length > PAGE_SIZE || !data.summary
+ || (nextOffset !== null && (!Number.isSafeInteger(nextOffset) || nextOffset <= offset))) {
+ throw new Error('Calendar returned an incomplete review page');
+ }
+ return {
+ items: data.events.map((event, index) => ({ id: reviewEventId(event) ?? `${offset}:${index}`, event })),
+ total: data.total,
+ meta: { ...data, date, events: undefined },
+ nextCursor: nextOffset,
+ };
}, [date]);
+ const { items, meta, loaded, loading: pageLoading, error, hasMore, loadMore, refreshFirst } = usePagedCollection(fetchPage);
+ // Review needs the whole day before "to review" is trustworthy; stop on
+ // failure and let Retry resume from the same cursor without losing rows.
useEffect(() => {
- fetchReview();
- }, [fetchReview]);
+ if (loaded && hasMore && !pageLoading && !error) loadMore();
+ }, [loaded, hasMore, pageLoading, error, loadMore]);
+
+ // A superseded day's rows can render for one commit before the hook resets.
+ const review = meta?.date === date ? meta : null;
+ const events = useMemo(() => (review ? items.map(item => item.event) : []), [review, items]);
+ const loading = !error && !(loaded && review);
+ const complete = loaded && !hasMore && !error;
const changeDate = (delta) => {
const d = new Date(date + 'T12:00:00');
@@ -70,7 +94,7 @@ export default function ReviewTab({ accounts = [] }) {
} else {
toast.success(happened ? 'Event confirmed' : 'Event skipped');
}
- fetchReview();
+ refreshFirst();
};
const handleConfirmWithEdit = async (event) => {
@@ -91,7 +115,7 @@ export default function ReviewTab({ accounts = [] }) {
if (!result) return toast.error('Failed to confirm event');
toast.success(result.progressEntry ? 'Event confirmed & progress logged' : 'Event confirmed');
- fetchReview();
+ refreshFirst();
};
const isToday = date === localDateStr();
@@ -99,14 +123,6 @@ export default function ReviewTab({ accounts = [] }) {
? (Date.now() - new Date(review.lastSyncAt).getTime()) > 12 * 60 * 60 * 1000
: true;
- if (loading) {
- return (
- <div className="flex items-center justify-center py-12">
- <BrailleSpinner text="Loading" />
- </div>
- );
- }
-
return (
<div className="space-y-4 max-w-3xl">
{/* Date Navigation */}
@@ -134,7 +150,7 @@ export default function ReviewTab({ accounts = [] }) {
</button>
)}
</div>
- {isSyncStale && (
+ {!loading && isSyncStale && (
<div className="flex items-center gap-1.5 text-xs text-port-warning">
<AlertTriangle size={14} />
<span>{review?.lastSyncAt ? 'Sync data may be stale' : 'No sync data'}</span>
@@ -143,7 +159,7 @@ export default function ReviewTab({ accounts = [] }) {
</div>
{/* Summary */}
- {review && (
+ {review && !loading && (
<div className="flex gap-4 text-xs">
<span className="text-gray-500">{formatCount(review.summary.totalEvents)} events</span>
{review.summary.confirmed > 0 && (
@@ -163,9 +179,31 @@ export default function ReviewTab({ accounts = [] }) {
</div>
)}
+ {/* The date controls stay live while a day loads so a slow day can be abandoned. */}
+ {loading && (
+ <div className="flex items-center justify-center py-12">
+ <BrailleSpinner text="Loading" />
+ </div>
+ )}
+
{/* Events */}
- {(!review?.events?.length) ? (
- accounts.length === 0 ? (
+ {!loading && !complete && (
+ <div role={error ? 'alert' : 'status'} className="flex flex-wrap items-center gap-3 rounded border border-port-border bg-port-card p-3 text-sm text-gray-400">
+ <p>{error
+ ? (review
+ ? `Showing ${formatCount(events.length)} of ${formatCount(review.total)} events. The rest could not be loaded, so the review is incomplete.`
+ : 'The daily review could not be loaded.')
+ : `Loading events… showing ${formatCount(events.length)} of ${formatCount(review.total)}.`}</p>
+ {error && (
+ <button type="button" onClick={loadMore} className="min-h-[44px] rounded px-3 py-2 text-port-accent hover:bg-port-border">
+ Retry
+ </button>
+ )}
+ </div>
+ )}
+
+ {loading ? null : (!events.length) ? (
+ !complete ? null : accounts.length === 0 ? (
<EmptyState
icon={CalendarDays}
title="No calendar connected"
@@ -180,7 +218,7 @@ export default function ReviewTab({ accounts = [] }) {
)
) : (
<div className="space-y-2">
- {[...review.events]
+ {[...events]
.sort((a, b) => {
if (a.isAllDay && !b.isAllDay) return -1;
if (!a.isAllDay && b.isAllDay) return 1;
@@ -188,8 +226,10 @@ export default function ReviewTab({ accounts = [] }) {
})
.map(event => {
const eventId = event.id || event.externalId;
- const isConfirmed = event.confirmation?.happened === true;
- const isSkipped = event.confirmation?.happened === false;
+ // The response's day-wide map is fresher than a row loaded on an earlier page.
+ const confirmation = review.confirmations?.[eventId] ?? event.confirmation;
+ const isConfirmed = confirmation?.happened === true;
+ const isSkipped = confirmation?.happened === false;
const isReviewed = isConfirmed || isSkipped;
const isEditing = editingEvent === eventId;
@@ -343,7 +383,7 @@ export default function ReviewTab({ accounts = [] }) {
)}
{/* Progress Entries */}
- {review?.progressEntries?.length > 0 && (
+ {!loading && review?.progressEntries?.length > 0 && (
<div>
<h3 className="text-sm font-medium text-gray-400 mb-2">Progress Logged Today</h3>
<div className="space-y-1">
diff --git a/client/src/components/calendar/ReviewTab.test.jsx b/client/src/components/calendar/ReviewTab.test.jsx
index 2ee7bfad01..e238f85866 100644
--- a/client/src/components/calendar/ReviewTab.test.jsx
+++ b/client/src/components/calendar/ReviewTab.test.jsx
@@ -2,12 +2,19 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import { afterEach, describe, expect, it, vi } from 'vitest';
+// Mirrors GET /calendar/review/:date: one bounded page plus full-day metadata.
+const reviewPage = (events, { total = events.length, offset = 0, nextOffset = null, unreviewed = total } = {}) => ({
+ events, total, offset, nextOffset, hasMore: nextOffset !== null,
+ confirmations: {},
+ progressEntries: [],
+ summary: { totalEvents: total, confirmed: 0, skipped: 0, unreviewed },
+});
+const dayEvents = (from, to) => Array.from({ length: to - from }, (_, i) => ({
+ id: `event-${from + i}`, title: `Event ${from + i}`, startTime: '2026-01-01T09:00:00',
+}));
+
vi.mock('../../services/api', () => ({
- getDailyReview: vi.fn(() => Promise.resolve({
- events: [],
- progressEntries: [],
- summary: { totalEvents: 0, confirmed: 0, skipped: 0, unreviewed: 0 },
- })),
+ getDailyReview: vi.fn(() => Promise.resolve(reviewPage([]))),
}));
import * as api from '../../services/api';
@@ -28,7 +35,7 @@ describe('ReviewTab', () => {
render(<MemoryRouter><ReviewTab /></MemoryRouter>);
- await waitFor(() => expect(api.getDailyReview).toHaveBeenCalledWith('2026-01-01'));
+ await waitFor(() => expect(api.getDailyReview).toHaveBeenCalledWith('2026-01-01', expect.objectContaining({ limit: 200, offset: 0 }), expect.anything()));
expect(screen.getByLabelText('Review date').value).toBe('2026-01-01');
expect(screen.queryByRole('button', { name: 'Today' })).toBeNull();
});
@@ -38,11 +45,11 @@ describe('ReviewTab', () => {
vi.setSystemTime(new Date(2026, 0, 1, 20));
render(<MemoryRouter><ReviewTab /></MemoryRouter>);
- await waitFor(() => expect(api.getDailyReview).toHaveBeenCalledWith('2026-01-01'));
+ await waitFor(() => expect(api.getDailyReview).toHaveBeenCalledWith('2026-01-01', expect.objectContaining({ limit: 200, offset: 0 }), expect.anything()));
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
- await waitFor(() => expect(api.getDailyReview).toHaveBeenCalledWith('2026-01-02'));
+ await waitFor(() => expect(api.getDailyReview).toHaveBeenCalledWith('2026-01-02', expect.objectContaining({ limit: 200, offset: 0 }), expect.anything()));
expect(screen.getByLabelText('Review date').value).toBe('2026-01-02');
});
@@ -68,4 +75,63 @@ describe('ReviewTab', () => {
expect(screen.queryByText('No calendar connected')).toBeNull();
expect(screen.queryByText('Sync your calendar to see events here')).toBeNull();
});
+
+ describe('paged days', () => {
+ it('loads the 201st event, keeping the full-day counts visible', async () => {
+ vi.setSystemTime(new Date(2026, 0, 1, 20));
+ api.getDailyReview
+ .mockResolvedValueOnce(reviewPage(dayEvents(0, 200), { total: 201, nextOffset: 200 }))
+ .mockResolvedValueOnce(reviewPage(dayEvents(200, 201), { total: 201, offset: 200 }));
+
+ render(<MemoryRouter><ReviewTab accounts={[{ id: 'acct-1' }]} /></MemoryRouter>);
+
+ expect(await screen.findByText('Event 200')).toBeTruthy();
+ expect(api.getDailyReview).toHaveBeenLastCalledWith('2026-01-01', { limit: 200, offset: 200 }, expect.anything());
+ expect(screen.getByText('201 events')).toBeTruthy();
+ expect(screen.getByText('201 to review')).toBeTruthy();
+ expect(screen.getAllByLabelText('Confirm - it happened')).toHaveLength(201);
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
+
+ it('keeps loaded rows when a later page fails and resumes from the same cursor on Retry', async () => {
+ vi.setSystemTime(new Date(2026, 0, 1, 20));
+ api.getDailyReview
+ .mockResolvedValueOnce(reviewPage(dayEvents(0, 200), { total: 201, nextOffset: 200 }))
+ .mockRejectedValueOnce(new Error('boom'))
+ .mockResolvedValueOnce(reviewPage(dayEvents(200, 201), { total: 201, offset: 200 }));
+
+ render(<MemoryRouter><ReviewTab accounts={[{ id: 'acct-1' }]} /></MemoryRouter>);
+
+ const alert = await screen.findByRole('alert');
+ expect(alert.textContent).toContain('Showing 200 of 201 events');
+ expect(screen.getAllByLabelText('Confirm - it happened')).toHaveLength(200);
+ expect(screen.getByText('201 to review')).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+
+ expect(await screen.findByText('Event 200')).toBeTruthy();
+ expect(api.getDailyReview).toHaveBeenLastCalledWith('2026-01-01', { limit: 200, offset: 200 }, expect.anything());
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
+
+ it('never shows an obsolete day when its response resolves after a date change', async () => {
+ vi.setSystemTime(new Date(2026, 0, 1, 20));
+ let resolveFirst;
+ api.getDailyReview
+ .mockImplementationOnce(() => new Promise(resolve => { resolveFirst = resolve; }))
+ .mockResolvedValueOnce(reviewPage([{ id: 'new-day', title: 'New day event', startTime: '2026-01-02T09:00:00' }]));
+
+ render(<MemoryRouter><ReviewTab accounts={[{ id: 'acct-1' }]} /></MemoryRouter>);
+ await waitFor(() => expect(api.getDailyReview).toHaveBeenCalledTimes(1));
+ fireEvent.click(screen.getByRole('button', { name: 'Next' }));
+ expect(await screen.findByText('New day event')).toBeTruthy();
+
+ resolveFirst(reviewPage([{ id: 'old-day', title: 'Old day event', startTime: '2026-01-01T09:00:00' }]));
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(screen.queryByText('Old day event')).toBeNull();
+ expect(screen.getByText('New day event')).toBeTruthy();
+ });
+ });
});
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index f3639d1bdc..142aeb253a 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -289,7 +289,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useGalleryPreviewResolver` | Builds the stable `resolveItem` callback that resolves a `?preview=` param the host's own items list does not contain, by looking the record up in the gallery and normalizing it. `usePreviewRoute` uses it as its DEFAULT. | Call it directly only to narrow the lookup — `collectionId` scopes it to one collection. |
| `useImageVariants` | Fetches the original-vs-cleaned variant set for the one open image (`GET /api/image-gen/:filename/variants`), normalized; reuses the held group across toggle clicks and aborts a superseded lookup. `null` while unfetched or failed, `[]` when the image is not indexed. | `MediaPreview` calls it for every image preview; neither a page-owned ref list nor a 60-row gallery window is a complete source of variant lineage. |
| `useGalleryPage` | Bounded image or mixed-media browsing with debounced server search, scopes, totals, stale-response cancellation and retryable next pages. | Gallery grids and pickers; `getGalleryImages` hydrates known references separately. |
-| `usePagedCollection` | `usePagedCollection(fetchPage, { enabled })` — bounded cursor pages, deduplication by id, single-flight loading, abort/stale-query protection, retry, reset, and local mutation via setItems. | Growing cursor-based collections; pair with `InfiniteScrollFooter`. |
+| `usePagedCollection` | `usePagedCollection(fetchPage, { enabled })` — bounded cursor pages, deduplication by id, single-flight loading, abort/stale-query protection, retry, reset, and local mutation via setItems; an optional `meta` returned by `fetchPage` is exposed as the latest page's response-level data. | Growing cursor-based collections; pair with `InfiniteScrollFooter`. |
| `useGoalOrganize` / `useGoalCreate` | Shared goal suggestion preview, explicit apply, and guarded create flows for both Goals views. | Goals List and Tree views. |
diff --git a/client/src/hooks/usePagedCollection.js b/client/src/hooks/usePagedCollection.js
index eeb4ea0faa..f473d5562c 100644
--- a/client/src/hooks/usePagedCollection.js
+++ b/client/src/hooks/usePagedCollection.js
@@ -1,8 +1,10 @@
import { useCallback, useEffect, useRef, useState } from 'react';
-const emptyPage = () => ({ items: [], total: null, nextCursor: null, loaded: false, loading: false, error: null });
+const emptyPage = () => ({ items: [], total: null, meta: null, nextCursor: null, loaded: false, loading: false, error: null });
-// fetchPage({ cursor, signal }) returns { items, total?, nextCursor }.
+// fetchPage({ cursor, signal }) returns { items, total?, meta?, nextCursor }.
+// `meta` is the latest page's response-level data (e.g. a day summary); it is
+// replaced by each page and shares the items' stale-query protection.
// Its identity is the query key: memoize it over the collection's filters.
export function usePagedCollection(fetchPage, { enabled = true } = {}) {
const [page, setPage] = useState(emptyPage);
@@ -29,7 +31,7 @@ export function usePagedCollection(fetchPage, { enabled = true } = {}) {
// their records after merging, including gaps backfilled after reconnect.
const items = new Map((refresh ? result.items : state.current.items).map(item => [item.id, item]));
for (const item of refresh ? state.current.items : result.items) if (!refresh || !items.has(item.id)) items.set(item.id, item);
- commit({ items: [...items.values()], total: result.total ?? state.current.total,
+ commit({ items: [...items.values()], total: result.total ?? state.current.total, meta: result.meta ?? state.current.meta,
nextCursor: refresh && overlaps ? state.current.nextCursor : result.nextCursor ?? null, loaded: true, loading: false, error: null });
} catch (error) {
if (generation.current === epoch) {
diff --git a/client/src/services/apiCalendar.js b/client/src/services/apiCalendar.js
index dd85aab8ed..4288581da5 100644
--- a/client/src/services/apiCalendar.js
+++ b/client/src/services/apiCalendar.js
@@ -28,5 +28,8 @@ export const apiSyncGoogleCalendar = (accountId, options = {}) => request(`/cale
export const apiDiscoverCalendars = (accountId) => request(`/calendar/sync/${accountId}/discover-api`, { method: 'POST' });
export const startGoogleAutoConfig = (options = {}) => request('/calendar/google/auto-configure/start', { method: 'POST', ...options });
export const runGoogleAutoConfig = (email, options = {}) => request('/calendar/google/auto-configure/run', { method: 'POST', body: JSON.stringify({ email }), ...options });
-export const getDailyReview = (date) => request(`/calendar/review/${date}`);
+export const getDailyReview = (date, params = {}, options = {}) => {
+ const str = new URLSearchParams(Object.entries(params).filter(([, v]) => v != null)).toString();
+ return request(`/calendar/review/${date}${str ? `?${str}` : ''}`, options);
+};
export const confirmDailyReviewEvent = (date, data, options = {}) => request(`/calendar/review/${date}/confirm`, { method: 'POST', body: JSON.stringify(data), ...options });
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 6c43cae7f9..9c4b023725 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -2758,6 +2758,13 @@ export const promptJobSkillBodySchema = z.object({ content: nonEmptyString });
export const promptPreviewBodySchema = z.object({ testData: z.record(z.string(), z.unknown()).default({}) });
// Smaller single-purpose bodies
+// GET /api/calendar/review/:date — bounded page of the day's events. The
+// defaults reproduce the legacy single-page response.
+export const dailyReviewQuerySchema = z.object({
+ limit: z.coerce.number().int().min(1).max(200).default(200),
+ offset: z.coerce.number().int().min(0).default(0),
+});
+
export const calendarAutoConfigureBodySchema = z.object({ email: optionalString });
export const commandExecuteBodySchema = z.object({ command: nonEmptyString, workspacePath: nullishString });
export const dataArchiveBodySchema = z.object({
diff --git a/server/routes/calendar.js b/server/routes/calendar.js
index 7805650ba4..5c27a208cf 100644
--- a/server/routes/calendar.js
+++ b/server/routes/calendar.js
@@ -1,7 +1,7 @@
import express from 'express';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { validateRequest, parsePagination, calendarAutoConfigureBodySchema } from '../lib/validation.js';
+import { validateRequest, parsePagination, calendarAutoConfigureBodySchema, dailyReviewQuerySchema } from '../lib/validation.js';
import { UUID_RE } from '../lib/fileUtils.js';
import { MEETING_URL_MAX } from '../lib/meetingUrl.js';
import * as calendarAccounts from '../services/calendarAccounts.js';
@@ -418,7 +418,8 @@ router.get('/review/:date', asyncHandler(async (req, res) => {
if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
throw new ServerError('Invalid date format, use YYYY-MM-DD', { status: 400, code: 'VALIDATION_ERROR' });
}
- const review = await dailyReview.getDailyReview(dateStr);
+ const { limit, offset } = validateRequest(dailyReviewQuerySchema, req.query);
+ const review = await dailyReview.getDailyReview(dateStr, { limit, offset });
res.json(review);
}));
diff --git a/server/routes/calendar.test.js b/server/routes/calendar.test.js
index 814fcea2a7..86936e80b3 100644
--- a/server/routes/calendar.test.js
+++ b/server/routes/calendar.test.js
@@ -89,6 +89,20 @@ describe('Calendar Routes — normalized error handling', () => {
});
describe('thrown ServerErrors map to the standard JSON envelope', () => {
+ it('GET /review/:date passes bounded page params to the service and defaults to the legacy first page', async () => {
+ dailyReview.getDailyReview.mockResolvedValue({ events: [], total: 0 });
+ await request(app).get('/api/calendar/review/2026-01-02');
+ expect(dailyReview.getDailyReview).toHaveBeenLastCalledWith('2026-01-02', { limit: 200, offset: 0 });
+ await request(app).get('/api/calendar/review/2026-01-02?limit=25&offset=200');
+ expect(dailyReview.getDailyReview).toHaveBeenLastCalledWith('2026-01-02', { limit: 25, offset: 200 });
+ dailyReview.getDailyReview.mockClear();
+ for (const bad of ['limit=999', 'limit=0', 'offset=-4', 'offset=abc']) {
+ const response = await request(app).get(`/api/calendar/review/2026-01-02?${bad}`);
+ expect(response.status, bad).toBe(400);
+ }
+ expect(dailyReview.getDailyReview).not.toHaveBeenCalled();
+ });
+
it('POST /review/:date/confirm preserves typed missing-goal errors', async () => {
dailyReview.confirmEvent.mockRejectedValue(new ServerError('Goal not found', { status: 404, code: 'GOAL_NOT_FOUND' }));
const response = await request(app).post('/api/calendar/review/2026-01-02/confirm')
diff --git a/server/services/dailyReview.js b/server/services/dailyReview.js
index 8f3db454b8..19ef70e5d8 100644
--- a/server/services/dailyReview.js
+++ b/server/services/dailyReview.js
@@ -24,7 +24,28 @@ async function saveReview(date, data) {
await atomicWrite(join(REVIEW_DIR, `${date}.json`), data);
}
-export async function getDailyReview(date) {
+export const DAILY_REVIEW_PAGE_SIZE = 200;
+
+const eventKey = event => event.id || event.externalId;
+
+// Walk the source collection by its own total so the summary describes the whole
+// day, whatever page the caller asked to display. The walk stops on an empty
+// page, so a source that under-reports its total cannot spin forever.
+async function collectDayEvents(startDate, endDate) {
+ const events = [];
+ let total = 0;
+ do {
+ const page = await calendarSync.getEvents({
+ startDate, endDate, limit: DAILY_REVIEW_PAGE_SIZE, offset: events.length
+ });
+ total = Number.isSafeInteger(page.total) ? page.total : page.events.length;
+ if (!page.events.length) break;
+ events.push(...page.events);
+ } while (events.length < total);
+ return events;
+}
+
+export async function getDailyReview(date, { limit = DAILY_REVIEW_PAGE_SIZE, offset = 0 } = {}) {
// Recover a durable intent before projecting confirmations or goal progress.
const existing = await reviewQueue(date, async () => {
const review = await loadReview(date) || { confirmations: Object.create(null), updatedAt: null };
@@ -40,8 +61,8 @@ export async function getDailyReview(date) {
// Get all events for this date across all accounts
const startDate = `${date}T00:00:00`;
const endDate = `${date}T23:59:59`;
- const [{ events }, accounts, goalsData] = await Promise.all([
- calendarSync.getEvents({ startDate, endDate, limit: 200 }),
+ const [dayEvents, accounts, goalsData] = await Promise.all([
+ collectDayEvents(startDate, endDate),
calendarAccounts.listAccounts(),
getGoals()
]);
@@ -65,8 +86,9 @@ export async function getDailyReview(date) {
}
// Enrich events with confirmation status and goal matches
- const enrichedEvents = events.map(event => {
- const confirmation = existing.confirmations[event.id || event.externalId];
+ const pageEvents = dayEvents.slice(offset, offset + limit);
+ const enrichedEvents = pageEvents.map(event => {
+ const confirmation = existing.confirmations[eventKey(event)];
const subcalInfo = subcalendarMap[event.subcalendarId];
const matchingGoals = (subcalInfo?.linkedGoals || []).filter(lg => {
if (!lg.matchPattern) return true;
@@ -100,19 +122,26 @@ export async function getDailyReview(date) {
}
}
+ const nextOffset = offset + pageEvents.length < dayEvents.length ? offset + pageEvents.length : null;
+
return {
date,
events: enrichedEvents,
+ total: dayEvents.length,
+ limit,
+ offset,
+ nextOffset,
+ hasMore: nextOffset !== null,
confirmations: existing.confirmations,
pendingConfirmations: Object.fromEntries(Object.keys(existing.pendingOperations || {})
.map(eventId => [eventId, { code: 'GOAL_NOT_FOUND' }])),
progressEntries,
lastSyncAt,
summary: {
- totalEvents: enrichedEvents.length,
+ totalEvents: dayEvents.length,
confirmed: Object.values(existing.confirmations).filter(c => c.happened).length,
skipped: Object.values(existing.confirmations).filter(c => c.happened === false).length,
- unreviewed: enrichedEvents.filter(e => !existing.confirmations[e.id || e.externalId]).length
+ unreviewed: dayEvents.filter(e => !existing.confirmations[eventKey(e)]).length
},
updatedAt: existing.updatedAt
};
diff --git a/server/services/dailyReview.test.js b/server/services/dailyReview.test.js
index e05edded9d..d571b6d3fc 100644
--- a/server/services/dailyReview.test.js
+++ b/server/services/dailyReview.test.js
@@ -4,6 +4,8 @@ import { dirname, join } from 'node:path';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
const fault = vi.hoisted(() => ({ kind: null, countdown: 0 }));
+// Mirrors calendarSync.getEvents: a bounded page plus the filtered window's total.
+const source = vi.hoisted(() => ({ events: [], calls: [] }));
vi.mock('../lib/fileUtils.js', async original => {
const actual = await original();
return makePathsProxy(actual, {
@@ -22,7 +24,12 @@ vi.mock('./mortalLoomStore.js', () => ({
mlArrayIfEnabled: async () => null,
mlReplace: vi.fn()
}));
-vi.mock('./calendarSync.js', () => ({ getEvents: async () => ({ events: [{ id: 'event-a' }] }) }));
+vi.mock('./calendarSync.js', () => ({
+ getEvents: async ({ limit = 50, offset = 0 }) => {
+ source.calls.push({ limit, offset });
+ return { events: source.events.slice(offset, offset + limit), total: source.events.length };
+ }
+}));
vi.mock('./calendarAccounts.js', () => ({ listAccounts: async () => [] }));
vi.mock('./aiProvider.js', () => ({ callProviderAISimple: vi.fn(), parseLLMJSON: vi.fn() }));
vi.mock('./meatspaceCalendar.js', () => ({ getActivities: async () => [] }));
@@ -47,6 +54,8 @@ let review;
let goals;
beforeEach(async () => {
fault.kind = null;
+ source.events = [{ id: 'event-a' }];
+ source.calls = [];
vi.resetModules();
await rm(PATHS.calendar, { force: true, recursive: true });
await write(goalsPath, { goals: [
@@ -60,6 +69,36 @@ afterAll(cleanupTempDataRoots);
const allProgress = async () => (await read(goalsPath)).goals.flatMap(goal => goal.progressLog || []);
+describe('daily review pagination', () => {
+ const dayOf = count => Array.from({ length: count }, (_, i) => ({ id: `event-${i}`, title: `Event ${i}` }));
+
+ it('exposes the 201st event on a continuation page and keeps full-day counts on every page', async () => {
+ source.events = dayOf(201);
+ await review.confirmEvent(date, { eventId: 'event-200', happened: true });
+
+ const first = await review.getDailyReview(date);
+ expect(first.events).toHaveLength(200);
+ expect(first).toMatchObject({ total: 201, limit: 200, offset: 0, nextOffset: 200, hasMore: true });
+ expect(first.summary).toMatchObject({ totalEvents: 201, confirmed: 1, unreviewed: 200 });
+ expect(first.events.some(event => event.id === 'event-200')).toBe(false);
+ expect(first.confirmations['event-200'].happened).toBe(true);
+
+ const second = await review.getDailyReview(date, { limit: 200, offset: first.nextOffset });
+ expect(second.events.map(event => event.id)).toEqual(['event-200']);
+ expect(second.events[0].confirmation).toMatchObject({ happened: true });
+ expect(second).toMatchObject({ total: 201, offset: 200, nextOffset: null, hasMore: false });
+ expect(second.summary).toEqual(first.summary);
+ });
+
+ it('honors a smaller caller page without shrinking the summary', async () => {
+ source.events = dayOf(5);
+ const page = await review.getDailyReview(date, { limit: 2, offset: 2 });
+ expect(page.events.map(event => event.id)).toEqual(['event-2', 'event-3']);
+ expect(page).toMatchObject({ total: 5, nextOffset: 4, hasMore: true });
+ expect(page.summary.unreviewed).toBe(5);
+ });
+});
+
describe('calendar confirmation persistence workflow', () => {
it('replays a lost response, edits and moves one owned entry, then skips without removing manual progress', async () => {
const first = await review.confirmEvent(date, input);