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

9.8 KB
Raw Blame
import React, { useState, useEffect, useMemo } from 'react';
import { interpolate, useI18n } from '../../i18n';
import { Feed } from './Feed';
import { CopyButton } from './CopyButton';
import { StampToggle } from './ShortTime';
import { BookOpenIcon, ChevronRightIcon, FileTextIcon, FolderIcon, MessageSquareIcon, SearchIcon, SquarePenIcon } from './icons';
import { FeedItem, SessionCatalogEntry, Summary } from '../types';
import type { DeletableItemType } from '../utils/feed-deletion';
import { matchesSearch } from '../utils/feed-display';
import { epochMs, formatCount, formatDate, formatShortDate, formatShortTime, localDayKey } from '../utils/formatters';
import {
  SESSION_NAME_SOURCE_WORDS, sessionKey, sessionName, sessionNameText, shortSessionId, type SessionNameSource, type SessionRef,
} from '../utils/sessions';
import { sessionsHash } from '../utils/memory-route';
import { isPlainClick } from '../utils/links';
import { useFeedDeletes } from '../hooks/useFeedItemDelete';

interface SessionDetailPageProps {
  /** Page notices ("Refresh latest memories"), under the session's heading. */
  notices?: React.ReactNode;
  session: SessionRef;
  /** The Sessions list's row for this session, when it was loaded: its name's fields, memory count and start. */
  catalogEntry?: SessionCatalogEntry | null;
  /** This session's rows, newest first (App owns loading and deletes). */
  items: FeedItem[];
  isLoading: boolean;
  hasMore: boolean;
  loadError?: string | null;
  canRetry?: boolean;
  offsetCapReachedAt?: number | null;
  onLoadMore: () => void;
  onDeleted: (itemType: DeletableItemType, id: number) => void;
  /** The rows' deletes, kept by the page above this one so a refusal outlives the view. */
  deletes?: ReturnType<typeof useFeedDeletes>;
  /** The breadcrumb's way back to the Sessions list (its address is sessionsHash(), so the browser's Back works too). */
  onBack: () => void;
}

type SummaryItem = Summary & { itemType: 'summary' };

/**
 * Past this many characters a name takes more than two lines of the 53px page heading (a line holds about 39 at the
 * 1064px column: measured on the owner's newest session page, 2026-11-29), so it shows at the 34px phone heading size
 * instead of filling the first screen. Summary requests often run to 200 characters.
 */
const LONG_SESSION_TITLE_CHARS = 78;

/** The mark beside the words that say where the session's name came from (SESSION_NAME_SOURCE_WORDS). */
const SESSION_NAME_SOURCE_MARKS: Record<SessionNameSource, React.ReactNode> = {
  'custom-title': <SquarePenIcon size={18} />,
  summary: <BookOpenIcon size={18} />,
  'first-prompt': <MessageSquareIcon size={18} />,
  project: <FolderIcon size={18} />,
  record: <FileTextIcon size={18} />,
};

/** "Nov 15, 5:21 pm to 5:57 pm", or with both dates when the session crossed midnight; one stamp when there is no span. */
function timeSpan(start: number | null, end: number | null, t: (english: string) => string): string | null {
  const stamp = (epoch: number) => interpolate(t('{date}, {time}'), { date: formatShortDate(epoch), time: formatShortTime(epoch) });
  if (end === null) return start === null ? null : stamp(start);
  if (start === null || start >= end) return stamp(end);
  const endText = localDayKey(start) === localDayKey(end) ? formatShortTime(end) : stamp(end);
  // Within one minute the two stamps read the same: say it once rather than "3:01 pm to 3:01 pm".
  if (endText === formatShortTime(start)) return stamp(start);
  return interpolate(t('{start} to {end}'), { start: stamp(start), end: endText });
}

/**
 * One session (Codex's memory-session): one way back, the breadcrumb "Sessions › {name}"; where the name came from,
 * the name, then the tool, short id and time span; the project and Copy session ID; then "{count} memories", "Find in
 * this session" and the session's rows, which do not repeat the project.
 */
