Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(explorer): align visible legend with semantic node colors (#1483)

Wei Tao008b9e0b64a8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0fb781a7..917afbfe 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -93,6 +93,7 @@ jobs:
npm run test:graph-workspace
npm run test:plugin-registry
npm run test:deterministic-e2e
+ npm run test:graph-legend-e2e
- name: Build Explorer frontend
working-directory: explorer
run: npm run build
diff --git a/explorer/package.json b/explorer/package.json
index 714aacb2..fb4132c5 100644
--- a/explorer/package.json
+++ b/explorer/package.json
@@ -9,9 +9,9 @@
"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/markdownEditorInteraction.test.tsx tests/markdownEditorState.test.ts tests/nodeMarkdownSync.test.ts tests/graphSceneState.display.test.ts tests/temporalLifecycle.test.ts tests/deterministicExplorerRendering.test.ts tests/explorerCapabilities.test.tsx tests/smallGraphLayout.test.ts tests/realtimeGraphAttributes.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 tests/ontologyEditorModel.test.ts",
+ "test:graph-workspace": "node --import tsx --test tests/markdownContentViewer.test.ts tests/markdownEditorInteraction.test.tsx tests/markdownEditorState.test.ts tests/nodeMarkdownSync.test.ts tests/graphSceneState.display.test.ts tests/temporalLifecycle.test.ts tests/deterministicExplorerRendering.test.ts tests/explorerCapabilities.test.tsx tests/smallGraphLayout.test.ts tests/realtimeGraphAttributes.test.ts tests/ontologyEditorModel.test.ts tests/graphColorLegend.test.ts",
"test:deterministic-e2e": "node --import tsx --test tests/deterministicExplorerRendering.e2e.ts",
+ "test:graph-legend-e2e": "node --import tsx --test tests/graphColorLegend.e2e.ts",
"test:plugin-registry": "node --import tsx --test tests/pluginRegistry.temporal.test.mjs"
},
"dependencies": {
diff --git a/explorer/src/store/graphStore.ts b/explorer/src/store/graphStore.ts
index d7c42e79..a374fe17 100644
--- a/explorer/src/store/graphStore.ts
+++ b/explorer/src/store/graphStore.ts
@@ -26,6 +26,8 @@ export interface NodeAttributes {
size: number;
color: string;
baseColor?: string;
+ /** Original semantic color when a display clone bakes interaction styling into baseColor. */
+ semanticBaseColor?: string;
mutedColor?: string;
glowColor?: string;
baseSize?: number;
diff --git a/explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx b/explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx
index 3d710bfb..872d961c 100644
--- a/explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx
+++ b/explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx
@@ -28,7 +28,7 @@ import { useLoadGraph, useReloadGraph } from "./useLoadGraph";
import { GraphLoadingOverlay } from "./GraphLoadingOverlay";
import { createGraphLoadProgress, getGraphLoadTitle } from "./graphLoading";
import { GRAPH_THEME, withAlpha } from "./graphTheme";
-import type { GraphEntityShapeVariant } from "./graphTheme";
+import { buildGraphColorLegend, type GraphColorLegendItem } from "./graphColorLegend";
import { buildHeatmapRenderSnapshot, buildStructuralDistanceSnapshot, checkGroupedViewAvailability, getDistanceBandColor, resolveDisplayGraph, resolveDisplayStateSnapshot, resolveGroupedDisplayNodeId, resolveGroupedDisplayStateSnapshot, summarizeDistanceBuckets } from "./graphSceneState";
import {
type GraphPlugin,
@@ -169,14 +169,7 @@ const loadNeighborhoodPanelPlugin = () => import("./plugins/neighborhoodPanelPlu
const loadTemporalOverlayPlugin = () => import("./plugins/temporalOverlayPlugin").then((module) => module.temporalOverlayPlugin);
const EMPTY_PATH: string[] = [];
const COMPACT_TOOLBAR_CLUSTER_IDS = new Set(["camera", "utility"]);
-const ENTITY_VISUAL_KEY: Array<{ shape: GraphEntityShapeVariant; label: string }> = [
- { shape: "biomolecule", label: "Biomolecule" },
- { shape: "condition", label: "Condition" },
- { shape: "compound", label: "Compound" },
- { shape: "process", label: "Process" },
- { shape: "community", label: "Community" },
- { shape: "entity", label: "Other" },
-];
+
const DEBUG_GRAPH_WORKSPACE = import.meta.env.DEV;
function debugGraphWorkspace(message: string, payload?: Record<string, unknown>) {
@@ -459,15 +452,21 @@ function SearchCommandBar({
);
}
-function EntityVisualKey() {
+function SemanticColorLegend({ items }: { items: GraphColorLegendItem[] }) {
+ if (!items.length) return null;
return (
- <div className="explore-entity-key" aria-label="Node visual key">
- {ENTITY_VISUAL_KEY.map((item) => (
- <div key={item.shape} className="explore-entity-key-item">
- <span className="explore-entity-key-mark" data-shape={item.shape} />
- <span>{item.label}</span>
- </div>
- ))}
+ <div className="explore-color-legend" role="group" aria-label="Node colors">
+ <span className="explore-color-legend-label" title="Base semantic colors; selection, zoom, and distance effects can change node appearance.">
+ Node colors
+ </span>
+ <ul className="explore-color-legend-items">
+ {items.map((item) => (
+ <li key={item.id} className="explore-color-legend-item" title={`${item.group}: ${item.count.toLocaleString()} nodes`}>
+ <span className="explore-color-legend-mark" style={{ backgroundColor: item.color }} aria-hidden="true" />
+ <span className="explore-color-legend-name">{item.group}</span>
+ </li>
+ ))}
+ </ul>
</div>
);
}
@@ -906,55 +905,46 @@ const HUD_CSS = `
.explore-tool-button[data-compact="true"] .explore-tool-button-label {
display: none;
}
- .explore-entity-key {
+ .explore-color-legend {
display: flex;
- align-items: center;
- gap: 10px;
- flex-wrap: wrap;
+ align-items: baseline;
+ gap: 12px;
padding: 2px 1px 0;
color: ${GRAPH_THEME.ui.text.subtle};
- font-size: 10px;
- font-weight: 700;
- letter-spacing: 0.02em;
+ font-size: 11px;
+ font-weight: 600;
+ }
+ .explore-color-legend-label {
+ flex-shrink: 0;
+ color: ${GRAPH_THEME.ui.text.muted};
+ }
+ .explore-color-legend-items {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px 14px;
+ min-width: 0;
+ max-height: 76px;
+ overflow-y: auto;
+ margin: 0;
+ padding: 0;
+ list-style: none;
}
- .explore-entity-key-item {
+ .explore-color-legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
- white-space: nowrap;
- }
- .explore-entity-key-mark {
- width: 13px;
- height: 13px;
- display: inline-block;
- border: 1px solid rgba(194, 214, 218, 0.42);
- background: rgba(73, 154, 150, 0.58);
- box-shadow: inset 0 1px 0 rgba(255,255,255,0.08);
- }
- .explore-entity-key-mark[data-shape="entity"] {
- border-radius: 999px;
- }
- .explore-entity-key-mark[data-shape="biomolecule"] {
- clip-path: polygon(50% 7%, 86% 28%, 86% 72%, 50% 93%, 14% 72%, 14% 28%);
- }
- .explore-entity-key-mark[data-shape="condition"] {
- border-radius: 5px;
- transform: rotate(45deg) scale(0.88);
- }
- .explore-entity-key-mark[data-shape="compound"] {
- width: 20px;
- border-radius: 999px;
+ min-width: 0;
+ max-width: 100%;
}
- .explore-entity-key-mark[data-shape="process"] {
- border-radius: 4px;
- clip-path: polygon(0 0, 86% 0, 100% 16%, 100% 100%, 0 100%);
+ .explore-color-legend-name {
+ overflow-wrap: anywhere;
}
- .explore-entity-key-mark[data-shape="community"] {
- width: 15px;
- height: 15px;
- border-radius: 999px;
- background: rgba(96, 190, 180, 0.16);
- border-color: rgba(229, 213, 175, 0.54);
+ .explore-color-legend-mark {
+ width: 10px;
+ height: 10px;
+ flex-shrink: 0;
+ border-radius: 50%;
+ box-shadow: inset 0 0 0 1px rgba(255,255,255,0.16);
}
.explore-search-results {
display: flex;
@@ -2280,6 +2270,11 @@ export function GraphWorkspace({ externalFocusNodeId, externalFocusToken, onDirt
structuralSelectedNodeId,
viewMode,
]);
+ const colorLegendItems = useMemo(() => {
+ // Store mutations can preserve graph identity while changing its attributes.
+ void graphVersion;
+ return buildGraphColorLegend(displayResult.graph);
+ }, [displayResult.graph, graphVersion]);
const displayState = useMemo(
() => (
viewMode === "grouped"
@@ -3122,7 +3117,7 @@ export function GraphWorkspace({ externalFocusNodeId, externalFocusToken, onDirt
))}
</div>
</div>
- <EntityVisualKey />
+ {!showDistanceStatus ? <SemanticColorLegend items={colorLegendItems} /> : null}
</div>
{egoModeEnabled && (
diff --git a/explorer/src/workspaces/GraphWorkspace/graphColorLegend.ts b/explorer/src/workspaces/GraphWorkspace/graphColorLegend.ts
new file mode 100644
index 00000000..e888ea74
--- /dev/null
+++ b/explorer/src/workspaces/GraphWorkspace/graphColorLegend.ts
@@ -0,0 +1,36 @@
+import type Graph from "graphology";
+
+import type { NodeAttributes } from "../../store/graphStore";
+import { GRAPH_THEME, type GraphTheme } from "./graphTheme";
+
+export type GraphColorLegendItem = {
+ id: string;
+ group: string;
+ color: string;
+ count: number;
+};
+
+/** Normal semantic color, before selection, distance, or zoom styling. */
+export function getSemanticNodeColor(
+ attrs: Pick<NodeAttributes, "baseColor" | "color">,
+ theme: GraphTheme = GRAPH_THEME,
+) {
+ return String(attrs.baseColor || attrs.color || theme.palette.semantic[0]);
+}
+
+/** Use the displayed graph so synthetic groups and filtered views keep their colors. */
+export function buildGraphColorLegend(graph: Graph, theme: GraphTheme = GRAPH_THEME): GraphColorLegendItem[] {
+ const entries = new Map<string, GraphColorLegendItem>();
+ graph.forEachNode((_id, attrs) => {
+ if (attrs.hidden) return;
+ const group = String(attrs.semanticGroup || attrs.nodeType || "entity");
+ // Focused clones bake interaction colors into baseColor; keep those out of the semantic key.
+ const color = String(attrs.semanticBaseColor || getSemanticNodeColor(attrs as NodeAttributes, theme));
+ // A synthetic display node can share a semantic label with a different color.
+ const id = JSON.stringify([group, color]);
+ const current = entries.get(id);
+ if (current) current.count += 1;
+ else entries.set(id, { id, group, color, count: 1 });
+ });
+ return [...entries.values()].sort((a, b) => a.group.localeCompare(b.group) || a.color.localeCompare(b.color));
+}
diff --git a/explorer/src/workspaces/GraphWorkspace/graphSceneState.ts b/explorer/src/workspaces/GraphWorkspace/graphSceneState.ts
index 7e301d06..485a11c5 100644
--- a/explorer/src/workspaces/GraphWorkspace/graphSceneState.ts
+++ b/explorer/src/workspaces/GraphWorkspace/graphSceneState.ts
@@ -19,6 +19,7 @@ import {
withAlpha,
zoomTierAtLeast,
} from "./graphTheme";
+import { getSemanticNodeColor } from "./graphColorLegend";
import { classifyEntityShape } from "./graphEntityShape";
import { computeGraphAnalyticsBase } from "./graphAnalytics";
import type {
@@ -1013,9 +1014,8 @@ function resolveNodeColor(
state: GraphNodeVisualState,
attrs: NodeAttributes,
cameraRatio: number,
- fallbackColor?: string,
) {
- const semanticColor = String(attrs.baseColor || fallbackColor || theme.palette.semantic[0]);
+ const semanticColor = getSemanticNodeColor(attrs, theme);
const isCommunityGroup = Boolean(attrs.isCommunityGroup);
const entityShapeConfig = theme.nodes.entityShapes[resolveEntityShape(attrs)];
const overviewTint = state === "neighbor"
@@ -1062,9 +1062,8 @@ function resolveNodeShellColor(
state: GraphNodeVisualState,
attrs: NodeAttributes,
cameraRatio: number,
- fallbackColor?: string,
) {
- const semanticColor = String(attrs.baseColor || fallbackColor || theme.palette.semantic[0]);
+ const semanticColor = getSemanticNodeColor(attrs, theme);
const isCommunityGroup = Boolean(attrs.isCommunityGroup);
const entityShapeConfig = theme.nodes.entityShapes[resolveEntityShape(attrs)];
const presenceBoost = getOverviewPresenceBoost(cameraRatio);
@@ -1633,8 +1632,8 @@ export function resolveNodeElementStyle(
const isCommunityGroup = Boolean(attrs.isCommunityGroup);
const baseSize = Number(attrs.baseSize || attrs.size || 4);
const labelPriority = Number(attrs.labelPriority ?? 0);
- const color = resolveNodeColor(theme, zoomTier, state, attrs, cameraRatio, attrs.color);
- const shellColor = resolveNodeShellColor(theme, zoomTier, state, attrs, cameraRatio, attrs.color);
+ const color = resolveNodeColor(theme, zoomTier, state, attrs, cameraRatio);
+ const shellColor = resolveNodeShellColor(theme, zoomTier, state, attrs, cameraRatio);
const sizeMultiplier = (state === "default" ? tierConfig.nodeScale : stateConfig.sizeMultiplier)
* variantConfig.sizeMultiplier
* (isCommunityGroup ? theme.grouped.style.nodeSizeScale : 1);
@@ -2570,6 +2569,7 @@ export function createFocusedGraph(
color: selectedState.color,
size: Math.max(selectedState.size, 22),
baseColor: selectedState.color,
+ semanticBaseColor: getSemanticNodeColor(selectedAttrs),
baseSize: Math.max(selectedState.size, 22),
label: selectedState.label,
});
@@ -2609,6 +2609,7 @@ export function createFocusedGraph(
color: style.color,
size: Math.max(style.size, 8.5),
baseColor: style.color,
+ semanticBaseColor: getSemanticNodeColor(baseAttrs),
baseSize: Math.max(style.size, 8.5),
label: style.label,
});
diff --git a/explorer/src/workspaces/GraphWorkspace/plugins/explorationEffectsPluginPhaseC.tsx b/explorer/src/workspaces/GraphWorkspace/plugins/explorationEffectsPluginPhaseC.tsx
index d8427a7e..e07ec242 100644
--- a/explorer/src/workspaces/GraphWorkspace/plugins/explorationEffectsPluginPhaseC.tsx
+++ b/explorer/src/workspaces/GraphWorkspace/plugins/explorationEffectsPluginPhaseC.tsx
@@ -1,5 +1,6 @@
import type { CSSProperties } from "react";
+import { buildGraphColorLegend } from "../graphColorLegend";
import type {
GraphAnalyticsSnapshot,
GraphDiagnosticsSnapshot,
@@ -104,19 +105,7 @@ function renderAvailabilityText(availability: GraphEffectAvailability) {
}
function collectFallbackLegendItems(context: Parameters<NonNullable<GraphPlugin["renderPanel"]>>[0]) {
- const groups = new Map<string, { count: number; color: string }>();
- context.graph.forEachNode((_nodeId, attrs) => {
- const semanticGroup = String(attrs.semanticGroup || attrs.nodeType || "entity");
- const color = String(attrs.baseColor || context.theme.palette.semantic[0]);
- const current = groups.get(semanticGroup);
- groups.set(semanticGroup, {
- count: (current?.count ?? 0) + 1,
- color,
- });
- });
-
- return [...groups.entries()]
- .map(([group, data]) => ({ group, ...data }))
+ return buildGraphColorLegend(context.graph, context.theme)
.sort((left, right) => right.count - left.count)
.slice(0, context.theme.effects.legend.maxGroups);
}
@@ -255,7 +244,7 @@ function renderRegionsAndSignals(
<div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
<div style={subsectionTitleStyle}>Fallback semantic legend</div>
{fallbackLegendItems.map((item) => (
- <div key={item.group} style={legendRowStyle}>
+ <div key={item.id} style={legendRowStyle}>
<span
style={{
...legendSwatchStyle,
diff --git a/explorer/src/workspaces/GraphWorkspace/plugins/legendPlugin.tsx b/explorer/src/workspaces/GraphWorkspace/plugins/legendPlugin.tsx
index d90a35db..8feeb400 100644
--- a/explorer/src/workspaces/GraphWorkspace/plugins/legendPlugin.tsx
+++ b/explorer/src/workspaces/GraphWorkspace/plugins/legendPlugin.tsx
@@ -1,5 +1,6 @@
import type { CSSProperties } from "react";
+import { buildGraphColorLegend } from "../graphColorLegend";
import type { GraphPlugin } from "./types";
const LEGEND_PANEL_ID = "legend-panel";
@@ -25,19 +26,7 @@ export const legendPlugin: GraphPlugin = {
return null;
}
- const groups = new Map<string, { count: number; color: string }>();
- context.graph.forEachNode((_nodeId, attrs) => {
- const semanticGroup = String(attrs.semanticGroup || attrs.nodeType || "entity");
- const color = String(attrs.baseColor || context.theme.palette.semantic[0]);
- const current = groups.get(semanticGroup);
- groups.set(semanticGroup, {
- count: (current?.count ?? 0) + 1,
- color,
- });
- });
-
- const items = [...groups.entries()]
- .map(([group, data]) => ({ group, ...data }))
+ const items = buildGraphColorLegend(context.graph, context.theme)
.sort((left, right) => right.count - left.count)
.slice(0, MAX_GROUPS);
@@ -55,7 +44,7 @@ export const legendPlugin: GraphPlugin = {
{items.length ? (
<div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
{items.map((item) => (
- <div key={item.group} style={legendRowStyle}>
+ <div key={item.id} style={legendRowStyle}>
<span
style={{
...swatchStyle,
diff --git a/explorer/tests/graphColorLegend.e2e.ts b/explorer/tests/graphColorLegend.e2e.ts
new file mode 100644
index 00000000..db57631a
--- /dev/null
+++ b/explorer/tests/graphColorLegend.e2e.ts
@@ -0,0 +1,112 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { existsSync } from "node:fs";
+import { setTimeout as delay } from "node:timers/promises";
+import test from "node:test";
+import { chromium, type Page } from "playwright";
+
+const BASE_URL = "http://127.0.0.1:4175";
+const initialNodes = [
+ { id: "alice", type: "Person", content: "Alice", properties: {} },
+ { id: "bob", type: "Person", content: "Bob", properties: {} },
+ { id: "acme", type: "Organization", content: "Acme", properties: {} },
+ { id: "london", type: "Location", content: "London", properties: {} },
+ { id: "research", type: "Project", content: "Research", properties: {} },
+ { id: "report", type: "Document", content: "Report", properties: {} },
+];
+const edges = [
+ ["alice", "acme", "WORKS_AT"], ["bob", "acme", "WORKS_AT"],
+ ["acme", "london", "LOCATED_IN"], ["alice", "research", "LEADS"],
+ ["bob", "report", "AUTHORED"], ["report", "research", "DESCRIBES"],
+].map(([source, target, type], i) => ({
+ id: `edge_${i}`, familyId: `edge_${i}`, source, target, type, weight: 1, properties: {},
+}));
+
+async function assertLegendMatchesGraph(page: Page, nodeIds?: string[]) {
+ const result = await page.evaluate(async (includedNodeIds) => {
+ const storePath = "/src/store/graphStore.ts";
+ const { graph } = await import(storePath);
+ const colors: Record<string, string> = {};
+ graph.forEachNode((id: string, attrs: { semanticGroup: string; baseColor: string }) => {
+ if (includedNodeIds && !includedNodeIds.includes(id)) return;
+ const hex = attrs.baseColor.replace("#", "");
+ colors[attrs.semanticGroup] = `rgb(${[0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16)).join(", ")})`;
+ });
+ const items = [...document.querySelectorAll(".explore-color-legend-item")].map((item) => ({
+ group: item.querySelector(".explore-color-legend-name")?.textContent,
+ color: getComputedStyle(item.querySelector(".explore-color-legend-mark")!).backgroundColor,
+ }));
+ return { colors, items };
+ }, nodeIds);
+ assert.equal(result.items.length, Object.keys(result.colors).length);
+ for (const item of result.items) {
+ assert.equal(item.color, result.colors[item.group!], `Swatch for ${item.group} must match the loaded canvas color`);
+ }
+}
+
+test("visible legend follows loaded data, reloads, focused views, and distance mode", async (t) => {
+ const server = spawn("npm", ["run", "dev", "--", "--host", "127.0.0.1", "--port", "4175", "--strictPort"], { stdio: "ignore" });
+ t.after(() => { server.kill(); });
+ let ready = false;
+ for (let i = 0; i < 100; i += 1) {
+ try { if ((await fetch(BASE_URL)).ok) { ready = true; break; } } catch { /* Starting Vite. */ }
+ await delay(100);
+ }
+ assert.ok(ready, "Vite must start");
+ const browser = await chromium.launch({
+ headless: true,
+ executablePath:
+ process.env.CHROMIUM_PATH || (existsSync("/usr/bin/chromium") ? "/usr/bin/chromium" : undefined),
+ });
+ t.after(() => browser.close());
+ const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
+ page.setDefaultTimeout(10_000);
+ const errors: string[] = [];
+ page.on("pageerror", (error) => errors.push(error.message));
+ page.on("console", (message) => { if (message.type() === "error") errors.push(message.text()); });
+ let nodes = initialNodes;
+ await page.routeWebSocket("**/ws/graph-updates", () => {});
+ await page.route("**/api/**", async (route) => {
+ const path = new URL(route.request().url()).pathname;
+ let json: unknown = {};
+ if (path === "/api/info") json = { capabilities: { agent_memory: false } };
+ if (path === "/api/graph/stats") json = { node_count: nodes.length, edge_count: edges.length };
+ if (path === "/api/graph/nodes") json = { nodes, total: nodes.length, next_cursor: null };
+ if (path === "/api/graph/edges") json = { edges, total: edges.length, next_cursor: null };
+ if (path === "/api/temporal/bounds") json = { min: null, max: null };
+ if (path === "/api/temporal/snapshot") json = { active_node_ids: nodes.map((n) => n.id), active_node_count: nodes.length };
+ if (path === "/api/graph/search") json = { results: [{ node: nodes[0], score: 1 }] };
+ await route.fulfill({ json });
+ });
+ await page.goto(BASE_URL);
+ await page.getByRole("button", { name: "Open Semantica Explorer" }).click();
+ const legend = page.getByRole("group", { name: "Node colors" });
+ await legend.waitFor();
+ await page.locator("canvas").first().waitFor({ state: "visible" });
+ await assertLegendMatchesGraph(page);
+ assert.equal(await legend.getByText("Person", { exact: true }).count(), 1);
+ assert.equal(await legend.getByText("Biomolecule", { exact: true }).count(), 0);
+
+ nodes = initialNodes.map((node) => ({ ...node, type: node.type === "Person" ? "Researcher" : node.type }));
+ await page.getByRole("button", { name: "Reload graph data" }).click();
+ await legend.getByText("Researcher", { exact: true }).waitFor();
+ assert.equal(await legend.getByText("Person", { exact: true }).count(), 0);
+ await assertLegendMatchesGraph(page);
+
+ await page.getByPlaceholder("Search command, node, or concept").fill("Alice");
+ await page.getByRole("option").filter({ hasText: "Alice" }).click();
+ const heatmap = page.getByRole("button", { name: "Heatmap", exact: true });
+ await heatmap.click();
+ await legend.waitFor({ state: "hidden" });
+ await heatmap.click();
+ await legend.waitFor();
+ await assertLegendMatchesGraph(page);
+ await page.getByRole("button", { name: "Focused", exact: true }).click();
+ await legend.getByText("Document", { exact: true }).waitFor({ state: "hidden" });
+ await assertLegendMatchesGraph(page, ["alice", "acme", "research"]);
+ assert.equal(await legend.getByText("Researcher", { exact: true }).count(), 1);
+ await page.getByRole("button", { name: "Full Graph", exact: true }).click();
+ await legend.getByText("Document", { exact: true }).waitFor();
+ await assertLegendMatchesGraph(page);
+ assert.deepEqual(errors, []);
+});
diff --git a/explorer/tests/graphColorLegend.test.ts b/explorer/tests/graphColorLegend.test.ts
new file mode 100644
index 00000000..45d3fdb8
--- /dev/null
+++ b/explorer/tests/graphColorLegend.test.ts
@@ -0,0 +1,103 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import Graph from "graphology";
+
+import { clearGraph, graph as sourceGraph, type NodeAttributes } from "../src/store/graphStore.ts";
+import { buildGraphColorLegend } from "../src/workspaces/GraphWorkspace/graphColorLegend.ts";
+import { resolveDisplayGraph, resolveNodeElementStyle } from "../src/workspaces/GraphWorkspace/graphSceneState.ts";
+import { GRAPH_THEME, withAlpha } from "../src/workspaces/GraphWorkspace/graphTheme.ts";
+
+function attributes(overrides: Partial<NodeAttributes> = {}): NodeAttributes {
+ return {
+ label: "Example", content: "Example", x: 0, y: 0, size: 8,
+ nodeType: "Person", semanticGroup: "Person", color: "#123456",
+ properties: {}, ...overrides,
+ };
+}
+
+test("legend matches normal canvas colors, including color and theme fallbacks", () => {
+ const graph = new Graph();
+ const samples = [
+ attributes({ baseColor: "#abcdef" }),
+ attributes({ semanticGroup: "Organization" }),
+ attributes({ semanticGroup: "Location", color: "" }),
+ ];
+ samples.forEach((attrs, i) => graph.addNode(String(i), attrs));
+ const items = buildGraphColorLegend(graph);
+ for (const attrs of samples) {
+ const item = items.find((entry) => entry.group === attrs.semanticGroup)!;
+ const style = resolveNodeElementStyle(GRAPH_THEME, "inspection", "default", attrs, attrs.label);
+ assert.equal(style.color, withAlpha(item.color, GRAPH_THEME.nodes.entityShapes.entity.fillAlpha));
+ }
+ assert.equal(items.find((item) => item.group === "Person")?.color, "#abcdef");
+ assert.equal(items.find((item) => item.group === "Organization")?.color, "#123456");
+ assert.equal(items.find((item) => item.group === "Location")?.color, GRAPH_THEME.palette.semantic[0]);
+});
+
+test("semantic groups, not shape categories, determine labels and distinct entries", () => {
+ const graph = new Graph();
+ graph.addNode("one", attributes({ semanticGroup: "Research", entityShape: "compound" }));
+ graph.addNode("two", attributes({ semanticGroup: "Research", entityShape: "entity" }));
+ graph.addNode("synthetic", attributes({ semanticGroup: "Research", baseColor: "#654321", isCommunityGroup: true }));
+ graph.addNode("hidden", { ...attributes(), hidden: true });
+ assert.deepEqual(buildGraphColorLegend(graph).map(({ group, color, count }) => ({ group, color, count })), [
+ { group: "Research", color: "#123456", count: 2 },
+ { group: "Research", color: "#654321", count: 1 },
+ ]);
+ assert.equal(new Set(buildGraphColorLegend(graph).map((item) => item.id)).size, 2);
+});
+
+test("legend rebuilds after in-place changes and uses only the supplied display graph", () => {
+ const graph = new Graph();
+ graph.addNode("one", attributes());
+ graph.addNode("two", attributes({ semanticGroup: "Location" }));
+ const first = buildGraphColorLegend(graph);
+ graph.mergeNodeAttributes("one", { semanticGroup: "Project", baseColor: "#fedcba" });
+ graph.dropNode("two");
+ assert.equal(first.length, 2);
+ assert.deepEqual(buildGraphColorLegend(graph).map(({ group, color }) => ({ group, color })), [
+ { group: "Project", color: "#fedcba" },
+ ]);
+ graph.clear();
+ assert.deepEqual(buildGraphColorLegend(graph), []);
+});
+
+test("fallback labels and ordering are stable and no groups are silently dropped", () => {
+ const graph = new Graph();
+ graph.addNode("fallback", attributes({ semanticGroup: undefined, nodeType: "" }));
+ for (let i = 11; i >= 0; i -= 1) graph.addNode(String(i), attributes({ semanticGroup: undefined, nodeType: `Type ${i}` }));
+ const items = buildGraphColorLegend(graph);
+ assert.equal(items.length, 13);
+ assert.ok(items.some((item) => item.group === "entity"));
+ const reverse = new Graph();
+ graph.nodes().reverse().forEach((id) => reverse.addNode(id, graph.getNodeAttributes(id)));
+ assert.deepEqual(items, buildGraphColorLegend(reverse));
+});
+
+
+test("focused legend keeps semantic colors for selected, path, and neighbor clones", (t) => {
+ clearGraph();
+ t.after(clearGraph);
+ for (const id of ["selected", "path", "neighbor", "outside"]) {
+ sourceGraph.addNode(id, attributes({ label: id, baseColor: "#abcdef" }));
+ }
+ sourceGraph.addDirectedEdgeWithKey("path-edge", "selected", "path", { weight: 1 });
+ sourceGraph.addDirectedEdgeWithKey("neighbor-edge", "selected", "neighbor", { weight: 1 });
+ const focused = resolveDisplayGraph("selected", ["selected", "path"], ["path-edge"], "focused").graph;
+
+ // Verify the fixture exercises baked interaction colors, not ordinary clones.
+ assert.equal(focused.getNodeAttribute("selected", "baseColor"), GRAPH_THEME.palette.accent.selected);
+ assert.equal(focused.getNodeAttribute("path", "baseColor"), GRAPH_THEME.palette.accent.path);
+ assert.notEqual(focused.getNodeAttribute("neighbor", "baseColor"), "#abcdef");
+ assert.ok(!focused.hasNode("outside"));
+ assert.deepEqual(buildGraphColorLegend(focused).map(({ group, color, count }) => ({ group, color, count })), [
+ { group: "Person", color: "#abcdef", count: 3 },
+ ]);
+ assert.equal(sourceGraph.getNodeAttribute("selected", "baseColor"), "#abcdef");
+
+ // Changing focus retains the semantic swatch while following the displayed subset.
+ const nextFocus = resolveDisplayGraph("neighbor", [], [], "focused").graph;
+ assert.deepEqual(buildGraphColorLegend(nextFocus).map(({ color, count }) => ({ color, count })), [
+ { color: "#abcdef", count: 2 },
+ ]);
+});