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
fix: load every calendar event page before showing complete availability (#9698)
Adam Eivyf16e79cbe1c7
diff --git a/client/src/components/calendar/CalendarWindowStatus.jsx b/client/src/components/calendar/CalendarWindowStatus.jsxnew file mode 100644index 0000000000..8894e36a72--- /dev/null+++ b/client/src/components/calendar/CalendarWindowStatus.jsx@@ -0,0 +1,15 @@+export default function CalendarWindowStatus({ complete, error, retry }) {+ if (complete) return null;+ return (+ <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+ ? 'Calendar events are incomplete. Some events could not be loaded; empty times may still be busy.'+ : 'Loading calendar events… Empty times may still be busy until all events are loaded.'}</p>+ {error && (+ <button type="button" onClick={retry} className="min-h-[44px] rounded px-3 py-2 text-port-accent hover:bg-port-border">+ Retry+ </button>+ )}+ </div>+ );+}diff --git a/client/src/components/calendar/DayView.jsx b/client/src/components/calendar/DayView.jsxindex a74b814132..9cd2ac5033 100644--- a/client/src/components/calendar/DayView.jsx+++ b/client/src/components/calendar/DayView.jsx@@ -1,7 +1,7 @@import { useState, useEffect, useMemo } from 'react';import {CalendarDays, ChevronLeft, ChevronRight, MapPin} from 'lucide-react';-import * as api from '../../services/api';-import socket from '../../services/socket';+import { useCalendarWindowEvents } from '../../hooks/useCalendarWindowEvents';+import CalendarWindowStatus from './CalendarWindowStatus';import EventDetail from './EventDetail';import ChronotypeOverlay from './ChronotypeOverlay';import { buildSubcalendarColorMap, eventChipStyle, eventOccursOnDay } from './calendarUtils';@@ -18,33 +18,13 @@ export default function DayView({ accounts }) {d.setHours(0, 0, 0, 0);return d;});- const [events, setEvents] = useState([]);- const [loading, setLoading] = useState(true);const [searchParams, updateParams] = useUrlParams();const { theme } = useThemeContext();- useEffect(() => {- let active = true;- let request = 0;- const fetchEvents = async () => {- const currentRequest = ++request;- const startDate = date.toISOString();- const nextDay = new Date(date);- nextDay.setDate(nextDay.getDate() + 1);- const endDate = nextDay.toISOString();- const data = await api.getCalendarEvents({ startDate, endDate, limit: 200 }).catch(() => ({ events: [] }));- if (!active || currentRequest !== request) return;- setEvents(data?.events || []);- setLoading(false);- };- setLoading(true);- fetchEvents();- socket.on('calendar:sync:completed', fetchEvents);- return () => {- active = false;- socket.off('calendar:sync:completed', fetchEvents);- };- }, [date]);+ const nextDay = new Date(date);+ nextDay.setDate(nextDay.getDate() + 1);+ const windowEvents = useCalendarWindowEvents(date.toISOString(), nextDay.toISOString());+ const { events, loading } = windowEvents;const navigate = (days) => {setDate(prev => {@@ -95,7 +75,9 @@ export default function DayView({ accounts }) {</button></div>- {loading ? (+ <CalendarWindowStatus {...windowEvents} />++ {loading && events.length === 0 ? (<div className="flex items-center justify-center py-12"><BrailleSpinner text="Loading" /></div>diff --git a/client/src/components/calendar/MonthView.jsx b/client/src/components/calendar/MonthView.jsxindex 08d65af3cf..e185f0e51c 100644--- a/client/src/components/calendar/MonthView.jsx+++ b/client/src/components/calendar/MonthView.jsx@@ -1,7 +1,7 @@-import { useState, useEffect, useMemo, useRef } from 'react';+import { useEffect, useMemo, useRef } from 'react';import {CalendarDays, ChevronLeft, ChevronRight} from 'lucide-react';-import * as api from '../../services/api';-import socket from '../../services/socket';+import { useCalendarWindowEvents } from '../../hooks/useCalendarWindowEvents';+import CalendarWindowStatus from './CalendarWindowStatus';import EventDetail from './EventDetail';import Drawer from '../Drawer';import { buildSubcalendarColorMap, eventChipStyle, eventOccursOnDay } from './calendarUtils';@@ -40,8 +40,6 @@ const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];export default function MonthView({ accounts }) {const now = new Date();- const [events, setEvents] = useState([]);- const [loading, setLoading] = useState(true);const [searchParams, updateParams] = useUrlParams();const { theme } = useThemeContext();const monthParam = searchParams.get('month');@@ -53,29 +51,11 @@ export default function MonthView({ accounts }) {const cells = getMonthGrid(year, month);const monthLabel = formatMonthYear(new Date(year, month));- useEffect(() => {- let active = true;- let request = 0;- const fetchEvents = async () => {- const currentRequest = ++request;- const grid = getMonthGrid(year, month);- const last = grid[grid.length - 1].date;- const startDate = grid[0].date.toISOString();- const endDate = new Date(last.getFullYear(), last.getMonth(), last.getDate() + 1).toISOString();- const data = await api.getCalendarEvents({ startDate, endDate, limit: 500 }).catch(() => ({ events: [] }));- if (!active || currentRequest !== request) return;- setEvents(data?.events || []);- setLoading(false);- };- setEvents([]);- setLoading(true);- fetchEvents();- socket.on('calendar:sync:completed', fetchEvents);- return () => {- active = false;- socket.off('calendar:sync:completed', fetchEvents);- };- }, [year, month]);+ const last = cells[cells.length - 1].date;+ const startDate = cells[0].date.toISOString();+ const endDate = new Date(last.getFullYear(), last.getMonth(), last.getDate() + 1).toISOString();+ const windowEvents = useCalendarWindowEvents(startDate, endDate);+ const { events, loading, complete } = windowEvents;const navigate = (dir) => {updateParams({@@ -132,7 +112,9 @@ export default function MonthView({ accounts }) {</button></div>- {loading ? (+ <CalendarWindowStatus {...windowEvents} />++ {loading && events.length === 0 ? (<div className="flex items-center justify-center py-12"><BrailleSpinner text="Loading" /></div>@@ -217,31 +199,30 @@ export default function MonthView({ accounts }) {)}<Drawer- open={!!selectedDay && !selectedEvent && !loading}+ open={!!selectedDay && !selectedEvent && (events.length > 0 || !loading)}onClose={() => updateParams({ day: null, event: null })}title={selectedDay ? formatDateFull(selectedDay.date) : ''}- subtitle={`${selectedDayEvents.length} events`}+ subtitle={`${selectedDayEvents.length} events${complete ? '' : ' loaded'}`}closeLabel="Close day events">- {loading ? <BrailleSpinner text="Loading" /> : (- <div className="space-y-2">- {selectedDayEvents.length === 0 && <p className="text-sm text-gray-400">No events available for this date.</p>}- {selectedDayEvents.map(event => (- <button- key={`${event.accountId}:${event.id}`}- type="button"- onClick={() => openEvent(event)}- className="w-full min-h-[44px] text-left px-3 py-2 rounded transition-colors hover:brightness-125"- style={eventChipStyle(colorMap.get(event.subcalendarId) || null, theme?.mode)}- >- <span className="block text-xs">{event.isAllDay ? 'All day'- : new Date(event.startTime).toDateString() === selectedDay.date.toDateString()- ? formatTimeOfDay(event.startTime) : 'Continues'}</span>- <span className="block text-sm break-words">{event.title}</span>- </button>- ))}- </div>- )}+ <div className="space-y-2">+ <CalendarWindowStatus {...windowEvents} />+ {complete && selectedDayEvents.length === 0 && <p className="text-sm text-gray-400">No events available for this date.</p>}+ {selectedDayEvents.map(event => (+ <button+ key={`${event.accountId}:${event.id}`}+ type="button"+ onClick={() => openEvent(event)}+ className="w-full min-h-[44px] text-left px-3 py-2 rounded transition-colors hover:brightness-125"+ style={eventChipStyle(colorMap.get(event.subcalendarId) || null, theme?.mode)}+ >+ <span className="block text-xs">{event.isAllDay ? 'All day'+ : new Date(event.startTime).toDateString() === selectedDay.date.toDateString()+ ? formatTimeOfDay(event.startTime) : 'Continues'}</span>+ <span className="block text-sm break-words">{event.title}</span>+ </button>+ ))}+ </div></Drawer>{selectedEvent && <EventDetail event={selectedEvent} onClose={() => updateParams({ event: null })} />}</div>diff --git a/client/src/components/calendar/WeekView.jsx b/client/src/components/calendar/WeekView.jsxindex 4dd228dc14..f2221cc943 100644--- a/client/src/components/calendar/WeekView.jsx+++ b/client/src/components/calendar/WeekView.jsx@@ -1,7 +1,7 @@-import { useState, useEffect, useMemo } from 'react';+import { useState, useMemo } from 'react';import {CalendarDays, ChevronLeft, ChevronRight} from 'lucide-react';-import * as api from '../../services/api';-import socket from '../../services/socket';+import { useCalendarWindowEvents } from '../../hooks/useCalendarWindowEvents';+import CalendarWindowStatus from './CalendarWindowStatus';import EventDetail from './EventDetail';import ChronotypeOverlay from './ChronotypeOverlay';import { buildSubcalendarColorMap, eventChipStyle, eventOccursOnDay } from './calendarUtils';@@ -29,8 +29,6 @@ function getWeekDays(weekStart) {export default function WeekView({ accounts }) {const [weekStart, setWeekStart] = useState(() => getWeekStart(new Date()));- const [events, setEvents] = useState([]);- const [loading, setLoading] = useState(true);const [searchParams, updateParams] = useUrlParams();const { theme } = useThemeContext();@@ -40,28 +38,8 @@ export default function WeekView({ accounts }) {const weekStartIso = weekStart.toISOString();const weekEndIso = weekEnd.toISOString();- useEffect(() => {- let active = true;- let request = 0;- const fetchEvents = async () => {- const currentRequest = ++request;- const data = await api.getCalendarEvents({- startDate: weekStartIso,- endDate: weekEndIso,- limit: 200- }).catch(() => ({ events: [] }));- if (!active || currentRequest !== request) return;- setEvents(data?.events || []);- setLoading(false);- };- setLoading(true);- fetchEvents();- socket.on('calendar:sync:completed', fetchEvents);- return () => {- active = false;- socket.off('calendar:sync:completed', fetchEvents);- };- }, [weekEndIso, weekStartIso]);+ const windowEvents = useCalendarWindowEvents(weekStartIso, weekEndIso);+ const { events, loading } = windowEvents;const navigate = (weeks) => {setWeekStart(prev => {@@ -119,7 +97,9 @@ export default function WeekView({ accounts }) {</button></div>- {loading ? (+ <CalendarWindowStatus {...windowEvents} />++ {loading && events.length === 0 ? (<div className="flex items-center justify-center py-12"><BrailleSpinner text="Loading" /></div>diff --git a/client/src/components/calendar/calendarEventChips.test.jsx b/client/src/components/calendar/calendarEventChips.test.jsxindex 5a1b0c1758..d0c269ce12 100644--- a/client/src/components/calendar/calendarEventChips.test.jsx+++ b/client/src/components/calendar/calendarEventChips.test.jsx@@ -42,6 +42,8 @@ const at = (hour, minute = 0, dayOffset = 0) => {return d.toISOString();};+const calendarPage = events => ({ events, total: events.length });+const ALL_DAY = {id: 'e1', accountId: 'acct-1', subcalendarId: 'cal-1',title: 'Quarter Close', isAllDay: true, startTime: at(0), endTime: at(23),@@ -67,11 +69,11 @@ it('keeps all-day membership consistent across Day, Week, and Month views', asynstartTime: new Date(2026, 8, start).toISOString(),endTime: new Date(2026, 8, end).toISOString(),});- api.getCalendarEvents.mockResolvedValue({ events: [+ api.getCalendarEvents.mockResolvedValue(calendarPage([allDay('previous', 'Previous day only', 22, 23),allDay('spanning', 'Spanning days', 21, 25),allDay('tomorrow', 'Tomorrow only', 24, 25),- ] });+ ]));const mounted = render(<MemoryRouter><DayView accounts={ACCOUNTS} /></MemoryRouter>);await act(async () => {});@@ -135,8 +137,9 @@ const expectTitleInheritsGrading = (chip, title) => {beforeEach(() => {vi.clearAllMocks();+ api.getCalendarEvents.mockReset();themeMode.current = 'night';- api.getCalendarEvents.mockResolvedValue({ events: [ALL_DAY, TIMED] });+ api.getCalendarEvents.mockResolvedValue(calendarPage([ALL_DAY, TIMED]));api.getChronotypeEnergySchedule.mockResolvedValue(null);});@@ -212,18 +215,18 @@ describe.each([};it('keeps all 24 hours when the only event is during ordinary hours', async () => {- api.getCalendarEvents.mockResolvedValue({ events: [event('Ordinary meeting', at(10), at(11))] });+ api.getCalendarEvents.mockResolvedValue(calendarPage([event('Ordinary meeting', at(10), at(11))]));await renderView(<View accounts={ACCOUNTS} />);expectFullDayGrid();expect(positions('Ordinary meeting')).toEqual([{ top: 800, height: 80 }]);});it('positions early and late events inside the grid and opens their details', async () => {- api.getCalendarEvents.mockResolvedValue({ events: [+ api.getCalendarEvents.mockResolvedValue(calendarPage([event('Early meeting', at(5), at(5, 30)),event('Late meeting', at(23, 30), at(23, 45)),event('Midnight finish', at(22), at(0, 0, 1)),- ] });+ ]));await renderView(<View accounts={ACCOUNTS} />);expectFullDayGrid();expect(positions('Early meeting')).toEqual([{ top: 400, height: 40 }]);@@ -238,11 +241,11 @@ describe.each([});it('clips overnight portions to each intersecting day and treats midnight as exclusive', async () => {- api.getCalendarEvents.mockResolvedValue({ events: [+ api.getCalendarEvents.mockResolvedValue(calendarPage([event('Overnight arrival', at(22, 0, -1), at(1)),event('Overnight departure', at(23), at(2, 0, 1)),event('Already ended', at(23, 0, -1), at(0)),- ] });+ ]));await renderView(<View accounts={ACCOUNTS} />);if (name === 'DayView') {expect(positions('Overnight arrival')).toEqual([{ top: 0, height: 80 }]);@@ -276,9 +279,9 @@ describe.each([start.setHours(10);const end = new Date(start);end.setHours(11);- await act(async () => request.resolve({ events: [{+ await act(async () => request.resolve(calendarPage([{...TIMED, id: title, title, startTime: start.toISOString(), endTime: end.toISOString(),- }] }));+ }])));};it('keeps the new date heading and events when the previous window resolves last', async () => {@@ -341,13 +344,13 @@ describe.each([it('requests the next local midnight on a daylight-saving transition day', async () => {vi.useFakeTimers({ toFake: ['Date'] });vi.setSystemTime(new Date(2026, 2, 8, 12));- api.getCalendarEvents.mockResolvedValue({ events: [] });+ api.getCalendarEvents.mockResolvedValue(calendarPage([]));await renderView(<DayView accounts={ACCOUNTS} />);expect(api.getCalendarEvents).toHaveBeenCalledWith({startDate: new Date(2026, 2, 8).toISOString(),endDate: new Date(2026, 2, 9).toISOString(),- limit: 200,- });+ limit: 200, offset: 0,+ }, { signal: expect.any(AbortSignal), silent: true });});describe('ChronotypeOverlay zone labels', () => {@@ -392,12 +395,12 @@ function MonthHistory() {describe('MonthView overflow navigation', () => {beforeEach(() => {- api.getCalendarEvents.mockResolvedValue({ events: [+ api.getCalendarEvents.mockResolvedValue(calendarPage([{ ...TIMED, id: 'late', title: 'Example late appointment', startTime: new Date(2027, 0, 12, 18).toISOString(), endTime: new Date(2027, 0, 12, 19).toISOString() },{ ...ALL_DAY, id: 'day', title: 'Example all-day entry', startTime: new Date(2027, 0, 12).toISOString(), endTime: new Date(2027, 0, 13).toISOString() },{ ...TIMED, id: 'early', title: 'Example early appointment', startTime: new Date(2027, 0, 12, 8).toISOString(), endTime: new Date(2027, 0, 12, 9).toISOString() },{ ...TIMED, id: 'hidden', title: 'Example hidden appointment', startTime: new Date(2027, 0, 12, 12).toISOString(), endTime: new Date(2027, 0, 12, 13).toISOString() },- ] });+ ]));});it('opens overflow, reloads details, returns to the day, and restores month/day history', async () => {@@ -458,7 +461,7 @@ describe('MonthView overflow navigation', () => {api.getCalendarEvents.mockReturnValue(new Promise(resolve => { finish = resolve; }));render(<MemoryRouter initialEntries={['/calendar/month?month=2027-01&day=2027-01-12&event=acct-1:hidden']}><MonthView accounts={ACCOUNTS} /></MemoryRouter>);expect(screen.queryByRole('dialog')).not.toBeInTheDocument();- await act(async () => finish({ events: [{ ...TIMED, id: 'hidden', title: 'Example hidden appointment', startTime: new Date(2027, 0, 12, 12).toISOString(), endTime: new Date(2027, 0, 12, 13).toISOString() }] }));+ await act(async () => finish(calendarPage([{ ...TIMED, id: 'hidden', title: 'Example hidden appointment', startTime: new Date(2027, 0, 12, 12).toISOString(), endTime: new Date(2027, 0, 12, 13).toISOString() }])));expect(screen.getByRole('dialog', { name: 'Example hidden appointment' })).toBeInTheDocument();fireEvent.click(screen.getByRole('button', { name: 'Close', exact: true }));expect(screen.getByRole('button', { name: 'Close day events' })).toBeInTheDocument();@@ -472,7 +475,7 @@ describe('MonthView overflow navigation', () => {});it('falls back from an invalid month and keeps a short day directly actionable', async () => {- api.getCalendarEvents.mockResolvedValue({ events: [ALL_DAY, TIMED] });+ api.getCalendarEvents.mockResolvedValue(calendarPage([ALL_DAY, TIMED]));render(<MemoryRouter initialEntries={['/calendar/month?month=2027-99']}><MonthView accounts={ACCOUNTS} /></MemoryRouter>);await act(async () => {});expect(screen.queryByRole('button', { name: /View all/ })).not.toBeInTheDocument();@@ -480,3 +483,113 @@ describe('MonthView overflow navigation', () => {expect(screen.getByRole('dialog', { name: 'Quarter Close' })).toBeInTheDocument();});});++// These regressions exercise the rendered grids rather than duplicating the+// collection hook's unit tests: a loaded row must become selectable in each UI.+describe('Calendar window completeness', () => {+ beforeEach(() => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date(2026, 8, 23, 12));+ });++ const exampleEvent = (id, title = id, date = new Date(2026, 8, 23)) => {+ const end = new Date(date);+ end.setDate(end.getDate() + 1);+ return { ...ALL_DAY, id, title, startTime: date.toISOString(), endTime: end.toISOString() };+ };+ const firstPage = () => Array.from({ length: 200 }, (_, i) => exampleEvent(`example-${i}`));+ const mount = async View => renderView(<View accounts={ACCOUNTS} />);+ const openDay = () => fireEvent.click(screen.getByRole('button', { name: /View all .* events/ }));++ it.each([['Day', DayView], ['Week', WeekView], ['Month', MonthView]])(+ '%s loads the 201st event with capped requests and opens its details', async (name, View) => {+ const rows = [...firstPage(), exampleEvent('last', 'Example last event')];+ api.getCalendarEvents.mockImplementation(({ offset }) => Promise.resolve({ events: rows.slice(offset, offset + 200), total: rows.length }));+ await mount(View);+ expect(api.getCalendarEvents.mock.calls.map(([params]) => [params.limit, params.offset])).toEqual([[200, 0], [200, 200]]);+ expect(screen.queryByText(/Empty times may still be busy/)).not.toBeInTheDocument();+ if (name === 'Month') {+ openDay();+ expect(within(screen.getByRole('dialog')).getByText('201 events')).toBeInTheDocument();+ }+ fireEvent.click(screen.getByRole('button', { name: /Example last event/ }));+ expect(screen.getByRole('dialog', { name: 'Example last event' })).toBeInTheDocument();+ }+ );++ it('preserves partial Month events, retries the failed offset and deduplicates within each account', async () => {+ const first = firstPage();+ let finishRetry;+ api.getCalendarEvents+ .mockResolvedValueOnce({ events: first, total: 203 })+ .mockRejectedValueOnce(new Error('Example page failure'))+ .mockImplementationOnce(() => new Promise(resolve => { finishRetry = resolve; }));+ await mount(MonthView);+ expect(screen.getByRole('alert')).toHaveTextContent(/incomplete.*empty times may still be busy/);+ expect(api.getCalendarEvents).toHaveBeenCalledTimes(2);+ openDay();+ let drawer = screen.getByRole('dialog');+ expect(within(drawer).getByText('200 events loaded')).toBeInTheDocument();+ expect(within(drawer).getByRole('button', { name: /example-199$/ })).toBeInTheDocument();+ fireEvent.click(within(drawer).getByRole('button', { name: 'Retry' }));+ expect(within(drawer).getByRole('button', { name: /example-199$/ })).toBeInTheDocument();+ expect(within(drawer).getByRole('status')).toHaveTextContent(/Loading calendar events/);+ await act(async () => finishRetry({ events: [+ first[199], // duplicate provider row must not become another event+ { ...first[0], accountId: 'acct-2', title: 'Example other account' },+ exampleEvent('last', 'Example recovered event'),+ ], total: 203 }));+ drawer = screen.getByRole('dialog');+ expect(within(drawer).getByText('202 events')).toBeInTheDocument();+ expect(within(drawer).getAllByRole('button', { name: /example-199$/ })).toHaveLength(1);+ expect(within(drawer).getByRole('button', { name: /Example other account$/ })).toBeInTheDocument();+ expect(within(drawer).getByRole('button', { name: /Example recovered event$/ })).toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expect(api.getCalendarEvents.mock.calls.map(([params]) => params.offset)).toEqual([0, 200, 200]);+ });++ it.each([['day', DayView], ['week', WeekView], ['month', MonthView]])(+ 'discards a pending page after rapid %s navigation', async (name, View) => {+ let finishOld;+ api.getCalendarEvents+ .mockResolvedValueOnce({ events: firstPage(), total: 201 })+ .mockImplementationOnce(() => new Promise(resolve => { finishOld = resolve; }))+ .mockImplementation(({ startDate }) => Promise.resolve(calendarPage([exampleEvent('current', 'Example current window', new Date(startDate))])));+ await mount(View);+ const oldSignal = api.getCalendarEvents.mock.calls[1][1].signal;+ fireEvent.click(screen.getByRole('button', { name: `Next ${name}` }));+ fireEvent.click(screen.getByRole('button', { name: `Next ${name}` }));+ await act(async () => {});+ expect(oldSignal.aborted).toBe(true);+ expect(screen.getByRole('button', { name: /Example current window/ })).toBeInTheDocument();+ await act(async () => finishOld({ events: [exampleEvent('obsolete', 'Example obsolete page')], total: 201 }));+ expect(screen.queryByRole('button', { name: /Example obsolete page/ })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /example-0$/ })).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Example current window/ })).toBeInTheDocument();+ }+ );++ it('resets the same window on sync and ignores its obsolete later page', async () => {+ let finishOld;+ api.getCalendarEvents+ .mockResolvedValueOnce({ events: firstPage(), total: 201 })+ .mockImplementationOnce(() => new Promise(resolve => { finishOld = resolve; }))+ .mockResolvedValueOnce(calendarPage([exampleEvent('synced', 'Example synced event')]));+ await mount(MonthView);+ const syncHandler = socketMock.on.mock.calls.find(([event]) => event === 'calendar:sync:completed')[1];+ await act(async () => syncHandler());+ await act(async () => finishOld({ events: [exampleEvent('obsolete', 'Example obsolete page')], total: 201 }));+ expect(screen.getByRole('button', { name: /Example synced event/ })).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /Example obsolete page/ })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /View all/ })).not.toBeInTheDocument();+ expect(api.getCalendarEvents.mock.calls.map(([params]) => params.offset)).toEqual([0, 200, 0]);+ });++ it('shows Retry for an empty page before the advertised total instead of claiming completion or looping', async () => {+ api.getCalendarEvents.mockResolvedValue({ events: [], total: 201 });+ await mount(DayView);+ expect(screen.getByRole('alert')).toHaveTextContent(/incomplete/);+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();+ expect(api.getCalendarEvents).toHaveBeenCalledTimes(1);+ });+});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 92d986591e..2c5a3dc8f6 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -290,3 +290,5 @@ grep -i "what you want to do" client/src/hooks/README.md| `useModelLifecycle` | Targeted 3D model lifecycle reads, cancellation and bounded transient recovery. | Image-to-3D and procedural model views. || `useMusicVideoProductionReview` | Server-authoritative art/storyboard/proof approvals and SSE proof rendering, with stale-readiness suppression. | Music Video production review. |++| `useCalendarWindowEvents` | `useCalendarWindowEvents(startDate, endDate)` — sequential 200-event offset pages for a complete calendar window, account/event deduplication, retry and date/sync supersession. | Day/Week/Month grids; pair with CalendarWindowStatus to disclose incomplete availability. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 03dd7e22fd..358e5784be 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -271,3 +271,5 @@ export { default as useGraphNodeDetail } from './useGraphNodeDetail.js';export * from './useModelLifecycle.js';export { default as useMusicVideoProductionReview } from './useMusicVideoProductionReview.js';++export * from './useCalendarWindowEvents.js';diff --git a/client/src/hooks/useCalendarWindowEvents.js b/client/src/hooks/useCalendarWindowEvents.jsnew file mode 100644index 0000000000..f996971fef--- /dev/null+++ b/client/src/hooks/useCalendarWindowEvents.js@@ -0,0 +1,45 @@+import { useCallback, useEffect } from 'react';+import { getCalendarEvents } from '../services/api';+import socket from '../services/socket';+import { usePagedCollection } from './usePagedCollection';++const PAGE_SIZE = 200;++// Offset counts server rows, including duplicates; collection identity includes+// the account because distinct calendars may use the same provider event id.+export function useCalendarWindowEvents(startDate, endDate) {+ const fetchPage = useCallback(async ({ cursor, signal }) => {+ const offset = cursor ?? 0;+ const data = await getCalendarEvents({ startDate, endDate, limit: PAGE_SIZE, offset }, { signal, silent: true });+ if (!Array.isArray(data?.events) || !Number.isSafeInteger(data.total) || data.total < 0+ || data.events.length > PAGE_SIZE || (data.events.length === 0 && offset < data.total)) {+ throw new Error('Calendar returned an incomplete event page');+ }+ const nextOffset = offset + data.events.length;+ return {+ items: data.events.map(event => ({ id: JSON.stringify([event.accountId, event.id]), event })),+ total: data.total,+ nextCursor: nextOffset < data.total ? nextOffset : null,+ };+ }, [startDate, endDate]);+ const { items, loaded, loading, error, hasMore, loadMore, reload } = usePagedCollection(fetchPage);++ // A grid needs its whole date window before empty cells imply availability.+ // Stop on failure; loadMore retries the same cursor without losing prior rows.+ useEffect(() => {+ if (loaded && hasMore && !loading && !error) loadMore();+ }, [loaded, hasMore, loading, error, loadMore]);++ useEffect(() => {+ socket.on('calendar:sync:completed', reload);+ return () => socket.off('calendar:sync:completed', reload);+ }, [reload]);++ return {+ events: items.map(item => item.event),+ loading: loading || (!loaded && !error),+ error,+ complete: loaded && !hasMore && !error,+ retry: loadMore,+ };+}diff --git a/client/src/services/apiCalendar.js b/client/src/services/apiCalendar.jsindex 84ee3371ff..0a1e82145c 100644--- a/client/src/services/apiCalendar.js+++ b/client/src/services/apiCalendar.js@@ -6,9 +6,9 @@ export const createCalendarAccount = (data, options = {}) => request('/calendar/export const updateCalendarAccount = (id, data, options = {}) => request(`/calendar/accounts/${id}`, { method: 'PUT', body: JSON.stringify(data), ...options });export const deleteCalendarAccount = (id) => request(`/calendar/accounts/${id}`, { method: 'DELETE' });export const syncCalendarAccount = (accountId, options = {}) => request(`/calendar/sync/${accountId}`, { method: 'POST', ...options });-export const getCalendarEvents = (params = {}) => {+export const getCalendarEvents = (params = {}, options = {}) => {const str = new URLSearchParams(Object.entries(params).filter(([, v]) => v != null)).toString();- return request(`/calendar/events${str ? `?${str}` : ''}`);+ return request(`/calendar/events${str ? `?${str}` : ''}`, options);};export const getCalendarAgenda = (options = {}) => request('/calendar/agenda', options);export const getCalendarTokenStatus = () => request('/calendar/debug/token-status');