export function SessionDetailPage({
  notices, session, catalogEntry = null, items, isLoading, hasMore, loadError, canRetry,
  offsetCapReachedAt, onLoadMore, onDeleted, deletes: pageDeletes, onBack,
}: SessionDetailPageProps) {
  const { t } = useI18n();
  const [query, setQuery] = useState('');
  const ownDeletes = useFeedDeletes(onDeleted);
  const deletes = pageDeletes ?? ownDeletes;
  const currentSessionKey = sessionKey(session);

  useEffect(() => { setQuery(''); }, [currentSessionKey]);

  const searching = query.trim() !== '';
  // The search. The list applies it after folding prompt repeats over the whole session (G2), so "<n> times in a
  // row" stays true under a search.
  const matches = useMemo(() => searching ? (item: FeedItem) => matchesSearch(item, query) : undefined, [query, searching]);
  const matchCount = useMemo(() => matches ? items.filter(matches).length : items.length, [items, matches]);

  const newestSummary = items.find((item): item is SummaryItem => item.itemType === 'summary');
  const name = sessionName(session.contentSessionId, catalogEntry, newestSummary?.request);
  // Until the first rows arrive, a session the list did not load yet has nothing to name it by but its record.
  const naming = isLoading && items.length === 0 && !catalogEntry;
  const title = naming ? t('Loading this session…') : sessionNameText(name, t);
  const project = catalogEntry?.project ?? items[0]?.project ?? null;
  // The catalog counts every memory of the session; without it, the loaded rows are a floor while older pages remain.
  const memoryCount = catalogEntry?.item_count ?? items.length;
  const countText = interpolate(t(memoryCount === 1 ? '{count} memory' : '{count} memories'), {
    count: `${formatCount(memoryCount)}${catalogEntry || !hasMore ? '' : '+'}`,
  });
  // Normalized before the `start >= end` comparison and the day grouping: a legacy
  // seconds row read raw sits at 1970 and would flip the span's ends.
  const start = catalogEntry?.started_at_epoch != null
    ? epochMs(catalogEntry.started_at_epoch)
    : (hasMore || items.length === 0 ? null : epochMs(items[items.length - 1].created_at_epoch));
  const end = items.length > 0 ? epochMs(items[0].created_at_epoch) : null;
  const span = timeSpan(start, end, t);
  // The full stamps, on hover, focus and tap (G9, G10).
  const spanFull = [start, end].filter((epoch): epoch is number => epoch !== null).map(formatDate).join(' – ');
  const back = (event: React.MouseEvent) => { if (isPlainClick(event)) { event.preventDefault(); onBack(); } };

  const header = (
    <>
      <nav className="mem-crumbs mem-session-crumbs" aria-label={t('Breadcrumb')}>
        <ol>
          <li>
            <a href={sessionsHash()} onClick={back}>{t('Sessions')}</a>
            <ChevronRightIcon size={14} />
          </li>
          <li aria-current="page" className="mem-session-crumb-here"><span className="mem-session-crumb-text">{title}</span></li>
        </ol>
      </nav>
      {!naming && (
        <p className="mem-session-flag" data-source={name.source}>
          <span className="mem-session-flag-mark" aria-hidden="true">{SESSION_NAME_SOURCE_MARKS[name.source]}</span>
          {SESSION_NAME_SOURCE_WORDS[name.source](t)}
        </p>
      )}
      <header className="mem-pagehead mem-session-head">
        <h1 className={`mem-title mem-session-title${title.length > LONG_SESSION_TITLE_CHARS ? ' mem-session-title--long' : ''}`} tabIndex={-1}>{title}</h1>
        <p className="mem-leadtext mem-session-lead">
          <span className="mem-session-tool">{session.platformSource}</span>
          <span className="mem-sep" aria-hidden="true">·</span>
          <span className="mem-session-id" title={session.contentSessionId}>{shortSessionId(session.contentSessionId)}</span>
          {span && <><span className="mem-sep" aria-hidden="true">·</span><StampToggle className="mem-session-when" shown={span} full={spanFull} /></>}
        </p>
      </header>
      <div className="mem-session-utility">
        {project && <span className="mem-code mem-session-project">{project}</span>}
        <CopyButton text={() => session.contentSessionId} label={t('Copy session ID')} className="mem-textbtn mem-session-copy" />
      </div>
      {notices}
      <div className="mem-sectionline mem-session-memories">
        <h2 className="mem-section-title">{countText}</h2>
      </div>
      {items.length > 0 && (
        <div className="mem-toolbar">
          <label className="mem-search">
            <SearchIcon size={18} />
            <span className="visually-hidden">{t('Find in this session')}</span>
            <input type="search" value={query} onChange={event => setQuery(event.target.value)} placeholder={t('Find in this session')} />
          </label>
        </div>
      )}
      {searching && (
        <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(matchCount), total: formatCount(items.length),
          })}
        </p>
      )}
    </>
  );

  // Rows recycle past FEED_WINDOW_THRESHOLD (50), as on the timeline: "Find in this session" searches every
  // loaded row, including the ones the window has not drawn, which the browser's own find cannot see.
  return (
    <Feed
      header={header}
      items={items}
      matches={matches}
      showProject={false}
      showLoadedCount={false}
      onLoadMore={onLoadMore}
      onDeleted={onDeleted}
      deletes={deletes}
      isLoading={isLoading}
      hasMore={hasMore}
      loadError={loadError}
      canRetry={canRetry}
      offsetCapReachedAt={offsetCapReachedAt}
      emptyHint={searching ? { actions: [{ label: t('Clear search'), onClick: () => setQuery('') }] } : undefined}
      // Older pages keep loading by themselves while a search is on: one session is bounded (unlike the whole
      // timeline, which pauses), and a search that empties the loaded rows must still reach older matches.
    />
  );
}