Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

36.5 KB
Raw Blame
import React, { useState, useEffect, useCallback, useMemo, useRef, useLayoutEffect } from 'react';
import { useI18n, interpolate } from '../i18n';
import { Header, PlaceBottomBar } from './components/Header';
import { TimelineGift, useTimelineGiftDismissal } from './components/TimelineGift';
import { Feed, type FeedEmptyHint } from './components/Feed';
import { CategoryFilter } from './components/CategoryFilter';
import { ProjectPicker } from './components/ProjectPicker';
import { ErrorBoundary } from './components/ErrorBoundary';
import { SearchIcon } from './components/icons';
import { ViewTabs } from './components/ViewTabs';
import { SessionList } from './components/SessionList';
import { SessionDetailPage } from './components/SessionDetailPage';
import { SettingsPage } from './components/ContextSettingsModal';
import { ContextPreviewPage } from './components/ContextPreviewPage';
import { LogsPage } from './components/LogsPage';
import { WelcomeCard, getStoredWelcomeDismissed, setStoredWelcomeDismissed } from './components/WelcomeCard';
import { useSSE, type MemoryChange } from './hooks/useSSE';
import { useSettings } from './hooks/useSettings';
import { useSettingsDraft } from './hooks/useSettingsDraft';
import { PageRejectedError, usePagination } from './hooks/usePagination';
import { useSessionCatalog } from './hooks/useSessionCatalog';
import { useTheme } from './hooks/useTheme';
import { useAppearance } from './hooks/useAppearance';
import { useFeedDeletes } from './hooks/useFeedItemDelete';
import { Observation, Summary, UserPrompt, FeedItemType, type FeedItem } from './types';
import { buildFeedItems, mergeAndDeduplicateByProject } from './utils/data';
import { categoryOf, countByCategory, type Category } from './utils/category';
import { matchesSearch } from './utils/feed-display';
import { formatCount } from './utils/formatters';
import { removeLoadedRow } from './utils/feed-deletion';
import {
  catalogEntryRef,
  deleteSession,
  removeSessionRows,
  rowInProject,
  sameSession,
  sessionKey,
  sessionRefOf,
  type SessionRef,
  type SessionScopedRow,
} from './utils/sessions';
import { parseViewRoute, sessionHash, sessionsHash, tabOfRoute, timelineHash, type ViewRoute } from './utils/memory-route';

/** What the feed shows: the project timeline, or one session's rows. */
interface FeedScope {
  project: string;
  session: SessionRef | null;
}

function feedScopeKey(scope: FeedScope): string {
  return `${scope.project}|${scope.session ? sessionKey(scope.session) : ''}`;
}

/** The feed a page shows, or null for a page with no feed (the Sessions list, settings, logs), which keeps the last one. */
function scopeForRoute(route: ViewRoute, project: string): FeedScope | null {
  if (route.view === 'session') return { project: '', session: route.session };
  if (route.view === 'timeline') return { project, session: null };
  return null;
}

function navigate(hash: string): void {
  window.location.hash = hash;
}

