Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
fix(ui): count Galaxy layer progress per page and warn on hubs early
Bernhard Jackiewicz284937d5b67f
diff --git a/graph-ui/src/galaxy/GalaxyPanel.layers.test.tsx b/graph-ui/src/galaxy/GalaxyPanel.layers.test.tsxindex bc3b60733..3025a9e80 100644--- a/graph-ui/src/galaxy/GalaxyPanel.layers.test.tsx+++ b/graph-ui/src/galaxy/GalaxyPanel.layers.test.tsx@@ -63,6 +63,8 @@ it('K8: shows loaded nodes and edges while a layer loads, and "−" cancels backawait act(async () => button('Expand +1').click());await settle(() => expect(status()?.textContent).toBe('Loading layer 2: 4 nodes, 3 edges so far'));expect(status()?.getAttribute('data-state')).toBe('loading');+ // The tooltip counts the requests, so a long batch reads as work in progress (review of K8).+ expect(status()?.getAttribute('title')).toMatch(/^Loading layer 2: 4 nodes, 3 edges so far\. Request \d+ to the index; "−" cancels\.$/);// While loading, "−" is the way out, and it says so.expect(minus().disabled).toBe(false);expect(minus().title).toBe('Cancel loading layer 2 and return to 1 layer');@@ -115,3 +117,19 @@ it('K8: a large finished layer keeps its arranged cloud instead of being pushed// Screen separation pushed a dense cloud of thousands of nodes into a cross of long lines (layer 3 of JSONBAgg).expect(scene.separateNodes).toBe(false);});++it('K8: Expand warns before loading when the nodes at the edge have more indexed calls than the render limit allows', async () => {+ window.localStorage.setItem(viewPreferencesKey('sample'), JSON.stringify({ version: 1, preferences: { galaxyNodes: 500, galaxyEdges: 1000 } }));+ const nodes = [1, 2, 3].map(id => scopeNode(id));+ const edges: GraphEdge[] = [{ id: 1, source: 1, target: 2, type: 'CALLS' }, { id: 2, source: 3, target: 1, type: 'CALLS' }];+ // n2 is called from all over the code, like len or str at the edge of JSONBAgg's second layer.+ const { fetch, calls } = scopeFetch({ nodes, edges, degrees: { 2: { in: 1270, out: 3 }, 3: { in: 0, out: 2 } } });+ await act(async () => root.render(<GalaxyPanel project="sample" visible workspaceExpanded onOpenNode={vi.fn()} fetch={fetch} />));+ await settle(() => expect(seam().nodes).toBe(3));+ await act(async () => { seam().clickNode('sample.n1'); });+ await settle(() => expect(button('Expand +1').getAttribute('data-warning')).toBe('true'));+ // 1,270 + 3 + 2 calls, less the two already loaded.+ expect(button('Expand +1').title).toBe(`Likely past the render limit. Load layer 2: 2 nodes to expand. The index lists ${(1273).toLocaleString()} calls at them that are not loaded yet; `+ + 'growing like the last layer it adds about 4 nodes. Loading stops at the render limit of 500 nodes and marks the layer partial.');+ expect(calls.filter(call => String(call.args.query).includes('n.in_degree'))).toHaveLength(1);+});diff --git a/graph-ui/src/galaxy/GalaxyPanel.tsx b/graph-ui/src/galaxy/GalaxyPanel.tsxindex 90ec33e63..6038aa1be 100644--- a/graph-ui/src/galaxy/GalaxyPanel.tsx+++ b/graph-ui/src/galaxy/GalaxyPanel.tsx@@ -2066,9 +2066,12 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {: `${galaxyLayerText.counts(data?.nodes.length ?? 0, data?.edges.length ?? 0)}${scope.result?.exhausted ? galaxyLayerText.endOfTrace : ''}`: galaxyLayerText.partialPreview;const estimate = scope.complete ? nextLayerEstimate(scope.result) : undefined;- const expandWarning = Boolean(estimate && props.workspaceExpanded && (data?.nodes.length ?? 0) + estimate.estimate > nodeBudget);+ // Die gezaehlten Aufrufe am Rand sind eine Untergrenze; das Wachstum allein uebersah die Knoten mit tausend Aufrufern (Review zu K8).+ const edgeCalls = estimate ? scope.edgeCalls : undefined;+ const expandWarning = Boolean(estimate && props.workspaceExpanded && ((data?.nodes.length ?? 0) + Math.max(estimate.estimate, edgeCalls ?? 0) > nodeBudget+ || (data?.edges.length ?? 0) + (edgeCalls ?? 0) > edgeBudget));const expandTitle = partial ? galaxyLayerText.expandPartial : scope.result?.exhausted ? galaxyLayerText.expandEnd- : estimate ? `${expandWarning ? `${galaxyLayerText.expandOverLimit} ` : ''}${galaxyLayerText.expandTitle(estimate.layer, estimate.frontier, estimate.estimate, nodeBudget)}`+ : estimate ? `${expandWarning ? `${galaxyLayerText.expandOverLimit} ` : ''}${galaxyLayerText.expandTitle(estimate.layer, estimate.frontier, estimate.estimate, nodeBudget, edgeCalls)}`: undefined;/*@@ -2596,7 +2599,8 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {</>}<span className="atlas-graph-scope-count" role="status" data-state={scopeState}title={partial ? galaxyLayerText.partialTitle(partial.layer, partial.limit === 'nodes' ? nodeBudget : edgeBudget, partial.limit)- : [scopeStatus, groupsText].filter(Boolean).join('. ')}>{scopeStatus}</span>+ : [scopeStatus, scope.loading && scope.progress ? galaxyLayerText.loadingRequest(scope.progress.requests) : groupsText]+ .filter(Boolean).join('. ')}>{scopeStatus}</span>{scope.error && <span className="atlas-graph-scope-warning" title={scope.error}>Some relationships could not be loaded. <button type="button" onClick={scope.retry}>Retry</button></span>}{!props.workspaceExpanded && scope.complete && <small>All indexed direct dependencies included.</small>}{!props.workspaceExpanded && groupCount > 1 && <small className="atlas-graph-scope-groups" title={groupsText}>{galaxyToolbarText.groups(groupCount)}</small>}diff --git a/graph-ui/src/galaxy/galaxy-strings.ts b/graph-ui/src/galaxy/galaxy-strings.tsindex 920463172..7e5ace725 100644--- a/graph-ui/src/galaxy/galaxy-strings.ts+++ b/graph-ui/src/galaxy/galaxy-strings.ts@@ -77,6 +77,8 @@ export const galaxyLayerText = {// A comma, not the dot of the finished counts: tools that wait for "N nodes · M edges" must not take this for done.loadingProgress: (layer: number, nodes: number, edges: number) =>`Loading layer ${layer}: ${count(nodes, 'node', 'nodes')}, ${count(edges, 'edge', 'edges')} so far`,+ /** The tooltip of a running load: which request it is on, page by page (review of K8). */+ loadingRequest: (request: number) => `Request ${request.toLocaleString()} to the index; "−" cancels.`,arranging: 'Arranging nodes…',counts: (nodes: number, edges: number) => `${count(nodes, 'node', 'nodes')} · ${count(edges, 'edge', 'edges')}`,endOfTrace: ' · end of trace',@@ -89,9 +91,13 @@ export const galaxyLayerText = {removeLayer: 'Remove the outermost layer',cancelLoading: (layer: number) => `Cancel loading layer ${layer} and return to ${layer - 1 === 1 ? '1 layer' : `${layer - 1} layers`}`,/* Measured, not promised: a hub at the edge can bring far more than the last layer did (JSONBAgg layer 3: about 400 expected, over 9,000 loaded). */- expandTitle: (layer: number, frontier: number, estimate: number, limit: number) =>- `Load layer ${layer}: ${count(frontier, 'node', 'nodes')} to expand. Growing like the last layer it adds about ${estimate.toLocaleString()} nodes; `- + `a hub can add many more. Loading stops at the render limit of ${limit.toLocaleString()} nodes and marks the layer partial.`,+ /* With `calls` the index has counted the calls at the edge nodes (review of K8): a floor, where the growth alone missed the hubs. */+ expandTitle: (layer: number, frontier: number, estimate: number, limit: number, calls?: number) =>+ `Load layer ${layer}: ${count(frontier, 'node', 'nodes')} to expand. `+ + (calls === undefined+ ? `Growing like the last layer it adds about ${estimate.toLocaleString()} nodes; a hub can add many more. `+ : `The index lists ${count(calls, 'call', 'calls')} at them that ${calls === 1 ? 'is' : 'are'} not loaded yet; growing like the last layer it adds about ${estimate.toLocaleString()} nodes. `)+ + `Loading stops at the render limit of ${limit.toLocaleString()} nodes and marks the layer partial.`,expandOverLimit: 'Likely past the render limit.',expandPartial: 'This layer stopped at the render limit, so there is no complete edge to grow from. Raise the limit under Limits first.',expandEnd: 'End of trace: no relationship leads further.',diff --git a/graph-ui/src/galaxy/graph-scope.test.ts b/graph-ui/src/galaxy/graph-scope.test.tsindex 9a5476e90..4d2ccd4cf 100644--- a/graph-ui/src/galaxy/graph-scope.test.ts+++ b/graph-ui/src/galaxy/graph-scope.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest';-import { arrangeScopedGraph, graphEdgeTypesKey, hierarchyLabelWidth, limitGraphRender, loadGraphScope, nextLayerEstimate, readGraphPages, scenePictureFor, scopedHierarchy, type GraphQueryClient } from './graph-scope';+import { arrangeScopedGraph, frontierCallCount, graphEdgeTypesKey, hierarchyLabelWidth, limitGraphRender, loadGraphScope, nextLayerEstimate, readGraphPages, scenePictureFor, scopedHierarchy, type GraphQueryClient } from './graph-scope';import type { QueryGraphResult } from '../provider/rpc-schemas';import type { GraphData, GraphNode } from './types';@@ -338,6 +338,68 @@ describe('handtest K8: deep layers load in few large pages, report progress andexpect(nextLayerEstimate({ ...scoped, partial: { layer: 2, nodes: 7, edges: 6, limit: 'nodes' } })).toBeUndefined();});+ /* Review of K8: one batch of layer 3 read eight continuation pages, and the toolbar stood still for 8 s. */+ const continued = (records: Record<string, string>[][]) => {+ const total = records.flat().length;+ let at = 0;+ return records.map((rows, index) => {+ const offset = at; at += rows.length;+ return page(rows, { total, offset, ...(index < records.length - 1 ? { nextCursor: `c${index + 1}`, nextOffset: at } : {}) });+ });+ };++ it('reports progress after every page of a long batch, not only when the batch ends', async () => {+ const a = node(1);+ const queryGraph = vi.fn<GraphQueryClient['queryGraph']>().mockResolvedValueOnce(page([row(a)]));+ for (const result of continued([star(a, 2, 10), star(a, 2, 12), star(a, 2, 14)])) queryGraph.mockResolvedValueOnce(result);+ const progress = vi.fn();+ await loadGraphScope('p', scope, 1, 'outbound', undefined, { client: { queryGraph }, onProgress: progress });+ expect(progress.mock.calls.map(([value]) => [value.nodes, value.edges, value.requests])).toEqual([[3, 2, 2], [5, 4, 3], [7, 6, 4]]);+ });++ it('stops inside a batch at the page that passes the limit, and never caches the cut neighbourhood', async () => {+ const a = node(1);+ const queryGraph = vi.fn<GraphQueryClient['queryGraph']>().mockResolvedValueOnce(page([row(a)]));+ for (const result of continued([star(a, 3, 10), star(a, 3, 13), star(a, 3, 16)])) queryGraph.mockResolvedValueOnce(result);+ const cache = { node: () => undefined, roots: () => undefined, rememberRoots: vi.fn(), neighborhood: () => undefined, rememberNeighborhood: vi.fn() };+ const result = await loadGraphScope('p', scope, 2, 'outbound', undefined,+ { client: { queryGraph }, limits: { nodes: 5, edges: 1000 }, cache: cache as never });+ // Root, then two of the three pages: the second page passed five nodes.+ expect(queryGraph).toHaveBeenCalledTimes(3);+ expect(result.partial).toEqual({ layer: 1, nodes: 7, edges: 6, limit: 'nodes' });+ expect(result.data.nodes).toHaveLength(7);+ expect(cache.rememberNeighborhood).not.toHaveBeenCalled();+ });++ /*+ * Review of K8: growing like the last layer predicted about 400 nodes for layer 3 of JSONBAgg,+ * and over 9,000 came. Its 75 edge nodes carry 9,006 indexed calls (len, create, str, list ...);+ * the index counts them per node without walking a relationship.+ */+ describe('the indexed calls at the edge of a scope', () => {+ const degrees = (rows: [number, number, number][]) => page(rows.map(([id, calls_in, calls_out]) => ({ id: String(id), calls_in: String(calls_in), calls_out: String(calls_out) })));+ const edge = (node1: GraphNode, node2: GraphNode, node3: GraphNode) => ({+ data: { nodes: [node1, node2, node3], edges: [{ id: 1, source: 1, target: 2, type: 'CALLS' }, { id: 2, source: 1, target: 3, type: 'IMPORTS' }], total_nodes: 3 },+ roots: new Set([1]), depth: 1, exhausted: false, frontier: [2, 3], levels: new Map([[1, 0], [2, 1], [3, 1]]) });++ it('adds the calls into and out of the edge nodes and leaves out the ones already loaded', async () => {+ const queryGraph = vi.fn<GraphQueryClient['queryGraph']>().mockResolvedValueOnce(degrees([[2, 5, 1], [3, 0, 4]]));+ expect(await frontierCallCount({ queryGraph }, 'p', edge(node(1), node(2), node(3)), 'both', undefined)).toBe(9);+ expect(queryGraph).toHaveBeenCalledTimes(1);+ expect(queryGraph.mock.calls[0]![1]).toMatch(/^MATCH \(n\) WHERE \(n\.qualified_name = "p\.n2" OR n\.qualified_name = "p\.n3"\) RETURN id\(n\) AS id, n\.in_degree AS calls_in, n\.out_degree AS calls_out$/);+ });++ it('counts only the traced direction, and nothing when calls are not traced', async () => {+ const queryGraph = vi.fn<GraphQueryClient['queryGraph']>().mockResolvedValue(degrees([[2, 5, 1], [3, 0, 4]]));+ expect(await frontierCallCount({ queryGraph }, 'p', edge(node(1), node(2), node(3)), 'outbound', undefined)).toBe(5);+ expect(await frontierCallCount({ queryGraph }, 'p', edge(node(1), node(2), node(3)), 'inbound', ['CALLS', 'TESTS'])).toBe(4);+ queryGraph.mockClear();+ expect(await frontierCallCount({ queryGraph }, 'p', edge(node(1), node(2), node(3)), 'both', ['IMPORTS'])).toBeUndefined();+ expect(await frontierCallCount({ queryGraph }, 'p', { ...edge(node(1), node(2), node(3)), exhausted: true }, 'both', undefined)).toBeUndefined();+ expect(queryGraph).not.toHaveBeenCalled();+ });+ });+it('stops at the edge limit too', async () => {const a = node(1);const queryGraph = vi.fn<GraphQueryClient['queryGraph']>().mockResolvedValueOnce(page([row(a)]))diff --git a/graph-ui/src/galaxy/graph-scope.ts b/graph-ui/src/galaxy/graph-scope.tsindex a1015bc13..227a2d828 100644--- a/graph-ui/src/galaxy/graph-scope.ts+++ b/graph-ui/src/galaxy/graph-scope.ts@@ -39,9 +39,11 @@ const nodeColumns = (alias: string, prefix: string) => [`id(${alias}) AS ${prefi/** The cursor binds a complete query result to one graph generation. Every* continuation is consumed; a daemon cap or missing cursor is never silently- * accepted as the selected file's complete neighborhood. */+ * accepted as the selected file's complete neighborhood. The one exception is+ * `onPage` answering 'stop' (a layer at its render limit, K8): the caller then+ * holds a deliberately cut result and must mark it partial. */export async function readGraphPages(client: GraphQueryClient, project: string, query: string, key: string, signal?: AbortSignal,- onRequest?: () => void): Promise<Record<string, string>[]> {+ onRequest?: () => void, onPage?: (rows: readonly Record<string, string>[]) => 'stop' | void): Promise<Record<string, string>[]> {signal?.throwIfAborted();onRequest?.();let page = await client.queryGraph(project, query, undefined, SCOPE_PAGE_BUDGET);@@ -51,12 +53,14 @@ export async function readGraphPages(client: GraphQueryClient, project: string,signal?.throwIfAborted();if (JSON.stringify(columns) !== JSON.stringify(page.columns) || page.total !== total|| (page.offset !== undefined && page.offset !== records.length)) throw new Error('Graph pagination changed its result snapshot.');+ const fresh: Record<string, string>[] = [];for (const row of page.rows) {const record = Object.fromEntries(columns.map((column, index) => [column, row[index] ?? '']));const identity = id(record[key]);if (identities.has(identity)) throw new Error('Graph pagination repeated a row.');- identities.add(identity); records.push(record);+ identities.add(identity); records.push(record); fresh.push(record);}+ if (onPage?.(fresh) === 'stop') return records;if (!page.nextCursor) {if (page.hasMore || page.truncated || page.totalRelation === 'gte' || (total !== undefined && records.length < total))throw new Error(`Incomplete graph response (${records.length} relationships read); ${page.truncationReason ?? 'the server did not provide a continuation'}.`);@@ -197,25 +201,35 @@ export async function loadGraphScope(project: string, scope: GraphScope, depth:// Keep each predicate on the left seed, so early WHERE prunes before// adjacency expansion. An OR spanning a and b materializes the repo.const pattern = leg === 'inbound' ? `(b)<-${relationship}-(a)` : `(a)-${relationship}->(b)`;- const rows = await readGraphPages(client, project, `MATCH ${pattern} WHERE ${relation} RETURN id(r) AS edge_id, type(r) AS edge_type, r.line AS edge_line, ${nodeColumns('a', 'a_')}, ${nodeColumns('b', 'b_')}`, 'edge_id', options.signal, counted);const evidenceNodes = new Map(batch.map(identity => [identity, nodes.get(identity)!]));const evidenceEdges: GraphEdge[] = [];- for (const row of rows) {- // Filter before discovering a frontier, including on older servers- // whose typed-pattern implementation may return extra rows.- if (allowedTypes && !allowedTypes.has(row.edge_type ?? '')) continue;- const source = readNode(row, 'a_', known), target = readNode(row, 'b_', known);- const incident = leg === 'inbound' ? batchIds.has(target.id) : batchIds.has(source.id);- if (!incident) continue; // Qualified names are not assumed unique.- evidenceNodes.set(source.id, source); evidenceNodes.set(target.id, target);- const identity = id(row.edge_id);- evidenceEdges.push({ id: identity, source: source.id, target: target.id, type: row.edge_type ?? '', line: number(row.edge_line) });- }- const verifiedNodes = [...evidenceNodes.values()];- options.cache?.rememberNeighborhood(batch, leg, edgeTypes, verifiedNodes, evidenceEdges);- accept(verifiedNodes, evidenceEdges);- options.onProgress?.({ layer: hop + 1, nodes: nodes.size, edges: edges.size, requests });- partial = overLimit(hop + 1);+ /*+ * Seite fuer Seite (Review zu K8): ein Stapel der dritten Ebene+ * um JSONBAgg las acht Fortsetzungsseiten, und die Leiste stand+ * dabei 8 s still. Jetzt zaehlt jede Seite sofort, und die Seite,+ * die ueber das Render-Limit fuehrt, ist die letzte: der Rest des+ * Stapels wird nicht mehr gelesen. Ein so abgeschnittener Stapel+ * kommt nicht in den Nachbarschafts-Cache.+ */+ await readGraphPages(client, project, `MATCH ${pattern} WHERE ${relation} RETURN id(r) AS edge_id, type(r) AS edge_type, r.line AS edge_line, ${nodeColumns('a', 'a_')}, ${nodeColumns('b', 'b_')}`, 'edge_id', options.signal, counted, (rows) => {+ const pageNodes = new Map<number, GraphNode>(), pageEdges: GraphEdge[] = [];+ for (const row of rows) {+ // Filter before discovering a frontier, including on older servers+ // whose typed-pattern implementation may return extra rows.+ if (allowedTypes && !allowedTypes.has(row.edge_type ?? '')) continue;+ const source = readNode(row, 'a_', known), target = readNode(row, 'b_', known);+ const incident = leg === 'inbound' ? batchIds.has(target.id) : batchIds.has(source.id);+ if (!incident) continue; // Qualified names are not assumed unique.+ for (const end of [source, target]) { evidenceNodes.set(end.id, end); pageNodes.set(end.id, end); }+ const edge = { id: id(row.edge_id), source: source.id, target: target.id, type: row.edge_type ?? '', line: number(row.edge_line) };+ evidenceEdges.push(edge); pageEdges.push(edge);+ }+ accept([...pageNodes.values()], pageEdges);+ options.onProgress?.({ layer: hop + 1, nodes: nodes.size, edges: edges.size, requests });+ partial = overLimit(hop + 1);+ return partial ? 'stop' : undefined;+ });+ if (!partial) options.cache?.rememberNeighborhood(batch, leg, edgeTypes, [...evidenceNodes.values()], evidenceEdges);}}reachedDepth = hop + 1;@@ -230,6 +244,38 @@ export async function loadGraphScope(project: string, scope: GraphScope, depth:exhausted: !partial && (edgeTypes?.length === 0 || (depth > 0 && frontier.length === 0)), frontier, levels, traversalKey, ...(partial ? { partial } : {}) };}+/*+ * Die Aufrufe am Rand eines Ausschnitts, bevor die naechste Ebene laedt+ * (Review zu K8). Das Wachstum der letzten Ebene sagte fuer die dritte Ebene um+ * JSONBAgg rund 400 Knoten voraus, und es kamen ueber 9.000: unter den 75+ * Randknoten stehen len, create, str und list mit je ueber tausend Aufrufern.+ * Der Index zaehlt die CALLS eines Knotens, ohne eine Beziehung abzulaufen+ * (`n.in_degree`, `n.out_degree`, rund 0,2 s fuer 64 Knoten). Was davon schon+ * geladen ist, faellt heraus; der Rest ist eine Untergrenze fuer die Zeilen der+ * naechsten Ebene, und meist fuehrt jede zu einem neuen Knoten. Andere Arten+ * zaehlt der Index so nicht; ohne CALLS gibt es keine Zahl.+ */+export async function frontierCallCount(client: GraphQueryClient, project: string, scoped: ScopedGraph, direction: TraceDirection,+ edgeTypes: readonly string[] | undefined, signal?: AbortSignal): Promise<number | undefined> {+ if (scoped.exhausted || scoped.partial || !scoped.frontier?.length || (edgeTypes && !edgeTypes.includes('CALLS'))) return undefined;+ const frontier = new Set(scoped.frontier), byId = new Map(scoped.data.nodes.map(node => [node.id, node]));+ const names = [...frontier].map(identity => byId.get(identity)?.qualified_name).filter((name): name is string => Boolean(name));+ let calls = 0;+ for (let at = 0; at < names.length; at += BATCH_SIZE) {+ const rows = await readGraphPages(client, project, `MATCH (n) WHERE ${anyNames('n', names.slice(at, at + BATCH_SIZE))} RETURN id(n) AS id, n.in_degree AS calls_in, n.out_degree AS calls_out`, 'id', signal);+ for (const row of rows) {+ if (!frontier.has(id(row.id))) continue;+ calls += (direction !== 'outbound' ? number(row.calls_in) ?? 0 : 0) + (direction !== 'inbound' ? number(row.calls_out) ?? 0 : 0);+ }+ }+ for (const edge of scoped.data.edges) {+ if (edge.type !== 'CALLS') continue;+ if (direction !== 'outbound' && frontier.has(edge.target)) calls -= 1;+ if (direction !== 'inbound' && frontier.has(edge.source)) calls -= 1;+ }+ return Math.max(0, calls);+}+/** Eine Schaetzung der naechsten Ebene, bevor sie geladen wird (K8): so viele* Knoten stehen an ihrem Rand, und so viele neue brachte jeder Knoten der* letzten Ebene. Eine Schaetzung und keine Zusage; die Grenze beim Ladendiff --git a/graph-ui/src/galaxy/test-scope-fetch.ts b/graph-ui/src/galaxy/test-scope-fetch.tsindex 639b51a0d..c56c2c03c 100644--- a/graph-ui/src/galaxy/test-scope-fetch.ts+++ b/graph-ui/src/galaxy/test-scope-fetch.ts@@ -14,6 +14,8 @@ export interface ScopeFetchOptions {edges: GraphEdge[];/** Jede Kantenabfrage wartet auf dieses Versprechen, wenn es gesetzt ist. */gate?: () => Promise<void>;+ /** Die CALLS je Knoten, die der Index zaehlt (`n.in_degree`, `n.out_degree`); fehlt einer, sind es keine. */+ degrees?: Record<number, { in: number; out: number }>;}export function scopeNode(id: number, extra: Partial<GraphNode> = {}): GraphNode {@@ -21,7 +23,7 @@ export function scopeNode(id: number, extra: Partial<GraphNode> = {}): GraphNodestart_line: 1, end_line: 5, x: id * 10, y: 0, z: 0, size: 2, color: '#999999', ...extra };}-export function scopeFetch({ nodes, edges, gate }: ScopeFetchOptions) {+export function scopeFetch({ nodes, edges, gate, degrees = {} }: ScopeFetchOptions) {const calls: { tool: string; args: Record<string, unknown> }[] = [];const fetch = vi.fn(async (url: RequestInfo | URL, init?: RequestInit) => {if (String(url).includes('/api/layout')) return new Response(JSON.stringify({ nodes, edges, total_nodes: nodes.length }));@@ -35,7 +37,11 @@ export function scopeFetch({ nodes, edges, gate }: ScopeFetchOptions) {const values = (entry: GraphNode) => [entry.id, entry.label, entry.name, entry.qualified_name ?? '', entry.file_path ?? '', entry.start_line ?? '', entry.end_line ?? ''].map(String);const names = [...query.matchAll(/qualified_name = "([^"]+)"/g)].map(match => match[1]);let cols: string[], rows: string[][];- if (query.startsWith('MATCH (n)')) {+ if (query.includes('n.in_degree')) {+ cols = ['id', 'calls_in', 'calls_out'];+ rows = nodes.filter(entry => names.includes(entry.qualified_name ?? ''))+ .map(entry => [String(entry.id), String(degrees[entry.id]?.in ?? 0), String(degrees[entry.id]?.out ?? 0)]);+ } else if (query.startsWith('MATCH (n)')) {cols = columns(''); rows = nodes.filter(entry => names.includes(entry.qualified_name ?? '')).map(values);} else {if (gate) await gate();diff --git a/graph-ui/src/galaxy/use-graph-scope.ts b/graph-ui/src/galaxy/use-graph-scope.tsindex c4f8988e5..0c73f881d 100644--- a/graph-ui/src/galaxy/use-graph-scope.ts+++ b/graph-ui/src/galaxy/use-graph-scope.ts@@ -1,5 +1,5 @@import { useEffect, useMemo, useRef, useState } from 'react';-import { graphEdgeTypesKey, loadGraphScope, type GraphScope, type ScopedGraph, type ScopeProgress, type TraceDirection } from './graph-scope';+import { frontierCallCount, graphEdgeTypesKey, loadGraphScope, type GraphScope, type ScopedGraph, type ScopeProgress, type TraceDirection } from './graph-scope';import { RpcIntelligenceClient } from '../provider/rpc-client';import { readerGraphFocus, type SourceFocusRange } from './reader-graph-focus';import type { GraphData } from './types';@@ -104,6 +104,27 @@ export function useGraphScope({ project, layout, filePath, range, fetch: fetchIm}, [key, fetchImpl]);const complete = result?.key === key ? result.value : undefined;const error = failure?.key === key ? failure.message : undefined;+ /*+ * Die Aufrufe am Rand, sobald eine Ebene fertig ist (Review zu K8): eine+ * kurze Zaehlabfrage, damit "Expand +1" vor einer Explosion warnt und nicht+ * erst das Render-Limit sie anhaelt. Je Ausschnitt und Tiefe einmal.+ */+ const edgeCallsCache = useRef(new Map<string, number>());+ const [edgeCalls, setEdgeCalls] = useState<{ key: string; calls: number }>();+ useEffect(() => {+ if (!complete || !project) return;+ const known = edgeCallsCache.current.get(key);+ if (known !== undefined) { setEdgeCalls({ key, calls: known }); return; }+ const abort = new AbortController();+ const client = new RpcIntelligenceClient({ fetch: fetchImpl, signal: abort.signal });+ void frontierCallCount(client, project, complete, actualDirection, selectedTypes, abort.signal).then(calls => {+ if (abort.signal.aborted || calls === undefined) return;+ if (edgeCallsCache.current.size >= 16) edgeCallsCache.current.delete(edgeCallsCache.current.keys().next().value!);+ edgeCallsCache.current.set(key, calls); setEdgeCalls({ key, calls });+ }).catch(() => { /* Ohne Zahl bleibt es bei der Schaetzung aus dem Wachstum. */ });+ return () => abort.abort();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [complete, key]);const fallback = useMemo<ScopedGraph | undefined>(() => {if (!scope || !layout) return undefined;const roots = scope.kind === 'file' ? readerGraphFocus(layout.nodes, scope.path, scope.range).ids@@ -137,6 +158,8 @@ export function useGraphScope({ project, layout, filePath, range, fetch: fetchImconst minDepth = filePath ? 1 : minimumScopeDepth(scope);return { scope, depth: actualDepth, minDepth, direction, setDirection,progress: progress?.key === key && !complete ? progress.value : undefined,+ /** The indexed calls at the edge of a complete layer that are not loaded yet, once counted. */+ edgeCalls: edgeCalls?.key === key && complete ? edgeCalls.calls : undefined,result: complete ?? (cachedPreview?.key === key ? cachedPreview.value : undefined)?? (result?.scopeKey === scopeKey && result.value.depth <= actualDepth ? result.value : fallback), loading: Boolean(scope && !complete && !error), error,validating: Boolean(scope && !complete && !error && pendingPhase?.key === key && pendingPhase.validating),