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
feat(ui): add Galaxy back and forward and keep the scope on empty clicks
Bernhard Jackiewicz80b8f7965fda
diff --git a/docs/development/pr-2068-galaxy-history.md b/docs/development/pr-2068-galaxy-history.mdnew file mode 100644index 000000000..758b5c6d7--- /dev/null+++ b/docs/development/pr-2068-galaxy-history.md@@ -0,0 +1,71 @@+# PR 2068: Galaxy back and forward (K2)++Hand test finding K2: a click on a node makes it the new root, and the only way+out is "All graph". This note fixes the concept before the code. K9 belongs to+it: a click on empty canvas no longer leaves the scope, so Back is the way to+undo a step.++## What an entry is++One entry is the complete question the Galaxy workspace answers at that moment:++| Field | Meaning |+|---|---|+| `scope` | The root identity: node id, qualified name and display name, or a file or folder path. Missing means "All graph". |+| `depth` | Loaded layers (hops). |+| `direction` | `both`, `inbound` or `outbound`. |+| `edgeTypes` | The traced relationship types, or all. |+| `trail` | The open path target (`path` to node id) or `calls` (call order), if one is shown. |+| `mode` | `galaxy` or `hierarchy`. |++The entry holds identities and parameters only, never loaded nodes, edges,+layouts or camera positions. Going back re-runs the scope; the bounded scope+cache (four results) and the neighbourhood cache make that fast in practice,+and nothing grows with the session.++"All graph" is an entry like any other, so Back after "All graph" returns to+the scope that was open before.++## Rules++1. **Bounded.** At most 25 entries. A push beyond that drops the oldest entry.+2. **Consecutive duplicates merge.** An entry equal to the current one (same+ key over all fields) is not pushed. Revisiting the same root later is a new+ entry, because it is a new step.+3. **Browser semantics.** Back and Forward move a cursor. A new navigation after+ going back drops the forward branch.+4. **No browser history per step.** There is no `pushState` per step: a long+ session would leave thousands of browser entries, and the browser Back button+ would no longer leave the page. The address bar keeps its current role.+5. **Recent roots.** Besides the linear history a list of the last 8 distinct+ roots (newest first) allows a direct jump. A jump is a new navigation: it+ restores that root with its last depth, direction and edge types and drops the+ forward branch. The list is independent of the cursor, so going back does not+ shorten it.+6. **Keyboard.** Alt+Left is Back, Alt+Right is Forward, not while typing in a+ field or the editor, and not while another surface takes the keys+ (`escapeTaken`). The page prevents the browser default for these keys.+7. **Escape.** Escape first clears an open path, then leaves the scope ("All+ graph"), which is itself a history entry.+8. **Per project.** A project switch starts a fresh history.++## Where it lives++- `graph-ui/src/graph/navigation-history.ts`: the generic, pure model+ (`push`, `back`, `forward`, `recent`) over any entry with a key function. K27+ (Architecture back and forward) is meant to reuse this module rather than+ write a second one.+- `graph-ui/src/galaxy/scope-history.ts`: the Galaxy entry, its key and the+ tooltips that name a target ("Back to JSONBAgg · 2 layers").+- `GalaxyPanel.tsx`: derives the current entry from its state, pushes it when it+ changes, restores an entry on Back, Forward or a recent jump, and shows the+ Back and Forward buttons with disabled states and the Recent list in the+ scoped toolbar.++## Not in scope++- No breadcrumb of the whole chain. The tooltips name the Back and Forward+ targets, and the Recent list names the roots; a breadcrumb would cost the one+ toolbar row that K3 asks for.+- No persistence across reloads. A reload starts with an empty history, the same+ as a new browser tab.diff --git a/graph-ui/src/galaxy/GalaxyPanel.history.test.tsx b/graph-ui/src/galaxy/GalaxyPanel.history.test.tsxnew file mode 100644index 000000000..62aa0773d--- /dev/null+++ b/graph-ui/src/galaxy/GalaxyPanel.history.test.tsx@@ -0,0 +1,208 @@+// @vitest-environment jsdom+/*+ * Handtest K9 und K2: ein Klick ins Leere verlaesst den Ausschnitt nicht mehr,+ * und Zurueck/Vor fuehren durch die letzten Ausschnitte. Die Szene ist eine+ * Attrappe mit einem Knopf fuer die leere Flaeche; die Beziehungen kommen ueber+ * dieselbe RPC-Strecke wie im Betrieb (test-scope-fetch.ts).+ */+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import GalaxyPanel from './GalaxyPanel';+import type { GraphData } from './types';+import type { ScenePath } from './PathLayer';+import { scopeFetch, scopeNode } from './test-scope-fetch';++const scene = vi.hoisted(() => ({ path: undefined as ScenePath | undefined, nodes: 0 }));+vi.mock('./GraphScene', async importOriginal => ({+ ...await importOriginal<typeof import('./GraphScene')>(),+ GraphScene: ({ data, path, onBackgroundClick }: { data: GraphData; path?: ScenePath; onBackgroundClick?: () => void }) => {+ scene.path = path; scene.nodes = data.nodes.length;+ return <button type="button" onClick={onBackgroundClick}>Empty canvas</button>;+ },+}));++const nodes = [1, 2, 3, 4, 5].map(id => scopeNode(id));+const edges = [+ { id: 11, source: 1, target: 2, type: 'CALLS', line: 3 }, { id: 12, source: 3, target: 1, type: 'CALLS', line: 4 },+ { id: 13, source: 2, target: 4, type: 'CALLS', line: 2 }, { id: 14, source: 4, target: 5, type: 'IMPORTS' },+ { id: 15, source: 1, target: 5, type: 'CALLS', line: 1 },+];++let host: HTMLDivElement, root: Root;+beforeEach(() => {+ (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;+ host = document.createElement('div'); document.body.append(host); root = createRoot(host);+});+afterEach(async () => { await act(async () => root.unmount()); host.remove(); globalThis.__atlasGalaxy = undefined; });++const seam = () => globalThis.__atlasGalaxy!;+const settle = (check: () => void) => vi.waitFor(async () => {+ await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });+ check();+});+const button = (label: string) => [...host.querySelectorAll('button')].find(entry => entry.textContent === label);+const named = (name: string) => host.querySelector<HTMLButtonElement>(`button[aria-label="${name}"]`);+const scopeName = () => host.querySelector('.atlas-graph-scope-name')?.textContent ?? '';+const layers = () => [...host.querySelectorAll('.atlas-graph-exploration span')].map(entry => entry.textContent ?? '').find(text => /^\d+ layers?$/.test(text));+const pathPanel = () => host.querySelector('[data-testid="atlas-galaxy-path-panel"]');+const pickPath = (name: string) => act(async () => {+ host.querySelector<HTMLDetailsElement>('.atlas-graph-path-picker')!.open = true;+ [...host.querySelectorAll<HTMLButtonElement>('.atlas-graph-path-menu li button')]+ .find(entry => entry.querySelector('strong')?.textContent === name)!.click();+});+const key = (init: KeyboardEventInit, target: EventTarget = window) => {+ const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init });+ act(() => { target.dispatchEvent(event); });+ return event;+};++async function openScope(clearSelection = vi.fn()) {+ await act(async () => root.render(<GalaxyPanel project="sample" visible workspaceExpanded onOpenNode={vi.fn()}+ onClearSelection={clearSelection} fetch={scopeFetch({ nodes, edges }).fetch} />));+ await settle(() => expect(seam().nodes).toBe(5));+ await act(async () => { seam().clickNode('sample.n1'); });+ await settle(() => expect(host.querySelector('.atlas-graph-scope-count')?.textContent).toBe('4 nodes · 3 edges'));+}++it('K9: a click on empty canvas keeps the scope, its layers and trace and only clears the path highlight', async () => {+ const clearSelection = vi.fn();+ await openScope(clearSelection);+ await act(async () => button('Expand +1')!.click());+ await settle(() => expect(seam().nodes).toBe(5));+ await pickPath('n4');+ expect(pathPanel()).not.toBeNull();++ await act(async () => button('Empty canvas')!.click());+ expect(scopeName()).toBe('n1');+ expect(layers()).toBe('2 layers');+ expect(seam().nodes).toBe(5);+ expect(pathPanel()).toBeNull();+ expect(scene.path).toBeUndefined();+ expect(clearSelection).not.toHaveBeenCalled();+ // A second click on empty canvas changes nothing either.+ await act(async () => button('Empty canvas')!.click());+ expect(scopeName()).toBe('n1');+});++it('K9: Escape clears an open path first and then leaves the scope, unless another surface takes the key', async () => {+ await openScope();+ await pickPath('n2');+ expect(key({ key: 'Escape' }).defaultPrevented).toBe(true);+ expect(pathPanel()).toBeNull();+ expect(scopeName()).toBe('n1');+ // Typing in a field: Escape stays with the field.+ expect(key({ key: 'Escape' }, host.querySelector('input[aria-label="Find a graph node"]')!).defaultPrevented).toBe(false);+ expect(scopeName()).toBe('n1');+ expect(key({ key: 'Escape' }).defaultPrevented).toBe(true);+ await settle(() => expect(seam().nodes).toBe(5));+ expect(host.querySelector('.atlas-graph-scope-name')).toBeNull();+});++it('K2: Back and Forward walk the recent scopes, name their targets and stop at both ends', async () => {+ await openScope();+ expect(named('Back')?.disabled).toBe(false);+ expect(named('Back')?.title).toBe('Back to All graph (Alt+Left)');+ expect(named('Forward')?.disabled).toBe(true);+ await act(async () => button('Expand +1')!.click());+ await settle(() => expect(seam().nodes).toBe(5));+ await act(async () => { seam().clickNode('sample.n4'); });+ await settle(() => expect(scopeName()).toBe('n4'));+ expect(named('Back')?.title).toBe('Back to n1 · 2 layers (Alt+Left)');++ await act(async () => named('Back')!.click());+ await settle(() => expect(seam().nodes).toBe(5));+ expect(scopeName()).toBe('n1');+ expect(layers()).toBe('2 layers');+ expect(named('Forward')?.title).toBe('Forward to n4 · 1 layer (Alt+Right)');+ await act(async () => named('Back')!.click());+ await settle(() => expect(layers()).toBe('1 layer'));+ await act(async () => named('Back')!.click());+ await settle(() => expect(host.querySelector('.atlas-graph-scope-name')).toBeNull());+ expect(seam().nodes).toBe(5);+ expect(named('Back')?.disabled).toBe(true);++ await act(async () => named('Forward')!.click());+ await settle(() => expect(scopeName()).toBe('n1'));+ expect(layers()).toBe('1 layer');+ // A new navigation after going back drops the forward branch.+ await act(async () => { seam().clickNode('sample.n3'); });+ await settle(() => expect(scopeName()).toBe('n3'));+ expect(named('Forward')?.disabled).toBe(true);+});++it('K2: a project that arrives after the first render starts its history with All graph', async () => {+ const { fetch } = scopeFetch({ nodes, edges });+ await act(async () => root.render(<GalaxyPanel project="" visible workspaceExpanded onOpenNode={vi.fn()} fetch={fetch} />));+ await act(async () => root.render(<GalaxyPanel project="sample" visible workspaceExpanded onOpenNode={vi.fn()} fetch={fetch} />));+ await settle(() => expect(seam().nodes).toBe(5));+ await act(async () => { seam().clickNode('sample.n1'); });+ await settle(() => expect(scopeName()).toBe('n1'));+ expect(seam().history).toMatchObject({ index: 1, entries: ['All graph', 'n1 · 1 layer'] });+ expect(named('Back')?.title).toBe('Back to All graph (Alt+Left)');+ // A project switch with an open scope starts again from the new project's whole graph.+ await act(async () => root.render(<GalaxyPanel project="other" visible workspaceExpanded onOpenNode={vi.fn()} fetch={fetch} />));+ await settle(() => expect(host.querySelector('.atlas-graph-scope-name')).toBeNull());+ expect(seam().history.entries).toEqual(['All graph']);+});++it('K2: All graph is an entry, so Back returns to the scope that was open', async () => {+ await openScope();+ await act(async () => button('All graph')!.click());+ await settle(() => expect(host.querySelector('.atlas-graph-scope-name')).toBeNull());+ expect(named('Back')?.title).toBe('Back to n1 · 1 layer (Alt+Left)');+ await act(async () => named('Back')!.click());+ await settle(() => expect(scopeName()).toBe('n1'));+});++it('K2: Back restores the trace direction and the path that a click on empty canvas cleared', async () => {+ await openScope();+ await pickPath('n2');+ await act(async () => button('Empty canvas')!.click());+ expect(pathPanel()).toBeNull();+ expect(named('Back')?.title).toBe('Back to n1 · 1 layer · path to n2 (Alt+Left)');+ await act(async () => named('Back')!.click());+ expect(pathPanel()?.textContent).toContain('Path to n2');++ await act(async () => {+ const select = host.querySelector<HTMLSelectElement>('select[aria-label="Trace direction"]')!;+ select.value = 'inbound'; select.dispatchEvent(new Event('change', { bubbles: true }));+ });+ await settle(() => expect(seam().nodes).toBe(2));+ await act(async () => named('Back')!.click());+ await settle(() => expect(seam().nodes).toBe(4));+ expect(host.querySelector<HTMLSelectElement>('select[aria-label="Trace direction"]')!.value).toBe('both');+});++it('K2: Alt+Left and Alt+Right go back and forward, but not while typing', async () => {+ await openScope();+ await act(async () => { seam().clickNode('sample.n2'); });+ await settle(() => expect(scopeName()).toBe('n2'));+ const field = host.querySelector('input[aria-label="Find a graph node"]')!;+ expect(key({ key: 'ArrowLeft', altKey: true }, field).defaultPrevented).toBe(false);+ expect(scopeName()).toBe('n2');+ expect(key({ key: 'ArrowLeft', altKey: true }).defaultPrevented).toBe(true);+ await settle(() => expect(scopeName()).toBe('n1'));+ expect(key({ key: 'ArrowRight', altKey: true }).defaultPrevented).toBe(true);+ await settle(() => expect(scopeName()).toBe('n2'));+ // Without Alt the arrows stay with the page.+ expect(key({ key: 'ArrowLeft' }).defaultPrevented).toBe(false);+});++it('K2: the recent list jumps straight to an earlier root with its last depth', async () => {+ await openScope();+ await act(async () => button('Expand +1')!.click());+ await settle(() => expect(seam().nodes).toBe(5));+ await act(async () => { seam().clickNode('sample.n4'); });+ await settle(() => expect(scopeName()).toBe('n4'));+ await act(async () => { seam().clickNode('sample.n5'); });+ await settle(() => expect(scopeName()).toBe('n5'));+ const recent = host.querySelector<HTMLDetailsElement>('details.atlas-graph-recent')!;+ expect([...recent.querySelectorAll('li button strong')].map(entry => entry.textContent)).toEqual(['n5', 'n4', 'n1']);+ recent.open = true;+ await act(async () => [...recent.querySelectorAll<HTMLButtonElement>('li button')].find(entry => entry.querySelector('strong')?.textContent === 'n1')!.click());+ await settle(() => expect(scopeName()).toBe('n1'));+ expect(layers()).toBe('2 layers');+ expect(named('Forward')?.disabled).toBe(true);+ expect(named('Back')?.title).toBe('Back to n5 · 1 layer (Alt+Left)');+});diff --git a/graph-ui/src/galaxy/GalaxyPanel.tsx b/graph-ui/src/galaxy/GalaxyPanel.tsxindex 098cb970f..5a396816a 100644--- a/graph-ui/src/galaxy/GalaxyPanel.tsx+++ b/graph-ui/src/galaxy/GalaxyPanel.tsx@@ -139,7 +139,9 @@ import GalaxyNavigator from './GalaxyNavigator';import { TraceEdgeFilter } from './TraceEdgeFilter';import { PathPicker, PathSteps } from './ScopePathControls';import { callOrder, pathNodes, shortestScopePath, type ScopePathStep } from './scope-path';-import { galaxyPathText, galaxyToolbarText } from './galaxy-strings';+import { galaxyHistoryText, galaxyPathText, galaxyToolbarText } from './galaxy-strings';+import { emptyNavigationHistory, moveNavigation, peekNavigation, pushNavigation } from '../graph/navigation-history';+import { galaxyHistoryOptions, historyEntryDetail, historyEntryLabel, scopeIdentity, type GalaxyHistoryEntry, type ScopeTrail } from './scope-history';import { useOrganicLayout } from './use-organic-layout';import RenderProgress from './RenderProgress';import { useGraphScope } from './use-graph-scope';@@ -451,6 +453,8 @@ export interface AtlasGalaxySeam {drawnEdges: number;/** Die zweite Kopfzeile: woraus die Linien bestehen und was fehlt. */edgeNote: string;+ /** Der Verlauf aus Zurueck und Vor (K2): Eintraege als Tooltip-Text, der Zeiger, die letzten Wurzeln. */+ history: { index: number; entries: string[]; recent: string[] };}/** Ein Akteur, so wie der Beweislauf ihn liest. */@@ -1834,7 +1838,8 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {[layout, data, picture, mode, flyTo, onOpenNode, props.onSelectNode, props.workspaceExpanded, scope.select, clearTrail],);- const handleBackgroundClick = useCallback(() => {+ /* "All graph" und Escape: der Ausschnitt wird verlassen, und das ist selbst ein Schritt im Verlauf (K2). */+ const leaveScope = useCallback(() => {setBackgroundCleared(true);if (props.workspaceExpanded) setChosenMode('galaxy');clearTrail();@@ -1845,6 +1850,140 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {refitNow();props.onClearSelection?.();}, [mode, refitNow, props.onClearSelection, readerProjection, scope.reset, props.workspaceExpanded, changeTraceTypes, clearTrail]);+ /*+ * Ein Klick ins Leere hebt im Ausschnitt nur die Markierung auf (Handtest+ * K9). Bis dahin verliess er den Ausschnitt samt Ebenen und Pfad, ohne+ * Rueckfrage, und ein Klick knapp neben einen Knoten genuegte. Aus dem+ * Ausschnitt fuehren jetzt nur "All graph", Escape und Zurueck; der+ * aufgehobene Pfad ist ein Schritt im Verlauf und kommt mit Zurueck wieder.+ */+ const handleBackgroundClick = useCallback(() => {+ if (props.workspaceExpanded && scope.scope) { clearTrail(); return; }+ leaveScope();+ }, [props.workspaceExpanded, scope.scope, clearTrail, leaveScope]);++ /*+ * Zurueck und Vor (Handtest K2), wie beim Blaettern.+ *+ * Der Eintrag ist die ganze Frage dieses Augenblicks: Wurzel, Tiefe,+ * Richtung, Kantenarten, offener Pfad und Ansicht, und nichts von der+ * Antwort. Er wird aus dem Zustand ABGELEITET und nicht an jeder Stelle+ * abgelegt, die ihn aendert; so kann kein Weg in einen neuen Ausschnitt den+ * Verlauf vergessen. Was ein Zurueck selbst herstellt, legt keinen neuen+ * Eintrag ab (`restoringKey`). Regeln und Grenzen: src/graph/navigation-history.ts+ * und docs/development/pr-2068-galaxy-history.md.+ */+ const historyTrail: ScopeTrail | undefined = trail?.key !== organicKey ? undefined+ : trail.kind === 'calls' ? { kind: 'calls' } : { kind: 'path', target: trail.target, name: trail.name };+ const historyEntry: GalaxyHistoryEntry | undefined = props.workspaceExpanded ? {+ ...(scope.scope ? { scope: scope.scope } : {}), depth: scope.depth, direction: scope.direction,+ ...(traceTypes ? { edgeTypes: traceTypes } : {}), ...(historyTrail ? { trail: historyTrail } : {}), mode,+ } : undefined;+ const historyKey = historyEntry ? galaxyHistoryOptions.key(historyEntry) : '';+ const latestEntry = useRef(historyEntry);+ latestEntry.current = historyEntry;+ const [history, setHistory] = useState(() => emptyNavigationHistory<GalaxyHistoryEntry>());+ const restoringKey = useRef<string | undefined>(undefined);+ const selectOnComplete = useRef<string | undefined>(undefined);+ const historyProject = useRef(project);+ useEffect(() => {+ const entry = latestEntry.current;+ /*+ * Ein Projektwechsel beginnt einen neuen Verlauf. Das Projekt kommt oft+ * erst nach dem ersten Bild aus der Adresszeile; der ganze Graph steht+ * dann schon da und muss der erste Eintrag bleiben. Ein offener+ * Ausschnitt gehoert noch zum alten Projekt und wird nicht uebernommen.+ */+ if (historyProject.current !== project) {+ historyProject.current = project;+ restoringKey.current = undefined;+ const fresh = emptyNavigationHistory<GalaxyHistoryEntry>();+ setHistory(entry !== undefined && !entry.scope ? pushNavigation(fresh, entry, galaxyHistoryOptions) : fresh);+ return;+ }+ if (entry === undefined) return;+ const expected = restoringKey.current;+ restoringKey.current = undefined;+ if (expected === historyKey) return;+ setHistory((current) => pushNavigation(current, entry, galaxyHistoryOptions));+ }, [historyKey, project]);+ const applyEntry = useCallback((entry: GalaxyHistoryEntry) => {+ scope.restore({ ...(entry.scope ? { scope: entry.scope } : {}), depth: entry.depth, direction: entry.direction });+ const types = entry.edgeTypes ? [...entry.edgeTypes] : undefined;+ changeTraceTypes(types);+ setChosenMode(entry.mode);+ const nextKey = JSON.stringify([project, entry.scope, entry.scope ? entry.direction : 'both', types]);+ setTrail(entry.trail ? { key: nextKey, ...entry.trail } : undefined);+ setTrailStep(0);+ setBackgroundCleared(false);+ setNote('');+ // A symbol scope reports its root itself once it is complete (see `notifiedScopedSymbol`).+ if (entry.scope) selectOnComplete.current = entry.scope.kind === 'symbol' ? undefined : scopeIdentity(entry.scope);+ else { setHighlighted(null); props.onClearSelection?.(); }+ }, [scope.restore, changeTraceTypes, project, props.onClearSelection]);+ const historyBack = peekNavigation(history, -1);+ const historyForward = peekNavigation(history, 1);+ const goHistory = useCallback((step: -1 | 1) => {+ const entry = peekNavigation(history, step);+ if (entry === undefined) return;+ restoringKey.current = galaxyHistoryOptions.key(entry);+ setHistory((current) => moveNavigation(current, step, galaxyHistoryOptions));+ applyEntry(entry);+ }, [history, applyEntry]);+ // A recent root is a new navigation: it is pushed and drops the forward branch.+ const jumpToRecent = useCallback((entry: GalaxyHistoryEntry) => applyEntry(entry), [applyEntry]);+ useEffect(() => {+ if (!scope.complete || !scopedRoot || !scope.scope || selectOnComplete.current !== scopeIdentity(scope.scope)) return;+ selectOnComplete.current = undefined;+ props.onSelectNode?.(layoutNodeForSelection(layout, scopedRoot) ?? scopedRoot);+ }, [scope.complete, scopedRoot, scope.scope, layout, props.onSelectNode]);+ useEffect(() => {+ if (!props.workspaceExpanded || escapeTaken) return;+ const onKey = (event: globalThis.KeyboardEvent): void => {+ if (event.defaultPrevented || !event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;+ if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;+ if (isTypingTarget(event.target instanceof Element ? event.target : null)) return;+ const step = event.key === 'ArrowLeft' ? -1 : 1;+ if (peekNavigation(history, step) === undefined) return;+ event.preventDefault();+ goHistory(step);+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [props.workspaceExpanded, escapeTaken, history, goHistory]);+ /* Escape ohne offenen Pfad verlaesst den Ausschnitt (K9); den Pfad gibt der Griff weiter oben frei. */+ useEffect(() => {+ if (!props.workspaceExpanded || !scope.scope || trailView || escapeTaken) return;+ const onKey = (event: globalThis.KeyboardEvent): void => {+ if (event.key !== 'Escape' || event.defaultPrevented) return;+ if (isTypingTarget(event.target instanceof Element ? event.target : null)) return;+ event.preventDefault();+ leaveScope();+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [props.workspaceExpanded, scope.scope, trailView, escapeTaken, leaveScope]);+ const historyControls = props.workspaceExpanded ? <span className="atlas-graph-history" role="group" aria-label={galaxyHistoryText.recentList}>+ <button type="button" aria-label={galaxyHistoryText.back} disabled={!historyBack} onClick={() => goHistory(-1)}+ title={historyBack ? galaxyHistoryText.backTo(historyEntryLabel(historyBack)) : galaxyHistoryText.noBack}>{galaxyHistoryText.backGlyph}</button>+ <button type="button" aria-label={galaxyHistoryText.forward} disabled={!historyForward} onClick={() => goHistory(1)}+ title={historyForward ? galaxyHistoryText.forwardTo(historyEntryLabel(historyForward)) : galaxyHistoryText.noForward}>{galaxyHistoryText.forwardGlyph}</button>+ {history.recent.length > 1 && <details className="atlas-graph-recent" onKeyDown={event => {+ if (event.key === 'Escape') { event.stopPropagation(); event.currentTarget.open = false; }+ }}>+ <summary title={galaxyHistoryText.recentTitle}>{galaxyHistoryText.recent}</summary>+ <ul className="atlas-graph-recent-menu" aria-label={galaxyHistoryText.recentList}>{history.recent.map((entry) => {+ const current = galaxyHistoryOptions.recentKey?.(entry) === (scope.scope ? scopeIdentity(scope.scope) : undefined);+ return <li key={galaxyHistoryOptions.recentKey?.(entry)}>+ <button type="button" disabled={current} aria-current={current ? 'true' : undefined} onClick={(event) => {+ const details = event.currentTarget.closest('details');+ if (details) details.open = false;+ jumpToRecent(entry);+ }}><strong>{entry.scope?.name}</strong><span>{historyEntryDetail(entry)}</span></button>+ </li>;+ })}</ul>+ </details>}+ </span> : null;/** Die Vorgabe der Ansicht, mit der Wahl des Lesers darauf.@@ -2064,6 +2203,7 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {hiddenKinds: [...hiddenKinds].sort(),drawnEdges: sceneShown?.edges.length ?? 0,edgeNote,+ history: { index: history.index, entries: history.entries.map(historyEntryLabel), recent: history.recent.map(historyEntryLabel) },hierarchy:projection === undefined? undefined@@ -2323,9 +2463,10 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {)}</header>{(props.workspaceExpanded || scope.scope) && <div className="atlas-graph-exploration" aria-label="Graph scope">+ {historyControls}{props.workspaceExpanded && <GalaxyNavigator embedded nodes={layout?.nodes ?? []} project={project} fetch={fetchImpl} onSelect={handleNodeClick} onSelectScope={next => { props.onClearSelection?.(); setBackgroundCleared(false); clearTrail(); scope.select(next); }} />}{scope.scope ? <>- {props.workspaceExpanded && <button type="button" onClick={handleBackgroundClick}>All graph</button>}+ {props.workspaceExpanded && <button type="button" onClick={leaveScope}>{galaxyHistoryText.allGraph}</button>}<strong className="atlas-graph-scope-name" title={scope.scope.name}>{scope.scope.name}</strong>{props.workspaceExpanded && scopedRoot?.file_path && <button type="button" onClick={() => props.onOpenNode(layoutNodeForSelection(layout, scopedRoot) ?? scopedRoot)}>Open source</button>}{props.workspaceExpanded && <label>Trace <select aria-label="Trace direction" value={scope.direction}diff --git a/graph-ui/src/galaxy/galaxy-strings.ts b/graph-ui/src/galaxy/galaxy-strings.tsindex 0538dd323..e7381e51b 100644--- a/graph-ui/src/galaxy/galaxy-strings.ts+++ b/graph-ui/src/galaxy/galaxy-strings.ts@@ -34,6 +34,28 @@ export const galaxyPathText = {position: (index: number, total: number) => `${index} of ${total}`,};+/** Back, Forward and the recent roots of the scoped Galaxy (K2). */+export const galaxyHistoryText = {+ back: 'Back',+ forward: 'Forward',+ backGlyph: '←',+ forwardGlyph: '→',+ backTo: (label: string) => `Back to ${label} (Alt+Left)`,+ forwardTo: (label: string) => `Forward to ${label} (Alt+Right)`,+ noBack: 'Nothing to go back to yet',+ noForward: 'Nothing to go forward to',+ recent: 'Recent',+ recentTitle: 'Jump straight to a recently visited root with its last depth, direction and edge types',+ recentList: 'Recently visited roots',+ allGraph: 'All graph',+ layers: (depth: number) => (depth === 1 ? '1 layer' : `${depth} layers`),+ direction: { inbound: 'incoming', outbound: 'outgoing' } as Record<'inbound' | 'outbound', string>,+ noTypes: 'no edge types',+ hierarchy: 'hierarchy',+ callOrder: 'call order',+ pathTo: (name: string) => `path to ${name}`,+};+/** Compact toolbar words, so the scoped toolbar keeps to one row at 1600 px. */export const galaxyToolbarText = {groups: (count: number) => `${count.toLocaleString()} groups`,diff --git a/graph-ui/src/galaxy/graph-exploration.css b/graph-ui/src/galaxy/graph-exploration.cssindex 6b5451398..c87ebc648 100644--- a/graph-ui/src/galaxy/graph-exploration.css+++ b/graph-ui/src/galaxy/graph-exploration.css@@ -79,3 +79,13 @@.atlas-galaxy-root-marker { position:relative; display:block; width:0; height:0; pointer-events:none; }.atlas-galaxy-root-marker > i { position:absolute; left:-15px; top:-15px; width:30px; height:30px; box-sizing:border-box; border:2px solid #f0cf73; border-radius:50%; box-shadow:0 0 0 4px rgba(240, 207, 115, .16), 0 0 16px rgba(240, 207, 115, .5); }.atlas-galaxy-root-marker > b { position:absolute; top:19px; left:0; transform:translateX(-50%); padding:1px 6px; border-radius:4px; background:rgba(13, 15, 18, .84); color:#f5e2a6; font:600 12px/1.4 var(--atlas-ui-font, system-ui, sans-serif); white-space:nowrap; }++/* Zurueck, Vor und die letzten Wurzeln (Handtest K2): klein, damit die Leiste einzeilig bleibt (K3). */+.atlas-graph-history { display:flex; align-items:center; gap:.25rem; flex:none; }+.atlas-graph-history > button { min-width:1.9rem; padding:.25rem .45rem; }+.atlas-graph-recent { position:relative; }+.atlas-graph-recent > summary { padding:.25rem .5rem; border:1px solid #29473a; border-radius:6px; cursor:pointer; color:#b5c9bc; white-space:nowrap; }+.atlas-graph-recent-menu { position:absolute; top:calc(100% + .35rem); left:0; z-index:30; width:min(24rem, calc(100vw - 3rem)); max-height:18rem; overflow:auto; margin:0; padding:.45rem; list-style:none; border:1px solid #355246; border-radius:8px; background:rgba(13,25,19,.98); box-shadow:0 8px 24px #0005; }+.atlas-graph-recent-menu button { width:100%; display:flex; flex-direction:column; align-items:flex-start; gap:.1rem; text-align:left; border:0; background:transparent; }+.atlas-graph-recent-menu button span { max-width:100%; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:.72rem; color:#95a89e; }+.atlas-graph-recent-menu button[aria-current=true] { opacity:.6; }diff --git a/graph-ui/src/galaxy/scope-history.ts b/graph-ui/src/galaxy/scope-history.tsnew file mode 100644index 000000000..930ff0294--- /dev/null+++ b/graph-ui/src/galaxy/scope-history.ts@@ -0,0 +1,60 @@+/**+ * Der Galaxy-Eintrag fuer den Verlauf (K2): welche Frage der Ausschnitt gerade+ * beantwortet, ohne die Antwort selbst.+ *+ * Ein Eintrag haelt Identitaeten und Parameter (Wurzel, Tiefe, Richtung,+ * Kantenarten, offener Pfad, Ansicht) und nie geladene Knoten, Kanten oder eine+ * Kamera. Zurueck laedt den Ausschnitt neu; der kleine Scope-Cache und der+ * Nachbarschafts-Cache machen das in der Regel sofort. Das Modell dahinter ist+ * src/graph/navigation-history.ts, das Konzept steht in+ * docs/development/pr-2068-galaxy-history.md.+ */+import type { NavigationHistoryOptions } from '../graph/navigation-history';+import type { GraphScope, TraceDirection } from './graph-scope';+import { galaxyHistoryText as text } from './galaxy-strings';++export type ScopeTrail = { kind: 'path'; target: number; name: string } | { kind: 'calls' };++export interface GalaxyHistoryEntry {+ /** Fehlt sie, ist es der ganze Graph ("All graph"). */+ scope?: GraphScope;+ depth: number;+ direction: TraceDirection;+ /** Fehlt die Liste, sind alle Kantenarten verfolgt. */+ edgeTypes?: readonly string[];+ trail?: ScopeTrail;+ mode: 'galaxy' | 'hierarchy';+}++/** Wer die Wurzel ist, unabhaengig davon, ob sie per Klick oder per Suche kam. */+export function scopeIdentity(scope: GraphScope): string {+ if (scope.kind === 'node') return scope.qualifiedName ? `qn:${scope.qualifiedName}` : `node:${scope.id}`;+ if (scope.kind === 'symbol') return `qn:${scope.qualifiedName}`;+ return `${scope.kind}:${scope.path}`;+}++function trailKey(trail: ScopeTrail | undefined): string {+ return trail === undefined ? '' : trail.kind === 'calls' ? 'calls' : `path:${trail.target}`;+}++export const galaxyHistoryOptions: NavigationHistoryOptions<GalaxyHistoryEntry> = {+ key: (entry) => JSON.stringify([entry.scope ? scopeIdentity(entry.scope) : null, entry.scope ? entry.depth : 0,+ entry.scope ? entry.direction : 'both', entry.edgeTypes ? [...entry.edgeTypes].sort() : null, trailKey(entry.trail), entry.mode]),+ recentKey: (entry) => (entry.scope ? scopeIdentity(entry.scope) : undefined),+};++/** Wie ein Eintrag in einem Tooltip heisst: "n1 · 2 layers · path to n4". */+export function historyEntryLabel(entry: GalaxyHistoryEntry): string {+ return entry.scope ? `${entry.scope.name} · ${historyEntryDetail(entry)}` : text.allGraph;+}++/** Dasselbe ohne den Namen, fuer die Zeile unter dem Namen in der Liste der letzten Wurzeln. */+export function historyEntryDetail(entry: GalaxyHistoryEntry): string {+ if (!entry.scope) return text.allGraph;+ const parts = [text.layers(entry.depth)];+ if (entry.direction !== 'both') parts.push(text.direction[entry.direction]);+ if (entry.edgeTypes) parts.push(entry.edgeTypes.length ? entry.edgeTypes.join(', ') : text.noTypes);+ if (entry.mode === 'hierarchy') parts.push(text.hierarchy);+ if (entry.trail) parts.push(entry.trail.kind === 'calls' ? text.callOrder : text.pathTo(entry.trail.name));+ return parts.join(' · ');+}diff --git a/graph-ui/src/galaxy/test-scope-fetch.ts b/graph-ui/src/galaxy/test-scope-fetch.tsnew file mode 100644index 000000000..639b51a0d--- /dev/null+++ b/graph-ui/src/galaxy/test-scope-fetch.ts@@ -0,0 +1,55 @@+/**+ * Testhilfe: /api/layout und die beiden query_graph-Formen des Scope-Laders,+ * ueber dieselbe RPC-Strecke wie im Betrieb (dieselbe Form wie in+ * GalaxyPanel.stability.test.tsx, hier fuer beliebige Knoten und Kanten).+ *+ * `delay` haelt jede Kantenabfrage an, bis der Test sie freigibt; so laesst+ * sich ein laufendes Laden beobachten und abbrechen.+ */+import { vi } from 'vitest';+import type { GraphEdge, GraphNode } from './types';++export interface ScopeFetchOptions {+ nodes: GraphNode[];+ edges: GraphEdge[];+ /** Jede Kantenabfrage wartet auf dieses Versprechen, wenn es gesetzt ist. */+ gate?: () => Promise<void>;+}++export function scopeNode(id: number, extra: Partial<GraphNode> = {}): GraphNode {+ return { id, name: `n${id}`, qualified_name: `sample.n${id}`, label: 'Function', file_path: `src/n${id}.ts`,+ start_line: 1, end_line: 5, x: id * 10, y: 0, z: 0, size: 2, color: '#999999', ...extra };+}++export function scopeFetch({ nodes, edges, gate }: 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 }));+ const request = JSON.parse(String(init?.body)) as { params: { name: string; arguments: Record<string, unknown> } };+ calls.push({ tool: request.params.name, args: request.params.arguments });+ if (request.params.name === 'index_status') {+ return new Response(JSON.stringify({ jsonrpc: '2.0', id: 1, result: { content: [{ type: 'text', text: JSON.stringify({ indexed_at: 'generation-1' }) }] } }));+ }+ const query = String(request.params.arguments.query);+ const columns = (prefix: string) => ['id', 'label', 'name', 'qn', 'file', 'start_line', 'end_line'].map(key => prefix + key);+ 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)')) {+ cols = columns(''); rows = nodes.filter(entry => names.includes(entry.qualified_name ?? '')).map(values);+ } else {+ if (gate) await gate();+ const inbound = query.startsWith('MATCH (b)<-');+ cols = ['edge_id', 'edge_type', 'edge_line', ...columns('a_'), ...columns('b_')];+ rows = edges.flatMap((edge, i) => {+ const a = nodes.find(entry => entry.id === edge.source)!, b = nodes.find(entry => entry.id === edge.target)!;+ const seed = inbound ? b : a;+ return names.includes(seed.qualified_name ?? '')+ ? [[String(edge.id ?? i + 1), edge.type, String(edge.line ?? ''), ...values(a), ...values(b)]] : [];+ });+ }+ const text = `rows: ${rows.length} (cols: ${cols.join(' ')})\n${rows.map(row => ' ' + row.map(value => JSON.stringify(value || '-')).join(' ')).join('\n')}\ntotal: ${rows.length}\nhas_more: false\ntruncated: false`;+ return new Response(JSON.stringify({ jsonrpc: '2.0', id: 1, result: { content: [{ type: 'text', text }] } }));+ });+ return { fetch, calls };+}diff --git a/graph-ui/src/galaxy/use-graph-scope.ts b/graph-ui/src/galaxy/use-graph-scope.tsindex 47aa4668b..2c7f9711c 100644--- a/graph-ui/src/galaxy/use-graph-scope.ts+++ b/graph-ui/src/galaxy/use-graph-scope.ts@@ -136,6 +136,11 @@ export function useGraphScope({ project, layout, filePath, range, fetch: fetchImcomplete: Boolean(complete), retry: () => setReload(value => value + 1),select: (next: GraphScope) => { setChosen(next); setDepth(minimumScopeDepth(next)); setDirection('both'); },reset: () => { setChosen(undefined); setDepth(0); setReaderDepth(undefined); setDirection('both'); },+ /** Back, Forward and a recent jump (K2): the whole question at once, not a fresh selection. */+ restore: (next: { scope?: GraphScope; depth: number; direction: TraceDirection }) => {+ setChosen(next.scope); setDirection(next.scope ? next.direction : 'both');+ setDepth(next.scope ? Math.max(minimumScopeDepth(next.scope), next.depth) : 0);+ },setDepth: (next: number) => filePath ? setReaderDepth({ key: readerKey, depth: Math.max(minDepth, next) }) : setDepth(Math.max(minDepth, next)),};}diff --git a/graph-ui/src/graph/navigation-history.test.ts b/graph-ui/src/graph/navigation-history.test.tsnew file mode 100644index 000000000..6ff5b4b31--- /dev/null+++ b/graph-ui/src/graph/navigation-history.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest';+import {+ NAVIGATION_HISTORY_LIMIT,+ emptyNavigationHistory,+ moveNavigation,+ peekNavigation,+ pushNavigation,+ type NavigationHistory,+ type NavigationHistoryOptions,+} from './navigation-history';++interface Entry { root?: string; depth: number }+const options: NavigationHistoryOptions<Entry> = { key: (entry) => `${entry.root ?? '*'}@${entry.depth}`, recentKey: (entry) => entry.root };+const keys = (history: NavigationHistory<Entry>) => history.entries.map(options.key);+const push = (history: NavigationHistory<Entry>, ...entries: Entry[]) => entries.reduce((next, entry) => pushNavigation(next, entry, options), history);++describe('bounded back and forward history', () => {+ it('moves a cursor back and forward like a browser, and stops at both ends', () => {+ let history = push(emptyNavigationHistory<Entry>(), { depth: 0 }, { root: 'A', depth: 1 }, { root: 'B', depth: 1 });+ expect(peekNavigation(history, -1)).toEqual({ root: 'A', depth: 1 });+ expect(peekNavigation(history, 1)).toBeUndefined();+ history = moveNavigation(history, -1, options);+ history = moveNavigation(history, -1, options);+ expect(history.index).toBe(0);+ expect(peekNavigation(history, -1)).toBeUndefined();+ expect(moveNavigation(history, -1, options)).toBe(history);+ history = moveNavigation(history, 1, options);+ expect(history.entries[history.index]).toEqual({ root: 'A', depth: 1 });+ expect(peekNavigation(history, 1)).toEqual({ root: 'B', depth: 1 });+ });++ it('merges a step equal to the current one, but keeps a later revisit as its own step', () => {+ const history = push(emptyNavigationHistory<Entry>(), { root: 'A', depth: 1 }, { root: 'A', depth: 1 }, { root: 'A', depth: 2 },+ { root: 'B', depth: 1 }, { root: 'A', depth: 2 });+ expect(keys(history)).toEqual(['A@1', 'A@2', 'B@1', 'A@2']);+ });++ it('drops the forward branch on a new navigation after going back', () => {+ let history = push(emptyNavigationHistory<Entry>(), { root: 'A', depth: 1 }, { root: 'B', depth: 1 }, { root: 'C', depth: 1 });+ history = moveNavigation(moveNavigation(history, -1, options), -1, options);+ history = push(history, { root: 'D', depth: 1 });+ expect(keys(history)).toEqual(['A@1', 'D@1']);+ expect(peekNavigation(history, 1)).toBeUndefined();+ });++ it('never holds more than the limit and drops the oldest entries first', () => {+ const many = Array.from({ length: NAVIGATION_HISTORY_LIMIT + 40 }, (_, at) => ({ root: `N${at}`, depth: 1 }));+ const history = push(emptyNavigationHistory<Entry>(), ...many);+ expect(history.entries).toHaveLength(NAVIGATION_HISTORY_LIMIT);+ expect(history.entries[0]!.root).toBe('N40');+ expect(history.entries.at(-1)!.root).toBe(`N${NAVIGATION_HISTORY_LIMIT + 39}`);+ expect(history.index).toBe(NAVIGATION_HISTORY_LIMIT - 1);+ const short = push(emptyNavigationHistory<Entry>(), ...many.slice(0, 5));+ expect(pushNavigation(short, { root: 'X', depth: 1 }, { ...options, limit: 3 }).entries.map((entry) => entry.root)).toEqual(['N3', 'N4', 'X']);+ });++ it('keeps the last distinct roots, newest first, independent of the cursor', () => {+ let history = push(emptyNavigationHistory<Entry>(), { depth: 0 }, { root: 'A', depth: 1 }, { root: 'B', depth: 1 },+ { root: 'A', depth: 3 }, { root: 'C', depth: 1 });+ expect(history.recent).toEqual([{ root: 'C', depth: 1 }, { root: 'A', depth: 3 }, { root: 'B', depth: 1 }]);+ history = moveNavigation(history, -1, options);+ // Going back visits A again: it moves to the front, nothing is lost.+ expect(history.recent.map((entry) => entry.root)).toEqual(['A', 'C', 'B']);+ const capped = push(emptyNavigationHistory<Entry>(), ...Array.from({ length: 12 }, (_, at) => ({ root: `R${at}`, depth: 1 })));+ expect(capped.recent).toHaveLength(8);+ expect(capped.recent[0]!.root).toBe('R11');+ });+});diff --git a/graph-ui/src/graph/navigation-history.ts b/graph-ui/src/graph/navigation-history.tsnew file mode 100644index 000000000..cdda112ef--- /dev/null+++ b/graph-ui/src/graph/navigation-history.ts@@ -0,0 +1,74 @@+/**+ * Ein begrenzter Verlauf mit Zurueck und Vor, wie beim Blaettern (K2).+ *+ * Rein und ohne React, damit Galaxy und spaeter Architecture (K27) dasselbe+ * Modell benutzen und nicht zwei. Das Konzept steht in+ * docs/development/pr-2068-galaxy-history.md; hier stehen nur die Regeln, die+ * der Code einhaelt:+ *+ * - Hoechstens `limit` Eintraege (Vorgabe 25). Wer darueber hinaus schiebt,+ * verliert den aeltesten, nicht den neuesten.+ * - Ein Eintrag, der dem aktuellen gleicht (gleicher Schluessel), wird nicht+ * noch einmal abgelegt. Derselbe Ort spaeter ist ein neuer Schritt.+ * - Eine neue Navigation nach Zurueck verwirft den Vorwaertszweig.+ * - Daneben eine kurze Liste der zuletzt besuchten Orte (`recentKey`), neueste+ * zuerst und ohne Doppelte. Sie haengt nicht am Zeiger: Zurueck kuerzt sie+ * nicht, ein Besuch zieht seinen Ort nach vorn.+ *+ * Gespeichert werden nur die Eintraege, die der Aufrufer baut. Was sie+ * bedeuten (welche Knoten, welche Kamera), weiss dieses Modul nicht, und es+ * waechst darum auch nicht mit dem, was ein Bild an Daten traegt.+ */++export interface NavigationHistory<T> {+ readonly entries: readonly T[];+ /** Der Eintrag, auf dem der Leser steht. -1 heisst: noch keiner. */+ readonly index: number;+ /** Die zuletzt besuchten Orte, neueste zuerst. */+ readonly recent: readonly T[];+}++export interface NavigationHistoryOptions<T> {+ /** Gleicher Schluessel heisst gleicher Eintrag. */+ key: (entry: T) => string;+ /** Der Ort eines Eintrags fuer die Liste der letzten Orte. Ohne Ort steht er nicht darin. */+ recentKey?: (entry: T) => string | undefined;+ limit?: number;+ recentLimit?: number;+}++export const NAVIGATION_HISTORY_LIMIT = 25;+export const NAVIGATION_RECENT_LIMIT = 8;++export function emptyNavigationHistory<T>(): NavigationHistory<T> {+ return { entries: [], index: -1, recent: [] };+}++function visit<T>(recent: readonly T[], entry: T, options: NavigationHistoryOptions<T>): readonly T[] {+ const place = options.recentKey?.(entry);+ if (place === undefined) return recent;+ const rest = recent.filter((candidate) => options.recentKey?.(candidate) !== place);+ return [entry, ...rest].slice(0, Math.max(1, options.recentLimit ?? NAVIGATION_RECENT_LIMIT));+}++/** Ein neuer Schritt. Gleicht er dem aktuellen, bleibt alles, wie es ist. */+export function pushNavigation<T>(history: NavigationHistory<T>, entry: T, options: NavigationHistoryOptions<T>): NavigationHistory<T> {+ const current = history.entries[history.index];+ if (current !== undefined && options.key(current) === options.key(entry)) return history;+ const limit = Math.max(1, options.limit ?? NAVIGATION_HISTORY_LIMIT);+ const kept = [...history.entries.slice(0, history.index + 1), entry];+ const entries = kept.slice(Math.max(0, kept.length - limit));+ return { entries, index: entries.length - 1, recent: visit(history.recent, entry, options) };+}++/** Der Eintrag, zu dem Zurueck (-1) oder Vor (+1) fuehren wuerde. */+export function peekNavigation<T>(history: NavigationHistory<T>, step: -1 | 1): T | undefined {+ return history.index < 0 ? undefined : history.entries[history.index + step];+}++/** Einen Schritt zurueck oder vor. Ohne Ziel bleibt der Verlauf derselbe. */+export function moveNavigation<T>(history: NavigationHistory<T>, step: -1 | 1, options: NavigationHistoryOptions<T>): NavigationHistory<T> {+ const entry = peekNavigation(history, step);+ if (entry === undefined) return history;+ return { entries: history.entries, index: history.index + step, recent: visit(history.recent, entry, options) };+}diff --git a/graph-ui/src/graph/useGraphBackgroundReset.test.tsx b/graph-ui/src/graph/useGraphBackgroundReset.test.tsxindex 945df104a..93dee15ad 100644--- a/graph-ui/src/graph/useGraphBackgroundReset.test.tsx+++ b/graph-ui/src/graph/useGraphBackgroundReset.test.tsx@@ -24,13 +24,13 @@ function pointer(target: Element, type: string, x = 10, y = 10, changes: { buttoObject.defineProperties(event, { pointerId: { value: changes.pointerId ?? 1 }, isPrimary: { value: changes.isPrimary ?? true } });target.dispatchEvent(event);}-it('resets only after a primary click on genuinely empty canvas', async () => {+it('reports an empty-canvas click only after a primary click on genuinely empty canvas (the caller decides what it clears, K9)', async () => {const { reset, canvas } = await setup();pointer(canvas, 'pointerdown'); pointer(canvas, 'pointerup'); pointer(canvas, 'click');expect(reset).toHaveBeenCalledOnce();pointer(canvas, 'click'); expect(reset).toHaveBeenCalledOnce();});-it('does not reset orbit/pan drags, including drags that return to their starting point', async () => {+it('does not report orbit/pan drags, including drags that return to their starting point', async () => {const { reset, canvas } = await setup();pointer(canvas, 'pointerdown'); pointer(canvas, 'pointermove', 50); pointer(canvas, 'pointermove');pointer(canvas, 'pointerup'); pointer(canvas, 'click'); expect(reset).not.toHaveBeenCalled();diff --git a/graph-ui/src/graph/useGraphBackgroundReset.ts b/graph-ui/src/graph/useGraphBackgroundReset.tsindex fab91a179..2c74adaf5 100644--- a/graph-ui/src/graph/useGraphBackgroundReset.ts+++ b/graph-ui/src/graph/useGraphBackgroundReset.ts@@ -1,7 +1,10 @@import { useRef, type PointerEvent as ReactPointerEvent } from 'react';-/** A missed raycast is a reset only after a primary, stationary canvas gesture.- * Tracking the entire gesture also excludes drags that return to their start. */+/** A missed raycast counts as an empty-canvas click only after a primary,+ * stationary canvas gesture. Tracking the entire gesture also excludes drags+ * that return to their start. What the click does is the caller's decision:+ * inside a Galaxy scope it only clears highlights and never leaves the scope+ * (hand test K9, GalaxyPanel `handleBackgroundClick`). */export function useGraphBackgroundReset(onReset?: () => void) {const gesture = useRef<{ id: number; x: number; y: number; moved: boolean } | undefined>(undefined);const onPointerDownCapture = (event: ReactPointerEvent) => {diff --git a/graph-ui/tools/handtest-fixes-galaxy.mjs b/graph-ui/tools/handtest-fixes-galaxy.mjsnew file mode 100644index 000000000..a9cb49529--- /dev/null+++ b/graph-ui/tools/handtest-fixes-galaxy.mjs@@ -0,0 +1,324 @@+#!/usr/bin/env node+/*+ * Browser-Pruefung der Galaxy-Korrekturen aus dem Handtest vom 03.10.2026+ * (graph-ui/verification/call-feedback-2026-10-02/KORREKTURPLAN.md, K2, K3,+ * K5, K6, K8, K9, K13).+ *+ * node tools/handtest-fixes-galaxy.mjs --origin http://127.0.0.1:4371 \+ * --out /tmp/handtest-galaxy [--only K2,K9] [--project django-demo]+ *+ * Jede Pruefung faehrt genau den Ablauf aus dem Korrekturplan, misst in der+ * laufenden Seite und druckt PASS oder FAIL mit den Messwerten. Die Bilder+ * liegen je Punkt unter <out>/<K>/, daneben eine index.md, die jedes Bild und+ * das, was es zeigt, auffuehrt. Gegen einen Stand ohne die Korrekturen+ * gefahren, sollen die Pruefungen fehlschlagen; das ist der Vorher-Beweis.+ *+ * Es startet keinen Server. Gebraucht wird ein Ursprung mit UI und /rpc, etwa+ * tools/lib/static-proxy.mjs vor einem laufenden Server.+ */++import { chromium } from 'playwright';+import { appendFile, mkdir, writeFile } from 'node:fs/promises';+import { join, resolve } from 'node:path';++const argv = process.argv.slice(2);+const arg = (name, fallback) => {+ const index = argv.indexOf(`--${name}`);+ if (index < 0) return fallback;+ const value = argv[index + 1];+ return value === undefined || value.startsWith('--') ? true : value;+};++const ORIGIN = String(arg('origin', 'http://127.0.0.1:4371')).replace(/\/$/, '');+const OUT = resolve(String(arg('out', 'verification/handtest-galaxy')));+const PROFILE = resolve(String(arg('profile', join(OUT, 'profile'))));+const PROJECT = String(arg('project', 'django-demo'));+const ONLY = String(arg('only', 'K9,K2,K3,K13,K6,K5,K8')).split(',');+const VIEWPORT = { width: 1600, height: 1000 };+const ROOT = 'JSONBAgg';+const wait = (ms) => new Promise((done) => setTimeout(done, ms));++/* ------------------------------------------------------------------ */+/* Server */++let rpcId = 1;+async function tool(name, args) {+ const res = await fetch(`${ORIGIN}/rpc`, {+ method: 'POST', headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: rpcId++, method: 'tools/call', params: { name, arguments: args } }),+ });+ const body = await res.json();+ const text = body?.result?.content?.[0]?.text ?? '';+ try { return JSON.parse(text); } catch { return { raw: text }; }+}++/** Der qualifizierte Name eines Symbols, so wie der Index ihn kennt. */+async function qualifiedName(name) {+ const answer = await tool('query_graph', { project: PROJECT, format: 'json', query: `MATCH (n) WHERE n.name = "${name}" RETURN n.qualified_name ORDER BY n.qualified_name LIMIT 1` });+ return answer?.rows?.[0]?.[0] ?? '';+}++/** Die direkten Beziehungen eines Symbols nach Richtung und Art, als Wahrheit fuer K13. */+async function relationCounts(name) {+ const count = async (pattern) => {+ const answer = await tool('query_graph', { project: PROJECT, format: 'json', query: `MATCH ${pattern} WHERE n.name = "${name}" RETURN type(r) AS type, count(r) AS edges ORDER BY type` });+ return Object.fromEntries((answer?.rows ?? []).map(([type, edges]) => [type, Number(edges)]));+ };+ return { incoming: await count('(a)-[r]->(n)'), outgoing: await count('(n)-[r]->(b)') };+}++/* ------------------------------------------------------------------ */+/* In jede Seite */++function pageProbe() {+ try { localStorage.setItem('cbm.workspace.setup', 'done'); } catch { /* ohne Speicher geht es auch */ }+ window.__probeErrors = [];+ window.addEventListener('error', (event) => window.__probeErrors.push(String(event.message)));+ window.__probeRpc = [];+ const nativeFetch = window.fetch.bind(window);+ window.fetch = async (input, init) => {+ const url = typeof input === 'string' ? input : input?.url ?? '';+ if (url.endsWith('/rpc') && init?.body) {+ try {+ const body = JSON.parse(String(init.body));+ window.__probeRpc.push({ t: Math.round(performance.now()), tool: body?.params?.name, cursor: Boolean(body?.params?.arguments?.cursor), maxRows: body?.params?.arguments?.max_rows ?? null });+ } catch { /* nur Beobachtung */ }+ }+ return nativeFetch(input, init);+ };+}++/* ------------------------------------------------------------------ */+/* Ergebnis */++const results = [];+const counters = new Map();++function check(id, title, pass, measured) {+ results.push({ id, title, pass: Boolean(pass), measured });+ console.log(`${pass ? 'PASS' : 'FAIL'} ${id} ${title} ${JSON.stringify(measured)}`);+ return appendFile(join(OUT, id, 'index.md'), `\n**${pass ? 'PASS' : 'FAIL'}** ${title}\n\n\`\`\`json\n${JSON.stringify(measured, null, 2)}\n\`\`\`\n`);+}++/** Ein Bild, mit dem, was es zeigen soll, in der index.md des Punktes. */+async function shot(page, id, label, caption) {+ const next = (counters.get(id) ?? 0) + 1;+ counters.set(id, next);+ const file = `${String(next).padStart(2, '0')}-${label}.png`;+ await page.screenshot({ path: join(OUT, id, file) });+ await appendFile(join(OUT, id, 'index.md'), `- \`${file}\`: ${caption}\n`);+ return file;+}++async function section(page, id, title) {+ await mkdir(join(OUT, id), { recursive: true });+ await writeFile(join(OUT, id, 'index.md'), `# ${id}: ${title}\n\nOrigin ${ORIGIN}, project ${PROJECT}, viewport ${VIEWPORT.width}x${VIEWPORT.height}.\n\n`);+}++/* ------------------------------------------------------------------ */+/* Bedienung */++const toolbar = (page) => page.locator('.atlas-graph-exploration').first();+const scopeName = (page) => page.locator('.atlas-graph-scope-name').first().innerText({ timeout: 1000 }).catch(() => '');+const countText = (page) => page.locator('.atlas-graph-scope-count').first().innerText({ timeout: 1000 }).catch(() => '');+const layerText = (page) => toolbar(page).evaluate((bar) => [...bar.querySelectorAll('span')].map((el) => el.textContent?.trim() ?? '')+ .find((text) => /^\d+ layers?$/.test(text)) ?? '').catch(() => '');++async function open(page) {+ await page.goto(`${ORIGIN}/?project=${encodeURIComponent(PROJECT)}&workspace=galaxy`, { waitUntil: 'domcontentloaded' });+ await page.waitForSelector('.atlas-shell', { timeout: 30000 });+ await page.waitForFunction(() => (globalThis.__atlasGalaxy?.nodes ?? 0) > 0 && globalThis.__atlasGalaxyFit !== undefined, null, { timeout: 60000 });+ await wait(1200);+}++async function select(page, name) {+ const input = page.getByRole('searchbox', { name: 'Find a graph node' }).first();+ await input.click();+ await input.fill('');+ await input.type(name, { delay: 20 });+ const choice = page.locator('.atlas-galaxy-search-results button', { has: page.locator('strong', { hasText: new RegExp(`^${name}$`) }) }).first();+ await choice.waitFor({ timeout: 20000 });+ await choice.click();+}++/** Bis die Statuszeile einen fertigen Ausschnitt meldet. */+async function settled(page, timeout = 30000) {+ const started = Date.now();+ const ok = await page.waitForFunction(() => {+ const text = document.querySelector('.atlas-graph-scope-count')?.textContent ?? '';+ return /\d[\d,.]* nodes? · \d[\d,.]* edges?/.test(text) && !/Loading|Checking/.test(text);+ }, null, { timeout }).then(() => true).catch(() => false);+ await wait(900);+ return { ok, ms: Date.now() - started };+}++async function expand(page) {+ await page.getByRole('button', { name: 'Expand +1' }).click();+ return settled(page, 60000);+}++const canvasBox = (page) => page.locator('.atlas-galaxy canvas').first().boundingBox();++/* ------------------------------------------------------------------ */+/* K9: ein Klick ins Leere verlaesst den Ausschnitt nicht */++async function checkK9(page) {+ await section(page, 'K9', 'A click on empty canvas keeps the scope; only All graph, Escape or Back leave it');+ await open(page);+ await select(page, ROOT);+ await settled(page);+ await expand(page);+ const before = { scope: await scopeName(page), layers: await layerText(page), count: await countText(page) };+ await shot(page, 'K9', 'before-click', `${ROOT} at ${before.layers}, ${before.count}: the scope before the click on empty canvas`);+ const box = await canvasBox(page);+ const root = await page.locator('[data-testid="atlas-galaxy-root-marker"] i').first().boundingBox().catch(() => null);+ // Wie im Handtest: knapp neben einen Knoten, und einmal in eine leere Ecke.+ const spots = [+ root ? { label: 'beside-root', x: root.x + root.width / 2 + 34, y: root.y + root.height / 2 - 30 } : null,+ { label: 'empty-corner', x: box.x + 60, y: box.y + box.height - 60 },+ ].filter(Boolean);+ const after = [];+ for (const spot of spots) {+ await page.mouse.click(spot.x, spot.y);+ await shot(page, 'K9', `${spot.label}-0ms`, `0 ms after a click at ${spot.label} (${Math.round(spot.x)}, ${Math.round(spot.y)})`);+ await wait(250);+ await shot(page, 'K9', `${spot.label}-250ms`, '250 ms after the click');+ await wait(750);+ await shot(page, 'K9', `${spot.label}-1s`, '1 s after the click: scope, layers and toolbar unchanged');+ await wait(2000);+ await shot(page, 'K9', `${spot.label}-3s`, '3 s after the click');+ after.push({ spot: spot.label, scope: await scopeName(page), layers: await layerText(page), count: await countText(page),+ headline: await page.locator('[data-testid="atlas-galaxy-headline"]').innerText().catch(() => '') });+ }+ const kept = after.every((row) => row.scope === before.scope && row.layers === before.layers && row.count === before.count);+ await check('K9', 'Clicks on empty canvas keep scope, layers and counts', kept, { before, after });++ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);+ await page.keyboard.press('Escape');+ await wait(1500);+ const escaped = { scope: await scopeName(page), headline: await page.locator('[data-testid="atlas-galaxy-headline"]').innerText().catch(() => '') };+ await shot(page, 'K9', 'escape', `After Escape: back on the whole graph (${escaped.headline})`);+ await page.keyboard.press('Alt+ArrowLeft');+ const back = await settled(page);+ const restored = { scope: await scopeName(page), layers: await layerText(page), count: await countText(page), ms: back.ms };+ await shot(page, 'K9', 'alt-left', `After Alt+Left: ${restored.scope} at ${restored.layers} again`);+ await check('K9', 'Escape leaves the scope, Back (Alt+Left) returns to it', escaped.scope === '' && restored.scope === before.scope && restored.layers === before.layers,+ { escaped, restored });+}++/* ------------------------------------------------------------------ */+/* K2: Zurueck und Vor */++async function checkK2(page) {+ await section(page, 'K2', 'Back and Forward through the visited scopes, bounded, with a recent list');+ await open(page);+ const backButton = page.getByRole('button', { name: 'Back', exact: true });+ const forwardButton = page.getByRole('button', { name: 'Forward', exact: true });+ const state = async () => ({ scope: await scopeName(page), layers: await layerText(page), count: await countText(page),+ back: await backButton.getAttribute('title', { timeout: 1000 }).catch(() => null),+ backDisabled: await backButton.isDisabled({ timeout: 1000 }).catch(() => null),+ forward: await forwardButton.getAttribute('title', { timeout: 1000 }).catch(() => null),+ forwardDisabled: await forwardButton.isDisabled({ timeout: 1000 }).catch(() => null),+ history: await page.evaluate(() => { const h = globalThis.__atlasGalaxy?.history; return h ? { index: h.index, entries: h.entries.length } : null; }) });+ const steps = [];+ await select(page, ROOT);+ await settled(page);+ steps.push({ step: `select ${ROOT}`, ...await state() });+ await shot(page, 'K2', 'select-root', `${ROOT} selected from the whole graph: Back names "All graph"`);+ await expand(page);+ steps.push({ step: 'expand', ...await state() });+ const child = await qualifiedName('test_jsonb_agg_jsonfield_order_by');+ await page.evaluate((qn) => globalThis.__atlasGalaxy?.clickNode(qn), child);+ await settled(page);+ steps.push({ step: 'click test_jsonb_agg_jsonfield_order_by', ...await state() });+ await shot(page, 'K2', 'new-root', 'A click on a test made it the new root; Back names the previous scope');+ await page.locator('.atlas-graph-history').screenshot({ path: join(OUT, 'K2', 'history-buttons.png') }).catch(() => {});++ if (await backButton.count() === 0) {+ await check('K2', 'Back and Forward buttons exist in the scoped toolbar', false, { steps });+ return;+ }+ const t0 = Date.now();+ await backButton.click();+ await shot(page, 'K2', 'back-0ms', '0 ms after Back');+ await wait(250);+ await shot(page, 'K2', 'back-250ms', '250 ms after Back');+ const backOne = await settled(page);+ steps.push({ step: 'Back', ms: Date.now() - t0, settledOk: backOne.ok, ...await state() });+ await shot(page, 'K2', 'back-1', `After Back: ${ROOT} at 2 layers again, Forward names the test`);+ await backButton.click();+ await settled(page);+ steps.push({ step: 'Back', ...await state() });+ await backButton.click();+ await wait(1500);+ steps.push({ step: 'Back', ...await state() });+ await shot(page, 'K2', 'back-all-graph', 'Third Back: the whole graph, Back disabled, Forward enabled');+ await forwardButton.click();+ await settled(page);+ steps.push({ step: 'Forward', ...await state() });+ await page.keyboard.press('Alt+ArrowRight');+ await settled(page);+ steps.push({ step: 'Alt+Right', ...await state() });+ await page.keyboard.press('Alt+ArrowRight');+ await settled(page);+ steps.push({ step: 'Alt+Right', ...await state() });+ await shot(page, 'K2', 'forward-end', 'Forward twice by keyboard: back at the test root, Forward disabled');++ const recent = page.locator('details.atlas-graph-recent');+ let recentNames = [];+ if (await recent.count()) {+ await recent.locator('summary').click();+ await wait(300);+ recentNames = await recent.locator('li button strong').allInnerTexts();+ await shot(page, 'K2', 'recent-open', `Recent list: ${recentNames.join(', ')}`);+ await recent.locator('li button', { has: page.locator('strong', { hasText: new RegExp(`^${ROOT}$`) }) }).first().click();+ await settled(page);+ steps.push({ step: `Recent ${ROOT}`, ...await state() });+ await shot(page, 'K2', 'recent-jump', `Jump from the recent list: ${ROOT} with its last depth, Forward dropped`);+ }+ // Begrenzt: viele Schritte, und der Verlauf haelt hoechstens 25 Eintraege.+ for (let i = 0; i < 30; i += 1) {+ await page.getByRole('button', { name: i % 2 ? 'Expand +1' : 'Remove graph layer' }).click({ timeout: 3000 }).catch(() => {});+ await settled(page, 10000);+ }+ await settled(page);+ let backs = 0;+ for (; backs < 40 && !(await backButton.isDisabled()); backs += 1) { await backButton.click(); await wait(60); }+ await settled(page);+ steps.push({ step: `Back until disabled (${backs} steps)`, ...await state() });+ const at = (index) => steps[index] ?? {};+ const pass = at(0).back?.startsWith('Back to All graph') && at(2).back?.startsWith(`Back to ${ROOT} · 2 layers`)+ && at(3).scope === ROOT && at(3).layers === '2 layers' && at(3).forward?.startsWith('Forward to test_jsonb_agg_jsonfield_order_by')+ && at(4).layers === '1 layer' && at(5).scope === '' && at(5).backDisabled === true && at(6).scope === ROOT+ && at(8).scope === 'test_jsonb_agg_jsonfield_order_by' && at(8).forwardDisabled === true+ && recentNames.slice(0, 2).join() === `test_jsonb_agg_jsonfield_order_by,${ROOT}` && at(9).scope === ROOT && at(9).forwardDisabled === true+ && backs <= 24 && (at(10).history?.entries ?? 99) <= 25;+ await check('K2', 'Back/Forward/Alt+arrows/Recent restore root, depth and direction; history stays bounded', pass, { steps, recentNames, backsUntilStart: backs });+}++/* ------------------------------------------------------------------ */++const CHECKS = { K9: checkK9, K2: checkK2 };++await mkdir(OUT, { recursive: true });+const context = await chromium.launchPersistentContext(PROFILE, {+ headless: false, viewport: VIEWPORT, deviceScaleFactor: 2,+ args: ['--enable-unsafe-webgpu', '--ignore-gpu-blocklist'],+});+await context.addInitScript(pageProbe);+const page = context.pages()[0] ?? await context.newPage();+const pageErrors = [];+page.on('pageerror', (error) => { pageErrors.push(error.message); console.error(`[pageerror] ${error.message}`); });+for (const id of ONLY) {+ const run = CHECKS[id];+ if (!run) continue;+ try { await run(page); } catch (error) {+ console.error(`[${id}] ABORT ${error?.stack ?? error}`);+ await check(id, 'check ran to completion', false, { error: String(error?.message ?? error).split('\n')[0] }).catch(() => {});+ }+}+await context.close();+const passed = results.filter((row) => row.pass).length;+await writeFile(join(OUT, 'report.json'), JSON.stringify({ origin: ORIGIN, project: PROJECT, passed, total: results.length, results, pageErrors }, null, 2));+console.log(`${passed}/${results.length} PASS${pageErrors.length ? `, page errors: ${pageErrors.length}` : ''}`);+if (passed !== results.length) process.exitCode = 1;