export function App() {
  const { t } = useI18n();
  const [currentFilter, setCurrentFilter] = useState('');
  const [welcomeDismissed, setWelcomeDismissed] = useState<boolean>(getStoredWelcomeDismissed);
  const [paginatedObservations, setPaginatedObservations] = useState<Observation[]>([]);
  const [paginatedSummaries, setPaginatedSummaries] = useState<Summary[]>([]);
  const [paginatedPrompts, setPaginatedPrompts] = useState<UserPrompt[]>([]);
  const [feedLoadError, setFeedLoadError] = useState<string | null>(null);
  // The last feed error the server gave as a refusal (4xx): retrying repeats it.
  const rejectedFeedErrorRef = useRef<string | null>(null);
  // A failed "load older" stays on screen until a load succeeds or the reader
  // retries; a later successful refresh of the newest rows does not answer it (B2).
  const loadMoreErrorRef = useRef<string | null>(null);
  const [timelineKinds, setTimelineKinds] = useState<Set<Category>>(() => new Set());
  // "Find in loaded memories" opens with the words of `#/?find=<words>` (My Work's Find work links here).
  const [timelineQuery, setTimelineQuery] = useState(() => {
    const opened = parseViewRoute(window.location.hash);
    return opened.view === 'timeline' ? opened.find ?? '' : '';
  });
  const timelineSearchRef = useRef<HTMLInputElement>(null);
  // "Show welcome card" in the bar's menu brought the panel back: it takes focus, so it is seen wherever the page was.
  const [welcomeFocus, setWelcomeFocus] = useState(false);
  const timelineGift = useTimelineGiftDismissal();
  const [showLatestRefresh, setShowLatestRefresh] = useState(false);
  const [feedRefreshNotice, setFeedRefreshNotice] = useState<string | null>(null);
  const handledDeletionsRef = useRef(new Set<string>());
  // A page started before a session was deleted must not restore its old rows,
  // even if a live row has since re-created that same session identity.
  const deletionVersionRef = useRef(0);
  const sessionDeletionVersionsRef = useRef(new Map<string, number>());
  const itemDeletionVersionsRef = useRef(new Map<string, number>());
  const contentGenerationRef = useRef(0);
  const initialReadStartedRef = useRef(false);
  const loadedVisitRef = useRef(-1);
  const resyncTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const resyncBusyRef = useRef(false);
  const resyncPausedRef = useRef(false);
  const resyncInterruptionsRef = useRef(0);
  const pendingResyncRef = useRef(new Set<FeedItemType>());
  const activeResyncKindsRef = useRef<FeedItemType[]>([]);
  const failedResyncRef = useRef(new Set<FeedItemType>());
  const refreshLatestRef = useRef(false);
  const runResyncRef = useRef<() => Promise<void>>(async () => {});
  const disposedRef = useRef(false);
  const [connectionWaitExpired, setConnectionWaitExpired] = useState(false);
  const [route, setRoute] = useState<ViewRoute>(() => parseViewRoute(window.location.hash));
  // The Sessions list keeps the last timeline/session scope, so switching back
  // does not reload pages that are still correct.
  const [feedScope, setFeedScope] = useState<FeedScope>(
    () => scopeForRoute(route, currentFilter) ?? { project: currentFilter, session: null }
  );
  // The feed follows the route in the same render, never an effect later: a session page's first frame must not draw
  // the previous scope's rows (they would vanish when its own load starts). React re-renders before committing.
  const routeScope = scopeForRoute(route, currentFilter);
  if (routeScope && feedScopeKey(routeScope) !== feedScopeKey(feedScope)) {
    setFeedScope(routeScope);
    setPaginatedObservations([]);
    setPaginatedSummaries([]);
    setPaginatedPrompts([]);
  }
  const scopeKey = feedScopeKey(feedScope);
  const activeFeedScopeRef = useRef({ key: scopeKey, version: 0 });
  const feedVisit = activeFeedScopeRef.current.key === scopeKey
    ? activeFeedScopeRef.current
    : { key: scopeKey, version: activeFeedScopeRef.current.version + 1 };
  // Only a committed scope retires the previous visit's rows and errors.
  useLayoutEffect(() => { activeFeedScopeRef.current = feedVisit; }, [feedVisit]);
  const feedVersion = feedVisit.version;

  const catalog = useSessionCatalog();
  const { observations, summaries, prompts, projects, isProcessing, isConnected, syncStatus, removeLiveItem, removeLiveSession,
    captureLiveVersion, clearLiveThrough, refreshProjects } = useSSE({
    onItemDeleted: removeDeletedItem,
    onSessionDeleted: removeDeletedSession,
    onLiveItem: item => {
      handledDeletionsRef.current.delete(`session:${sessionKey(item.session)}`);
      catalog.touch(item);
    },
    onDataChanged: queueDataRefresh,
  });
  const {
    settings, saveSettings, isSaving, saveStatus,
    isLoaded: settingsLoaded, loadError: settingsLoadError, reload: reloadSettings,
  } = useSettings();
  // The settings draft and its save state, above the settings and preview pages so the trip between them keeps both.
  // Declared before the hashchange listener below: its own (capturing) listener asks before the settings pages are left.
  const settingsDraft = useSettingsDraft({ settings, isSaving, saveStatus }, route);
  const { preference, setThemePreference } = useTheme();
  // The reading palette, face and size (src/ui/theme-appearance.ts): applied here so every page and the error card share it.
  useAppearance();
  const pagination = usePagination(feedScope.project, feedScope.session);
  // Held here, above the views, so a delete's refusal is still on its card after the reader leaves and comes back.
  const feedDeletes = useFeedDeletes(removeDeletedItem);

  useEffect(() => {
    disposedRef.current = false;
    const timeout = setTimeout(() => setConnectionWaitExpired(true), 250);
    return () => {
      disposedRef.current = true;
      clearTimeout(timeout);
      if (resyncTimerRef.current) clearTimeout(resyncTimerRef.current);
    };
  }, []);

  function scheduleDataRefresh(): void {
    if (disposedRef.current || resyncPausedRef.current || resyncBusyRef.current || resyncTimerRef.current) return;
    resyncTimerRef.current = setTimeout(() => {
      resyncTimerRef.current = null;
      void runResyncRef.current();
    }, 250);
  }

  function queueDataRefresh(change: MemoryChange): void {
    // The initial baseline starts after stream admission. If HTTP already
    // started via the outage fallback, this first connection must catch up.
    if (!initialReadStartedRef.current) return;
    if (resyncPausedRef.current) return;
    if (change.kinds && !change.kinds.some(kind => ['observation', 'summary', 'prompt', 'mutation'].includes(kind))) return;
    // These three lists share one displayed visit/generation. Cancelling an
    // older read must also refresh its siblings, even if only one kind changed.
    const kinds = ['observation', 'summary', 'prompt'] as const;
    contentGenerationRef.current++;
    for (const kind of kinds) pendingResyncRef.current.add(kind);
    for (const kind of activeResyncKindsRef.current) pendingResyncRef.current.add(kind);
    // Scope hints are advisory: aliases and linked-session repairs can affect
    // a filtered view even when its spelling is absent from the event.
    pagination.observations.invalidate();
    pagination.summaries.invalidate();
    pagination.prompts.invalidate();
    catalog.invalidate();
    if (resyncBusyRef.current && ++resyncInterruptionsRef.current >= 3) {
      // A live database can keep invalidating every in-flight read. Stop the
      // automatic loop after a bounded number of retries, keeping shown rows.
      resyncPausedRef.current = true;
      pendingResyncRef.current.clear();
      for (const kind of kinds) failedResyncRef.current.add(kind);
      setFeedLoadError('Memories are changing faster than this view can refresh. Retry, or refresh the latest memories.');
      setShowLatestRefresh(true);
      return;
    }
    scheduleDataRefresh();
  }

  async function runDataRefresh(): Promise<void> {
    if (disposedRef.current || resyncBusyRef.current || !pendingResyncRef.current.size) return;
    resyncBusyRef.current = true;
    const kinds = [...pendingResyncRef.current];
    activeResyncKindsRef.current = kinds;
    pendingResyncRef.current.clear();
    const generation = contentGenerationRef.current;
    const visit = activeFeedScopeRef.current.version;
    const liveVersion = captureLiveVersion();
    const latest = refreshLatestRef.current;
    refreshLatestRef.current = false;
    const deletedBeforeRead = deletionVersionRef.current;
    const current = () => !disposedRef.current && contentGenerationRef.current === generation && activeFeedScopeRef.current.version === visit;
    const errors: string[] = [];
    const retain = <T extends SessionScopedRow & { id: number }>(rows: T[], kind: FeedItemType) => rows.filter(row => {
      const key = `${kind}:${row.id}`;
      if ((itemDeletionVersionsRef.current.get(key) ?? 0) > deletedBeforeRead) return false;
      const session = sessionRefOf(row);
      if (session && (sessionDeletionVersionsRef.current.get(sessionKey(session)) ?? 0) > deletedBeforeRead) return false;
      // This request began after older deletes: its returned rows can include
      // a valid recreation, so old tombstones must not hide it forever.
      handledDeletionsRef.current.delete(key);
      if (session) handledDeletionsRef.current.delete(`session:${sessionKey(session)}`);
      return true;
    });
    try {
      await Promise.all(kinds.map(async kind => {
        try {
          if (kind === 'observation') {
            const rows = await (latest ? pagination.observations.refreshLatest() : pagination.observations.refresh());
            if (!current()) return;
            const kept = retain(rows, kind); pagination.observations.noteRemoved(rows.length - kept.length);
            setPaginatedObservations(kept);
          } else if (kind === 'summary') {
            const rows = await (latest ? pagination.summaries.refreshLatest() : pagination.summaries.refresh());
            if (!current()) return;
            const kept = retain(rows, kind); pagination.summaries.noteRemoved(rows.length - kept.length);
            setPaginatedSummaries(kept);
          } else {
            const rows = await (latest ? pagination.prompts.refreshLatest() : pagination.prompts.refresh());
            if (!current()) return;
            const kept = retain(rows, kind); pagination.prompts.noteRemoved(rows.length - kept.length);
            setPaginatedPrompts(kept);
          }
          clearLiveThrough(kind, liveVersion);
          failedResyncRef.current.delete(kind);
          for (const [key, version] of itemDeletionVersionsRef.current) {
            if (key.startsWith(`${kind}:`) && version <= deletedBeforeRead) {
              itemDeletionVersionsRef.current.delete(key); handledDeletionsRef.current.delete(key);
            }
          }
        } catch (error) {
          if (!current()) return;
          failedResyncRef.current.add(kind);
          errors.push(error instanceof Error ? error.message : 'Could not refresh saved memories.');
        }
      }));
      if (current()) {
        setFeedLoadError(previous => errors.length ? `Could not refresh saved memories. ${errors.join(' ')}` : failedResyncRef.current.size ? previous : loadMoreErrorRef.current);
        setShowLatestRefresh(failedResyncRef.current.size > 0);
        if (latest && !errors.length) setFeedRefreshNotice('Showing the newest memories. Load more to browse older history.');
        resyncInterruptionsRef.current = 0;
        void refreshProjects();
        void catalog.refreshLoaded(route.view === 'session' ? '' : currentFilter);
      }
    } finally {
      resyncBusyRef.current = false;
      activeResyncKindsRef.current = [];
      if (pendingResyncRef.current.size) scheduleDataRefresh();
    }
  }
  useLayoutEffect(() => { runResyncRef.current = runDataRefresh; });

  useEffect(() => {
    const onHashChange = () => setRoute(parseViewRoute(window.location.hash));
    window.addEventListener('hashchange', onHashChange);
    return () => window.removeEventListener('hashchange', onHashChange);
  }, []);

  // A link to `#/?find=<words>` (or Back to one) puts its words in the find box; `#/` alone keeps what was typed.
  useEffect(() => {
    if (route.view === 'timeline' && route.find !== null) setTimelineQuery(route.find);
  }, [route]);

  // The address says what the find box holds: each change replaces the timeline's address, never adding a history
  // entry per key, so Back still leaves the timeline in one step. replaceState fires no hashchange, so `route` keeps
  // the words it was opened with; only a real navigation changes it.
  useEffect(() => {
    if (route.view !== 'timeline') return;
    const shown = parseViewRoute(window.location.hash);
    const words = timelineQuery.trim();
    if (shown.view === 'timeline' && (shown.find ?? '') === words) return;
    window.history.replaceState(window.history.state, '', timelineHash(words));
  }, [route, timelineQuery]);

  const refreshCatalog = catalog.refresh;
  useEffect(() => {
    if (route.view === 'sessions') void refreshCatalog(currentFilter);
  }, [route.view, currentFilter, refreshCatalog]);

  const matchesScope = useCallback((item: SessionScopedRow & { project: string; merged_into_project?: string | null }) => {
    if (feedScope.session) return sameSession(sessionRefOf(item), feedScope.session);
    return !feedScope.project || rowInProject(item, feedScope.project);
  }, [feedScope]);

  useEffect(() => {
    if (currentFilter && !projects.includes(currentFilter)) {
      setCurrentFilter('');
    }
  }, [projects, currentFilter]);

  const allObservations = useMemo(() => {
    const live = observations.filter(matchesScope);
    const paginated = paginatedObservations.filter(matchesScope);
    return mergeAndDeduplicateByProject(live, paginated);
  }, [observations, paginatedObservations, matchesScope]);

  const allSummaries = useMemo(() => {
    const live = summaries.filter(matchesScope);
    const paginated = paginatedSummaries.filter(matchesScope);
    return mergeAndDeduplicateByProject(live, paginated);
  }, [summaries, paginatedSummaries, matchesScope]);

  const allPrompts = useMemo(() => {
    const live = prompts.filter(matchesScope);
    const paginated = paginatedPrompts.filter(matchesScope);
    return mergeAndDeduplicateByProject(live, paginated);
  }, [prompts, paginatedPrompts, matchesScope]);

  const feedItems = useMemo(
    () => buildFeedItems(allObservations, allSummaries, allPrompts),
    [allObservations, allSummaries, allPrompts]
  );

  const timelineCounts = useMemo(() => countByCategory(feedItems), [feedItems]);
  const timelineFiltered = timelineKinds.size > 0 || timelineQuery.trim() !== '';
  const plan = settings.CLAUDE_MEM_PRO_PLAN?.trim() || 'none';
  const showTimelineGift = route.view === 'timeline' && !currentFilter && !timelineFiltered
    && !timelineGift.dismissed && settingsLoaded && plan === 'none'
    && !settings.CLAUDE_MEM_TEAMBRAIN_URL?.trim() && !settings.CLAUDE_MEM_CLOUD_SYNC_HUB_URL?.trim()
    && syncStatus.state === 'unconfigured';
  // The kinds and the search. The feed applies them after folding prompt repeats over the whole timeline (G2), so
  // "<n> times in a row" stays true under a search; the counts below are the memories that match.
  const timelineMatches = useMemo(() => timelineFiltered
    ? (item: FeedItem) => (timelineKinds.size === 0 || timelineKinds.has(categoryOf(item))) && matchesSearch(item, timelineQuery)
    : undefined, [timelineKinds, timelineQuery, timelineFiltered]);
  const timelineItems = useMemo(() => timelineMatches ? feedItems.filter(timelineMatches) : feedItems, [feedItems, timelineMatches]);
  const toggleTimelineKind = useCallback((kind: Category) => {
    setTimelineKinds(previous => {
      const next = new Set(previous);
      if (next.has(kind)) next.delete(kind); else next.add(kind);
      return next;
    });
  }, []);
  const clearTimelineFilters = useCallback(() => { setTimelineKinds(new Set()); setTimelineQuery(''); }, []);

  const visibleSessions = useMemo(() => {
    return catalog.sessions
      .filter(session => !currentFilter || rowInProject(session, currentFilter))
      .sort((a, b) => b.started_at_epoch - a.started_at_epoch);
  }, [catalog.sessions, currentFilter]);

  const handleLoadMore = useCallback(async () => {
    // A second visit to the same scope has a new owner, even if its key matches.
    if (activeFeedScopeRef.current.version !== feedVersion) return;
    if (!isConnected && !connectionWaitExpired) return;
    if (failedResyncRef.current.size) {
      resyncPausedRef.current = false;
      resyncInterruptionsRef.current = 0;
      queueDataRefresh({ kinds: [...failedResyncRef.current] });
      return;
    }
    initialReadStartedRef.current = true;
    const requestFeedVersion = feedVersion;
    const contentGeneration = contentGenerationRef.current;
    const deletionVersion = deletionVersionRef.current;
    // Rows from a page that started before the view changed or memory changed are stale.
    const isCurrentVisit = () => activeFeedScopeRef.current.version === requestFeedVersion
      && contentGenerationRef.current === contentGeneration;
    loadMoreErrorRef.current = null;
    setFeedLoadError(null);
    const retainPageRows = <T extends SessionScopedRow & { id: number }>(rows: T[], itemType: FeedItemType): T[] => {
      return rows.filter(row => {
        if (handledDeletionsRef.current.has(`${itemType}:${row.id}`)) return false;
        const session = sessionRefOf(row);
        if (!session) return true;
        const key = sessionKey(session);
        if ((sessionDeletionVersionsRef.current.get(key) ?? 0) > deletionVersion) return false;
        // A server page started after deletion is authoritative, including a
        // recreation whose live SSE event this tab missed. Keep history for
        // older pending pages while rearming the identity for future deletes.
        handledDeletionsRef.current.delete(`session:${key}`);
        return true;
      });
    };
    try {
      // Each cursor advances independently; commit its rows before a sibling
      // request can reject the group, or successful pages would be skipped.
      await Promise.all([
        pagination.observations.loadMore().then(rows => {
          if (!isCurrentVisit() || !rows.length) return;
          const retained = retainPageRows(rows, 'observation');
          pagination.observations.noteRemoved(rows.length - retained.length);
          setPaginatedObservations(prev => [...prev, ...retained]);
        }),
        pagination.summaries.loadMore().then(rows => {
          if (!isCurrentVisit() || !rows.length) return;
          const retained = retainPageRows(rows, 'summary');
          pagination.summaries.noteRemoved(rows.length - retained.length);
          setPaginatedSummaries(prev => [...prev, ...retained]);
        }),
        pagination.prompts.loadMore().then(rows => {
          if (!isCurrentVisit() || !rows.length) return;
          const retained = retainPageRows(rows, 'prompt');
          pagination.prompts.noteRemoved(rows.length - retained.length);
          setPaginatedPrompts(prev => [...prev, ...retained]);
        })
      ]);
    } catch (error) {
      console.error('Failed to load more data:', error);
      // A page in flight when memory changes is not lost: queueDataRefresh
      // invalidates it (it resolves empty, so it never lands here) and, once the
      // refresh is in, the end of the list asks for it again. A failure that does
      // land here belongs to the current visit and shows in the list with Retry;
      // loadMoreErrorRef keeps it there through later refreshes (B2).
      if (isCurrentVisit()) {
        const message = error instanceof Error ? error.message : 'Failed to load more data';
        if (error instanceof PageRejectedError) rejectedFeedErrorRef.current = message;
        loadMoreErrorRef.current = message;
        setFeedLoadError(message);
      }
    }
  }, [feedVersion, isConnected, connectionWaitExpired, pagination.observations, pagination.summaries, pagination.prompts]);

  // One removal path for a deleted row, whether this tab deleted it or another
  // tab did (item_deleted SSE, which also reaches this tab): drop it from the
  // live and loaded lists once, and move a loaded page's offset back by one so
  // the next page does not skip a row.
  const loadedRowsRef = useRef({ observation: paginatedObservations, summary: paginatedSummaries, prompt: paginatedPrompts });
  loadedRowsRef.current = { observation: paginatedObservations, summary: paginatedSummaries, prompt: paginatedPrompts };

  function removeDeletedItem(itemType: FeedItemType, id: number): void {
    const key = `${itemType}:${id}`;
    if (handledDeletionsRef.current.has(key)) return;
    handledDeletionsRef.current.add(key);
    itemDeletionVersionsRef.current.set(key, ++deletionVersionRef.current);

    const liveRows = { observation: observations, summary: summaries, prompt: prompts };
    const deletedRow = liveRows[itemType].find(row => row.id === id)
      ?? loadedRowsRef.current[itemType].find(row => row.id === id);
    const deletedSession = deletedRow ? sessionRefOf(deletedRow) : null;
    if (deletedSession) catalog.noteItemRemoved(deletedSession);

    removeLiveItem(itemType, id);
    if (itemType === 'observation') {
      if (removeLoadedRow(loadedRowsRef.current.observation, id).wasLoaded) pagination.observations.noteRemoved();
      setPaginatedObservations(prev => removeLoadedRow(prev, id).rows);
    } else if (itemType === 'summary') {
      if (removeLoadedRow(loadedRowsRef.current.summary, id).wasLoaded) pagination.summaries.noteRemoved();
      setPaginatedSummaries(prev => removeLoadedRow(prev, id).rows);
    } else {
      if (removeLoadedRow(loadedRowsRef.current.prompt, id).wasLoaded) pagination.prompts.noteRemoved();
      setPaginatedPrompts(prev => removeLoadedRow(prev, id).rows);
    }
  }

  // Same single path for a whole deleted session (this tab or session_deleted
  // SSE): drop it from the catalog and every list, rebase each loaded page's
  // offset by the rows it lost, and leave its detail view if it is open.
  function removeDeletedSession(session: SessionRef): void {
    const key = `session:${sessionKey(session)}`;
    if (handledDeletionsRef.current.has(key)) return;
    handledDeletionsRef.current.add(key);
    sessionDeletionVersionsRef.current.set(sessionKey(session), ++deletionVersionRef.current);

    catalog.remove(session);
    removeLiveSession(session);
    const loaded = loadedRowsRef.current;
    const lostObservations = removeSessionRows(loaded.observation, session).removedCount;
    const lostSummaries = removeSessionRows(loaded.summary, session).removedCount;
    const lostPrompts = removeSessionRows(loaded.prompt, session).removedCount;
    if (lostObservations > 0) pagination.observations.noteRemoved(lostObservations);
    if (lostSummaries > 0) pagination.summaries.noteRemoved(lostSummaries);
    if (lostPrompts > 0) pagination.prompts.noteRemoved(lostPrompts);
    setPaginatedObservations(prev => removeSessionRows(prev, session).rows);
    setPaginatedSummaries(prev => removeSessionRows(prev, session).rows);
    setPaginatedPrompts(prev => removeSessionRows(prev, session).rows);

    if (route.view === 'session' && sameSession(route.session, session)) {
      navigate(sessionsHash());
    }
  }

  /** Rejects with a user-facing reason; the row shows it. `signal` stops waiting for the worker. */
  async function handleDeleteSession(session: SessionRef, signal?: AbortSignal): Promise<void> {
    const key = sessionKey(session);
    const deletionVersion = sessionDeletionVersionsRef.current.get(key) ?? 0;
    await deleteSession(session, fetch, { signal });
    // The stream may have already delivered this delete, followed by a new
    // live row recreating the session. Its HTTP acknowledgment must not delete
    // that newer incarnation a second time.
    if ((sessionDeletionVersionsRef.current.get(key) ?? 0) === deletionVersion) {
      removeDeletedSession(session);
    }
  }

  useEffect(() => {
    if (!isConnected && !connectionWaitExpired) return;
    // Run once per committed visit, not again when an outage reconnects.
    if (initialReadStartedRef.current && loadedVisitRef.current === feedVersion) return;
    loadedVisitRef.current = feedVersion;
    contentGenerationRef.current++;
    pendingResyncRef.current.clear(); failedResyncRef.current.clear();
    refreshLatestRef.current = false;
    resyncPausedRef.current = false; resyncInterruptionsRef.current = 0;
    setShowLatestRefresh(false); setFeedRefreshNotice(null);
    if (resyncTimerRef.current) clearTimeout(resyncTimerRef.current);
    resyncTimerRef.current = null;
    setPaginatedObservations([]);
    setPaginatedSummaries([]);
    setPaginatedPrompts([]);
    handleLoadMore();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [feedScopeKey(feedScope), isConnected, connectionWaitExpired]);

  // A new scope's first frame, before its load starts, is loading too: the previous scope's "nothing more" must not
  // draw this page's empty state.
  const isLoading = (!initialReadStartedRef.current && !isConnected && !connectionWaitExpired)
    || (initialReadStartedRef.current && loadedVisitRef.current !== feedVersion)
    || pagination.observations.isLoading || pagination.summaries.isLoading || pagination.prompts.isLoading;
  const hasMore = pagination.observations.hasMore || pagination.summaries.hasMore || pagination.prompts.hasMore;
  const feedOffsetCapReachedAt = hasMore ? null : pagination.observations.offsetCapReachedAt
    ?? pagination.summaries.offsetCapReachedAt ?? pagination.prompts.offsetCapReachedAt;
  // Retry still helps when a sibling list has more, even if one list was refused.
  const feedCanRetry = hasMore || feedLoadError !== rejectedFeedErrorRef.current;
  const activeTab = tabOfRoute(route);
  // Below the heading and tabs, so its arrival never moves them.
  const notices = (showLatestRefresh || feedRefreshNotice) ? (
    <div className="memory-page-notices">
      {showLatestRefresh && <button type="button" className="mem-btn mem-btn--primary" onClick={() => {
        resyncPausedRef.current = false;
        resyncInterruptionsRef.current = 0;
        refreshLatestRef.current = true;
        queueDataRefresh({});
      }}>{t('Refresh latest memories')}</button>}
      {feedRefreshNotice && <p role="status">{t(feedRefreshNotice)}</p>}
    </div>
  ) : null;
  // The All projects picker: one project filter for the timeline and the Sessions list (Codex's toolbar).
  const projectPicker = <ProjectPicker projects={projects} value={currentFilter} onChange={setCurrentFilter} />;
  // A session's own page heads itself (breadcrumb, its real title, id and time span: SessionDetailPage).
  const tabs = (
    <>
      <header className="mem-pagehead">
        <h1 className="mem-title" tabIndex={-1}>{route.view === 'timeline' ? t('Memory timeline') : t('Sessions')}</h1>
        {route.view === 'sessions' && <p className="mem-leadtext">{t('Revisit one agent conversation and what it saved.')}</p>}
      </header>
      {activeTab && <ViewTabs active={activeTab} />}
      {notices}
    </>
  );
  const timelineHeader = (
    <>
      {tabs}
      {!welcomeDismissed && (
        <WelcomeCard focusOnShow={welcomeFocus} onFocused={() => setWelcomeFocus(false)} onDismiss={() => {
          setWelcomeDismissed(true);
          setWelcomeFocus(false);
          timelineSearchRef.current?.focus({ preventScroll: true });
        }} />
      )}
      {showTimelineGift && <TimelineGift onDismiss={() => {
        timelineGift.dismiss();
        timelineSearchRef.current?.focus({ preventScroll: true });
      }} />}
      <div className="mem-toolbar">
        <label className="mem-search">
          <SearchIcon size={18} />
          <span className="visually-hidden">{t('Find in loaded memories')}</span>
          <input
            ref={timelineSearchRef}
            type="search"
            value={timelineQuery}
            onChange={event => setTimelineQuery(event.target.value)}
            placeholder={t('Find in loaded memories')}
          />
        </label>
        {projectPicker}
        <CategoryFilter
          categoryCounts={timelineCounts}
          activeCategories={timelineKinds}
          onToggle={toggleTimelineKind}
          onClear={() => setTimelineKinds(new Set())}
          filteredCount={timelineItems.length}
          totalCount={feedItems.length}
          totalIsPartial={hasMore}
        />
      </div>
      {/* Under a search or a type: how many loaded memories match, and that older ones are not looked at yet. */}
      {timelineFiltered && (
        <p className="mem-meta mem-find-note" role="status">
          {interpolate(t('{count} of the {total} loaded memories match. Older memories are not searched until they load.'), {
            count: formatCount(timelineItems.length), total: formatCount(feedItems.length),
          })}
        </p>
      )}
    </>
  );
  const timelineEmptyHint: FeedEmptyHint | undefined = timelineFiltered
    ? { actions: [{ label: t('Clear filters'), onClick: clearTimelineFilters }] }
    : currentFilter
      ? { detail: interpolate(t('Project filter: {project}'), { project: currentFilter }), actions: [{ label: t('Show all projects'), onClick: () => setCurrentFilter('') }] }
      : undefined;

  let content: React.ReactNode;
  if (route.view === 'sessions') {
    content = (
      <SessionList
        header={tabs}
        projectPicker={projectPicker}
        sessions={visibleSessions}
        isLoading={catalog.isLoading}
        hasMore={catalog.hasMore}
        loadError={catalog.loadError}
        canRetry={!catalog.loadErrorIsFinal}
        offsetCapReachedAt={catalog.offsetCapReachedAt}
        projectFilter={currentFilter}
        onClearProjectFilter={() => setCurrentFilter('')}
        onOpen={session => navigate(sessionHash(session))}
        onDelete={handleDeleteSession}
        onLoadMore={catalog.loadMore}
        onRefreshLatest={catalog.refreshFailed ? () => { void catalog.refresh(currentFilter); } : undefined}
      />
    );
  } else if (route.view === 'session') {
    const catalogEntry = catalog.sessions.find(entry => sameSession(catalogEntryRef(entry), route.session));
    content = (
      <SessionDetailPage
        notices={notices}
        session={route.session}
        catalogEntry={catalogEntry}
        items={feedItems}
        isLoading={isLoading}
        hasMore={hasMore}
        loadError={feedLoadError ? t(feedLoadError) : null}
        canRetry={feedCanRetry}
        offsetCapReachedAt={feedOffsetCapReachedAt}
        onLoadMore={handleLoadMore}
        onDeleted={removeDeletedItem}
        deletes={feedDeletes}
        onBack={() => navigate(sessionsHash())}
      />
    );
  } else if (route.view === 'logs') {
    content = <LogsPage />;
  } else if (route.view === 'settings') {
    content = (
      <SettingsPage
        section={route.section}
        settings={settings}
        isLoaded={settingsLoaded}
        loadError={settingsLoadError}
        onRetryLoad={reloadSettings}
        onSave={saveSettings}
        isSaving={isSaving}
        saveStatus={saveStatus}
        draft={settingsDraft}
        onThemeChange={setThemePreference}
      />
    );
  } else if (route.view === 'context-preview') {
    content = (
      <ContextPreviewPage
        draft={settingsDraft}
        onShowInTimeline={project => {
          // A shortened preview's left-out observations, all of them: the timeline filtered to that project, with no
          // kind or search left from before to hide some. Run as the page is left (after asking, with unsaved changes).
          clearTimelineFilters();
          setCurrentFilter(project);
        }}
      />
    );
  } else {
    content = (
      <Feed
        header={timelineHeader}
        items={feedItems}
        matches={timelineMatches}
        onLoadMore={handleLoadMore}
        onDeleted={removeDeletedItem}
        deletes={feedDeletes}
        isLoading={isLoading}
        hasMore={hasMore}
        loadError={feedLoadError ? t(feedLoadError) : null}
        canRetry={feedCanRetry}
        offsetCapReachedAt={feedOffsetCapReachedAt}
        emptyHint={timelineEmptyHint}
        autoLoad={!timelineFiltered}
      />
    );
  }
  const contentKey = route.view === 'session' ? `session|${sessionKey(route.session)}` : route.view;
  // An in-app page change (a breadcrumb, a row, a tab, a "…" item) takes focus to the new page's heading when the old
  // focus went with the old page or stayed in the bar, so the next Tab starts in the page, not at the top of the
  // document. Not on the first page, and not when the new page put focus somewhere itself (the welcome panel).
  const shownPageRef = useRef(contentKey);
  useEffect(() => {
    if (shownPageRef.current === contentKey) return;
    shownPageRef.current = contentKey;
    const page = document.querySelector('main');
    const focused = document.activeElement;
    if (focused && focused !== document.body && page?.contains(focused)) return;
    page?.querySelector<HTMLElement>('h1[tabindex="-1"]')?.focus({ preventScroll: true });
  }, [contentKey]);

  return (
    <>
      <Header
        isProcessing={isProcessing}
        themePreference={preference}
        onThemeChange={setThemePreference}
        onNavigate={settingsDraft.requestLeave}
        onShowHelp={() => {
          const showWelcome = () => {
            setStoredWelcomeDismissed(false);
            setWelcomeDismissed(false);
            setWelcomeFocus(true);
          };
          // From another page it is a move to the timeline, asked first when unsaved settings would be lost: on Cancel
          // the saved flag and the focus stay as they were.
          if (route.view === 'timeline') showWelcome();
          else settingsDraft.requestLeave(timelineHash(), showWelcome);
        }}
        showProTrialLink={route.view !== 'timeline'}
        showTeamBrainLink={settingsLoaded && !settings.CLAUDE_MEM_TEAMBRAIN_URL?.trim()}
      />

      <ErrorBoundary resetKey={contentKey}>
        {content}
      </ErrorBoundary>

      <PlaceBottomBar />
    </>
  );
}