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.7 KB
Raw Blame
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import type { Settings } from '../types';
import type { SaveStatus } from './useSettings';
import { SETTINGS_SECTIONS, changedSettingKeys, type SettingsSection } from '../utils/settings-form';
import { correctedSettingsHash, parseViewRoute, timelineHash, type ViewRoute } from '../utils/memory-route';

/** The settings pages: a category (#/settings/<category>) and the saved context preview. Moving between them is not leaving. */
export function isSettingsRoute(route: ViewRoute): boolean {
  return route.view === 'settings' || route.view === 'context-preview';
}

/** The in-page question asked before the settings pages are left with unsaved changes, and where the person was going. */
export interface LeaveQuestion {
  /** The address they were going to. */
  hash: string;
  /**
   * The history steps the address had already moved before it was moved back: browser Back is -1, Forward +1, a typed
   * address or a link the page did not stop +1, a replaced address 0. Going on takes the same steps again, so history
   * ends as it would have without the question. Null when a control in the page asked before the address moved.
   */
  movedBy: number | null;
  /** What the leaving control does besides going there (the preview's "Show all in the timeline" sets the project). */
  then?: () => void;
  /** Where focus goes back to on "Cancel" (keep editing). */
  returnFocus: HTMLElement | null;
}

export interface SettingsDraft {
  /** The values the fields show and Save posts. */
  values: Settings;
  updateSetting: (key: keyof Settings, value: string) => void;
  toggleBoolean: (key: keyof Settings) => void;
  /** The settings the draft changed and did not save yet (changedSettingKeys). */
  changedKeys: (keyof Settings)[];
  /** When the last save went through with nothing changed since, while on the settings pages; null otherwise. */
  savedAt: number | null;
  /** The failed save the person has moved past (edited back to no changes, or came back to the settings pages): its words go. */
  setAsideFailure: SaveStatus | null;
  /** The category the person last had open: where the preview's breadcrumb goes back to. */
  lastSection: SettingsSection;
  leaveQuestion: LeaveQuestion | null;
  /**
   * Goes to `hash` (running `then` first), or, when going there leaves the settings pages with unsaved changes, asks
   * first, before the address moves. A settings category or the preview is not leaving.
   */
  requestLeave: (hash: string, then?: () => void) => void;
  /** The question's "Discard changes": puts the draft back to the saved settings and goes where the person was going. */
  discardAndLeave: () => void;
  /** The question's "Cancel": stays, focus back where it was. */
  keepEditing: () => void;
}

const focusedElement = () => (document.activeElement instanceof HTMLElement ? document.activeElement : null);

/**
 * Where each history entry of the page keeps its number (history.state), counted from the entry the page opened on. Two
 * numbers say how many steps browser Back or Forward moved, so the move can be undone by going the same steps back:
 * rewriting the entry the person arrived at (replaceState) would put the settings address in place of the timeline's.
 */
const ENTRY_NUMBER_KEY = 'claudeMemEntry';

const historyState = (): Record<string, unknown> => {
  const state: unknown = window.history.state;
  return state && typeof state === 'object' ? state as Record<string, unknown> : {};
};

function entryNumber(): number | null {
  const number = historyState()[ENTRY_NUMBER_KEY];
  return typeof number === 'number' ? number : null;
}

function numberEntry(number: number): void {
  window.history.replaceState({ ...historyState(), [ENTRY_NUMBER_KEY]: number }, '', window.location.href);
}

/**
 * Puts `hash` in the address in place of the current entry (no new history entry) and tells the page, as a move does
 * (a hashchange). Used for a settings category, so Back leaves the settings rather than stepping through them.
 * location.replace would drop the entry's number with its state, and Back from there could no longer be undone.
 */
export function replaceAddress(hash: string): void {
  const oldURL = window.location.href;
  window.history.replaceState(window.history.state, '', hash);
  window.dispatchEvent(new HashChangeEvent('hashchange', { oldURL, newURL: window.location.href }));
}

/**
 * The settings draft and its save state, held in App above the two settings pages (design pass Phase 11), so a trip
 * from a category to the saved context preview and back keeps both. It is what the settings dialog kept while it stayed
 * mounted: leaving the pages clears "Saved at …" and an open question; coming back sets an old failed save aside.
 *
 * Leaving with unsaved changes asks in the page, never the browser's confirm box, however the person leaves, and leaves
 * history as it was when they answer Cancel:
 * - A control in the page (a breadcrumb, Cancel, a menu item in the bar) calls requestLeave, which asks before the
 *   address moves.
 * - Browser Back or Forward (or a typed address) has moved it already. A capturing hashchange listener stops the event
 *   before App's own (bubbling) listener reads the address, so App never draws the page being left, and goes back the
 *   same number of steps (each entry is numbered, ENTRY_NUMBER_KEY); "Discard changes" goes them again.
 * - A full page load (a link in the bar, Cmd K) gets the browser's own beforeunload question, the only one a browser
 *   allows there.
 * None asks while a save is on its way (as before).
 */
