Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 | 9x 9x 9x 9x 20x 25x 2x 2x 2x 25x 9x 9x 12x 12x 12x 12x 9x 9x 9x 9x 9x 9x 2x 5x 12x 4x 9x 16x 16x 6x 16x 16x 6x 6x 6x 6x 6x 9x 25x 9x 8x 8x 8x 8x 8x 3x 8x 8x 6x 8x 6x 8x 7x 1x 1x 1x 1x 1x 8x 8x 8x 8x 7x 10x 8x 4x 8x 8x 3x 5x 5x 10x 1x 1x | import SiteIcon from "@/components/chat/Citations/SiteIcon";
import { SkeletonLines, StatusBadge, StatusTone } from "@/components/detail";
import {
WebGraphEdge,
WebGraphNode,
WebLinkGraph as WebLinkGraphData,
WebPage,
} from "@/objects/Knowledge";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery } from "@tanstack/react-query";
import {
Background,
BackgroundVariant,
Controls,
Edge,
EdgeProps,
Handle,
MarkerType,
Node,
NodeProps,
Position,
ReactFlow,
ReactFlowProvider,
useInternalNode,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import { ExternalLink, History } from "lucide-react";
import React, { useMemo, useState } from "react";
import { WEB_PAGE_STATUS } from "./webSource";
import { isTreeEdge, layoutLinkGraph } from "./webLinkGraphLayout";
/**
* A website source's stored pages as the network the crawl walked: seeds in
* the middle, one ring per link hop, pages on other sites (read because a
* crawled page cites them) dashed. The pages list says what was stored; this
* says how the crawl got to each page, and what each page leads to.
*/
// ─── Node ─────────────────────────────────────────────────────────────────────
/** Node box width; the circle sits at the top, its label below. */
const NODE_W = 120;
const RADIUS = { seed: 26, page: 20 } as const;
/** The ring round a page is its status, by the same tones its badge uses. */
const RING_CLASS: Record<StatusTone, string> = {
neutral: "border-gray-300 dark:border-gray-500",
muted: "border-gray-300 dark:border-gray-600 opacity-60",
progress: "border-blue-500",
success: "border-green-500",
done: "border-violet-500",
warning: "border-amber-500",
danger: "border-red-500",
};
interface PageNodeData extends Record<string, unknown> {
page: WebGraphNode;
dimmed: boolean;
}
type PageFlowNode = Node<PageNodeData, "page">;
const radiusOf = (page: WebGraphNode) =>
page.is_seed ? RADIUS.seed : RADIUS.page;
export function pageLabel(page: WebGraphNode): string {
if (page.title) return page.title;
try {
const url = new URL(page.url);
const path = url.pathname === "/" ? "" : url.pathname;
return `${page.host}${path}${url.search}`;
} catch {
return page.url;
}
}
const hidden = "!opacity-0 !pointer-events-none !min-w-0 !min-h-0 !size-px";
const PageNode: React.FC<NodeProps<PageFlowNode>> = ({ data, selected }) => {
const { page, dimmed } = data;
const r = radiusOf(page);
const tone = WEB_PAGE_STATUS[page.status] ?? "neutral";
return (
<div
style={{ width: NODE_W }}
className={`flex flex-col items-center gap-1 transition-opacity ${
dimmed ? "opacity-25" : "opacity-100"
}`}
>
<div
style={{ width: r * 2, height: r * 2 }}
className={`relative flex items-center justify-center rounded-full border-2 bg-white dark:bg-gray-800 shadow-sm ${
RING_CLASS[tone]
} ${page.origin === "linked" ? "border-dashed" : ""} ${
selected ? "ring-2 ring-offset-2 ring-gray-900 dark:ring-gray-100 dark:ring-offset-gray-900" : ""
}`}
>
<SiteIcon
hostname={page.host}
className={page.is_seed ? "w-6 h-6" : "w-4 h-4"}
/>
{/* Edges draw centre to centre (LinkEdge); the handles only
satisfy React Flow, which will not draw an edge without them. */}
<Handle type="target" position={Position.Top} className={hidden} />
<Handle type="source" position={Position.Bottom} className={hidden} />
</div>
<span
className={`line-clamp-2 w-full break-words text-center text-[11px] leading-tight ${
page.is_seed
? "font-semibold text-gray-900 dark:text-gray-100"
: "text-gray-600 dark:text-gray-300"
}`}
>
{pageLabel(page)}
</span>
</div>
);
};
// ─── Edge ─────────────────────────────────────────────────────────────────────
interface LinkEdgeData extends Record<string, unknown> {
link: WebGraphEdge;
dimmed: boolean;
}
type LinkFlowEdge = Edge<LinkEdgeData, "link">;
/** Centre of a page's circle, from where React Flow has put its node. */
function circleCentre(
node: ReturnType<typeof useInternalNode>,
): { x: number; y: number; r: number } | null {
const page = (node?.data as PageNodeData | undefined)?.page;
if (!node || !page) return null;
const r = radiusOf(page);
return {
x: node.internals.positionAbsolute.x + NODE_W / 2,
y: node.internals.positionAbsolute.y + r,
r,
};
}
/**
* A link, drawn from circle edge to circle edge along the line between the
* two centres — in a radial layout any fixed handle side would cut across
* the node. The anchor text is its tooltip.
*/
const LinkEdge: React.FC<EdgeProps<LinkFlowEdge>> = ({
source,
target,
data,
markerEnd,
}) => {
const from = circleCentre(useInternalNode(source));
const to = circleCentre(useInternalNode(target));
if (!from || !to || !data) return null;
const dx = to.x - from.x;
const dy = to.y - from.y;
const length = Math.hypot(dx, dy) || 1;
const ux = dx / length;
const uy = dy / length;
const sx = from.x + ux * from.r;
const sy = from.y + uy * from.r;
const tx = to.x - ux * (to.r + 3);
const ty = to.y - uy * (to.r + 3);
const path = `M ${sx},${sy} L ${tx},${ty}`;
const external = data.link.kind === "external";
return (
<g className={data.dimmed ? "opacity-10" : "opacity-100"}>
<path
d={path}
markerEnd={markerEnd}
className={`fill-none ${
external
? "stroke-indigo-400 dark:stroke-indigo-400 [stroke-dasharray:5_4]"
: "stroke-gray-300 dark:stroke-gray-600"
}`}
strokeWidth={1.25}
/>
{/* A wider transparent twin, so the tooltip is reachable. */}
<path d={path} className="fill-none stroke-transparent" strokeWidth={10}>
<title>{data.link.text || "(no anchor text)"}</title>
</path>
</g>
);
};
const nodeTypes = { page: PageNode };
const edgeTypes = { link: LinkEdge };
// Marker colours are SVG attributes, which Tailwind classes cannot reach;
// these are gray-400 and indigo-400, legible on both themes.
const MARKER_COLOUR = { internal: "#9ca3af", external: "#818cf8" } as const;
// ─── Selection panel ──────────────────────────────────────────────────────────
const buttonClass =
"flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-lg border border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors";
const SelectedPage: React.FC<{
page: WebGraphNode;
onHistory?: () => void;
}> = ({ page, onHistory }) => (
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<div className="min-w-0 basis-full sm:basis-0 sm:flex-1">
<div className="truncate text-sm font-medium text-gray-800 dark:text-gray-200">
{pageLabel(page)}
</div>
<div className="truncate text-xs text-gray-400 dark:text-gray-500">
{page.url}
</div>
<div className="text-xs text-gray-500 dark:text-gray-400">
{page.is_seed
? "A starting URL"
: page.depth === null
? "Not reached by a stored link"
: `${page.depth} link${page.depth === 1 ? "" : "s"} from a starting URL`}
{` · linked from ${page.in_links} · links to ${page.out_links} stored page${
page.out_links === 1 ? "" : "s"
}`}
{page.unfollowed_links > 0 &&
` · ${page.unfollowed_links} other link${
page.unfollowed_links === 1 ? "" : "s"
} not stored`}
</div>
</div>
<StatusBadge status={page.status} scale={WEB_PAGE_STATUS} size="xs" />
<a
href={page.url}
target="_blank"
rel="noopener noreferrer"
className={buttonClass}
>
<ExternalLink className="size-3.5" />
Open
</a>
{onHistory && (
<button type="button" onClick={onHistory} className={buttonClass}>
<History className="size-3.5" />
{page.version_count} version{page.version_count === 1 ? "" : "s"}
</button>
)}
</div>
);
// ─── The graph ────────────────────────────────────────────────────────────────
export type LinkGraphMode = "paths" | "all";
/** Which edges a mode draws. `paths` is the crawl's own tree: the link that
* first reached each page. `all` adds every other link between stored
* pages — on a site whose pages all link home, a lot of them. */
export function visibleEdges(
graph: WebLinkGraphData,
mode: LinkGraphMode,
): WebGraphEdge[] {
if (mode === "all") return graph.edges;
const depthOf = Object.fromEntries(graph.nodes.map((n) => [n.id, n.depth]));
return graph.edges.filter(
(e) =>
isTreeEdge(e, depthOf) ||
// Among pages no stored link reaches, whatever joins them.
(depthOf[e.source] === null && depthOf[e.target] === null),
);
}
export function graphSummary(graph: WebLinkGraphData): string {
const seeds = graph.nodes.filter((n) => n.is_seed).length;
const linked = graph.nodes.filter((n) => n.origin === "linked");
const sites = new Set(linked.map((n) => n.host)).size;
const unreached = graph.nodes.filter((n) => n.depth === null).length;
const deepest = Math.max(0, ...graph.nodes.map((n) => n.depth ?? 0));
const parts = [
`${graph.nodes.length} page${graph.nodes.length === 1 ? "" : "s"}`,
`${seeds} starting URL${seeds === 1 ? "" : "s"}`,
`up to ${deepest} link${deepest === 1 ? "" : "s"} deep`,
];
Eif (linked.length)
parts.push(
`${linked.length} linked page${linked.length === 1 ? "" : "s"} on ${sites} other site${
sites === 1 ? "" : "s"
}`,
);
if (unreached) parts.push(`${unreached} not reached by a stored link`);
return parts.join(" · ");
}
const LegendDot: React.FC<{ className: string; label: string }> = ({
className,
label,
}) => (
<span className="inline-flex items-center gap-1.5">
<span
aria-hidden
className={`inline-block size-3 rounded-full border-2 bg-white dark:bg-gray-800 ${className}`}
/>
{label}
</span>
);
export interface WebLinkGraphProps {
knowledgeId: string;
/** The source's pages, to open a selected page's history. Without them
* (a dashboard tile) the selection offers the page itself only. */
pages?: WebPage[];
/** A crawl is running: poll, so the graph grows as it walks. */
running?: boolean;
onOpenHistory?: (page: WebPage) => void;
/** Fill the parent's height and drop the legend — a dashboard tile. */
embedded?: boolean;
initialMode?: LinkGraphMode;
}
const WebLinkGraph: React.FC<WebLinkGraphProps> = ({
knowledgeId,
pages = [],
running = false,
onOpenHistory,
embedded = false,
initialMode = "paths",
}) => {
const { getApiHandler } = useApiHandler();
const api = getApiHandler().knowledge_router;
const [mode, setMode] = useState<LinkGraphMode>(initialMode);
const [selectedId, setSelectedId] = useState<string | null>(null);
const { data: graphData, isLoading } = useQuery<WebLinkGraphData | null>({
queryKey: [QUERY_KEYS.GET.KNOWLEDGE_WEB_GRAPH, knowledgeId],
queryFn: () => api.getWebLinkGraph(knowledgeId),
refetchInterval: running ? 5000 : false,
});
const graph: WebLinkGraphData | null = graphData ?? null;
const edges = useMemo(
() => (graph ? visibleEdges(graph, mode) : []),
[graph, mode],
);
const positions = useMemo(
() => (graph ? layoutLinkGraph(graph.nodes, graph.edges) : {}),
[graph],
);
// Selecting a page lights up the links it sends and receives.
const neighbours = useMemo(() => {
if (!selectedId) return null;
const near = new Set([selectedId]);
for (const e of edges) {
Iif (e.source === selectedId) near.add(e.target);
Eif (e.target === selectedId) near.add(e.source);
}
return near;
}, [edges, selectedId]);
const flowNodes: PageFlowNode[] = useMemo(
() =>
(graph?.nodes ?? []).map((page) => {
const at = positions[page.id] ?? { x: 0, y: 0 };
return {
id: page.id,
type: "page",
position: { x: at.x - NODE_W / 2, y: at.y - radiusOf(page) },
selected: page.id === selectedId,
ariaLabel: `${pageLabel(page)} — ${page.url}`,
data: { page, dimmed: !!neighbours && !neighbours.has(page.id) },
};
}),
[graph, positions, neighbours, selectedId],
);
const flowEdges: LinkFlowEdge[] = useMemo(
() =>
edges.map((link) => ({
id: `${link.source}->${link.target}`,
source: link.source,
target: link.target,
type: "link",
selectable: false,
markerEnd: {
type: MarkerType.ArrowClosed,
width: 14,
height: 14,
color: MARKER_COLOUR[link.kind],
},
data: {
link,
dimmed:
!!selectedId &&
link.source !== selectedId &&
link.target !== selectedId,
},
})),
[edges, selectedId],
);
const selected = graph?.nodes.find((n) => n.id === selectedId) ?? null;
const selectedPage = selected
? pages.find((p) => p.document_id === selected.id)
: undefined;
// Embedded, the tile's own padding frames it; on the page, the section's
// card does and each band pads itself.
const band = embedded ? "py-2" : "px-5 py-3";
if (isLoading) {
return (
<div className={embedded ? "" : "px-5 py-4"}>
<SkeletonLines count={3} />
</div>
);
}
Iif (!graph) {
return (
<p className={`${embedded ? "text-xs" : "px-5 py-4 text-sm"} text-red-500`}>
Could not load the link graph.
</p>
);
}
return (
<div className={embedded ? "flex h-full min-h-0 flex-col" : ""}>
<div
className={`flex flex-wrap items-center gap-x-4 gap-y-2 ${
embedded ? "pb-2" : `${band} border-b border-gray-100 dark:border-gray-700`
}`}
>
<p className="min-w-0 flex-1 text-xs text-gray-500 dark:text-gray-400">
{graphSummary(graph)}
{graph.truncated &&
" · very large: only the pages nearest the starting URLs are drawn"}
</p>
<div
role="group"
aria-label="Links shown"
className="inline-flex rounded-lg border border-gray-200 dark:border-gray-600 p-0.5"
>
{(
[
["paths", "Crawl paths"],
["all", "All links"],
] as const
).map(([value, label]) => (
<button
key={value}
type="button"
aria-pressed={mode === value}
onClick={() => setMode(value)}
className={`px-2.5 py-1 text-xs rounded-md transition-colors ${
mode === value
? "bg-gray-900 text-white dark:bg-gray-100 dark:text-gray-900"
: "text-gray-600 dark:text-gray-300"
}`}
>
{label}
</button>
))}
</div>
</div>
{/* React Flow's own colour mode follows the OS rather than the app's
theme class, so its chrome is themed through its CSS variables. */}
<div
className={`relative ${
embedded
? "min-h-[12rem] flex-1 overflow-hidden rounded-lg border border-gray-100 dark:border-gray-700"
: "h-[26rem] sm:h-[32rem]"
} dark:[--xy-controls-button-background-color:theme(colors.gray.800)] dark:[--xy-controls-button-background-color-hover:theme(colors.gray.700)] dark:[--xy-controls-button-color:theme(colors.gray.300)] dark:[--xy-controls-button-color-hover:theme(colors.gray.100)] dark:[--xy-controls-button-border-color:theme(colors.gray.700)] dark:[--xy-attribution-background-color:transparent]`}
data-testid="web-link-graph"
>
<ReactFlowProvider>
<ReactFlow
nodes={flowNodes}
edges={flowEdges}
nodeTypes={nodeTypes}
edgeTypes={edgeTypes}
nodesConnectable={false}
edgesFocusable={false}
onNodeClick={(_, node) =>
setSelectedId((id) => (id === node.id ? null : node.id))
}
onPaneClick={() => setSelectedId(null)}
fitView
fitViewOptions={{ padding: 0.15 }}
minZoom={0.1}
maxZoom={2}
>
<Background
variant={BackgroundVariant.Dots}
gap={20}
size={1}
className="!bg-gray-50 dark:!bg-gray-900"
/>
<Controls
showInteractive={false}
className="!shadow-none !border !border-gray-200 dark:!border-gray-700 !rounded-lg overflow-hidden"
/>
</ReactFlow>
</ReactFlowProvider>
</div>
{!embedded && (
<div className="flex flex-wrap items-center gap-x-4 gap-y-1.5 px-5 py-2 border-t border-gray-100 dark:border-gray-700 text-[11px] text-gray-500 dark:text-gray-400">
<LegendDot className={RING_CLASS.success} label="Active" />
<LegendDot className={RING_CLASS.muted} label="Gone" />
<LegendDot className={RING_CLASS.warning} label="Blocked" />
<LegendDot className={RING_CLASS.danger} label="Failed" />
<LegendDot
className={`${RING_CLASS.success} border-dashed`}
label="Linked page on another site"
/>
<span className="inline-flex items-center gap-1.5">
<svg aria-hidden width="22" height="6">
<line
x1="0"
y1="3"
x2="22"
y2="3"
className="stroke-indigo-400 [stroke-dasharray:5_4]"
strokeWidth="1.5"
/>
</svg>
Link off-site
</span>
<span>Seeds sit at the centre; each ring is one link further out.</span>
</div>
)}
<div
className={embedded ? "pt-2" : `${band} border-t border-gray-100 dark:border-gray-700`}
>
{selected ? (
<SelectedPage
page={selected}
onHistory={
selectedPage && onOpenHistory
? () => onOpenHistory(selectedPage)
: undefined
}
/>
) : (
<p className="text-xs text-gray-400 dark:text-gray-500 italic">
Select a page to see where it leads, and its history.
</p>
)}
</div>
</div>
);
};
export default WebLinkGraph;
|