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

15.7 KB
Raw Blame
import React, { useId, useLayoutEffect, useRef } from 'react';
import { useI18n, interpolate } from '../../i18n';
import type { FeedItem, Observation, Summary, UserPrompt } from '../types';
import { categoryOf } from '../utils/category';
import { feedItemKey } from '../utils/feed-display';
import { formatCount, formatDate, formatShortTime } from '../utils/formatters';
import { parseStoredStringList } from '../utils/stored-string-list';
import type { FeedItemDeletion } from '../hooks/useFeedItemDelete';
import type { DeletableItemType } from '../utils/feed-deletion';
import { ObservationMediaSection } from './ObservationMedia';
import { DELETE_ITEM_LABELS, DeleteConfirmation } from './DeleteButton';
import { MenuButton, MenuItem, MenuSeparator } from './MenuButton';
import { CopyButton, CopyMenuItem } from './CopyButton';
import { KIND_LOOK, KindMark } from './RecordKind';
import { ChevronRightIcon, MoreHorizontalIcon, TrashIcon } from './icons';

type Translate = (english: string) => string;

function stripProjectRoot(storedPath: string): string {
  // Windows sessions record `C:\Users\…\src\app.ts`; shorten it like a `/` path.
  const filePath = storedPath.replace(/\\/g, '/');
  const markers = ['/Scripts/', '/src/', '/plugin/', '/docs/'];

  for (const marker of markers) {
    const index = filePath.indexOf(marker);
    if (index !== -1) {
      return filePath.substring(index + 1);
    }
  }

  const projectIndex = filePath.indexOf('claude-mem/');
  if (projectIndex !== -1) {
    return filePath.substring(projectIndex + 'claude-mem/'.length);
  }

  const parts = filePath.split('/');
  return parts.length > 3 ? parts.slice(-3).join('/') : filePath;
}

/** A summary's sections, in the order an opened summary row shows them, with their headings. */
export const SUMMARY_SECTIONS = [
  { key: 'investigated', label: 'Investigated' },
  { key: 'learned', label: 'Learned' },
  { key: 'completed', label: 'Completed' },
  { key: 'next_steps', label: 'Next Steps' },
  { key: 'notes', label: 'Notes' },
] as const satisfies ReadonlyArray<{ key: keyof Summary; label: string }>;

/** The summary as plain text for Copy text, with the section headings in the reader's language. */
export function summaryText(summary: Summary, t: Translate): string {
  return [summary.request, ...SUMMARY_SECTIONS.map(section => summary[section.key] ? `${t(section.label)}\n${summary[section.key]}` : null)]
    .filter(Boolean).join('\n\n');
}

/**
 * The plain text of an observation for Copy text: every section its opened row shows (G4), as a summary's Copy text
 * has every section. Title, one-line summary, narrative, then its facts, concepts and files, with the row's own
 * labels in the reader's language.
 */
export function observationText(observation: Observation, t: Translate): string {
  const facts = parseStoredStringList(observation.facts);
  const concepts = parseStoredStringList(observation.concepts);
  const filesRead = parseStoredStringList(observation.files_read);
  const filesModified = parseStoredStringList(observation.files_modified);
  return [
    observation.title,
    observation.subtitle,
    observation.narrative,
    facts.length ? `${t('Facts')}\n${facts.map(fact => `- ${fact}`).join('\n')}` : null,
    concepts.length ? concepts.join(', ') : null,
    filesRead.length ? `${t('read:')} ${filesRead.join(', ')}` : null,
    filesModified.length ? `${t('modified:')} ${filesModified.join(', ')}` : null,
  ].filter(Boolean).join('\n\n');
}

/** Copy text for any record: an observation's sections, a summary's sections, a prompt's words. */
function recordText(item: FeedItem, t: Translate): string {
  if (item.itemType === 'observation') return observationText(item, t);
  if (item.itemType === 'summary') return summaryText(item, t);
  return item.prompt_text;
}

