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

11.4 KB
Raw Blame
import React, { useEffect } from 'react';
import { LOCALES, LOCALE_NAMES, useI18n, interpolate } from '../../i18n';
import { FIND_WORK_PLACE, MEMORY_PLACE, MY_WORK_PLACES, type MyWorkPlaceId } from '../../app-places';
import { THEME_LABELS } from './ThemeToggle';
import { THEME_PREFERENCES, type ThemePreference } from '../hooks/useTheme';
import { useAppearance } from '../hooks/useAppearance';
import { APPEARANCE_WORDS, PALETTE_THEMES, THEME_PRESETS, THEME_PRESET_LABELS } from '../../theme-appearance';
import { useSpinningFavicon } from '../hooks/useSpinningFavicon';
import { formatStarCount, useGitHubStars } from '../hooks/useGitHubStars';
import { PRO_TRIAL_PITCH, PRO_TRIAL_SHORT, PRO_TRIAL_URL, TEAMBRAIN_PITCH, TEAMBRAIN_START_URL } from '../constants/promo';
import { formatCount } from '../utils/formatters';
import { logsHash, settingsHash } from '../utils/memory-route';
import { BrandMark } from './BrandMark';
import { MenuButton, MenuGroup, MenuItem, MenuLink, MenuRadioItem, MenuSeparator } from './MenuButton';
import {
  BookIcon, BookMarkedIcon, DiscordIcon, GalleryVerticalEndIcon, GearIcon, GlobeIcon, HelpIcon, HouseIcon, LayersIcon,
  LibraryIcon, ListChecksIcon, MoreHorizontalIcon, SearchIcon, SparkleIcon, StarIcon, TerminalIcon, UsersIcon, XLogoIcon,
} from './icons';

/** Each place's mark in the phone's bottom bar: My Work's own (src/ui/my-work/src/components/app-bar.tsx PLACE_ICON). */
const PLACE_ICON: Record<MyWorkPlaceId, ({ size }: { size?: number }) => React.ReactElement> = {
  work: HouseIcon,
  focus: LayersIcon,
  requests: ListChecksIcon,
  'review-stack': GalleryVerticalEndIcon,
  rules: BookMarkedIcon,
};

/**
 * Whether My Work's places are on this server: the worker serves My Work at / and Memory at /viewer (as the cloud
 * viewer does), so Memory at /viewer draws every place. The self-hosted server runtime serves Memory alone at /
 * (src/server/runtime/ServerViewerRoutes.ts), where My Work does not exist: there the bar is the mark and Memory.
 */
export function myWorkIsServedHere(pathname: string = typeof window === 'undefined' ? '' : window.location.pathname): boolean {
  return pathname.replace(/\/+$/, '') === MEMORY_PLACE.address;
}

/** Apple's keyboards say ⌘ for the shortcut; every other says Ctrl (as My Work's bar). */
const APPLE_KEYBOARD = typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent);

const isTextField = (target: EventTarget | null) => target instanceof HTMLElement
  && (target.isContentEditable || target instanceof HTMLTextAreaElement
    || (target instanceof HTMLInputElement && !['checkbox', 'radio', 'button', 'submit'].includes(target.type)));

/**
 * Cmd K (Ctrl K) opens My Work's Find work from Memory too, as the shortcut beside it says. Read by the key's place
 * (`code`), so it works on every layout; on Apple keyboards Ctrl K in a text field is the field's own command; nothing
 * happens when the page already handled the key or while a dialog is open.
 */
