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

5.6 KB
Raw Blame
import { SETTINGS_SECTIONS, type SettingsSection } from './settings-form';
import type { SessionRef } from './sessions';

/**
 * Memory's pages and their addresses (My Work design pass, Phase 11). The one definition: the page switch in App.tsx,
 * the tabs, the bar's "…" menu and the tests import it. Every address is a hash, so the viewer stays one page that the
 * worker serves at /viewer (and the server runtime at /), and My Work links into it from src/ui/app-places.ts
 * (MEMORY_SETTINGS_ADDRESS is `#/settings`, memoryFindAddress is `#/?find=<words>`).
 *
 * - `#/` (or no hash): the timeline; `#/?find=<words>` opens it with those words in "Find in loaded memories".
 * - `#/sessions`: the Sessions list; `#/sessions/<platform>/<id>`: one session.
 * - `#/settings`: Memory settings on its first category; `#/settings/<category>` on that one.
 * - `#/context-preview`: the saved context preview, one action from the settings.
 * - `#/logs`: Memory logs.
 *
 * Anything else reads as the timeline, so an old or hand-edited link still opens Memory.
 */
export type ViewRoute =
  | { view: 'timeline'; find: string | null }
  | { view: 'sessions' }
  | { view: 'session'; session: SessionRef }
  | { view: 'settings'; section: SettingsSection }
  | { view: 'context-preview' }
  | { view: 'logs' };

/** Memory's pages, by the route that names them. */
export type MemoryView = ViewRoute['view'];

/** The two tabs under the Memory heading, in the order they show: one array, so another tab is one entry (PR #4800). */
export const MEMORY_TABS = ['timeline', 'sessions'] as const satisfies readonly MemoryView[];
export type MemoryTab = (typeof MEMORY_TABS)[number];

/** Which tab a page sits under; the settings, preview and logs pages sit under none. */
export function tabOfRoute(route: ViewRoute): MemoryTab | null {
  if (route.view === 'timeline') return 'timeline';
  if (route.view === 'sessions' || route.view === 'session') return 'sessions';
  return null;
}

const FIND_PARAMETER = 'find';
const SESSIONS_HASH = '#/sessions';
const SETTINGS_HASH = '#/settings';
const CONTEXT_PREVIEW_HASH = '#/context-preview';
const LOGS_HASH = '#/logs';

/** The timeline's address, with words in its find box when there are any. */
export function timelineHash(find: string | null = null): string {
  const words = find?.trim();
  return words ? `#/?${FIND_PARAMETER}=${encodeURIComponent(words)}` : '#/';
}

export function sessionsHash(): string {
  return SESSIONS_HASH;
}

export function sessionHash(ref: SessionRef): string {
  return `${SESSIONS_HASH}/${encodeURIComponent(ref.platformSource)}/${encodeURIComponent(ref.contentSessionId)}`;
}

/** Memory settings, on one category when it is given. */
export function settingsHash(section: SettingsSection | null = null): string {
  return section ? `${SETTINGS_HASH}/${section}` : SETTINGS_HASH;
}

export function contextPreviewHash(): string {
  return CONTEXT_PREVIEW_HASH;
}

export function logsHash(): string {
  return LOGS_HASH;
}

/** The address of a tab's page. */
export function tabHash(tab: MemoryTab): string {
  return tab === 'sessions' ? sessionsHash() : timelineHash();
}

const isSettingsSection = (value: string): value is SettingsSection => (SETTINGS_SECTIONS as readonly string[]).includes(value);

/**
 * The address to show in place of `hash` when it names a settings category this version does not have (an older link,
 * a typo): the category that opened instead, so a reload or a copied link says what is shown. Null when it reads right.
 */
export function correctedSettingsHash(hash: string): string | null {
  if (!hash.startsWith(`${SETTINGS_HASH}/`)) return null;
  return isSettingsSection(hash.slice(SETTINGS_HASH.length + 1)) ? null : settingsHash(SETTINGS_SECTIONS[0]);
}

/** The words of `#/?find=<words>`, or null when there are none. */
function findWords(hash: string): string | null {
  const query = hash.indexOf('?');
  if (query < 0) return null;
  const words = new URLSearchParams(hash.slice(query + 1)).get(FIND_PARAMETER)?.trim();
  return words ? words : null;
}

export function parseViewRoute(hash: string): ViewRoute {
  if (hash === SESSIONS_HASH) return { view: 'sessions' };
  if (hash.startsWith(`${SESSIONS_HASH}/`)) {
    const parts = hash.slice(SESSIONS_HASH.length + 1).split('/');
    if (parts.length !== 2 || !parts[0] || !parts[1]) return { view: 'sessions' };
    try {
      return {
        view: 'session',
        session: { platformSource: decodeURIComponent(parts[0]), contentSessionId: decodeURIComponent(parts[1]) },
      };
    } catch {
      // A hand-edited hash with broken percent-encoding: fall back to the list.
      return { view: 'sessions' };
    }
  }
  if (hash === SETTINGS_HASH || hash.startsWith(`${SETTINGS_HASH}/`)) {
    const asked = hash.slice(SETTINGS_HASH.length + 1);
    // An unknown category (an older link, a typo) opens the first one rather than an empty page.
    return { view: 'settings', section: isSettingsSection(asked) ? asked : SETTINGS_SECTIONS[0] };
  }
  if (hash === CONTEXT_PREVIEW_HASH) return { view: 'context-preview' };
  if (hash === LOGS_HASH) return { view: 'logs' };
  return { view: 'timeline', find: findWords(hash) };
}

/** The hash of a route, so a route read from an address writes back to the same address. */
export function routeHash(route: ViewRoute): string {
  switch (route.view) {
    case 'timeline': return timelineHash(route.find);
    case 'sessions': return sessionsHash();
    case 'session': return sessionHash(route.session);
    case 'settings': return settingsHash(route.section);
    case 'context-preview': return contextPreviewHash();
    case 'logs': return logsHash();
  }
}