/** The words a row leads with: an observation's title, a summary's request, a prompt's own words (CSS keeps its first lines). */
export function recordTitle(item: FeedItem, t: Translate): string {
  if (item.itemType === 'observation') return item.title?.trim() || t('Untitled');
  if (item.itemType === 'summary') return item.request?.trim() || t('Untitled');
  return item.prompt_text;
}

/**
 * The kind under a row's title. An observation of a type outside the known kinds (another mode's types) keeps its own
 * type word, as its card did, rather than reading "Other"; the All types menu still files it under Other.
 */
function kindWords(item: FeedItem, t: Translate): string {
  const kind = categoryOf(item);
  return kind === 'other' && item.itemType === 'observation' && item.type ? t(item.type) : KIND_LOOK[kind].words(t);
}

/** "6:07 pm" for the row; a stamp that is not a real time reads "Unknown time" instead of stopping the list. */
function rowTime(epoch: number, t: Translate): { short: string; full: string; iso?: string } {
  const date = new Date(epoch);
  if (!Number.isFinite(date.getTime())) return { short: t('Unknown time'), full: t('Unknown time') };
  return { short: formatShortTime(epoch), full: formatDate(epoch), iso: date.toISOString() };
}

function Section({ title, legend, children }: { title: string; legend?: string; children: React.ReactNode }) {
  return (
    <section className="mem-record-section">
      <div className="mem-record-sectionline">
        <h3 className="mem-record-heading">{title}</h3>
        {legend && <span className="mem-legend">{legend}</span>}
      </div>
      {children}
    </section>
  );
}

function ObservationDetails({ observation }: { observation: Observation }) {
  const { t } = useI18n();
  const facts = parseStoredStringList(observation.facts);
  const concepts = parseStoredStringList(observation.concepts);
  const filesRead = parseStoredStringList(observation.files_read).map(stripProjectRoot);
  const filesModified = parseStoredStringList(observation.files_modified).map(stripProjectRoot);
  return (
    <>
      {observation.subtitle && <p className="mem-record-lead">{observation.subtitle}</p>}
      {facts.length > 0 && (
        <Section title={t('Facts')} legend={interpolate(t(facts.length === 1 ? '{count} fact' : '{count} facts'), { count: formatCount(facts.length) })}>
          <ul className="mem-record-facts">{facts.map((fact, index) => <li key={index}>{fact}</li>)}</ul>
        </Section>
      )}
      {observation.narrative && (
        <Section title={t('Narrative')}>
          <p className="mem-record-text">{observation.narrative}</p>
        </Section>
      )}
      {concepts.length > 0 && (
        <Section title={t('Concepts')}>
          <ul className="mem-record-chips">{concepts.map((concept, index) => <li key={index}>{concept}</li>)}</ul>
        </Section>
      )}
      {(filesRead.length > 0 || filesModified.length > 0) && (
        <Section title={t('Files')}>
          {filesRead.length > 0 && <p className="mem-record-files"><span className="mem-record-files-label">{t('read:')}</span> {filesRead.join(', ')}</p>}
          {filesModified.length > 0 && <p className="mem-record-files"><span className="mem-record-files-label">{t('modified:')}</span> {filesModified.join(', ')}</p>}
        </Section>
      )}
      {/* Attached images: only rows with validated media refs render this */}
      {observation.media && observation.media.attachments.length > 0 && (
        <ObservationMediaSection observationId={observation.id} media={observation.media} />
      )}
    </>
  );
}

function SummaryDetails({ summary }: { summary: Summary }) {
  const { t } = useI18n();
  return (
    <>
      {SUMMARY_SECTIONS.filter(section => summary[section.key]).map(section => (
        <Section key={section.key} title={t(section.label)}>
          <p className="mem-record-text">{summary[section.key]}</p>
        </Section>
      ))}
    </>
  );
}

