use-active-doc-context.ts1.6 KBView on GitHub
import { useEffect } from 'react';

import type { ActiveDocContext } from '@/modules/cedar-os/src/store/agentContext/agentContextSlice';
import { useCedarStore } from '@/modules/store';

/**
 * Publish the file open on this surface as the chat's ambient file context.
 *
 * Every surface that opens a document mounts this, and that is the point: before it, the
 * doc badge existed but only three screens ever set it, so opening a file from a FILE
 * BROWSER — the agent workspace's Output tab, a deal's Files tab, the Brain explorer —
 * put nothing on the wire at all. You could be reading a file, ask the chat about "this",
 * and the chat had never been told which file you meant.
 *
 * Pass `null` (or nothing) when no file is open; the effect clears the context on unmount
 * too, so navigating away can never leave a stale file attached to the next screen.
 *
 * The fields are spread into the deps rather than the object itself: callers build the
 * descriptor inline, so a referentially-fresh object every render would rewrite the store
 * on every render and churn every subscriber of it.
 */
export function useActiveDocContext(doc: ActiveDocContext | null | undefined) {
  const setActiveDocContext = useCedarStore((s) => s.setActiveDocContext);
  const { path, documentId, title, documentType } = doc ?? {};

  useEffect(() => {
    if (!path) {
      setActiveDocContext(null);
      return;
    }
    setActiveDocContext({ path, documentId, title, documentType });
    return () => setActiveDocContext(null);
  }, [path, documentId, title, documentType, setActiveDocContext]);
}