export function useSettingsDraft(
  { settings, isSaving, saveStatus }: { settings: Settings; isSaving: boolean; saveStatus: SaveStatus },
  route: ViewRoute,
): SettingsDraft {
  const [values, setValues] = useState<Settings>(settings);
  const [savedAt, setSavedAt] = useState<number | null>(null);
  const [setAsideFailure, setSetAsideFailure] = useState<SaveStatus | null>(null);
  const [leaveQuestion, setLeaveQuestion] = useState<LeaveQuestion | null>(null);
  const [lastSection, setLastSection] = useState<SettingsSection>(route.view === 'settings' ? route.section : SETTINGS_SECTIONS[0]);
  const onSettingsPages = isSettingsRoute(route);
  const focusAfterQuestionRef = useRef<HTMLElement | null>(null);

  useEffect(() => { setValues(settings); }, [settings]);

  const changedKeys = useMemo(() => changedSettingKeys(values, settings), [values, settings]);
  const isDirty = changedKeys.length > 0;
  const saveSucceeded = saveStatus.outcome === 'saved';

  useEffect(() => { if (saveSucceeded) setSavedAt(Date.now()); }, [saveSucceeded]);
  useEffect(() => { if (isDirty) setSavedAt(null); }, [isDirty]);
  // Edited back to no changes after a refused save: "Could not save settings." no longer describes the form.
  useEffect(() => { if (!isDirty && saveStatus.outcome === 'failed') setSetAsideFailure(saveStatus); }, [isDirty, saveStatus]);
  useEffect(() => {
    if (onSettingsPages) return;
    setSavedAt(null);
    setLeaveQuestion(null);
  }, [onSettingsPages]);
  // Came to the settings pages from elsewhere: an old failed save stays behind (before paint, so it never flashes).
  useLayoutEffect(() => {
    if (onSettingsPages) setSetAsideFailure(saveStatus);
    // Only on arriving; saveStatus is read as it is then.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [onSettingsPages]);
  useEffect(() => { if (route.view === 'settings') setLastSection(route.section); }, [route]);
  // An unknown category opened the first one: the address says so too, in place (no new history entry, its number kept).
  useLayoutEffect(() => {
    const corrected = route.view === 'settings' ? correctedSettingsHash(window.location.hash) : null;
    if (corrected) window.history.replaceState(window.history.state, '', corrected);
  }, [route]);
  // "Cancel" on the question puts focus back where it was before the question took it.
  useEffect(() => {
    if (leaveQuestion || !focusAfterQuestionRef.current) return;
    const target = focusAfterQuestionRef.current;
    focusAfterQuestionRef.current = null;
    if (target.isConnected) target.focus();
  }, [leaveQuestion]);

  // Leaving would lose changes. Read through a ref by the hashchange listener, which is added once.
  const guarding = onSettingsPages && isDirty && !isSaving;
  const guardRef = useRef(false);
  guardRef.current = guarding;

  useEffect(() => {
    // The entry the page is on; the one it opened on is 0 unless an earlier load numbered it (a reload keeps the state).
    let current = entryNumber() ?? 0;
    numberEntry(current);
    // The entry a move the question undid goes back to: arriving there is not a move the page shows.
    let undoingTo: number | null = null;
    const onHashChange = (event: HashChangeEvent) => {
      // A new entry (a link, a menu item, a typed address) has no number yet: it comes right after the one left.
      const numbered = entryNumber();
      const arrived = numbered ?? current + 1;
      if (numbered === null) numberEntry(arrived);
      const steps = arrived - current;
      current = arrived;
      if (arrived === undoingTo) {
        undoingTo = null;
        event.stopImmediatePropagation();
        return;
      }
      if (!guardRef.current) return;
      // An address with no hash is the timeline; going there later by '#/' keeps it a move within the page.
      const hash = new URL(event.newURL).hash || timelineHash();
      if (isSettingsRoute(parseViewRoute(hash))) return;
      event.stopImmediatePropagation();
      if (steps === 0) {
        window.history.replaceState(window.history.state, '', event.oldURL);
      } else {
        undoingTo = arrived - steps;
        window.history.go(-steps);
      }
      setLeaveQuestion(previous => ({ hash, movedBy: steps, returnFocus: previous?.returnFocus ?? focusedElement() }));
    };
    window.addEventListener('hashchange', onHashChange, true);
    return () => window.removeEventListener('hashchange', onHashChange, true);
  }, []);

  useEffect(() => {
    if (!guarding) return;
    const onBeforeUnload = (event: BeforeUnloadEvent) => {
      event.preventDefault();
      // Older browsers show their question only when returnValue is set.
      event.returnValue = '';
    };
    window.addEventListener('beforeunload', onBeforeUnload);
    return () => window.removeEventListener('beforeunload', onBeforeUnload);
  }, [guarding]);

  const updateSetting = useCallback((key: keyof Settings, value: string) => {
    setValues(previous => ({ ...previous, [key]: value }));
  }, []);

  const toggleBoolean = useCallback((key: keyof Settings) => {
    setValues(previous => ({ ...previous, [key]: previous[key] === 'true' ? 'false' : 'true' }));
  }, []);

  const requestLeave = useCallback((hash: string, then?: () => void) => {
    if (guardRef.current && !isSettingsRoute(parseViewRoute(hash))) {
      setLeaveQuestion({ hash, movedBy: null, then, returnFocus: focusedElement() });
      return;
    }
    then?.();
    window.location.hash = hash;
  }, []);

  const discardAndLeave = useCallback(() => {
    if (!leaveQuestion) return;
    setLeaveQuestion(null);
    setValues(settings);
    // The draft is the saved settings again: the hashchange this causes is not stopped.
    guardRef.current = false;
    leaveQuestion.then?.();
    const { hash, movedBy } = leaveQuestion;
    if (movedBy === null) window.location.hash = hash;
    else if (movedBy === 0) replaceAddress(hash);
    else window.history.go(movedBy);
  }, [leaveQuestion, settings]);

  const keepEditing = useCallback(() => {
    focusAfterQuestionRef.current = leaveQuestion?.returnFocus ?? null;
    setLeaveQuestion(null);
  }, [leaveQuestion]);

  return {
    values, updateSetting, toggleBoolean, changedKeys, savedAt, setAsideFailure, lastSection,
    leaveQuestion, requestLeave, discardAndLeave, keepEditing,
  };
}