function PromptDetails({ prompt, repeats }: { prompt: UserPrompt; repeats: UserPrompt[] }) {
  const { t } = useI18n();
  return (
    <>
      <p className="mem-record-text mem-record-prompt">{prompt.prompt_text}</p>
      {repeats.length > 0 && (
        <Section title={interpolate(t('{count} times in a row'), { count: formatCount(repeats.length + 1) })}>
          <ul className="mem-record-repeats" aria-label={t('Earlier times')}>
            {repeats.map(repeat => (
              <li key={repeat.id}>
                <span className="mem-meta">
                  {formatDate(repeat.created_at_epoch)}<span className="mem-sep" aria-hidden="true"> · </span>#{repeat.id}
                  <span className="mem-sep" aria-hidden="true"> · </span>{repeat.platform_source || 'claude'}
                  <span className="mem-sep" aria-hidden="true"> · </span>{repeat.project}
                </span>
                {/* A repeat folds by its words, whatever their case and spacing (foldPromptRepeats); one typed
                    differently keeps its own text here, so nothing it said is lost (rule 2). */}
                {repeat.prompt_text !== prompt.prompt_text && <span className="mem-record-repeat-text">{repeat.prompt_text}</span>}
              </li>
            ))}
          </ul>
        </Section>
      )}
    </>
  );
}

interface RecordRowProps {
  item: FeedItem;
  open: boolean;
  /** Opens this row, or closes it when it is open; the list keeps one row open at a time. */
  onToggle: (key: string) => void;
  /** Say the project under the title; a session's own page leaves it out (every row there is that session's). */
  showProject?: boolean;
  /** Older prompts with the same words typed just before this one, newest first; folded into this row. */
  repeats?: UserPrompt[];
  /** This row's delete, held by the list so it outlives the row (observations and summaries; a prompt has none). */
  deletion?: FeedItemDeletion;
}

/**
 * One record as one row (design pass Phase 11, Codex D17): its time, its kind's mark, its title, then its kind and
 * project. Pressing it (or Enter or Space) opens the record in place under it: an observation's one-line summary,
 * facts, narrative, concepts, files and images, a summary's sections, a prompt's whole words and its repeats, then its
 * id and stamp, Copy text and Record actions (Copy id, Delete). The row's button says whether it is open and names
 * the details it controls, as a logs page row does (LogsPage.tsx).
 */
