Skip to content

armgit / cogit

Public Imported from GitHub
0

Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.

40.4 KB
Raw Blame
import {
  Controls,
  type Node,
  type NodeProps,
  type NodeTypes,
  ReactFlow,
  ReactFlowProvider,
  type ReactFlowState,
  useReactFlow,
  useStore,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import type { LineageViewModel, ViewSession } from "../../cli/src/view/model.js";
import { hitMessageIds, hitSessionIds } from "../../cli/src/view/search.js";
import { CapturesView, captureCounts, capturesButtonVisible } from "./CapturesView.js";
import { loadMapView, pageToken, saveOpenSessions, saveRowWidth } from "./data.js";
import { type FilesFocus, type FilesTarget, FilesView } from "./FilesView.js";
import { useFullscreen } from "./fullscreen.js";
import { GitGraph } from "./GitGraph.js";
import { type GitLayout, layoutGitGraph, ROW_WIDTH } from "./gitLayout.js";
import { centreViewport, headOf, inBand, type MapPoint, visibleBand } from "./graph.js";
import type { MapSearchState } from "./MapSearch.js";
import { Outline, type OutlineTarget } from "./Outline.js";
import { filterOf, type PersonFilter, peopleOf, valueOf } from "./people.js";
import { RowEdge, type RowWidths, rowWidthsOf } from "./RowEdge.js";
import { OPEN_LINK_DROP, SessionMap } from "./SessionMap.js";
import { DrillDown, type Selection } from "./SidePanel.js";
import { usePageWheel } from "./scroll.js";
import { applySearchHits, storedOpen } from "./searchOpen.js";
import { layoutSessionGraph, openAtLoad, type SessionGraph } from "./sessionLayout.js";
import { useTheme } from "./ThemeButton.js";

/**
 * The project map (Story 8.7). The sessions are a git graph, one dot each;
 * clicking a session opens its messages as their own git graph (8.2) right below
 * its row, accordion-style: the other sessions stay where they are and the ones
 * below move down. Several sessions can be open; clicking again closes one.
 * Both levels share the same layout engine.
 */

/** Gap between a session row and its opened messages, and below them. */
const OPEN_TOP = OPEN_LINK_DROP - 12;
const OPEN_BOTTOM = 20;
/** Room for the "no messages yet" line of an opened session with none. */
const OPEN_EMPTY = 36;

const GraphActions = createContext<{
  selection: Selection | null;
  openIds: ReadonlySet<string>;
  /** Changes at or above this many lines get the quiet highlight. */
  bigChangeLines: number;
  openSession: (sessionId: string) => void;
  /** Opens the session's card with its Captured work in view (the capture badge). */
  openSessionCard: (sessionId: string) => void;
  openNode: (sessionId: string, messageId: string) => void;
  openContinue: (sessionId: string, messageId: string) => void;
  unfold: (segmentId: string) => void;
  /** Sets the width of the open sessions' message rows (their right edge). */
  resizeRows: (sessionId: string, width: number) => void;
  storeRowWidth: (sessionId: string, width: number) => void;
  /** The person filter (Everyone, You, a teammate); null for everyone. */
  person: PersonFilter;
  people: ReturnType<typeof peopleOf>;
}>({
  selection: null,
  openIds: new Set(),
  bigChangeLines: 300,
  openSession: () => {},
  openSessionCard: () => {},
  openNode: () => {},
  openContinue: () => {},
  unfold: () => {},
  resizeRows: () => {},
  storeRowWidth: () => {},
  person: null,
  people: peopleOf({ sessions: [] }),
});

/** An opened session: its message graph and where it sits on the canvas. */
type Opening = { session: ViewSession; git: GitLayout; top: number; left: number };
type ProjectData = {
  model: LineageViewModel;
  graph: SessionGraph;
  openings: Opening[];
  /** Message ids to highlight, by session (Story 8.14). */
  highlights: Map<string, Set<string>>;
  /** Sessions whose title or status matched; their row is marked. */
  sessionHits: ReadonlySet<string>;
  /** The hit the user is on (or a pasted hash), if any. */
  activeHit: { sessionId: string; messageId: string | null } | null;
};

type ProjectFlowNode = Node<ProjectData, "project">;
type MapFlowNode = ProjectFlowNode;

function SessionMessages({
  session,
  git,
  highlights,
  activeHitId,
}: {
  session: ViewSession;
  git: GitLayout;
  highlights: ReadonlySet<string> | undefined;
  activeHitId: string | null;
}) {
  const { selection, bigChangeLines, openNode, unfold, resizeRows, storeRowWidth, person, people } =
    useContext(GraphActions);
  const own = selection?.sessionId === session.sessionId;
  if (git.rows.length === 0)
    return <p className="graph-status empty">No messages recorded in this session yet.</p>;
  const dimmed = !people.matches(session, person);
  return (
    <div className={dimmed ? "session-rows is-dimmed" : "session-rows"}>
      <GitGraph
        git={git}
        selectedId={selection?.type === "node" && own ? selection.nodeId : null}
        highlightIds={highlights}
        activeHitId={activeHitId}
        bigChangeLines={bigChangeLines}
        onSelect={(row) => openNode(session.sessionId, row.message.id)}
        onUnfold={unfold}
      />
      <RowEdge
        git={git}
        onResize={(width) => resizeRows(session.sessionId, width)}
        onDone={(width) => storeRowWidth(session.sessionId, width)}
      />
    </div>
  );
}

function ProjectBox({ data }: NodeProps<ProjectFlowNode>) {
  const { openSession, openSessionCard, openNode, openContinue, selection, openIds, person } =
    useContext(GraphActions);
  // The capture badge sits on each session's own row, expanded or folded
  // (Story 15.3): it counts the session's suggested + open items.
  const capture = useMemo(() => captureCounts(data.model.captures), [data.model.captures]);
  return (
    <div className="map-node">
      <SessionMap
        model={data.model}
        graph={data.graph}
        // Only the session itself: a selected message is highlighted on its own row.
        selectedSessionId={selection?.type === "session" ? selection.sessionId : null}
        openIds={openIds}
        highlightSessionIds={data.sessionHits}
        person={person}
        captured={capture}
        onOpen={openSession}
        onOpenCard={openSessionCard}
        onContinue={openContinue}
      />
      <OpenSessions
        openings={data.openings}
        highlights={data.highlights}
        activeHit={data.activeHit}
      />
    </div>
  );
}

/** The viewport's band as a string, so the store re-renders only when it moves a step. */
function bandKey(state: ReactFlowState): string {
  const band = visibleBand(state.transform, state.height);
  return band === null ? "all" : band.join(":");
}

/**
 * The open sessions' messages, only those near the viewport. Its own component,
 * so a pan re-renders these rows and never the session list above them.
 */
function OpenSessions({
  openings,
  highlights,
  activeHit,
}: Pick<ProjectData, "openings" | "highlights" | "activeHit">) {
  const key = useStore(bandKey);
  const band = key === "all" ? null : (key.split(":").map(Number) as [number, number]);
  return openings
    .filter((opening) => inBand(opening.top, opening.git.height, band))
    .map((opening) => (
      <div
        key={opening.session.sessionId}
        className="session-open"
        style={{ top: opening.top, left: opening.left }}
      >
        <SessionMessages
          session={opening.session}
          git={opening.git}
          highlights={highlights.get(opening.session.sessionId)}
          activeHitId={
            activeHit?.sessionId === opening.session.sessionId ? activeHit.messageId : null
          }
        />
      </div>
    ));
}

const nodeTypes: NodeTypes = {
  project: ProjectBox,
};

/**
 * The place a URL asks for. `#s=<sessionId>&m=<messageId>` (Story 8.8:
 * `cogit blame` prints such a URL) opens that session and message;
 * `#focus=head` is what the project switcher uses (8.12) — the newest message,
 * i.e. where the work left off. The session opens and the message's drill-down
 * is shown; a message id the record no longer holds opens the session.
 */
type Target = { sessionId: string; messageId?: string; quiet?: boolean };

/** "Left off here": the newest session and its newest message. */
function headTarget(model: LineageViewModel, quiet: boolean): Target | null {
  const head = headOf(model);
  if (head === null) return null;
  const target: Target =
    head.messageId === null
      ? { sessionId: head.sessionId }
      : { sessionId: head.sessionId, messageId: head.messageId };
  return quiet ? { ...target, quiet } : target;
}

/**
 * With no hash the map opens where the work left off: the newest session
 * unfolds and the view centres on its newest message, without opening the
 * side panel (`quiet`).
 */
function readTarget(model: LineageViewModel): Target | null {
  if (typeof window === "undefined") return null;
  const params = new URLSearchParams(window.location.hash.replace(/^#/, ""));
  if (!params.has("focus") && !params.has("s")) return headTarget(model, true);
  if (params.get("focus") === "head") {
    const head = headOf(model);
    if (head === null) return null;
    return head.messageId === null
      ? { sessionId: head.sessionId }
      : { sessionId: head.sessionId, messageId: head.messageId };
  }
  const sessionId = params.get("s");
  if (sessionId === null || sessionId === "") return null;
  const session = findSession(model, sessionId);
  if (session === undefined) return null;
  const messageId = params.get("m");
  if (messageId !== null && session.messages.some((message) => message.id === messageId))
    return { sessionId, messageId };
  return { sessionId };
}

function sameSet(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {
  return a.size === b.size && [...a].every((id) => b.has(id));
}

function findSession(model: LineageViewModel, id: string): ViewSession | undefined {
  return model.sessions.find((session) => session.sessionId === id);
}

function Flow({ model, search }: { model: LineageViewModel; search: MapSearchState }) {
  // One scroller (Story 9.2): a wheel outside the map moves the map.
  usePageWheel();
  // Read once: a live data swap must not move the page back to the hash target.
  const [initial] = useState(() => readTarget(model));
  useEffect(() => {
    // Land on the map, not on the page header, when it opens at a message.
    if (initial?.messageId !== undefined)
      document.querySelector(".lineage-map")?.scrollIntoView({ block: "start" });
  }, [initial]);
  const [openIds, setOpenIds] = useState<ReadonlySet<string>>(() =>
    openAtLoad(model, model.openSessions, initial),
  );
  /** Open sessions only the search opened: closed again when they stop matching, never stored. */
  const [searchOpened, setSearchOpened] = useState<ReadonlySet<string>>(() => new Set());
  /** The user took a search-opened session over (a click in it): it stays and is stored. */
  const keep = useCallback((sessionId: string) => {
    setSearchOpened((previous) => {
      if (!previous.has(sessionId)) return previous;
      const next = new Set(previous);
      next.delete(sessionId);
      return next;
    });
  }, []);
  const [selection, setSelection] = useState<Selection | null>(() => {
    if (initial === null || initial.quiet) return null;
    if (initial.messageId === undefined) return { type: "session", sessionId: initial.sessionId };
    return { type: "node", sessionId: initial.sessionId, nodeId: initial.messageId };
  });
  const [unfolded, setUnfolded] = useState<Set<string>>(() => new Set());
  /** Each session's message row width, dragged at the rows' right edge. */
  const [rowWidths, setRowWidths] = useState<RowWidths>(() => rowWidthsOf(model.rowWidths));
  /** Bumped when the stored view opens other sessions than the embedded one did. */
  const [refocus, setRefocus] = useState(0);
  /** Open sessions are stored only once the stored view has been read. */
  const viewLoaded = useRef(false);
  // The embedded view is as of the last build; a reload right after a change
  // can beat the rebuild, so a served page asks for the stored one once.
  useEffect(() => {
    const token = pageToken();
    if (token === null) return;
    void loadMapView(model.project.path, token)
      .then((view) => {
        setRowWidths(rowWidthsOf(view.rowWidths));
        const open = openAtLoad(model, view.open, initial);
        setOpenIds((previous) => {
          if (sameSet(previous, open)) return previous;
          setRefocus((value) => value + 1);
          return open;
        });
      })
      .catch(() => {
        // The embedded view stays; it is at most one change behind.
      })
      .finally(() => {
        viewLoaded.current = true;
      });
    // Once per page: later model swaps carry the view the page itself wrote.
  }, []);
  // Every open or close is stored, so a reload opens the same sessions again.
  useEffect(() => {
    const token = pageToken();
    if (token === null || !viewLoaded.current) return;
    const timer = window.setTimeout(() => {
      const stored = storedOpen({ open: openIds, bySearch: searchOpened });
      void saveOpenSessions(model.project.path, stored, token).catch((err: unknown) => {
        console.warn("cogit: could not save the open sessions", err);
      });
    }, 300);
    return () => window.clearTimeout(timer);
  }, [openIds, searchOpened, model.project.path]);
  const resizeRows = useCallback((sessionId: string, width: number) => {
    setRowWidths((previous) => {
      // Back at the default (double-click): forget the session.
      const { [sessionId]: _, ...rest } = previous;
      return width === ROW_WIDTH ? rest : { ...rest, [sessionId]: width };
    });
  }, []);
  /** A drag ended: store the width in the project's local state. */
  const storeRowWidth = useCallback(
    (sessionId: string, width: number) => {
      // Over `file://` there is no server; the width lasts for this open page.
      const token = pageToken();
      if (token === null) return;
      void saveRowWidth(
        model.project.path,
        sessionId,
        width === ROW_WIDTH ? null : width,
        token,
      ).catch((err: unknown) => {
        console.warn("cogit: could not save the row width", err);
      });
    },
    [model.project.path],
  );
  const [openAll, setOpenAll] = useState(false);
  const [showOutline, setShowOutline] = useState(true);
  // The files and outline views share the left column; only one shows.
  const [showFiles, setShowFiles] = useState(false);
  // The file a message's card asked the history of; the Files view opens on it.
  const [filesFocus, setFilesFocus] = useState<FilesFocus | null>(null);
  const [showCaptures, setShowCaptures] = useState(false);
  const [person, setPerson] = useState<PersonFilter>(null);
  const people = useMemo(() => peopleOf(model), [model]);
  const personOptions = useMemo(() => people.options(), [people]);
  const { expanded: fullscreen, toggle: toggleFullscreen } = useFullscreen();
  const bigChangeLines = model.settings?.bigChangeLines ?? 300;
  // The Captured button is only there while the setting is on and something
  // waits or is open; a store of only done items has no button and no empty list.
  const capturesVisible = capturesButtonVisible(model.captures, model.settings?.captures);
  const [focusedId, setFocusedId] = useState<string | null>(() => {
    if (initial === null) return null;
    if (initial.messageId === undefined) return `session:${initial.sessionId}`;
    return `node:session:${initial.sessionId}:${initial.messageId}`;
  });

  const head = headOf(model);

  // Search (Story 8.14): highlight matching messages, open their sessions and
  // centre the active hit. A pasted hash resolves to one message and shows it
  // like `show`; a session-level hit centres the session's row instead.
  const hashHit = search.hash?.kind === "ok" ? search.hash : null;
  // A live data swap can shrink the hit list under the cursor; clamp instead of
  // pointing at a row that is no longer there.
  const activeHit = search.hits[Math.min(search.active, search.hits.length - 1)] ?? null;
  const searchTarget = useMemo(
    () =>
      hashHit !== null
        ? { sessionId: hashHit.sessionId, messageId: hashHit.messageId }
        : activeHit === null
          ? null
          : { sessionId: activeHit.sessionId, messageId: activeHit.messageId },
    [hashHit?.sessionId, hashHit?.messageId, activeHit?.sessionId, activeHit?.messageId],
  );
  // The outline follows the hit the search is on, like a click on the map.
  useEffect(() => {
    if (searchTarget === null) return;
    setFocusedId(
      searchTarget.messageId === null
        ? `session:${searchTarget.sessionId}`
        : `node:session:${searchTarget.sessionId}:${searchTarget.messageId}`,
    );
  }, [searchTarget]);
  const highlights = useMemo(() => hitMessageIds(search.hits), [search.hits]);
  const sessionHits = useMemo(
    () => new Set(search.hits.flatMap((hit) => (hit.messageId === null ? [hit.sessionId] : []))),
    [search.hits],
  );
  const hitSessions = useMemo(() => hitSessionIds(search.hits), [search.hits]);

  // Opening the accordion for every match is what makes the highlights visible;
  // a session the search opened closes again once it no longer matches. Read
  // through refs so a user's own open or close does not rerun the search's.
  const openRef = useRef(openIds);
  openRef.current = openIds;
  const searchOpenedRef = useRef(searchOpened);
  searchOpenedRef.current = searchOpened;
  useEffect(() => {
    const next = applySearchHits(
      { open: openRef.current, bySearch: searchOpenedRef.current },
      hitSessions,
    );
    if (!sameSet(next.open, openRef.current)) setOpenIds(next.open);
    if (!sameSet(next.bySearch, searchOpenedRef.current)) setSearchOpened(next.bySearch);
  }, [hitSessions]);

  /** The open drill-down's message, if any. */
  const target = selection?.type === "node" ? selection : null;

  const sessionsById = useMemo(
    () => new Map(model.sessions.map((session) => [session.sessionId, session])),
    [model],
  );

  /** Message graph of every open session. */
  const messageGits = useMemo(() => {
    const out = new Map<string, GitLayout>();
    for (const sessionId of openIds) {
      const session = sessionsById.get(sessionId);
      if (!session) continue;
      let options = {
        unfolded,
        openAll,
        rowWidth: rowWidths[sessionId] ?? ROW_WIDTH,
        headId: head?.sessionId === sessionId ? head.messageId : null,
      };
      // A search hit inside a folded branch must be visible to be highlighted,
      // so every branch that holds a hit of this session opens.
      const hitIds = highlights.get(sessionId);
      if (hitIds !== undefined && hitIds.size > 0) {
        const folded = layoutGitGraph(session.messages, options);
        const extra = folded.segments
          .filter((segment) => segment.ids.some((id) => hitIds.has(id)))
          .map((segment) => segment.id);
        if (extra.length > 0) options = { ...options, unfolded: new Set([...unfolded, ...extra]) };
      }
      let layout = layoutGitGraph(session.messages, options);
      const targetId = target?.sessionId === sessionId ? target.nodeId : null;
      if (
        targetId !== null &&
        !layout.rows.some((row) => row.kind === "message" && row.message.id === targetId)
      ) {
        // A deep link (`blame` prints one) may point inside a folded branch: open it
        // rather than letting the page land on a row the user cannot see.
        const segment = layout.segments.find((candidate) => candidate.ids.includes(targetId));
        if (segment !== undefined)
          layout = layoutGitGraph(session.messages, {
            ...options,
            unfolded: new Set([...unfolded, segment.id]),
          });
      }
      out.set(sessionId, layout);
    }
    return out;
  }, [
    sessionsById,
    openIds,
    unfolded,
    openAll,
    rowWidths,
    highlights,
    head?.sessionId,
    head?.messageId,
    target?.sessionId,
    target?.nodeId,
  ]);

  /** Room under each open session's row for its messages. */
  const spaceAfter = useMemo(() => {
    const out = new Map<string, number>();
    for (const [sessionId, git] of messageGits)
      out.set(
        sessionId,
        OPEN_TOP + (git.rows.length === 0 ? OPEN_EMPTY : git.height) + OPEN_BOTTOM,
      );
    return out;
  }, [messageGits]);

  const sessionGraph = useMemo(() => layoutSessionGraph(model, spaceAfter), [model, spaceAfter]);

  const openings = useMemo(() => {
    const out: Opening[] = [];
    for (const row of sessionGraph.git.rows) {
      if (row.kind !== "message" || row.spaceTop === undefined) continue;
      const session = sessionGraph.sessions.get(row.message.id);
      const git = messageGits.get(row.message.id);
      if (!session || !git) continue;
      out.push({
        session,
        git,
        top: row.spaceTop + OPEN_TOP,
        left: sessionGraph.git.graphWidth + 8,
      });
    }
    return out;
  }, [sessionGraph, messageGits]);

  /** Canvas point of a message in an open session, or null when it is not drawn. */
  const pointOf = useCallback(
    (sessionId: string, messageId: string | undefined) => {
      if (messageId === undefined) return null;
      const opening = openings.find((candidate) => candidate.session.sessionId === sessionId);
      const row = opening?.git.rows.find(
        (candidate) => candidate.kind === "message" && candidate.message.id === messageId,
      );
      if (!opening || !row) return null;
      // Frame the whole row (lanes and text), not only its dot.
      return {
        x: opening.left + opening.git.graphWidth / 2,
        y: opening.top + row.y,
        left: opening.left,
        right: opening.left + opening.git.width,
      };
    },
    [openings],
  );

  /** A search hit's point: its message, or the session's row for a session hit. */
  const pointOfHit = useCallback(
    (hit: { sessionId: string; messageId: string | null }) => {
      if (hit.messageId !== null) return pointOf(hit.sessionId, hit.messageId);
      const row = sessionGraph.git.rows.find(
        (candidate) => candidate.kind === "message" && candidate.message.id === hit.sessionId,
      );
      if (row === undefined) return null;
      // Centre the row's text, not only its lanes: the same span a message row
      // reports, so a session hit and a captured row land where the reader looks.
      const left = sessionGraph.git.graphWidth + 8;
      const width = sessionGraph.git.rowWidth;
      return { x: left + width / 2, y: row.y, left, right: left + width };
    },
    [pointOf, sessionGraph],
  );

  /** Where the view centres on load: the target message, else the whole map. */
  const focusRow = useMemo(
    () => (initial === null ? null : pointOf(initial.sessionId, initial.messageId)),
    [initial, pointOf],
  );

  /** "Left off here" button: a request to centre on HEAD, re-sent on every click. */
  const [jumps, setJumps] = useState(0);
  /** "Fold all": a request to frame the whole map again once everything closed. */
  const [fits, setFits] = useState(0);
  const leftOff = useMemo(() => headTarget(model, true), [model]);
  const jump = useMemo(
    () =>
      jumps === 0 || leftOff === null
        ? null
        : { key: jumps, point: pointOf(leftOff.sessionId, leftOff.messageId) },
    [jumps, leftOff, pointOf],
  );

  /**
   * A search move: the step counter changes on every keystroke and on ↑/↓, and
   * the point may only resolve once the hit's session has opened, so the canvas
   * waits for both.
   */
  const searchPoint = useMemo(
    () => (searchTarget === null ? null : pointOfHit(searchTarget)),
    [searchTarget, pointOfHit],
  );
  const searchJump = useMemo(
    () =>
      search.step === 0 || searchPoint === null ? null : { key: search.step, point: searchPoint },
    [search.step, searchPoint],
  );

  const ensureOpen = useCallback(
    (sessionId: string) => {
      keep(sessionId);
      setOpenIds((previous) =>
        previous.has(sessionId) ? previous : new Set([...previous, sessionId]),
      );
    },
    [keep],
  );
  /** A request to bring a session card's "Captured work" into view (Story 15.3). */
  const [revealCaptures, setRevealCaptures] = useState(0);
  const toggleSession = useCallback(
    (sessionId: string) => {
      keep(sessionId);
      setRevealCaptures(0);
      if (openIds.has(sessionId)) {
        const next = new Set(openIds);
        next.delete(sessionId);
        setOpenIds(next);
        setSelection((previous) => (previous?.sessionId === sessionId ? null : previous));
        return;
      }
      // Opening only unfolds the accordion; the side panel waits for a message click
      // so it does not cover the messages that just opened.
      setOpenIds(new Set([...openIds, sessionId]));
      setFocusedId(`session:${sessionId}`);
    },
    [openIds, keep],
  );
  /**
   * The capture badge (Story 15.3): opens the session card without toggling the
   * row, and asks the panel to show the Captured work section.
   */
  const openSessionCard = useCallback(
    (sessionId: string) => {
      keep(sessionId);
      setFocusedId(`session:${sessionId}`);
      setSelection({ type: "session", sessionId });
      setRevealCaptures((value) => value + 1);
      // Bring the session's row into view, the way a search hit does.
      setSessionTarget(sessionId);
      setSessionJumps((value) => value + 1);
    },
    [keep],
  );
  const openNode = useCallback(
    (sessionId: string, messageId: string) => {
      ensureOpen(sessionId);
      setRevealCaptures(0);
      setFocusedId(`node:session:${sessionId}:${messageId}`);
      setSelection({ type: "node", sessionId, nodeId: messageId });
    },
    [ensureOpen],
  );
  const openContinue = useCallback(
    (sessionId: string, messageId: string) => openNode(sessionId, messageId),
    [openNode],
  );

  // A pasted hash opens the message the way clicking it would (`show` for the map).
  useEffect(() => {
    if (hashHit === null) return;
    openNode(hashHit.sessionId, hashHit.messageId);
  }, [hashHit?.sessionId, hashHit?.messageId, openNode]);
  // An inbox row (Story 11.1) links to a message in this same page, so the hash
  // changes without a reload; open it the way opening the page there would.
  useEffect(() => {
    function onHashChange(): void {
      const target = readTarget(model);
      if (target === null) return;
      ensureOpen(target.sessionId);
      if (target.messageId !== undefined) openNode(target.sessionId, target.messageId);
      document.querySelector(".lineage-map")?.scrollIntoView({ block: "start" });
    }
    window.addEventListener("hashchange", onHashChange);
    return () => window.removeEventListener("hashchange", onHashChange);
  }, [model, ensureOpen, openNode]);
  const unfold = useCallback((segmentId: string) => {
    setUnfolded((previous) => {
      const next = new Set(previous);
      next.add(segmentId);
      return next;
    });
  }, []);
  const selectFromOutline = useCallback(
    (target: OutlineTarget) => {
      setRevealCaptures(0);
      setFocusedId(target.focusId);
      if (target.sessionId !== null) ensureOpen(target.sessionId);
      setSelection(target.selection);
    },
    [ensureOpen],
  );

  // A changed file in a message's card opens that file's history in the Files
  // view: every message that touched it, the map's side of `cogit why <path>`.
  const openFileHistory = useCallback((path: string) => {
    setShowFiles(true);
    setShowOutline(false);
    setShowCaptures(false);
    setFilesFocus((current) => ({ path, key: (current?.key ?? 0) + 1 }));
  }, []);
  // A file row (8.15) opens its message exactly like a dot click, and the view
  // moves to it once the session's layout is in place.
  const [fileJumps, setFileJumps] = useState(0);
  const selectFromFiles = useCallback(
    (target: FilesTarget) => {
      openNode(target.sessionId, target.messageId);
      setFileJumps((value) => value + 1);
    },
    [openNode],
  );
  const filePoint = useMemo(
    () => (target === null ? null : pointOf(target.sessionId, target.nodeId)),
    // `pointOf` changes when an opened session's layout changes, which is how a
    // click that opens a session resolves its point on the next render.
    [target?.sessionId, target?.nodeId, pointOf],
  );
  const fileJump = useMemo(
    () => (fileJumps === 0 || filePoint === null ? null : { key: fileJumps, point: filePoint }),
    [fileJumps, filePoint],
  );
  // A captured row's click (Story 15.3): centre the project graph on that
  // session's row, so the card that opened on the side has a place on the map.
  const [sessionJumps, setSessionJumps] = useState(0);
  const [sessionTarget, setSessionTarget] = useState<string | null>(null);
  const sessionPoint = useMemo(
    () =>
      sessionTarget === null ? null : pointOfHit({ sessionId: sessionTarget, messageId: null }),
    [sessionTarget, pointOfHit],
  );
  const sessionJump = useMemo(
    () =>
      sessionJumps === 0 || sessionPoint === null
        ? null
        : { key: sessionJumps, point: sessionPoint },
    [sessionJumps, sessionPoint],
  );

  const actions = useMemo(
    () => ({
      selection,
      openIds,
      bigChangeLines,
      openSession: toggleSession,
      openSessionCard,
      openNode,
      openContinue,
      unfold,
      resizeRows,
      storeRowWidth,
      person,
      people,
    }),
    [
      selection,
      openIds,
      bigChangeLines,
      toggleSession,
      openSessionCard,
      openNode,
      openContinue,
      unfold,
      resizeRows,
      storeRowWidth,
      person,
      people,
    ],
  );

  const nodes = useMemo<MapFlowNode[]>(() => {
    const width = Math.max(
      sessionGraph.git.width,
      ...openings.map((opening) => opening.left + opening.git.width),
    );
    return [
      {
        id: "project",
        type: "project",
        position: { x: 0, y: 0 },
        width,
        height: sessionGraph.git.height,
        style: { width, height: sessionGraph.git.height },
        draggable: false,
        connectable: false,
        selectable: false,
        data: {
          model,
          graph: sessionGraph,
          openings,
          highlights,
          sessionHits,
          activeHit: searchTarget,
        },
      },
    ];
  }, [model, sessionGraph, openings, highlights, sessionHits, searchTarget]);

  return (
    <GraphActions.Provider value={actions}>
      <div className={fullscreen ? "map-shell is-expanded" : "map-shell"}>
        <div className="map-toolbar">
          <span className="map-title">
            {`${sessionGraph.git.rows.length} session${
              sessionGraph.git.rows.length === 1 ? "" : "s"
            }`}
          </span>
          {leftOff ? (
            <button
              type="button"
              className="outline-button"
              title="Open the newest session and go to its newest message"
              onClick={() => {
                ensureOpen(leftOff.sessionId);
                setJumps((value) => value + 1);
                document.querySelector(".lineage-map")?.scrollIntoView({ block: "start" });
              }}
            >
              ↧ Left off here
            </button>
          ) : null}
          <button
            type="button"
            className="outline-button"
            aria-pressed={openAll}
            title={
              openAll
                ? "Close every session and fold long branches again"
                : "Open every session and every folded branch"
            }
            onClick={() => {
              // "All" means the whole map: every session opens (or closes), not
              // only the folded branches of the sessions already open.
              setOpenIds(openAll ? new Set() : new Set(sessionGraph.sessions.keys()));
              setSearchOpened(new Set());
              if (openAll) setFits((value) => value + 1);
              setOpenAll((value) => !value);
              setUnfolded(new Set());
            }}
          >
            {openAll ? "Fold all" : "Unfold all"}
          </button>
          {personOptions.length > 0 ? (
            <select
              className="person-filter"
              aria-label="Whose sessions"
              title="Fade the other people's sessions; the lines between them stay"
              value={valueOf(person)}
              onChange={(event) => setPerson(filterOf(event.target.value))}
            >
              {personOptions.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          ) : null}
          <button
            type="button"
            className="outline-button"
            aria-pressed={fullscreen}
            onClick={toggleFullscreen}
          >
            {fullscreen ? "Exit full screen" : "Full screen"}
          </button>
          <button
            type="button"
            className="outline-button"
            aria-pressed={showOutline}
            onClick={() => {
              setShowOutline((value) => !value);
              setShowFiles(false);
              setShowCaptures(false);
            }}
          >
            {showOutline ? "Hide outline" : "Show outline"}
          </button>
          <button
            type="button"
            className="outline-button"
            aria-pressed={showFiles}
            title="Which conversations touched which file"
            onClick={() => {
              setShowFiles((value) => !value);
              setShowOutline(false);
              setShowCaptures(false);
            }}
          >
            {showFiles ? "Hide files" : "Files"}
          </button>
          {capturesVisible ? (
            <button
              type="button"
              className="outline-button capture-button"
              aria-pressed={showCaptures}
              title="Tasks: what your sessions left undone — cogit drafts, you decide"
              onClick={() => {
                setShowCaptures((value) => !value);
                setShowFiles(false);
                setShowOutline(false);
              }}
            >
              {showCaptures ? "Hide tasks" : "Tasks"}
            </button>
          ) : null}
        </div>
        <div className="graph-wrap">
          {showCaptures ? (
            <CapturesView
              captures={model.captures}
              sessions={model.sessions}
              dir={model.project.path}
              onSelectSession={openSessionCard}
              onClose={() => setShowCaptures(false)}
            />
          ) : showFiles ? (
            <FilesView
              files={model.files}
              sessions={model.sessions}
              active={
                selection?.type === "node"
                  ? { sessionId: selection.sessionId, messageId: selection.nodeId }
                  : null
              }
              focus={filesFocus}
              onSelect={selectFromFiles}
              onClose={() => setShowFiles(false)}
            />
          ) : showOutline ? (
            <Outline
              model={model}
              activeId={focusedId}
              onSelect={selectFromOutline}
              onClose={() => setShowOutline(false)}
            />
          ) : null}
          <div className="graph-canvas">
            {sessionGraph.git.rows.length === 0 ? (
              <p className="graph-status empty">
                {model.recordDownloadFailed === true
                  ? "Your team's session records could not be downloaded. Check your connection and run cogit open again."
                  : "No sessions recorded yet. They appear here as you work with Claude Code."}
              </p>
            ) : (
              <MapCanvas
                nodes={nodes}
                focusRow={focusRow}
                jump={jump}
                searchJump={searchJump}
                fileJump={fileJump}
                sessionJump={sessionJump}
                fit={fits}
                refocus={refocus}
              />
            )}
          </div>
          {/* Beside the map, not over it, so the rows it would cover stay readable;
              a narrow window lays it over the map (styles.css). */}
          <DrillDown
            model={model}
            selection={selection}
            captureReveal={revealCaptures}
            onClose={() => {
              setSelection(null);
              setRevealCaptures(0);
            }}
            onNavigate={selectFromOutline}
            onOpenFileHistory={openFileHistory}
            bigChangeLines={bigChangeLines}
          />
        </div>
      </div>
    </GraphActions.Provider>
  );
}

/**
 * One React Flow canvas for the whole map. It frames the map once on load (or
 * centres a deep-linked message); opening or closing a session and live data
 * swaps leave the viewport where the user put it.
 */
function MapCanvas({
  nodes,
  focusRow,
  jump,
  searchJump,
  fileJump,
  sessionJump,
  fit,
  refocus,
}: {
  nodes: MapFlowNode[];
  /** Point to centre on at load; null fits the whole graph. */
  focusRow: MapPoint | null;
  /** A user request to centre on a point; a new `key` moves the view again. */
  jump: { key: number; point: MapPoint | null } | null;
  /** A search move: the active hit or a pasted hash (Story 8.14). */
  searchJump: { key: number; point: { x: number; y: number } } | null;
  /** A files-view click: the message it opened (Story 8.15). */
  fileJump: { key: number; point: { x: number; y: number } } | null;
  /** A captured row's click: the session's row on the project graph. */
  sessionJump: { key: number; point: { x: number; y: number } } | null;
  /** A new value frames the whole map again (after "Fold all"). */
  fit: number;
  /** A new value centres on `focusRow` again: the stored view opened more sessions. */
  refocus: number;
}) {
  const { fitView, setViewport } = useReactFlow();
  const theme = useTheme();

  /** Centres the view on a canvas point; does nothing before the canvas exists. */
  function centre(point: MapPoint): void {
    const canvas = document.querySelector(".react-flow")?.getBoundingClientRect();
    if (!canvas) return;
    void setViewport(centreViewport(point, canvas, 0.9), { duration: 300 });
  }

  useEffect(() => {
    if (fit === 0) return;
    // Wait a frame so React Flow has the smaller, closed map before framing it.
    const timer = window.setTimeout(
      () => void fitView({ padding: 0.12, maxZoom: 1, duration: 300 }),
      50,
    );
    return () => window.clearTimeout(timer);
  }, [fit]);

  const jumpKey = jump?.key ?? 0;
  const jumpPoint = jump?.point ?? null;
  useEffect(() => {
    if (jumpKey === 0 || jumpPoint === null) return;
    centre(jumpPoint);
    // Only a new click moves the view; a live data swap must not.
  }, [jumpKey]);

  // A search step also re-centres when its point only resolves after the hit's
  // session has opened (`searchJump.key` stays the same in that case).
  const searchKey = searchJump?.key ?? 0;
  const searchPoint = searchJump?.point ?? null;
  useEffect(() => {
    if (searchKey === 0 || searchPoint === null) return;
    centre(searchPoint);
  }, [searchKey, searchPoint]);

  const fileKey = fileJump?.key ?? 0;
  const filePoint = fileJump?.point ?? null;
  useEffect(() => {
    if (fileKey === 0 || filePoint === null) return;
    centre(filePoint);
  }, [fileKey, filePoint]);

  const sessionKey = sessionJump?.key ?? 0;
  const sessionPt = sessionJump?.point ?? null;
  useEffect(() => {
    if (sessionKey === 0 || sessionPt === null) return;
    centre(sessionPt);
  }, [sessionKey, sessionPt]);

  useEffect(() => {
    if (refocus === 0 || focusRow === null) return;
    const canvas = document.querySelector(".react-flow")?.getBoundingClientRect();
    if (canvas) void setViewport(centreViewport(focusRow, canvas, 0.9));
    // Only the stored view arriving moves the view; `focusRow` follows it.
  }, [refocus]);

  useEffect(() => {
    const timer = window.setTimeout(() => {
      const canvas = document.querySelector(".react-flow")?.getBoundingClientRect();
      if (focusRow && canvas) {
        void setViewport(centreViewport(focusRow, canvas, 0.9));
        return;
      }
      void fitView({ padding: 0.12, maxZoom: 1, duration: 200 });
    }, 80);
    return () => window.clearTimeout(timer);
    // Mount only: opening a session or a model swap must not refit.
  }, []);

  return (
    <ReactFlow
      proOptions={{ hideAttribution: true }}
      nodes={nodes}
      edges={[]}
      nodeTypes={nodeTypes}
      fitView
      panOnScroll
      minZoom={0.05}
      maxZoom={2}
      nodesDraggable={false}
      nodesConnectable={false}
      elementsSelectable={false}
      colorMode={theme}
    >
      <Controls showInteractive={false} />
    </ReactFlow>
  );
}

/** The project map: sessions at the top, a session's messages in place. */
export function Graph({ model, search }: { model: LineageViewModel; search: MapSearchState }) {
  return (
    <section className="lineage-map" aria-label="Project lineage graph">
      <ReactFlowProvider>
        <Flow model={model} search={search} />
      </ReactFlowProvider>
    </section>
  );
}