Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(explorer): keep small Full Graph relationships readable (#1277)

Wei Tao8b125d647647
diff --git a/explorer/package.json b/explorer/package.json
index 540bf0ca..98a53773 100644
--- a/explorer/package.json
+++ b/explorer/package.json
@@ -9,7 +9,7 @@
"lint": "eslint .",
"preview": "vite preview",
"test:graph-store": "node --test tests/graphStore.multi-edge.test.mjs",
- "test:graph-workspace": "node --import tsx --test tests/markdownContentViewer.test.ts tests/graphSceneState.display.test.ts tests/temporalLifecycle.test.ts tests/deterministicExplorerRendering.test.ts",
+ "test:graph-workspace": "node --import tsx --test tests/markdownContentViewer.test.ts tests/graphSceneState.display.test.ts tests/temporalLifecycle.test.ts tests/deterministicExplorerRendering.test.ts tests/smallGraphLayout.test.ts tests/realtimeGraphAttributes.test.ts",
"test:deterministic-e2e": "node --import tsx --test tests/deterministicExplorerRendering.e2e.ts",
"test:plugin-registry": "node --import tsx --test tests/pluginRegistry.temporal.test.mjs"
},
diff --git a/explorer/src/store/graphStore.ts b/explorer/src/store/graphStore.ts
index 178c5236..d7c42e79 100644
--- a/explorer/src/store/graphStore.ts
+++ b/explorer/src/store/graphStore.ts
@@ -86,6 +86,7 @@ export interface EdgeAttributes {
dominantEdgeType?: string;
representativeWeight?: number;
bundleKind?: "parallel" | "bidirectional" | "community";
+ isSmallGraph?: boolean;
edgeType: string;
diff --git a/explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx b/explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx
index f18a2fe6..a586d2e9 100644
--- a/explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx
+++ b/explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx
@@ -21,7 +21,6 @@ import type Graph from "graphology";
import { batchMergeEdges, batchMergeNodes, graph } from "../../store/graphStore";
import { logEvent } from "../../store/registryStore";
import type { EdgeAttributes, NodeAttributes } from "../../store/graphStore";
-import { curveGroupForPair } from "../../store/edgePairKeys.js";
import { InspectorPanel, MetricChip, SurfaceCard } from "../../ui/primitives";
import { lazy, Suspense } from "react";
import { SigmaSceneAdapter } from "./SigmaSceneAdapter";
@@ -42,6 +41,8 @@ import {
import { explorationEffectsShouldLoad, neighborhoodPanelShouldLoad, temporalOverlayShouldLoad } from "./pluginRegistryPredicates";
import { shouldFetchTemporalBounds, shouldFetchTemporalSnapshot } from "./temporalLifecyclePredicates";
import { createTemporalSnapshotGuards, type TemporalSnapshotResponse } from "./temporalSnapshotGuards";
+import { SMALL_GRAPH_MAX_NODES } from "./smallGraphLayout";
+import { buildRealtimeEdgeAttributes } from "./realtimeGraphAttributes";
import type { LinkPrediction, PathResponse } from "./GraphInspectorPanel";
import type { GraphSceneHandle, GraphSceneRuntime } from "./scene";
import type {
@@ -1056,46 +1057,10 @@ function buildRealtimeNodeAttributes(payload: {
};
}
-function buildRealtimeEdgeAttributes(payload: {
- id: string;
- familyId?: string;
- source_id: string;
- target_id: string;
- type?: string;
- weight?: number;
- properties?: Record<string, unknown>;
-}): EdgeAttributes {
- const properties = payload.properties || {};
- const isInferred = Boolean(properties.inferred);
- const isBidirectional = graph.hasDirectedEdge(payload.target_id, payload.source_id);
- const baseColor = isInferred ? GRAPH_THEME.palette.accent.path : GRAPH_THEME.palette.muted.edgeStructure;
-
- return {
- edgeId: payload.id,
- familyId: payload.familyId || payload.id,
- sourceId: payload.source_id,
- targetId: payload.target_id,
- weight: Number(payload.weight ?? 1),
- edgeType: payload.type || "related_to",
- properties,
- size: 1,
- baseSize: 1,
- color: baseColor,
- baseColor,
- mutedColor: GRAPH_THEME.palette.muted.edgeOverview,
- visualPriority: isInferred ? 0.95 : 0.5,
- isBidirectional,
- edgeFamily: isInferred ? "path" : isBidirectional ? "bidirectional" : "line",
- curveGroup: isBidirectional ? curveGroupForPair(payload.source_id, payload.target_id) : null,
- type: "line",
- edgeVariant: isInferred ? "pathSignal" : isBidirectional ? "bidirectionalCurve" : "directional",
- arrowVisibilityPolicy: isInferred ? "always" : "contextual",
- relationshipStrength: isInferred ? 0.95 : 0.52,
- isParallelPair: false,
- parallelIndex: 0,
- parallelCount: 1,
- familySize: 1,
- };
+function synchronizeRealtimeSmallGraphEdges(isSmallGraph: boolean): void {
+ graph.forEachEdge((edgeId) => {
+ graph.setEdgeAttribute(edgeId, "isSmallGraph", isSmallGraph);
+ });
}
function buildSelectedNodeState(
@@ -1355,6 +1320,7 @@ export function GraphWorkspace({ externalFocusNodeId, externalFocusToken }: Grap
const lastExternalFocusTokenRef = useRef<number | undefined>(undefined);
const pluginRuntimeRef = useRef<GraphSceneRuntime | null>(null);
const appliedGraphSummarySignatureRef = useRef<string | null>(null);
+ const smallGraphModeRef = useRef(false);
const pluginInteractionStateRef = useRef<GraphInteractionState>({
hoveredNodeId: null,
selectedNodeId: "",
@@ -1382,6 +1348,12 @@ export function GraphWorkspace({ externalFocusNodeId, externalFocusToken }: Grap
}
appliedGraphSummarySignatureRef.current = signature;
+ smallGraphModeRef.current = Boolean(
+ graphSummary.layoutReady
+ && !graphSummary.hasCoordinates
+ && graphSummary.nodeCount > 0
+ && graphSummary.nodeCount <= SMALL_GRAPH_MAX_NODES,
+ );
setGraphReady(true);
setGraphVersion((current) => current + 1);
setIsLayoutRunning(!graphSummary.layoutReady);
@@ -1893,18 +1865,26 @@ export function GraphWorkspace({ externalFocusNodeId, externalFocusToken }: Grap
attributes: buildRealtimeNodeAttributes(payload),
},
]);
+ if (graph.order > SMALL_GRAPH_MAX_NODES) {
+ smallGraphModeRef.current = false;
+ }
+ synchronizeRealtimeSmallGraphEdges(smallGraphModeRef.current);
logEvent("add-node", `Added node ${payload.label ?? payload.id}${payload.nodeType ? ` (${payload.nodeType})` : ""} via realtime ws`, { nodeId: payload.id, nodeType: payload.nodeType });
setGraphVersion((current) => current + 1);
sceneRef.current?.getRuntime()?.requestRender();
}
if (eventType === "ADD_EDGE") {
+ const isSmallGraph = smallGraphModeRef.current;
batchMergeEdges([
{
id: String(payload.id),
familyId: payload.familyId ? String(payload.familyId) : String(payload.id),
source: payload.source_id,
target: payload.target_id,
- attributes: buildRealtimeEdgeAttributes(payload),
+ attributes: buildRealtimeEdgeAttributes(payload, {
+ isBidirectional: graph.hasDirectedEdge(payload.target_id, payload.source_id),
+ isSmallGraph,
+ }),
},
]);
logEvent("add-edge", `Added edge ${payload.edgeType ?? payload.id} (${payload.source_id} → ${payload.target_id}) via realtime ws`, { edgeId: payload.id, edgeType: payload.edgeType, source: payload.source_id, target: payload.target_id });
diff --git a/explorer/src/workspaces/GraphWorkspace/graphSceneState.ts b/explorer/src/workspaces/GraphWorkspace/graphSceneState.ts
index 5fa0d766..7e301d06 100644
--- a/explorer/src/workspaces/GraphWorkspace/graphSceneState.ts
+++ b/explorer/src/workspaces/GraphWorkspace/graphSceneState.ts
@@ -1783,6 +1783,7 @@ export function resolveEdgeElementStyle(
const isCommunityBundle = attrs.bundleKind === "community";
const baseSize = Number(attrs.baseSize || attrs.size || 0.9);
const visualPriority = Number(attrs.visualPriority ?? 0);
+ const isSmallGraphEdge = viewMode === "full" && attrs.isSmallGraph === true;
const isFullBridgeEdge = viewMode === "full" && fullEdgeClass === "bridge";
const isFullBackboneEdge = viewMode === "full" && fullEdgeClass === "backbone";
const shouldCurveBridge = isFullBridgeEdge
@@ -1790,11 +1791,13 @@ export function resolveEdgeElementStyle(
const visibilityPolicy = resolveEdgeVisibilityPolicy(theme, viewMode, zoomTier, isCommunityBundle);
const isContextEdge = isContextEdgeState(state);
const isNonCriticalEdge = isNonCriticalEdgeVariant(edgeVariant);
- const belowPriorityThreshold = state === "default"
+ const belowPriorityThreshold = !isSmallGraphEdge && state === "default"
&& visualPriority < Math.max(tierConfig.edgePriorityThreshold, visibilityPolicy.defaultPriorityThreshold)
&& isNonCriticalEdge;
- const hiddenByMutedState = (state === "muted" || state === "inactive") && visibilityPolicy.hideMuted;
- const sampledOut = isNonCriticalEdge
+ const hiddenByMutedState = !isSmallGraphEdge
+ && (state === "muted" || state === "inactive")
+ && visibilityPolicy.hideMuted;
+ const sampledOut = !isSmallGraphEdge && isNonCriticalEdge
&& (
(state === "default" && !isContextEdge && shouldSampleOutBackgroundEdge(visibilityPolicy.backgroundSampleRate, visualPriority, edgeId, sourceId, targetId))
|| (
@@ -1837,11 +1840,14 @@ export function resolveEdgeElementStyle(
? resolveEdgeCurvature(theme, state, edgeVariant, attrs, sourceId, targetId)
: 0;
const baseColor = resolveEdgeColor(theme, zoomTier, state, attrs, attrs.color, fullEdgeClass);
- const lodAlpha = resolveEdgeLodAlpha(theme, viewMode, zoomTier, state, attrs, isCommunityBundle, fullEdgeClass);
+ const resolvedLodAlpha = resolveEdgeLodAlpha(theme, viewMode, zoomTier, state, attrs, isCommunityBundle, fullEdgeClass);
+ const lodAlpha = isSmallGraphEdge
+ ? Math.max(resolvedLodAlpha ?? 1, isContextEdge ? 0.62 : 0.46)
+ : resolvedLodAlpha;
const color = lodAlpha === null ? baseColor : withAlpha(baseColor, lodAlpha);
const rawSize = Math.max(
baseSize * sizeMultiplier * (isCommunityBundle ? theme.grouped.style.edgeSizeScale : 1),
- stateConfig.minSize,
+ isSmallGraphEdge ? Math.max(stateConfig.minSize, 0.9) : stateConfig.minSize,
);
const interactionMaxSize = (fullEdgeClass === "path" || state === "path")
diff --git a/explorer/src/workspaces/GraphWorkspace/realtimeGraphAttributes.ts b/explorer/src/workspaces/GraphWorkspace/realtimeGraphAttributes.ts
new file mode 100644
index 00000000..167c5567
--- /dev/null
+++ b/explorer/src/workspaces/GraphWorkspace/realtimeGraphAttributes.ts
@@ -0,0 +1,50 @@
+import type { EdgeAttributes } from "../../store/graphStore";
+import { curveGroupForPair } from "../../store/edgePairKeys.js";
+import { GRAPH_THEME } from "./graphTheme";
+
+export type RealtimeEdgePayload = {
+ id: string;
+ familyId?: string;
+ source_id: string;
+ target_id: string;
+ type?: string;
+ weight?: number;
+ properties?: Record<string, unknown>;
+};
+
+export function buildRealtimeEdgeAttributes(
+ payload: RealtimeEdgePayload,
+ options: { isBidirectional: boolean; isSmallGraph: boolean },
+): EdgeAttributes {
+ const properties = payload.properties || {};
+ const isInferred = Boolean(properties.inferred);
+ const baseColor = isInferred ? GRAPH_THEME.palette.accent.path : GRAPH_THEME.palette.muted.edgeStructure;
+
+ return {
+ edgeId: payload.id,
+ familyId: payload.familyId || payload.id,
+ sourceId: payload.source_id,
+ targetId: payload.target_id,
+ weight: Number(payload.weight ?? 1),
+ edgeType: payload.type || "related_to",
+ properties,
+ size: 1,
+ baseSize: 1,
+ color: baseColor,
+ baseColor,
+ mutedColor: GRAPH_THEME.palette.muted.edgeOverview,
+ visualPriority: isInferred ? 0.95 : 0.5,
+ isBidirectional: options.isBidirectional,
+ edgeFamily: isInferred ? "path" : options.isBidirectional ? "bidirectional" : "line",
+ curveGroup: options.isBidirectional ? curveGroupForPair(payload.source_id, payload.target_id) : null,
+ type: "line",
+ edgeVariant: isInferred ? "pathSignal" : options.isBidirectional ? "bidirectionalCurve" : "directional",
+ arrowVisibilityPolicy: isInferred ? "always" : "contextual",
+ relationshipStrength: isInferred ? 0.95 : 0.52,
+ isParallelPair: false,
+ parallelIndex: 0,
+ parallelCount: 1,
+ familySize: 1,
+ isSmallGraph: options.isSmallGraph,
+ };
+}
diff --git a/explorer/src/workspaces/GraphWorkspace/smallGraphLayout.ts b/explorer/src/workspaces/GraphWorkspace/smallGraphLayout.ts
new file mode 100644
index 00000000..57135384
--- /dev/null
+++ b/explorer/src/workspaces/GraphWorkspace/smallGraphLayout.ts
@@ -0,0 +1,135 @@
+export const SMALL_GRAPH_MAX_NODES = 48;
+const PROVIDED_COORDINATE_COVERAGE = 0.92;
+const MAX_COMPONENT_RADIUS = 78;
+const COMPONENT_GAP = 48;
+
+type LayoutEdge = {
+ source: string;
+ target: string;
+};
+
+export function shouldUseSmallGraphLayout(nodeCount: number, coordinateCoverage: number): boolean {
+ return nodeCount > 0
+ && nodeCount <= SMALL_GRAPH_MAX_NODES
+ && coordinateCoverage < PROVIDED_COORDINATE_COVERAGE;
+}
+
+export function resolveGraphLayoutDecision(nodeCount: number, coordinateCoverage: number): {
+ useProvidedCoordinates: boolean;
+ useSmallGraphLayout: boolean;
+ layoutReady: boolean;
+} {
+ const useProvidedCoordinates = coordinateCoverage >= PROVIDED_COORDINATE_COVERAGE;
+ const useSmallGraphLayout = shouldUseSmallGraphLayout(nodeCount, coordinateCoverage);
+ return {
+ useProvidedCoordinates,
+ useSmallGraphLayout,
+ layoutReady: useProvidedCoordinates || useSmallGraphLayout,
+ };
+}
+
+export function resolveNodeLayoutPosition(
+ decision: ReturnType<typeof resolveGraphLayoutDecision>,
+ provided: { x: number | null; y: number | null },
+ seeded: { x: number; y: number } | undefined,
+): { x: number; y: number } {
+ if (decision.useProvidedCoordinates) {
+ return { x: provided.x ?? 0, y: provided.y ?? 0 };
+ }
+ if (decision.useSmallGraphLayout) {
+ return { x: seeded?.x ?? 0, y: seeded?.y ?? 0 };
+ }
+ return {
+ x: provided.x ?? seeded?.x ?? 0,
+ y: provided.y ?? seeded?.y ?? 0,
+ };
+}
+
+/**
+ * Produce a compact deterministic layout for small graphs.
+ *
+ * ForceAtlas2 is useful for large connected datasets, but it makes tiny graphs
+ * with several disconnected components look like scattered dots. This layout
+ * keeps each connected component together and packs components into a centered
+ * grid so instance relationships remain legible on first render.
+ */
+export function buildSmallGraphSeedPositions(
+ nodeIds: string[],
+ edges: LayoutEdge[],
+): Map<string, { x: number; y: number }> {
+ const ids = [...new Set(nodeIds)].sort((left, right) => left.localeCompare(right));
+ const adjacency = new Map(ids.map((id) => [id, new Set<string>()]));
+
+ edges.forEach(({ source, target }) => {
+ if (!adjacency.has(source) || !adjacency.has(target) || source === target) {
+ return;
+ }
+ adjacency.get(source)?.add(target);
+ adjacency.get(target)?.add(source);
+ });
+
+ const visited = new Set<string>();
+ const components: string[][] = [];
+ ids.forEach((start) => {
+ if (visited.has(start)) {
+ return;
+ }
+ const component: string[] = [];
+ const queue = [start];
+ visited.add(start);
+ while (queue.length > 0) {
+ const current = queue.shift();
+ if (!current) {
+ continue;
+ }
+ component.push(current);
+ [...(adjacency.get(current) ?? [])]
+ .sort((left, right) => left.localeCompare(right))
+ .forEach((neighbor) => {
+ if (!visited.has(neighbor)) {
+ visited.add(neighbor);
+ queue.push(neighbor);
+ }
+ });
+ }
+ component.sort((left, right) => {
+ const degreeDelta = (adjacency.get(right)?.size ?? 0) - (adjacency.get(left)?.size ?? 0);
+ return degreeDelta || left.localeCompare(right);
+ });
+ components.push(component);
+ });
+
+ components.sort((left, right) => right.length - left.length || left[0].localeCompare(right[0]));
+
+ const columns = Math.max(1, Math.ceil(Math.sqrt(components.length)));
+ const rows = Math.max(1, Math.ceil(components.length / columns));
+ // Adjacent cells must leave room for two maximum-radius components plus a
+ // readable gap. A smaller row height allows valid 12-node components to
+ // overlap vertically.
+ const cellWidth = MAX_COMPONENT_RADIUS * 2 + COMPONENT_GAP;
+ const cellHeight = MAX_COMPONENT_RADIUS * 2 + COMPONENT_GAP;
+ const positions = new Map<string, { x: number; y: number }>();
+
+ components.forEach((component, componentIndex) => {
+ const column = componentIndex % columns;
+ const row = Math.floor(componentIndex / columns);
+ const centerX = (column - (columns - 1) / 2) * cellWidth;
+ const centerY = (row - (rows - 1) / 2) * cellHeight;
+
+ if (component.length === 1) {
+ positions.set(component[0], { x: centerX, y: centerY });
+ return;
+ }
+
+ const radius = Math.min(MAX_COMPONENT_RADIUS, 30 + component.length * 9);
+ component.forEach((nodeId, nodeIndex) => {
+ const angle = -Math.PI / 2 + (nodeIndex * Math.PI * 2) / component.length;
+ positions.set(nodeId, {
+ x: centerX + Math.cos(angle) * radius,
+ y: centerY + Math.sin(angle) * radius,
+ });
+ });
+ });
+
+ return positions;
+}
diff --git a/explorer/src/workspaces/GraphWorkspace/useLoadGraph.ts b/explorer/src/workspaces/GraphWorkspace/useLoadGraph.ts
index cc39df99..21405b49 100644
--- a/explorer/src/workspaces/GraphWorkspace/useLoadGraph.ts
+++ b/explorer/src/workspaces/GraphWorkspace/useLoadGraph.ts
@@ -16,6 +16,11 @@ import {
} from "./graphTheme";
import { classifyEntityShape } from "./graphEntityShape";
import { createGraphLoadProgress } from "./graphLoading";
+import {
+ buildSmallGraphSeedPositions,
+ resolveGraphLayoutDecision,
+ resolveNodeLayoutPosition,
+} from "./smallGraphLayout";
import type { GraphLoadProgress, GraphLoadSummary } from "./types";
const SEMANTIC_COLOR_FIELDS = [
@@ -553,10 +558,19 @@ export function useLoadGraph(options: UseLoadGraphOptions = {}) {
: count;
}, 0);
const coordinateCoverage = fetchedNodes.length > 0 ? providedCoordinateCount / fetchedNodes.length : 0;
- const useProvidedCoordinates = coordinateCoverage >= 0.92;
+ const {
+ useProvidedCoordinates,
+ useSmallGraphLayout,
+ layoutReady,
+ } = resolveGraphLayoutDecision(fetchedNodes.length, coordinateCoverage);
const seededPositions = useProvidedCoordinates
? null
- : buildClusterSeedPositions(
+ : useSmallGraphLayout
+ ? buildSmallGraphSeedPositions(
+ fetchedNodes.map((node) => node.id),
+ fetchedEdges,
+ )
+ : buildClusterSeedPositions(
draftAttributes.map(({ id, attributes }) => ({
id,
semanticGroup: semanticKeyByNodeId.get(id) ?? structuralColorKey(id, attributes),
@@ -569,7 +583,9 @@ export function useLoadGraph(options: UseLoadGraphOptions = {}) {
const colorIndex = hashString(semanticGroup) % GRAPH_THEME.palette.semantic.length;
const baseColor = GRAPH_THEME.palette.semantic[colorIndex];
const sizeRatio = nodePriorityById.get(id) ?? 0;
- const dynamicSize = clamp(1.8, 1.8 + 8.8 * sizeRatio, 11.8);
+ const dynamicSize = useSmallGraphLayout
+ ? clamp(5.2, 5.2 + 6.6 * sizeRatio, 11.8)
+ : clamp(1.8, 1.8 + 8.8 * sizeRatio, 11.8);
const hasTemporalBounds = Boolean(attributes.valid_from || attributes.valid_until);
const provenanceCount = getProvenanceCount(attributes.properties ?? {});
const properties = attributes.properties as Record<string, unknown>;
@@ -577,12 +593,11 @@ export function useLoadGraph(options: UseLoadGraphOptions = {}) {
const providedX = readFiniteCoordinate(properties?.x);
const providedY = readFiniteCoordinate(properties?.y);
const seededPosition = seededPositions?.get(id);
- const x = useProvidedCoordinates
- ? providedX ?? 0
- : providedX ?? seededPosition?.x ?? 0;
- const y = useProvidedCoordinates
- ? providedY ?? 0
- : providedY ?? seededPosition?.y ?? 0;
+ const { x, y } = resolveNodeLayoutPosition(
+ { useProvidedCoordinates, useSmallGraphLayout, layoutReady },
+ { x: providedX, y: providedY },
+ seededPosition,
+ );
return {
id,
attributes: {
@@ -603,6 +618,7 @@ export function useLoadGraph(options: UseLoadGraphOptions = {}) {
borderSize: 0.72,
entityShape,
...resolveNodeVariantMetadata(baseColor, sizeRatio, hasTemporalBounds, provenanceCount),
+ ...(useSmallGraphLayout ? { labelVisibilityPolicy: "always" as const } : {}),
} as NodeAttributes,
};
});
@@ -659,6 +675,7 @@ export function useLoadGraph(options: UseLoadGraphOptions = {}) {
parallelIndex,
parallelCount,
familySize: familyCounts.get(edge.familyId) ?? 1,
+ isSmallGraph: useSmallGraphLayout,
...resolveEdgeVariantMetadata(edge, sourcePriority, targetPriority, isBidirectional),
} as EdgeAttributes,
};
@@ -701,7 +718,7 @@ export function useLoadGraph(options: UseLoadGraphOptions = {}) {
loadTimeMs: Math.round(performance.now() - startedAt),
hasCoordinates: useProvidedCoordinates,
layoutSource: useProvidedCoordinates ? "provided" : "runtime",
- layoutReady: useProvidedCoordinates,
+ layoutReady,
} satisfies GraphLoadSummary;
onProgress?.(createGraphLoadProgress({
diff --git a/explorer/tests/graphSceneState.display.test.ts b/explorer/tests/graphSceneState.display.test.ts
index 6621ba86..17049d38 100644
--- a/explorer/tests/graphSceneState.display.test.ts
+++ b/explorer/tests/graphSceneState.display.test.ts
@@ -407,6 +407,31 @@ test("resolveEdgeElementStyle applies full-graph LOD to directional background e
assert.equal(style.hidden, true);
});
+test("resolveEdgeElementStyle keeps small-graph relationships visible in overview", () => {
+ const style = resolveEdgeElementStyle(
+ GRAPH_THEME,
+ "overview",
+ "inactive",
+ {
+ edgeType: "related_to",
+ weight: 1,
+ properties: {},
+ edgeVariant: "directional",
+ visualPriority: 0.1,
+ baseSize: 0.5,
+ isSmallGraph: true,
+ },
+ "source",
+ "target",
+ "full",
+ "small-graph-low-priority",
+ "hidden",
+ );
+
+ assert.equal(style.hidden, false);
+ assert.ok(Number(style.size ?? 0) >= 0.9);
+});
+
test("classifyFullGraphEdge applies deterministic priority order", () => {
const edgeClass = classifyFullGraphEdge(
"edge-priority",
diff --git a/explorer/tests/realtimeGraphAttributes.test.ts b/explorer/tests/realtimeGraphAttributes.test.ts
new file mode 100644
index 00000000..9dc3eb96
--- /dev/null
+++ b/explorer/tests/realtimeGraphAttributes.test.ts
@@ -0,0 +1,31 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { buildRealtimeEdgeAttributes } from "../src/workspaces/GraphWorkspace/realtimeGraphAttributes.ts";
+
+const payload = {
+ id: "edge-live",
+ source_id: "source",
+ target_id: "target",
+ type: "related_to",
+ properties: {},
+};
+
+test("realtime edges retain the active small-graph visibility marker", () => {
+ const attributes = buildRealtimeEdgeAttributes(payload, {
+ isBidirectional: false,
+ isSmallGraph: true,
+ });
+
+ assert.equal(attributes.isSmallGraph, true);
+ assert.equal(attributes.edgeVariant, "directional");
+});
+
+test("realtime edges do not retain the marker after graph leaves small-graph mode", () => {
+ const attributes = buildRealtimeEdgeAttributes(payload, {
+ isBidirectional: false,
+ isSmallGraph: false,
+ });
+
+ assert.equal(attributes.isSmallGraph, false);
+});
diff --git a/explorer/tests/smallGraphLayout.test.ts b/explorer/tests/smallGraphLayout.test.ts
new file mode 100644
index 00000000..d62b0bb3
--- /dev/null
+++ b/explorer/tests/smallGraphLayout.test.ts
@@ -0,0 +1,100 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ SMALL_GRAPH_MAX_NODES,
+ buildSmallGraphSeedPositions,
+ resolveGraphLayoutDecision,
+ resolveNodeLayoutPosition,
+ shouldUseSmallGraphLayout,
+} from "../src/workspaces/GraphWorkspace/smallGraphLayout.ts";
+
+test("small graph layout is selected only when coordinates are not already usable", () => {
+ assert.equal(shouldUseSmallGraphLayout(12, 0), true);
+ assert.equal(shouldUseSmallGraphLayout(SMALL_GRAPH_MAX_NODES + 1, 0), false);
+ assert.equal(shouldUseSmallGraphLayout(12, 0.95), false);
+});
+
+test("small graph layout ignores isolated partial coordinates", () => {
+ const decision = resolveGraphLayoutDecision(12, 1 / 12);
+ assert.deepEqual(
+ resolveNodeLayoutPosition(decision, { x: 50_000, y: -50_000 }, { x: 24, y: -18 }),
+ { x: 24, y: -18 },
+ );
+ assert.deepEqual(
+ resolveNodeLayoutPosition(decision, { x: 50_000, y: null }, { x: -12, y: 36 }),
+ { x: -12, y: 36 },
+ );
+});
+
+test("small graph load is immediately ready and skips runtime stabilization", () => {
+ assert.deepEqual(resolveGraphLayoutDecision(12, 0), {
+ useProvidedCoordinates: false,
+ useSmallGraphLayout: true,
+ layoutReady: true,
+ });
+ assert.deepEqual(resolveGraphLayoutDecision(SMALL_GRAPH_MAX_NODES + 1, 0), {
+ useProvidedCoordinates: false,
+ useSmallGraphLayout: false,
+ layoutReady: false,
+ });
+ assert.deepEqual(resolveGraphLayoutDecision(12, 1), {
+ useProvidedCoordinates: true,
+ useSmallGraphLayout: false,
+ layoutReady: true,
+ });
+});
+
+test("small graph layout is deterministic and keeps connected nodes together", () => {
+ const nodes = ["Apple", "Steve", "Ronald", "Cupertino", "California"];
+ const edges = [
+ { source: "Apple", target: "Steve" },
+ { source: "Ronald", target: "Cupertino" },
+ ];
+ const first = buildSmallGraphSeedPositions(nodes, edges);
+ const second = buildSmallGraphSeedPositions([...nodes].reverse(), [...edges].reverse());
+
+ assert.deepEqual([...first.entries()].sort(), [...second.entries()].sort());
+ assert.equal(first.size, nodes.length);
+
+ const distance = (left: string, right: string) => {
+ const a = first.get(left);
+ const b = first.get(right);
+ assert.ok(a && b);
+ return Math.hypot(a.x - b.x, a.y - b.y);
+ };
+ assert.ok(distance("Apple", "Steve") < distance("Apple", "California"));
+ assert.ok(distance("Ronald", "Cupertino") < distance("Ronald", "California"));
+});
+
+test("small graph layout keeps maximum-radius components separated", () => {
+ const componentCount = 4;
+ const nodesPerComponent = 12;
+ const nodes = Array.from(
+ { length: componentCount * nodesPerComponent },
+ (_, index) => `component-${Math.floor(index / nodesPerComponent)}-node-${index % nodesPerComponent}`,
+ );
+ const edges = Array.from({ length: componentCount }).flatMap((_, componentIndex) => {
+ const prefix = `component-${componentIndex}-node-`;
+ return Array.from({ length: nodesPerComponent - 1 }, (_unused, nodeIndex) => ({
+ source: `${prefix}${nodeIndex}`,
+ target: `${prefix}${nodeIndex + 1}`,
+ }));
+ });
+ const positions = buildSmallGraphSeedPositions(nodes, edges);
+
+ for (let leftComponent = 0; leftComponent < componentCount; leftComponent += 1) {
+ for (let rightComponent = leftComponent + 1; rightComponent < componentCount; rightComponent += 1) {
+ let closestDistance = Number.POSITIVE_INFINITY;
+ for (let leftNode = 0; leftNode < nodesPerComponent; leftNode += 1) {
+ for (let rightNode = 0; rightNode < nodesPerComponent; rightNode += 1) {
+ const left = positions.get(`component-${leftComponent}-node-${leftNode}`);
+ const right = positions.get(`component-${rightComponent}-node-${rightNode}`);
+ assert.ok(left && right);
+ closestDistance = Math.min(closestDistance, Math.hypot(left.x - right.x, left.y - right.y));
+ }
+ }
+ assert.ok(closestDistance >= 48, `components are only ${closestDistance} units apart`);
+ }
+ }
+});