fabro/apps/fabro-web/app/hooks/use-annotated-run-graph-svg.ts
fabro-sh-0530[bot] b196a97ac4
Introduce approved effect hooks and migrate direct useEffect calls (#425)
## Summary

Implements the React Effects Policy by creating the approved hook
surface in `hooks/effects.ts` and migrating a broad set of direct
`useEffect` calls across the codebase to either purpose-named hooks or
non-effect patterns.

### Plan Summary

- Add `hooks/effects.ts` exporting `useMountEffect`, `useInterval`,
`useTimeout`, `useDebouncedValue`, `useWindowEvent`, `useDocumentEvent`,
`useDocumentTitle`, `useMediaQuery`, `useLocationHash`, and
`useResizeObserver`
- Extract large imperative effects into purpose-named hooks:
`useTerminalSession`, `useFloatingTooltipMeasurements`,
`useAnnotatedRunGraphSvg`, `useInstallEffects`, and others
- Move install session fetch from a component effect into a SWR query
(`install-query.ts`)
- Replace `useEffect` + `useState` state-derivation patterns with
render-time computation or ref callbacks
- Replace `AskFabroLayoutProvider`/`useAskFabroLayout` context with a
prop callback

## What changed and why

**`hooks/effects.ts`** — the new approved primitive surface. All
internal `useEffect` calls here are intentional; the hooks expose the
*external system* they manage rather than leaking `useEffect` to
component code. `useMediaQuery` and `useLocationHash` use
`useSyncExternalStore` instead of effect + state.

**`useTerminalSession`** — the largest extraction. The 130-line
xterm/WebSocket/ResizeObserver setup block moves from
`terminal-view.tsx` into its own hook, which now owns the `terminalRef`,
`fitRef`, and `socketRef` that previously cluttered the component.
`TerminalConnectionError` and `ConnectionStatus` types are exported from
the hook.

**`useFloatingTooltipMeasurements`** — extracts the `useLayoutEffect` +
ResizeObserver + window resize listener out of `FloatingTooltip`. The
`FloatingTooltipSize` type moves with it so consumers don't need to
import from the component.

**`useInstallSessionQuery` + `useInstallEffects`** — the install session
fetch moves from a component effect to SWR (`install-query.ts`). The
three remaining install effects (token URL scrubbing, GitHub error URL
scrubbing, health-poll restart) move into
`hooks/use-install-effects.ts`. The root-redirect effect is replaced
with a render-time `<Navigate>` gate. The `SessionState` discriminant
now carries `token` so stale query results can be discarded without an
effect chain.

**`SelectionCheckbox`** — `useEffect` setting `input.indeterminate` is
replaced with a ref callback, which runs synchronously after the node is
attached and avoids a stale-frame flash.

**`event-debug.tsx`** — the manual `window.addEventListener("keydown",
...)` pattern is replaced with `useWindowEvent`, removing the
`react-doctor-disable` suppression comments.

**`run-waterfall.tsx`** — the local `useTickingNow` is deleted;
`RunWaterfall` now calls the shared `useTickingNow` from `lib/time` with
the new `active` parameter signature.

**`toast.test.tsx`** — `useEffect(() => onReady?.(api), ...)` in the
test helper is replaced with a direct call during render, which is valid
because `onReady` has no side effects that React cares about.

**`AskFabroSidebar`** — `setIsResizing` from the layout context is
replaced with an `onResizeActiveChange` prop, removing the
`useAskFabroLayout` call and the hidden context coupling from the
sidebar.


### Fabro Details

<details>
<summary>Ran 3 stages in 114m 5s for $95.71</summary>

| Stage | Duration | Cost | Retries |
|---|---|---|---|
| start | 0s | – | 0 |
| work | 103m 3s | $80.42 | 0 |
| audit | 10m 19s | $15.29 | 0 |
| **Total** | **114m 5s** | **$95.71** | **0** |

</details>

<details>
<summary>Ran <code>Goal.fabro</code> (4 nodes and 5 edges)</summary>

```dot
digraph Goal {
    graph [
        goal="Complete the user-provided goal",
        rankdir=LR,
        max_node_visits=30
    ]

    start [shape=Mdiamond, label="Start"]
    exit  [shape=Msquare, label="Exit"]

    work [
        label="Work",
        thread_id="goal",
        fidelity="full",
        max_visits=12,
        model="gpt-55",
        reasoning_effort="xhigh",
        prompt="@prompts/continue.md"
    ]

    audit [
        label="Completion Audit",
        thread_id="goal",
        fidelity="full",
        goal_gate=true,
        retry_target="work",
        output_schema="routing",
        output_retries=2,
        max_visits=12,
        model="gpt-55",
        reasoning_effort="xhigh",
        prompt="@prompts/audit.md"
    ]

    start -> work -> audit

    audit -> exit [label="Done", condition="outcome=succeeded"]
    audit -> work [label="Continue", condition="outcome=failed || preferred_label=Continue"]
    audit -> work [label="No clear verdict"]
}

```

</details>

⚒️ Generated with [Fabro](https://fabro.sh)

---------

Co-authored-by: Fabro <noreply@fabro.sh>
Co-authored-by: Bryan Helmkamp <bryan@brynary.com>
2026-05-27 10:37:29 -04:00

183 lines
6.5 KiB
TypeScript

import { useEffect } from "react";
import { graphTheme } from "../lib/graph-theme";
import {
ACTIVE_STAGE_STATES,
SUCCEEDED_STAGE_STATES,
aggregateGraphNodeStatus,
type Stage,
} from "../lib/stage-sidebar";
const HOVER_OPEN_DELAY_MS = 200;
export interface RunGraphNodeHover {
stage: Stage;
rect: DOMRect;
}
/**
* Synchronizes Graphviz SVG markup with imperative DOM annotations, animation
* nodes, and pointer listeners. Timers and DOM listeners are cleaned up before
* resubscribe and on unmount.
*/
export function useAnnotatedRunGraphSvg({
graphSvg,
innerRef,
onHoverChange,
onStageClick,
stages,
svgRef,
terminalOutcome,
}: {
graphSvg: string | null | undefined;
innerRef: { current: HTMLDivElement | null };
onHoverChange: (hover: RunGraphNodeHover | null) => void;
onStageClick: (stageId: string) => void;
stages: Stage[];
svgRef: { current: SVGSVGElement | null };
terminalOutcome: "succeeded" | "failed" | "dead" | null;
}) {
useEffect(() => {
const inner = innerRef.current;
if (!inner || !graphSvg) return;
inner.innerHTML = graphSvg;
const svg = inner.querySelector("svg");
if (!svg) return;
svgRef.current = svg;
const stageById = new Map<string, Stage>();
for (const stage of stages) stageById.set(stage.id, stage);
const gt = graphTheme;
const aggregated = aggregateGraphNodeStatus(stages);
const runningDotIds = new Set<string>();
const failedDotIds = new Set<string>();
const completedDotIds = new Set<string>();
const dotIdToStageId = new Map<string, string>();
for (const [nodeId, { displayStatus, latestStageId }] of aggregated) {
dotIdToStageId.set(nodeId, latestStageId);
if (ACTIVE_STAGE_STATES.has(displayStatus)) {
runningDotIds.add(nodeId);
} else if (displayStatus === "failed") {
failedDotIds.add(nodeId);
} else if (SUCCEEDED_STAGE_STATES.has(displayStatus)) {
completedDotIds.add(nodeId);
}
}
const ns = "http://www.w3.org/2000/svg";
let openTimer: ReturnType<typeof setTimeout> | null = null;
const clearOpenTimer = () => {
if (openTimer !== null) {
clearTimeout(openTimer);
openTimer = null;
}
};
const listeners: Array<{ target: Element; type: string; listener: EventListener }> = [];
const addListener = (target: Element, type: string, listener: EventListener) => {
target.addEventListener(type, listener);
listeners.push({ target, type, listener });
};
for (const group of svg.querySelectorAll(".node")) {
const nodeId = group.querySelector("title")?.textContent?.trim();
if (!nodeId) continue;
const stageId = dotIdToStageId.get(nodeId);
const stage = stageId ? stageById.get(stageId) : undefined;
if (stageId) {
(group as SVGElement).style.cursor = "pointer";
addListener(group, "click", () => onStageClick(stageId));
}
if (stage) {
addListener(group, "mouseenter", () => {
clearOpenTimer();
const target = group as SVGGElement;
openTimer = setTimeout(() => {
openTimer = null;
onHoverChange({ stage, rect: target.getBoundingClientRect() });
}, HOVER_OPEN_DELAY_MS);
});
addListener(group, "mouseleave", () => {
clearOpenTimer();
onHoverChange(null);
});
}
if (nodeId === "exit" && terminalOutcome) {
const isSuccess = terminalOutcome === "succeeded";
const fill = isSuccess ? gt.completedFill : gt.failedFill;
const border = isSuccess ? gt.completedBorder : gt.failedBorder;
const text = isSuccess ? gt.completedText : gt.failedText;
for (const shape of group.querySelectorAll("ellipse, polygon, path")) {
shape.setAttribute("fill", fill);
shape.setAttribute("stroke", border);
}
for (const t of group.querySelectorAll("text")) {
t.setAttribute("fill", text);
}
} else if (runningDotIds.has(nodeId)) {
for (const shape of group.querySelectorAll("ellipse, polygon, path")) {
shape.setAttribute("fill", gt.runningFill);
shape.setAttribute("stroke", gt.runningBorder);
shape.setAttribute("stroke-width", "2");
const animFill = document.createElementNS(ns, "animate");
animFill.setAttribute("attributeName", "fill");
animFill.setAttribute(
"values",
`${gt.runningFill};${gt.runningPulseFill};${gt.runningFill}`,
);
animFill.setAttribute("dur", "1.5s");
animFill.setAttribute("repeatCount", "indefinite");
shape.appendChild(animFill);
const animStroke = document.createElementNS(ns, "animate");
animStroke.setAttribute("attributeName", "stroke");
animStroke.setAttribute(
"values",
`${gt.runningBorder};${gt.runningPulseStroke};${gt.runningBorder}`,
);
animStroke.setAttribute("dur", "1.5s");
animStroke.setAttribute("repeatCount", "indefinite");
shape.appendChild(animStroke);
const animWidth = document.createElementNS(ns, "animate");
animWidth.setAttribute("attributeName", "stroke-width");
animWidth.setAttribute("values", "2;3.5;2");
animWidth.setAttribute("dur", "1.5s");
animWidth.setAttribute("repeatCount", "indefinite");
shape.appendChild(animWidth);
}
for (const text of group.querySelectorAll("text")) {
text.setAttribute("fill", gt.runningText);
}
} else if (failedDotIds.has(nodeId)) {
for (const shape of group.querySelectorAll("ellipse, polygon, path")) {
shape.setAttribute("fill", gt.failedFill);
shape.setAttribute("stroke", gt.failedBorder);
}
for (const text of group.querySelectorAll("text")) {
text.setAttribute("fill", gt.failedText);
}
} else if (completedDotIds.has(nodeId)) {
for (const shape of group.querySelectorAll("ellipse, polygon, path")) {
shape.setAttribute("fill", gt.completedFill);
shape.setAttribute("stroke", gt.completedBorder);
}
for (const text of group.querySelectorAll("text")) {
text.setAttribute("fill", gt.completedText);
}
}
}
return () => {
clearOpenTimer();
for (const { target, type, listener } of listeners) {
target.removeEventListener(type, listener);
}
onHoverChange(null);
};
}, [graphSvg, innerRef, onHoverChange, onStageClick, stages, svgRef, terminalOutcome]);
}