function useFindWorkShortcut(enabled: boolean) {
  useEffect(() => {
    if (!enabled) return;
    const onKey = (event: KeyboardEvent) => {
      if (event.code !== 'KeyK' || event.altKey || event.shiftKey || !(event.metaKey || event.ctrlKey)) return;
      if (event.defaultPrevented || document.querySelector('[role="dialog"][aria-modal="true"]')) return;
      if (APPLE_KEYBOARD && !event.metaKey && isTextField(event.target)) return;
      event.preventDefault();
      window.location.assign(FIND_WORK_PLACE.address);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [enabled]);
}

/**
 * The phone's places (under 768px): My Work's places in a bar at the foot of the window, as My Work's own bottom bar.
 * Drawn after the page in the document, so Tab reaches it after the page, where it sits. None in the server runtime.
 */
export function PlaceBottomBar() {
  const { t } = useI18n();
  if (!myWorkIsServedHere()) return null;
  return (
    <nav className="mem-bottom-bar" aria-label={t('Pages')}>
      {MY_WORK_PLACES.map(place => {
        const Mark = PLACE_ICON[place.id];
        return (
          <a key={place.id} className="mem-bottom-place" href={place.address}>
            <Mark size={18} />
            <span>{t(place.shortLabel)}</span>
          </a>
        );
      })}
    </nav>
  );
}

/**
 * The brain mark and its name, My Work's places, Find work and Memory: the same bar as My Work's (design pass Phase 3,
 * src/ui/my-work/src/components/app-bar.tsx), with Memory as the page shown. Every link is a full page load (My Work
 * is another page). It reads nothing from the viewer's state, so the page's own error card can draw it too
 * (ErrorBoundary). `more` is the "…" control at its end. The phone's places are PlaceBottomBar, drawn after the page.
 */
export function BarFrame({ more }: { more?: React.ReactNode }) {
  const { t } = useI18n();
  const placesShown = myWorkIsServedHere();
  useFindWorkShortcut(placesShown);
  return (
    <>
      <header className="mem-bar">
        <div className="mem-bar-inner">
          <a className="mem-brand" href="/"><BrandMark /><span>claude-mem</span></a>
          {placesShown && (
            <nav className="mem-places" aria-label={t('Pages')}>
              {MY_WORK_PLACES.map(place => <a key={place.id} className="mem-place" href={place.address}>{t(place.label)}</a>)}
            </nav>
          )}
          <div className="mem-bar-tools">
            {placesShown && (
              <>
                <a className="mem-findwork" href={FIND_WORK_PLACE.address} aria-label={t(FIND_WORK_PLACE.label)} aria-keyshortcuts="Meta+K Control+K">
                  <SearchIcon size={18} />
                  <span className="mem-findwork-words">{t(FIND_WORK_PLACE.label)}</span>
                  <kbd aria-hidden="true">{APPLE_KEYBOARD ? '⌘ K' : 'Ctrl K'}</kbd>
                </a>
                <span className="mem-bar-divider" aria-hidden="true" />
              </>
            )}
            {/* Memory is where this page is served: /viewer beside My Work, / in the server runtime. */}
            <a className="mem-memory-link" href={placesShown ? MEMORY_PLACE.address : '/'} aria-current="page">
              <LibraryIcon size={18} />
              <span className="mem-memory-link-words">{t(MEMORY_PLACE.label)}</span>
            </a>
            {more}
          </div>
        </div>
      </header>
    </>
  );
}

interface HeaderProps {
  /** The worker is processing: the tab's icon spins. */
  isProcessing: boolean;
  themePreference: ThemePreference;
  onThemeChange: (theme: ThemePreference) => void;
  /**
   * Opens one of Memory's own pages (Settings, Memory logs) by its address. App asks first, before the address moves,
   * when unsaved settings would be lost (useSettingsDraft requestLeave).
   */
  onNavigate: (hash: string) => void;
  /** "Show welcome card": the welcome panel above the timeline comes back. */
  onShowHelp?: () => void;
  /** Show the TeamBrain link: settings have loaded and this install is in no team. */
  showTeamBrainLink?: boolean;
  /** The timeline supplies its own dismissible Cloud Sync offer, so the menu leaves its trial link out there. */
  showProTrialLink?: boolean;
}

/**
 * Memory's bar (BarFrame) with its "…" menu: Settings, Memory logs, Show welcome card, the trial link, Documentation and
 * the community links, the theme, the language and TeamBrain. The sync state is on My Work's Machine and sync page.
 */
export function Header({
  isProcessing,
  themePreference,
  onThemeChange,
  onNavigate,
  onShowHelp,
  showTeamBrainLink = false,
  showProTrialLink = true,
}: HeaderProps) {
  const { t, locale, setLocale } = useI18n();
  const { appearance, update: updateAppearance } = useAppearance();
  useSpinningFavicon(isProcessing);
  // The star count is only seen inside the "…" menu, so GitHub is asked once, when the menu first opens.
  const [starsWanted, setStarsWanted] = React.useState(false);
  const github = useGitHubStars('thedotmack', 'claude-mem', starsWanted);
  const starTitle = github.stars !== null
    ? interpolate(t('Star us on GitHub ({count} stars)'), { count: formatCount(github.stars) })
    : t('Star us on GitHub');

  const more = (
    <MenuButton
      label={t('More')}
      icon={<MoreHorizontalIcon size={20} />}
      triggerClassName="header-more"
      menuClassName="header-menu"
      onOpenChange={open => { if (open) setStarsWanted(true); }}
    >
      {close => (
        <>
          <MenuItem icon={<GearIcon />} onSelect={() => { close(); onNavigate(settingsHash()); }}>{t('Settings')}</MenuItem>
          <MenuItem icon={<TerminalIcon />} onSelect={() => { close(); onNavigate(logsHash()); }}>{t('Memory logs')}</MenuItem>
          <MenuItem icon={<HelpIcon />} onSelect={() => { close(); onShowHelp?.(); }}>{t('Show welcome card')}</MenuItem>
          {showProTrialLink && (
            <MenuLink href={PRO_TRIAL_URL} icon={<SparkleIcon />} title={t(PRO_TRIAL_PITCH)} onSelect={() => close()}>
              {t(PRO_TRIAL_SHORT)}
            </MenuLink>
          )}
          <MenuSeparator />
          <MenuLink href="https://docs.claude-mem.ai" icon={<BookIcon />} onSelect={() => close()}>{t('Documentation')}</MenuLink>
          <MenuLink href="https://x.com/Claude_Memory" icon={<XLogoIcon />} onSelect={() => close()}>{t('Follow us on X')}</MenuLink>
          <MenuLink href="https://discord.gg/J4wttp9vDu" icon={<DiscordIcon />} onSelect={() => close()}>{t('Join our Discord community')}</MenuLink>
          <MenuLink href={github.repoUrl} icon={<StarIcon />} title={starTitle} onSelect={() => close()}
            hint={github.stars !== null ? <span className="tabular">{formatStarCount(github.stars)}</span> : undefined}>
            {t('Star on GitHub')}
          </MenuLink>
          <MenuSeparator />
          <MenuGroup label={t('Theme')} className="menu-group--segments">
            {THEME_PREFERENCES.map(choice => (
              <MenuRadioItem key={choice} checked={themePreference === choice} className="menu-segment"
                onSelect={() => onThemeChange(choice)}>
                {t(THEME_LABELS[choice])}
              </MenuRadioItem>
            ))}
          </MenuGroup>
          <MenuGroup label={t(APPEARANCE_WORDS.palette)}>
            {THEME_PRESETS.map(preset => (
              <MenuRadioItem key={preset} checked={appearance.preset === preset}
                onSelect={() => {
                  // A palette belongs to one theme (PALETTE_THEMES), so choosing it also chooses that theme.
                  updateAppearance({ preset });
                  const theme = PALETTE_THEMES[preset];
                  if (theme) onThemeChange(theme);
                }}>
                {t(THEME_PRESET_LABELS[preset])}
              </MenuRadioItem>
            ))}
          </MenuGroup>
          <MenuGroup label={t('Language')} icon={<GlobeIcon size={14} />}>
            {LOCALES.map(code => (
              <MenuRadioItem key={code} checked={locale === code} lang={code} onSelect={() => setLocale(code)}>
                {LOCALE_NAMES[code]}
              </MenuRadioItem>
            ))}
          </MenuGroup>
          {showTeamBrainLink && (
            <>
              <MenuSeparator />
              <MenuLink className="teambrain-cta" href={TEAMBRAIN_START_URL} icon={<UsersIcon />} title={t(TEAMBRAIN_PITCH)} onSelect={() => close()}>
                TeamBrain
              </MenuLink>
            </>
          )}
        </>
      )}
    </MenuButton>
  );

  return <BarFrame more={more} />;
}