export function RecordRow({ item, open, onToggle, showProject = true, repeats = [], deletion }: RecordRowProps) {
  const { t } = useI18n();
  const key = feedItemKey(item);
  const kind = categoryOf(item);
  const title = recordTitle(item, t);
  const time = rowTime(item.created_at_epoch, t);
  const detailsId = useId();
  const titleId = useId();
  const rowRef = useRef<HTMLButtonElement>(null);
  const detailsRef = useRef<HTMLDivElement>(null);
  const source = item.platform_source || 'claude';
  // Observations and summaries can be deleted; a prompt cannot (DeletableItemType).
  const deleteType: DeletableItemType | null = item.itemType === 'prompt' ? null : item.itemType;
  const rowDeletion = deleteType ? deletion : undefined;

  // A row opened near the foot of the window opens out of sight: scroll up by what is hidden, but never so far that
  // the row itself goes under the pinned bar (the room the list's own scroll-padding-top keeps clear for it, read from
  // the stylesheet). A row drawn again while already open (scrolled back into the list's window) must not pull the list
  // to itself.
  const wasOpenRef = useRef(open);
  useLayoutEffect(() => {
    const opening = open && !wasOpenRef.current;
    wasOpenRef.current = open;
    const row = rowRef.current, details = detailsRef.current;
    const scroller = row?.closest<HTMLElement>('.mem-scroll');
    if (!opening || !row || !details || !scroller) return;
    const view = scroller.getBoundingClientRect();
    const hidden = details.getBoundingClientRect().bottom - view.bottom;
    const pinnedBarRoom = parseFloat(getComputedStyle(scroller).scrollPaddingTop) || 0;
    const room = row.getBoundingClientRect().top - view.top - pinnedBarRoom;
    const by = Math.min(hidden, room);
    if (by > 0) scroller.scrollBy({ top: by });
  }, [open]);

  const returnFocus = () => (document.getElementById(detailsId)?.querySelector<HTMLElement>('.mem-record-menu') ?? rowRef.current)?.focus();

  return (
    <div className={`mem-record mem-record--${item.itemType}${open ? ' mem-record--open' : ''}`}>
      <button ref={rowRef} type="button" className="mem-row mem-row--record mem-record-row" aria-expanded={open}
        aria-controls={open ? detailsId : undefined} onClick={() => onToggle(key)}>
        <time className="mem-time" dateTime={time.iso} title={time.full}>{time.short}</time>
        <KindMark kind={kind} />
        <span className="mem-row-body">
          <span className="mem-row-title" id={titleId}>{title}</span>
          <span className="mem-row-meta">
            <span>{kindWords(item, t)}</span>
            {showProject && <><span className="mem-sep" aria-hidden="true">·</span><span className="mem-record-project">{item.project}</span></>}
            {repeats.length > 0 && (
              <><span className="mem-sep" aria-hidden="true">·</span>
                <span>{interpolate(t('{count} times in a row'), { count: formatCount(repeats.length + 1) })}</span></>
            )}
          </span>
        </span>
        <span className="mem-chev mem-record-chev" aria-hidden="true"><ChevronRightIcon size={18} /></span>
      </button>
      {open && (
        <div className="mem-record-details" id={detailsId} ref={detailsRef} role="region" aria-labelledby={titleId}>
          {item.itemType === 'observation' && <ObservationDetails observation={item} />}
          {item.itemType === 'summary' && <SummaryDetails summary={item} />}
          {item.itemType === 'prompt' && <PromptDetails prompt={item} repeats={repeats} />}
          <p className="mem-record-stamp mem-meta">
            <span className="mem-code">#{item.id}</span>
            <span className="mem-sep" aria-hidden="true">·</span>
            <span>{time.full}</span>
            <span className="mem-sep" aria-hidden="true">·</span>
            <span>{source}</span>
            {!showProject && <><span className="mem-sep" aria-hidden="true">·</span><span>{item.project}</span></>}
            {item.itemType === 'observation' && item.merged_into_project && (
              <><span className="mem-sep" aria-hidden="true">·</span>
                <span title={interpolate(t('Merged into {project}'), { project: item.merged_into_project })}>
                  {interpolate(t('merged → {project}'), { project: item.merged_into_project })}
                </span></>
            )}
          </p>
          <div className="mem-record-actions">
            <CopyButton className="mem-textbtn" label={t('Copy text')} text={() => recordText(item, t)} />
            <MenuButton label={t('Record actions')} align="start" triggerClassName="mem-textbtn mem-record-menu"
              icon={<><MoreHorizontalIcon size={18} /><span>{t('Record actions')}</span></>}>
              {close => (
                <>
                  <CopyMenuItem label={interpolate(t('Copy id #{id}'), { id: item.id })} text={() => String(item.id)} />
                  {deleteType && rowDeletion && (
                    <>
                      <MenuSeparator />
                      <MenuItem danger icon={<TrashIcon />} onSelect={() => { close(false); rowDeletion.ask(); }}>
                        {interpolate(t('Delete {item}…'), { item: t(DELETE_ITEM_LABELS[deleteType]) })}
                      </MenuItem>
                    </>
                  )}
                </>
              )}
            </MenuButton>
          </div>
        </div>
      )}
      {/* Outside the details, so a question, a delete on its way and its refusal stay in view when the row closes. */}
      {deleteType && rowDeletion && rowDeletion.stage !== 'idle' && (
        <div className="mem-record-delete">
          <DeleteConfirmation itemType={deleteType} deletion={rowDeletion} returnFocus={returnFocus} />
        </div>
      )}
    </div>
  );
}