Skip to content

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.

feat(ui): Architecture back and forward on the shared history (K27)

Bernhard Jackiewicz9901f9776f75
diff --git a/docs/development/pr-2068-galaxy-history.md b/docs/development/pr-2068-galaxy-history.md
index 448757a04..7d8cb00f7 100644
--- a/docs/development/pr-2068-galaxy-history.md
+++ b/docs/development/pr-2068-galaxy-history.md
@@ -1,11 +1,18 @@
-# PR 2068: Galaxy back and forward (K2)
+# PR 2068: back and forward in Galaxy (K2) and Architecture (K27)
+
+Both workspaces share one bounded history model and one set of rules, and each
+keeps its own history. Galaxy came first and is described first; the section
+"Architecture (K27)" lists what an Architecture entry holds and the few rules
+Architecture adds.
+
+## Galaxy (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
+### What an entry is
One entry is the complete question the Galaxy workspace answers at that moment:
@@ -26,7 +33,7 @@ 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
+### 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
@@ -62,12 +69,11 @@ the scope that was open before.
cancelled layer) keeps the selection, so Selection details and the chat
context stay.
-## Where it lives
+### 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.
+ (`push`, `back`, `forward`, `recent`) over any entry with a key function.
+ Architecture (K27) uses the same module, see below.
- `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
@@ -75,10 +81,103 @@ the scope that was open before.
Back and Forward buttons with disabled states and the Recent list in the
scoped toolbar.
-## Not in scope
+### 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.
+
+## Architecture (K27)
+
+Hand test finding K27: Architecture had several ways back that meant different
+things. Overview had its location trail ("django-demo / django"), System
+structure had a "← Back" that walked the focus, Behavior had a "← Back" that
+walked the starts, and "Show these N routes" had no way back at all. Nothing
+went forward. Architecture now uses the same model (`navigation-history.ts`)
+and the same rules as Galaxy, with a history of its own.
+
+### What an entry is
+
+One entry is the place the workspace shows: the subtab and what that subtab
+has opened.
+
+| Field | Meaning |
+|---|---|
+| `view` | The subtab: Overview (Structure, or Entry points as its mode), Routes, Hotspots, System structure or Behavior. |
+| `spatial` | Overview, Entry points, Hotspots and Endpoints draw one map: the opened area (`areaPath`) or file (`filePath`), the hotspot area, and Plan or 3D (`planar`). |
+| `routes` | The Routes perspective: Service map or Endpoints. |
+| `filter` | The Routes filter. An opened route group ("Show these N routes") is that filter. |
+| `system.focus`, `system.expanded` | The System structure focus and the expanded groups. |
+| `system.behavior` | The Behavior start, the destination ("Reach") and, after a followed call (double-click, "Follow calls from here"), the start the hops began from. |
+| `system.shown` | The start Behavior shows when none was requested (the server picks one, or the first entry point), so a tooltip can name it. |
+
+The entry holds identities and names, never projections, scenes or cameras.
+Its key covers only what the current subtab shows: a field another subtab holds
+does not split a step, and the names are there for the tooltips only. The
+Behavior start is the numeric identity of one analysis snapshot and stays
+guarded by its generation, as before.
+
+### Rules
+
+All Galaxy rules apply: at most 25 entries, consecutive duplicates merge, a new
+navigation after Back drops the forward branch, no `pushState` per step, a
+Recent list of the last 8 distinct places that is independent of the cursor,
+Alt+Left and Alt+Right neither while typing nor while another surface takes the
+keys, and a fresh history per project (the workspace remounts per project).
+Architecture adds:
+
+1. **One Back.** Back, Forward and Recent sit beside the subtabs and serve the
+ whole workspace. The "← Back" buttons in System structure and Behavior stay
+ where users know them and take the same step, with the same tooltip; there
+ is no second, local meaning of Back. "Whole system" stays as a way to the
+ top, and the Overview location trail stays; both are ordinary steps.
+2. **Separate from Galaxy.** Galaxy and Architecture each keep their own
+ history, and Alt+Left and Alt+Right act only in the active workspace.
+3. **Typing is one step.** Typing in the Routes filter becomes a step once it
+ pauses (600 ms), not one step per key. A navigation while typing first
+ records what the field showed. Back or Forward while typing drops the text
+ that is not a step yet.
+4. **The page's own choices are no steps.** What the page sets by itself (the
+ suggested Behavior start such as `main`, a reset after reindexing) replaces
+ the current step (`replaceNavigation`). As a step of its own, Back would land
+ on an empty Behavior, the page would pick `main` again, and Back would never
+ get past it.
+5. **Followed calls.** A followed call is a new start that remembers where the
+ hops began. Empty background returns there, as it did before, and that is a
+ step too.
+6. **Tooltips name the target**, for example "Back to Overview · django",
+ "Forward to Routes · Endpoints · /edit" or "Back to Behavior · get_autocommit
+ · followed from handle".
+7. **The current step keeps its newest details.** A change that leaves the key
+ alone (a name known only later, a field another subtab holds) updates the
+ current entry in place (`refreshNavigation`) instead of adding a step. On
+ django-demo the suggested `main` is rejected once for a stale analysis
+ snapshot, the start is reset, and the journey shows `main` on its own; the
+ step is still named "Behavior · main".
+
+### Where it lives
+
+- `graph-ui/src/graph/navigation-history.ts`: the shared model, with
+ `replaceNavigation` for rule 4 and `refreshNavigation` for rule 7.
+- `graph-ui/src/architecture/architecture-history.ts`: the Architecture entry,
+ its key, its recent place and the labels for tooltips and the Recent list.
+- `graph-ui/src/architecture/use-architecture-history.ts`: the place as state,
+ pushing on a new key, restoring without a push, the filter pause and the keys.
+- `ArchitecturePanel.tsx` holds the place and shows Back, Forward and Recent.
+ `SpatialArchitecture`, `RoutesArchitecture`, `SystemArchitecture` and
+ `BehaviorJourney` read their part of the place and report changes back
+ (`lifted-place.ts`). Rendered on their own, as in their unit tests, they keep
+ that part as their own state and offer no Back.
+- Tests: `architecture-history.test.ts` (entry, key, labels),
+ `ArchitecturePanel.history.test.tsx` (the wiring) and the browser run
+ `graph-ui/tools/handtest-fixes-k27.mjs` on django-demo and cbm.
+
+### Not in scope
+
+- Not steps: the Plan or 3D switch in System structure and Behavior, the Entry
+ points start and call depth, selections, the path and step within a call
+ chain, paging, the relationship filters and the camera.
+- No persistence across reloads. As before, only the subtab is remembered per
+ project.
diff --git a/graph-ui/src/App.tsx b/graph-ui/src/App.tsx
index d295e7a88..3443bbf8c 100644
--- a/graph-ui/src/App.tsx
+++ b/graph-ui/src/App.tsx
@@ -4838,6 +4838,7 @@ export default function App(): JSX.Element {
workspacePanel={<>
<div hidden={workspace !== 'architecture'}>
<ArchitecturePanel projectName={project} overview={overview} active={workspace === 'architecture'}
+ escapeTaken={helpOpen || entryOpen || overlayOpen || settingsOpen || projectsOpen}
onClearSelection={clearGraphSelection}
onSelectionEvidence={onSelectionEvidence}
coverage={coverageAsked && coverageMeta.generation === repositoryReading.snapshot?.generation ? coverage : undefined}
diff --git a/graph-ui/src/architecture/ArchitecturePanel.history.test.tsx b/graph-ui/src/architecture/ArchitecturePanel.history.test.tsx
new file mode 100644
index 000000000..a705eb34d
--- /dev/null
+++ b/graph-ui/src/architecture/ArchitecturePanel.history.test.tsx
@@ -0,0 +1,366 @@
+// @vitest-environment jsdom
+/*
+ * Handtest K27: ein Zurueck und ein Vor fuer ganz Architecture, mit demselben
+ * Verlaufsmodell wie Galaxy (K2). Die Szenen sind Attrappen mit Knoepfen fuer
+ * Auswahl, Doppelklick und leere Flaeche; Analyse und Routen kommen aus
+ * festen Antworten.
+ */
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import ArchitecturePanel, { type ArchitecturePanelProps } from './ArchitecturePanel';
+import type { ArchitectureSceneProps } from './ArchitectureScene';
+import type { ArchitectureOverviewDto } from '../core/intelligence-provider';
+import type { GraphData, GraphNode } from '../galaxy/types';
+import type { SystemSceneModel } from './system-architecture-model';
+import type { SystemArchitectureLoader, SystemProjection, SystemSymbol } from './system-architecture-source';
+
+vi.mock('./ArchitectureScene', () => ({ ArchitectureScene: (props: ArchitectureSceneProps) => <div data-testid="scene">
+ {props.model.nodes.map(node => <button key={node.id} data-node={node.id} onClick={() => props.onSelect(node.id)} onDoubleClick={() => props.onOpen?.(node.id)}>{node.label}</button>)}
+ <button aria-label="Empty background" onClick={props.onClearSelection} /></div> }));
+vi.mock('./ContainerMap', () => ({ default: ({ filter }: { filter: string }) => <div data-testid="container-map" data-filter={filter} /> }));
+vi.mock('./route-graph-source', () => ({ loadRouteGraph: vi.fn(async () => ({ relationships: [], truncated: false, warnings: [] })) }));
+vi.mock('./BehaviorSourceEvidence', () => ({ default: () => <div /> }));
+vi.mock('../app/atlas-api', () => ({ AtlasApi: class { flows() { return Promise.resolve([]); } } }));
+vi.mock('./SystemArchitectureScene', () => ({ default: ({ model, onSelectNode, onExpandNode, onClearSelection }: {
+ model: SystemSceneModel; onSelectNode: (id: string) => void; onExpandNode?: (id: string) => void; onClearSelection?: () => void;
+}) => <div data-testid="system-scene" data-focus={model.focusId ?? ''}><button onClick={onClearSelection}>System background</button>
+ {model.nodes.map(node => <button key={node.id} data-system-node={node.id} onClick={() => onSelectNode(node.id)} onDoubleClick={() => onExpandNode?.(node.id)}>{node.label}</button>)}</div> }));
+
+const graphNode = (id: number, name: string, file_path: string, label = 'Function'): GraphNode =>
+ ({ id, label, name, qualified_name: `sample.${name}`, file_path, start_line: 3, x: 0, y: 0, z: 0, size: 1, color: '' });
+const graph: GraphData = { nodes: [graphNode(1, 'render', 'django/shortcuts.py'), graphNode(2, 'options', 'django/contrib/admin/options.py'),
+ graphNode(3, 'setup', 'setup.py'), graphNode(10, '/edit/one/', 'app/urls.py', 'Route'), graphNode(11, '/edit/two/', 'app/urls.py', 'Route'),
+ graphNode(12, '/home/', 'app/urls.py', 'Route')], edges: [], total_nodes: 6 };
+const overview: ArchitectureOverviewDto = { projectName: 'sample', totalSymbols: 6, totalRelations: 0, symbolKinds: [], relationKinds: [], languages: [],
+ groups: [], boundaries: [], layers: [], clusters: [], entryPoints: [], routes: [], hotspots: [], files: ['django/shortcuts.py', 'django/contrib/admin/options.py', 'setup.py', 'app/urls.py'] };
+
+const symbol = (id: number, component: string, name: string): SystemSymbol => ({
+ id, name, qualified_name: `sample.${name}`, label: 'Function', file_path: `src/${component}.ts`, start_line: id * 10, component_id: component, group_id: `g:${component}`,
+});
+function projection(): SystemProjection {
+ const main = symbol(1, 'api', 'main'), handle = symbol(2, 'service', 'handle'), save = symbol(3, 'store', 'save'), commit = symbol(4, 'store', 'commit');
+ const components = [main, handle, save].map(item => ({ id: item.component_id, label: item.component_id, basis: 'interaction_community', member_count: 4, file_count: 1, representatives: [item], group_id: `g:${item.component_id}` }));
+ const dependencies = [{ source: 'api', target: 'service', type: 'CALLS', count: 2, witnesses: [{ edge_id: 10, source: main, target: handle }] },
+ { source: 'service', target: 'store', type: 'CALLS', count: 1, witnesses: [{ edge_id: 11, source: handle, target: save }] }];
+ return {
+ schema_version: 1, status: 'ready', kind: 'static_projection', complete: true, components, dependencies, cycles: [], entrypoints: [main, handle],
+ paths: [{ entrypoint_id: 1, nodes: [main, handle, save], edges: [{ id: 10, source_id: 1, target_id: 2, type: 'CALLS' }, { id: 11, source_id: 2, target_id: 3, type: 'CALLS' }] },
+ { entrypoint_id: 2, nodes: [handle, save], edges: [{ id: 11, source_id: 2, target_id: 3, type: 'CALLS' }] },
+ { entrypoint_id: 3, nodes: [save, commit], edges: [{ id: 12, source_id: 3, target_id: 4, type: 'CALLS' }] }],
+ totals: { nodes: 12, files: 3, edges: 3, accounted_nodes: 12, structural_nodes: 0 }, limits: {}, warnings: [],
+ overview: { complete: true, grouping_basis: 'common_source_directory_aggregate', components,
+ groups: components.map(item => ({ id: `g:${item.id}`, label: item.label, component_count: 1, member_count: 4, file_count: 1, component_ids: [item.id], representatives: item.representatives })),
+ connections: dependencies.map(edge => ({ ...edge, source: `g:${edge.source}`, target: `g:${edge.target}` })), totals: { groups: 3, components: 3 }, limits: {} },
+ };
+}
+
+let container: HTMLDivElement;
+let root: Root;
+let storageDescriptor: PropertyDescriptor | undefined;
+let loader: ReturnType<typeof vi.fn<SystemArchitectureLoader>>;
+
+beforeEach(() => {
+ (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
+ container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container);
+ storageDescriptor = Object.getOwnPropertyDescriptor(window, 'localStorage');
+ const contents = new Map<string, string>();
+ Object.defineProperty(window, 'localStorage', { configurable: true, value: {
+ getItem: (key: string) => contents.get(key) ?? null, setItem: (key: string, value: string) => { contents.set(key, value); },
+ } });
+ loader = vi.fn<SystemArchitectureLoader>().mockImplementation(async () => ({ status: 'ready', generation: 'g1', result: projection() }));
+});
+afterEach(async () => {
+ await act(async () => root.unmount()); container.remove();
+ if (storageDescriptor) Object.defineProperty(window, 'localStorage', storageDescriptor);
+ else delete (window as unknown as Record<string, unknown>).localStorage;
+});
+
+async function render(changes: Partial<ArchitecturePanelProps> = {}): Promise<void> {
+ await act(async () => root.render(<ArchitecturePanel projectName="sample" overview={overview} graph={graph} graphGeneration="g1"
+ systemArchitectureLoader={loader} onNavigate={vi.fn()} active {...changes} />));
+ await settle();
+}
+async function settle(): Promise<void> {
+ for (let round = 0; round < 4; round++) await act(async () => { await vi.dynamicImportSettled(); await new Promise(resolve => setTimeout(resolve, 0)); });
+}
+const buttons = (scope: ParentNode = container) => [...scope.querySelectorAll<HTMLButtonElement>('button')];
+const byText = (text: string, scope?: ParentNode) => buttons(scope).find(button => button.textContent === text);
+async function press(target: HTMLElement | null | undefined): Promise<void> {
+ expect(target).toBeTruthy();
+ await act(async () => target!.click()); await settle();
+}
+const clickText = (text: string, scope?: ParentNode) => press(byText(text, scope));
+async function doubleClick(selector: string): Promise<void> {
+ const target = container.querySelector(selector); expect(target).not.toBeNull();
+ await act(async () => target!.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }))); await settle();
+}
+async function choose(label: string, value: string): Promise<void> {
+ const select = container.querySelector<HTMLSelectElement>(`select[aria-label="${label}"]`); expect(select).not.toBeNull();
+ await act(async () => { select!.value = value; select!.dispatchEvent(new Event('change', { bubbles: true })); }); await settle();
+}
+async function type(value: string): Promise<void> {
+ const search = container.querySelector<HTMLInputElement>('input[type="search"]')!;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(search, value);
+ search.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+}
+const history = () => container.querySelector<HTMLElement>('[role="group"][aria-label="Architecture history"]');
+const back = () => history()?.querySelector<HTMLButtonElement>('button[aria-label="Back"]') ?? null;
+const forward = () => history()?.querySelector<HTMLButtonElement>('button[aria-label="Forward"]') ?? null;
+const goBack = () => press(back());
+const goForward = () => press(forward());
+const view = () => container.querySelector('.atlas-arch-tab[aria-pressed="true"]')?.getAttribute('data-view');
+const trail = () => [...container.querySelectorAll('[aria-label="Architecture location"] button')].map(item => item.textContent);
+const planar = () => container.querySelector('[aria-label="Map camera"] button[aria-pressed="true"]')?.textContent;
+const perspective = () => container.querySelector('[aria-label="Routes perspective"] button[aria-pressed="true"]')?.textContent;
+const filter = () => container.querySelector<HTMLInputElement>('input[type="search"]')?.value;
+const focus = () => container.querySelector('[data-testid="system-scene"]')?.getAttribute('data-focus');
+const heading = () => container.querySelector('.behavior-heading h2')?.textContent;
+const sceneLabels = () => [...container.querySelectorAll('[data-testid="scene"] [data-node]')].map(item => item.textContent);
+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 openArea(name: string): Promise<void> {
+ await press(container.querySelector<HTMLButtonElement>(`[data-testid="scene"] [data-node="area:${name}"]`) ?? byText(name, container.querySelector('[data-testid="scene"]')!));
+ await clickText('Open area →');
+}
+
+describe('Architecture back and forward (K27)', () => {
+ it('goes back and forward across subtabs, an opened area and Plan, naming each target', async () => {
+ await render();
+ expect(back()?.disabled).toBe(true);
+ expect(back()?.title).toBe('Nothing to go back to yet');
+ expect(forward()?.disabled).toBe(true);
+ await openArea('django');
+ expect(trail()).toEqual(['sample', 'django']);
+ expect(back()?.title).toBe('Back to Overview (Alt+Left)');
+ await clickText('Plan', container.querySelector('[aria-label="Map camera"]')!);
+ expect(back()?.title).toBe('Back to Overview · django (Alt+Left)');
+ await press(container.querySelector<HTMLButtonElement>('[data-view="hotspots"]'));
+ expect(back()?.title).toBe('Back to Overview · django · Plan (Alt+Left)');
+
+ await goBack();
+ expect([view(), trail(), planar()]).toEqual(['overview', ['sample', 'django'], 'Plan']);
+ expect(forward()?.title).toBe('Forward to Hotspots · Plan (Alt+Right)');
+ await goBack();
+ expect([view(), trail(), planar()]).toEqual(['overview', ['sample', 'django'], '3D']);
+ await goBack();
+ expect(trail()).toEqual(['sample']);
+ expect(back()?.disabled).toBe(true);
+ await goForward(); await goForward(); await goForward();
+ expect(view()).toBe('hotspots');
+ expect(forward()?.disabled).toBe(true);
+ // The location trail stays: it still leads back to the repository, and that is a step of its own.
+ await goBack();
+ await press(byText('sample', container.querySelector('[aria-label="Architecture location"]')!));
+ expect(trail()).toEqual(['sample']);
+ expect(back()?.title).toBe('Back to Overview · django · Plan (Alt+Left)');
+ });
+
+ it('restores the Routes perspective and an opened route group', async () => {
+ await render();
+ await press(container.querySelector<HTMLButtonElement>('[data-view="routes"]'));
+ expect(perspective()).toBe('Service map');
+ await clickText('Endpoints', container.querySelector('[aria-label="Routes perspective"]')!);
+ expect(sceneLabels()).toContain('/edit · 2');
+ await press(byText('/edit · 2', container.querySelector('[data-testid="scene"]')!));
+ await clickText('Show these 2 routes →');
+ expect(filter()).toBe('/edit');
+ expect(sceneLabels()).toEqual(['/edit/one/', '/edit/two/']);
+ expect(back()?.title).toBe('Back to Routes · Endpoints (Alt+Left)');
+
+ await goBack();
+ expect([view(), perspective(), filter()]).toEqual(['routes', 'Endpoints', '']);
+ await goBack();
+ expect([perspective(), filter()]).toEqual(['Service map', '']);
+ expect(container.querySelector('[data-testid="container-map"]')).not.toBeNull();
+ await goBack();
+ expect(view()).toBe('overview');
+ await goForward(); await goForward(); await goForward();
+ expect([view(), perspective(), filter()]).toEqual(['routes', 'Endpoints', '/edit']);
+ expect(sceneLabels()).toEqual(['/edit/one/', '/edit/two/']);
+ });
+
+ it('takes a typed filter as one step once typing pauses, not one per key', async () => {
+ await render();
+ await press(container.querySelector<HTMLButtonElement>('[data-view="routes"]'));
+ await type('/e'); await type('/ed'); await type('/edit');
+ expect(filter()).toBe('/edit');
+ await act(async () => { await new Promise(resolve => setTimeout(resolve, 900)); });
+ expect(back()?.title).toBe('Back to Routes · Service map (Alt+Left)');
+ await goBack();
+ expect([view(), filter()]).toEqual(['routes', '']);
+ await goBack();
+ expect(view()).toBe('overview');
+ await goForward(); await goForward();
+ expect(filter()).toBe('/edit');
+ });
+
+ it('makes the System structure focus and expanded groups steps, and its old Back the shared Back', async () => {
+ await render();
+ await press(container.querySelector<HTMLButtonElement>('[data-view="structure"]'));
+ expect(focus()).toBe('');
+ const oldBack = () => byText('← Back', container.querySelector('.system-scope-actions')!);
+ expect(oldBack()?.disabled).toBe(false);
+ expect(oldBack()?.title).toBe('Back to Overview (Alt+Left)');
+ await doubleClick('[data-system-node="g:api"]');
+ expect(focus()).toBe('g:api');
+ expect(container.querySelector('[data-system-node="member:g:api:api"]')).not.toBeNull();
+ expect(back()?.title).toBe('Back to System structure (Alt+Left)');
+ await press(container.querySelector<HTMLButtonElement>('[data-system-node="g:service"]'));
+ await clickText('Focus here');
+ expect(focus()).toBe('g:service');
+ expect(oldBack()?.title).toBe('Back to System structure · api · 1 group open (Alt+Left)');
+
+ await press(oldBack());
+ expect(focus()).toBe('g:api');
+ await goBack();
+ expect(focus()).toBe('');
+ expect(container.querySelector('[data-system-node="member:g:api:api"]')).toBeNull();
+ // One meaning of Back: the old button now also leaves System structure.
+ await press(oldBack());
+ expect(view()).toBe('overview');
+ await goForward(); await goForward();
+ expect([view(), focus()]).toEqual(['structure', 'g:api']);
+ expect(container.querySelector('[data-system-node="member:g:api:api"]')).not.toBeNull();
+ // "Whole system" stays the way to the top, as a new step that drops the forward branch.
+ await clickText('Whole system');
+ expect(focus()).toBe('');
+ expect(forward()?.disabled).toBe(true);
+ expect(back()?.title).toBe('Back to System structure · api · 1 group open (Alt+Left)');
+ });
+
+ it('steps through Behavior starts and followed calls, and an automatic start is no extra step', async () => {
+ await render();
+ await press(container.querySelector<HTMLButtonElement>('[data-view="structure"]'));
+ await press(container.querySelector<HTMLButtonElement>('[data-view="behavior"]'));
+ expect(heading()).toBe('What can main call?');
+ // The suggested start completes the Behavior step instead of adding one Back would bounce on.
+ expect(back()?.title).toBe('Back to System structure (Alt+Left)');
+ await choose('Behavior entry point', '2');
+ expect(heading()).toBe('What can handle call?');
+ expect(back()?.title).toBe('Back to Behavior · main (Alt+Left)');
+ await doubleClick('[data-system-node="journey-choice:3"]');
+ expect(heading()).toBe('What can save call?');
+ const oldBack = () => byText('← Back', container.querySelector('.behavior-navigation')!);
+ expect(oldBack()?.title).toBe('Back to Behavior · handle (Alt+Left)');
+ expect(forward()?.disabled).toBe(true);
+
+ await press(oldBack());
+ expect(heading()).toBe('What can handle call?');
+ expect(forward()?.title).toBe('Forward to Behavior · save · followed from handle (Alt+Right)');
+ await goBack();
+ expect(heading()).toBe('What can main call?');
+ await goBack();
+ expect(view()).toBe('structure');
+ await goForward(); await goForward(); await goForward();
+ expect(heading()).toBe('What can save call?');
+ expect(container.querySelector<HTMLSelectElement>('select[aria-label="Behavior entry point"]')?.value).toBe('3');
+ // Empty background still returns from a followed call to where the hops started, as a step.
+ await clickText('System background');
+ expect(heading()).toBe('What can handle call?');
+ expect(back()?.title).toBe('Back to Behavior · save · followed from handle (Alt+Left)');
+ });
+
+ it('names the start a reset Behavior step shows, after the suggested start was rejected for a stale snapshot', async () => {
+ // django-demo: the suggested main is rejected once for another analysis generation; the journey then shows main on its own.
+ let calls = 0;
+ loader.mockImplementation(async request => {
+ calls++;
+ if (request.entryNodeId !== undefined && request.expectedGeneration === 'g1') return { status: 'failed', generation: 'g2', error: 'Entry snapshot changed.' };
+ return { status: 'ready', generation: calls === 1 ? 'g1' : 'g2', result: projection() };
+ });
+ await render();
+ await press(container.querySelector<HTMLButtonElement>('[data-view="behavior"]'));
+ expect(heading()).toBe('What can main call?');
+ expect(back()?.title).toBe('Back to Overview (Alt+Left)');
+ await choose('Behavior entry point', '2');
+ expect(heading()).toBe('What can handle call?');
+ expect(back()?.title).toBe('Back to Behavior · main (Alt+Left)');
+ await goBack();
+ expect(heading()).toBe('What can main call?');
+ expect(forward()?.title).toBe('Forward to Behavior · handle (Alt+Right)');
+ await goBack();
+ expect(view()).toBe('overview');
+ expect(forward()?.title).toBe('Forward to Behavior · main (Alt+Right)');
+ });
+
+ it('drops the forward branch on a new navigation after Back and keeps at most 25 steps', async () => {
+ await render();
+ for (const tab of ['routes', 'hotspots', 'structure']) await press(container.querySelector<HTMLButtonElement>(`[data-view="${tab}"]`));
+ await goBack(); await goBack();
+ expect(view()).toBe('routes');
+ expect(forward()?.disabled).toBe(false);
+ await press(container.querySelector<HTMLButtonElement>('[data-view="behavior"]'));
+ expect(forward()?.disabled).toBe(true);
+ await goBack();
+ expect(view()).toBe('routes');
+ expect(forward()?.title).toBe('Forward to Behavior · main (Alt+Right)');
+
+ for (let step = 0; step < 15; step++) for (const tab of ['overview', 'hotspots']) await press(container.querySelector<HTMLButtonElement>(`[data-view="${tab}"]`));
+ expect(history()?.getAttribute('data-position')).toBe('25/25');
+ let steps = 0;
+ while (!back()!.disabled && steps < 100) { await goBack(); steps++; }
+ expect(steps).toBe(24);
+ });
+
+ it('answers Alt+Left and Alt+Right only in the active workspace and never while typing', async () => {
+ await render();
+ await press(container.querySelector<HTMLButtonElement>('[data-view="routes"]'));
+ let event = key({ key: 'ArrowLeft', altKey: true });
+ expect(event.defaultPrevented).toBe(true);
+ await settle();
+ expect(view()).toBe('overview');
+ event = key({ key: 'ArrowRight', altKey: true });
+ await settle();
+ expect(view()).toBe('routes');
+ // Typing in the route filter keeps the arrows for the text field.
+ const search = container.querySelector<HTMLInputElement>('input[type="search"]')!;
+ event = key({ key: 'ArrowLeft', altKey: true }, search);
+ expect(event.defaultPrevented).toBe(false);
+ expect(view()).toBe('routes');
+ // Without Alt, or with another modifier, the arrows are not history keys.
+ expect(key({ key: 'ArrowLeft' }).defaultPrevented).toBe(false);
+ expect(key({ key: 'ArrowLeft', altKey: true, metaKey: true }).defaultPrevented).toBe(false);
+ // Another surface on top (help, settings) keeps its keys.
+ await render({ escapeTaken: true });
+ expect(key({ key: 'ArrowLeft', altKey: true }).defaultPrevented).toBe(false);
+ expect(view()).toBe('routes');
+ // A hidden Architecture (Galaxy is active) leaves Alt+arrows to that workspace.
+ await render({ active: false });
+ expect(key({ key: 'ArrowLeft', altKey: true }).defaultPrevented).toBe(false);
+ await settle();
+ expect(view()).toBe('routes');
+ });
+
+ it('jumps to a recent place as a new navigation and starts a fresh history per project', async () => {
+ await render();
+ await openArea('django');
+ await press(container.querySelector<HTMLButtonElement>('[data-view="routes"]'));
+ await press(container.querySelector<HTMLButtonElement>('[data-view="structure"]'));
+ await goBack();
+ const recent = container.querySelector<HTMLDetailsElement>('details.atlas-arch-recent')!;
+ expect(recent).not.toBeNull();
+ expect(recent.querySelector('summary')?.getAttribute('aria-label')).toBe('Recent');
+ const places = [...recent.querySelectorAll('[aria-label="Recently visited places"] li button')];
+ expect(places.map(item => [item.querySelector('strong')?.textContent, item.querySelector('span')?.textContent ?? ''])).toEqual([
+ ['Routes', 'Service map'], ['System structure', ''], ['Overview', 'django'], ['Overview', ''],
+ ]);
+ expect(places[0]?.getAttribute('aria-current')).toBe('true');
+ await act(async () => { recent.open = true; });
+ await press(places[2] as HTMLButtonElement);
+ expect([view(), trail()]).toEqual(['overview', ['sample', 'django']]);
+ expect(recent.open).toBe(false);
+ expect(forward()?.disabled).toBe(true);
+ expect(back()?.title).toBe('Back to Routes · Service map (Alt+Left)');
+
+ await render({ projectName: 'other', overview: { ...overview, projectName: 'other' } });
+ expect(back()?.disabled).toBe(true);
+ expect(forward()?.disabled).toBe(true);
+ expect(container.querySelector('details.atlas-arch-recent')).toBeNull();
+ });
+});
diff --git a/graph-ui/src/architecture/ArchitecturePanel.tsx b/graph-ui/src/architecture/ArchitecturePanel.tsx
index 5d725582e..5c90b625a 100644
--- a/graph-ui/src/architecture/ArchitecturePanel.tsx
+++ b/graph-ui/src/architecture/ArchitecturePanel.tsx
@@ -1,11 +1,17 @@
-import { lazy, Suspense, useEffect, useMemo, useState } from 'react';
+import { lazy, Suspense, useCallback, useEffect, useMemo, useState } from 'react';
import type { JSX, ReactNode } from 'react';
import type { ArchitectureHotspot, ArchitectureOverviewDto } from '../core/intelligence-provider';
import {
ARCHITECTURE_VIEWS, readArchitectureConfig, saveArchitectureConfig,
} from './architecture-model';
import type { ArchitectureView, ConfigStorage } from './architecture-model';
-import { architectureText as text } from './strings';
+import { architectureHistoryText as historyText, architectureText as text } from './strings';
+import { peekNavigation, type NavigationHistory } from '../graph/navigation-history';
+import {
+ architectureEntryDetail, architectureEntryLabel, architectureEntryName, architectureHistoryOptions, initialArchitecturePlace,
+ type ArchitectureHistoryEntry, type PlaceChange, type RoutesPerspective, type SharedBack, type SpatialPlace, type SystemPlace,
+} from './architecture-history';
+import { useArchitectureHistory } from './use-architecture-history';
import './architecture.css';
import { scenePaletteStyle } from './scene-palette';
import type { RepositoryMapProps } from './RepositoryMap';
@@ -21,6 +27,8 @@ export interface ArchitecturePanelProps extends Pick<RepositoryMapProps, 'graph'
projectName: string;
graphGeneration?: string;
active?: boolean;
+ /** Another surface (help, settings, a dialog) takes the keys: Alt+Left and Alt+Right stay with it. */
+ escapeTaken?: boolean;
coverage?: CoverageIndex;
overview?: ArchitectureOverviewDto;
loading?: boolean;
@@ -113,48 +121,112 @@ function Findings({ view, data, empty, onNavigate }: {
const paletteStyle = scenePaletteStyle();
-function ArchitectureWorkspace({ projectName, overview, loading = false, error, onRefresh, onNavigate, graph, selectionPanel, onSelect, onClearSelection, onSelectionEvidence, graphNote, graphGeneration, active = true, coverage, systemArchitectureLoader }: ArchitecturePanelProps): JSX.Element {
+/**
+ * Back, Forward and the Recent list for the whole workspace (K27). The
+ * tooltips name the target ("Back to Overview · django"); the list holds the
+ * last distinct places, newest first, and the current one is not a target.
+ */
+function HistoryControls({ history, place, onGo, onJump }: {
+ history: NavigationHistory<ArchitectureHistoryEntry>; place: ArchitectureHistoryEntry;
+ onGo: (step: -1 | 1) => void; onJump: (entry: ArchitectureHistoryEntry) => void;
+}): JSX.Element {
+ const back = peekNavigation(history, -1), forward = peekNavigation(history, 1);
+ const here = architectureHistoryOptions.recentKey?.(place);
+ return <div className="atlas-arch-history" role="group" aria-label={historyText.group} data-position={`${history.index + 1}/${history.entries.length}`}>
+ <button type="button" aria-label={historyText.back} disabled={!back} onClick={() => onGo(-1)}
+ title={back ? historyText.backTo(architectureEntryLabel(back)) : historyText.noBack}>{historyText.backGlyph}</button>
+ <button type="button" aria-label={historyText.forward} disabled={!forward} onClick={() => onGo(1)}
+ title={forward ? historyText.forwardTo(architectureEntryLabel(forward)) : historyText.noForward}>{historyText.forwardGlyph}</button>
+ {history.recent.length > 1 && <details className="atlas-arch-recent" onKeyDown={event => {
+ if (event.key === 'Escape') { event.stopPropagation(); event.currentTarget.open = false; }
+ }}>
+ <summary title={historyText.recentTitle} aria-label={historyText.recent}>{historyText.recentGlyph}</summary>
+ <ul className="atlas-arch-recent-menu" aria-label={historyText.recentList}>{history.recent.map(entry => {
+ const id = architectureHistoryOptions.recentKey?.(entry);
+ const current = id === here;
+ const detail = architectureEntryDetail(entry);
+ return <li key={id}>
+ <button type="button" disabled={current} aria-current={current ? 'true' : undefined} title={architectureEntryLabel(entry)} onClick={event => {
+ const details = event.currentTarget.closest('details');
+ if (details) details.open = false;
+ onJump(entry);
+ }}><strong>{architectureEntryName(entry)}</strong>{detail && <span>{detail}</span>}</button>
+ </li>;
+ })}</ul>
+ </details>}
+ </div>;
+}
+
+function ArchitectureWorkspace({ projectName, overview, loading = false, error, onRefresh, onNavigate, graph, selectionPanel, onSelect, onClearSelection, onSelectionEvidence, graphNote, graphGeneration, active = true, escapeTaken = false, coverage, systemArchitectureLoader }: ArchitecturePanelProps): JSX.Element {
const storage = useMemo(browserStorage, []);
- // A filter is a search for this visit: one saved by an earlier session would silently hide routes.
- const [config, setConfig] = useState(() => ({ ...readArchitectureConfig(storage, projectName), filter: '' }));
- useEffect(() => { saveArchitectureConfig(storage, projectName, config); }, [config, projectName, storage]);
+ /*
+ * The place is the whole history entry (K27): subtab, opened area or file,
+ * Plan or 3D, route perspective and filter, System structure focus and
+ * groups, Behavior start. The views below read their part of it and report
+ * changes back, so Back and Forward restore every part at once. A filter is
+ * a search for this visit: one saved by an earlier session would silently
+ * hide routes, so only the subtab is read back.
+ */
+ const navigation = useArchitectureHistory(() => initialArchitecturePlace(readArchitectureConfig(storage, projectName).view), {
+ active, escapeTaken, onRestore: (from, to) => { if (from.view !== to.view) onSelectionEvidence?.(undefined); },
+ });
+ const { place, navigate } = navigation;
+ useEffect(() => { saveArchitectureConfig(storage, projectName, { view: place.view, filter: place.filter }); }, [place.view, place.filter, projectName, storage]);
+ const setView = useCallback((view: ArchitectureView) => navigate(current => ({ ...current, view: view === 'dependencies' ? 'overview' : view })), [navigate]);
+ const changeSpatial = useCallback<PlaceChange<SpatialPlace>>((change, automatic) =>
+ navigate(current => ({ ...current, spatial: { ...current.spatial, ...change } }), automatic), [navigate]);
+ const changeSystem = useCallback<PlaceChange<SystemPlace>>((change, automatic) =>
+ navigate(current => ({ ...current, system: { ...current.system, ...change } }), automatic), [navigate]);
+ const changePerspective = useCallback((routes: RoutesPerspective) => navigate(current => ({ ...current, routes })), [navigate]);
+ // An opened route group ("Show these N routes") is a step at once; typing waits for a pause.
+ const openRouteGroup = useCallback((filter: string) => navigate(current => ({ ...current, filter })), [navigate]);
+ const sharedBack: SharedBack = { target: navigation.back ? architectureEntryLabel(navigation.back) : undefined, onBack: () => navigation.go(-1) };
// A cached summary from another project must never appear here.
const data = overview?.projectName && overview.projectName !== projectName ? undefined : overview;
const ready = Boolean(data && !loading && !error && projectName);
- const systemView = config.view === 'structure' || config.view === 'behavior' ? config.view : undefined;
+ const systemView = place.view === 'structure' || place.view === 'behavior' ? place.view : undefined;
useEffect(() => {
if (active && (!projectName || (!systemView && (!ready || !graph)))) onSelectionEvidence?.(undefined);
}, [active, projectName, systemView, ready, graph, onSelectionEvidence]);
- const SpatialView = config.view === 'routes' ? RoutesArchitecture : SpatialArchitecture;
// Only the Routes view offers the filter, so no other view may receive a stale one.
- const filter = config.view === 'routes' ? config.filter : '';
- const setFilter = (value: string) => setConfig(current => ({ ...current, filter: value }));
+ const filter = place.view === 'routes' ? navigation.filter : '';
+ const spatialProps = !systemView && ready && data && graph ? {
+ project: projectName, generation: graphGeneration, graph, overview: data,
+ view: place.view === 'dependencies' || place.view === 'structure' || place.view === 'behavior' ? 'overview' as const : place.view,
+ filter, onFilter: openRouteGroup, active, graphNote, coverage, onSelect, onClearSelection, onSelectionEvidence, selectionPanel, onNavigate,
+ onView: (view: ArchitectureView) => { onSelectionEvidence?.(undefined); setView(view); }, place: place.spatial, onPlace: changeSpatial,
+ } : undefined;
// Every scene below draws with the same palette; the DOM reads it as CSS variables.
return <section className="atlas-architecture" data-testid="atlas-architecture" data-system-view={systemView} aria-label={text.title} aria-busy={!systemView && loading} style={paletteStyle}>
- <nav className="atlas-arch-tabs" aria-label={text.navigation}>{ARCHITECTURE_VIEWS.map(view =>
- <button className="atlas-arch-tab" key={view} aria-pressed={config.view === view || (view === 'overview' && ['dependencies', 'entryPoints'].includes(config.view))} data-view={view}
- onClick={() => { if (view !== config.view) onSelectionEvidence?.(undefined); setConfig(current => ({ ...current, view })); }}>{text.views[view]}</button>)}</nav>
+ <div className="atlas-arch-tabrow">
+ <nav className="atlas-arch-tabs" aria-label={text.navigation}>{ARCHITECTURE_VIEWS.map(view =>
+ <button className="atlas-arch-tab" key={view} aria-pressed={place.view === view || (view === 'overview' && ['dependencies', 'entryPoints'].includes(place.view))} data-view={view}
+ onClick={() => { if (view !== place.view) onSelectionEvidence?.(undefined); setView(view); }}>{text.views[view]}</button>)}</nav>
+ <HistoryControls history={navigation.history} place={place} onGo={navigation.go} onJump={navigation.jump} />
+ </div>
{systemView && projectName ? <Suspense fallback={<div role="status"><Empty>Preparing system analysis…</Empty></div>}><SystemArchitecture
project={projectName} generation={graphGeneration} view={systemView} filter={filter} active={active}
- graph={graph} onSelect={onSelect} onClearSelection={onClearSelection} onSelectionEvidence={onSelectionEvidence} onNavigate={onNavigate} loader={systemArchitectureLoader} /></Suspense> : null}
+ graph={graph} onSelect={onSelect} onClearSelection={onClearSelection} onSelectionEvidence={onSelectionEvidence} onNavigate={onNavigate} loader={systemArchitectureLoader}
+ place={place.system} onPlace={changeSystem} back={sharedBack} /></Suspense> : null}
{!systemView && (!projectName ? <Empty>{text.chooseProject}</Empty> : loading ? <div role="status"><Empty>{text.loading}</Empty></div>
: error ? <div role="alert" className="atlas-arch-empty" data-error="true"><p>{text.loadFailed}</p><p className="atlas-arch-error-detail">{error}</p>
{onRefresh && <button className="atlas-arch-action" onClick={onRefresh}>{text.retry}</button>}</div>
: !data ? <Empty>{text.unavailable}</Empty> : null)}
{systemView && !projectName && <Empty>{text.chooseProject}</Empty>}
- {!systemView && ready && data && graph && config.view === 'routes' && <div className="atlas-arch-toolbar"><label className="atlas-arch-filter">
+ {spatialProps && place.view === 'routes' && <div className="atlas-arch-toolbar"><label className="atlas-arch-filter">
<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><circle cx="6.5" cy="6.5" r="4.5" fill="none" stroke="currentColor" strokeWidth="1.4" /><path d="m10 10 4 4" stroke="currentColor" strokeWidth="1.4" /></svg>
- <input aria-label={text.filter} placeholder={text.filterPlaceholder} type="search" value={config.filter} onChange={event => setFilter(event.target.value)} /></label></div>}
- {!systemView && ready && data && graph && <SpatialView project={projectName} generation={graphGeneration} graph={graph} overview={data}
- view={config.view === 'dependencies' || config.view === 'structure' || config.view === 'behavior' ? 'overview' : config.view} filter={filter} onFilter={setFilter} active={active}
- graphNote={graphNote} coverage={coverage} onSelect={onSelect} onClearSelection={onClearSelection} onSelectionEvidence={onSelectionEvidence} selectionPanel={selectionPanel} onNavigate={onNavigate} onView={view => { onSelectionEvidence?.(undefined); setConfig(current => ({ ...current, view: view === 'dependencies' ? 'overview' : view })); }} />}
+ <input aria-label={text.filter} placeholder={text.filterPlaceholder} type="search" value={navigation.filter} onChange={event => navigation.type(event.target.value)} /></label></div>}
+ {spatialProps && (place.view === 'routes'
+ ? <RoutesArchitecture {...spatialProps} perspective={place.routes} onPerspective={changePerspective} />
+ : <SpatialArchitecture {...spatialProps} />)}
{!systemView && ready && data && !graph && <div className="atlas-arch-content" data-testid="atlas-architecture-content">
<p className="atlas-arch-fallback-summary">{data.files.length.toLocaleString()} files · {data.groups.length.toLocaleString()} source areas · {data.boundaries.length.toLocaleString()} cross-area connections</p>
- <Findings view={config.view === 'overview' || config.view === 'dependencies' ? 'entryPoints' : config.view} data={data} empty={text.noData} onNavigate={onNavigate} />
+ <Findings view={place.view === 'overview' || place.view === 'dependencies' ? 'entryPoints' : place.view} data={data} empty={text.noData} onNavigate={onNavigate} />
</div>}
</section>;
}
+/** A project switch remounts the workspace: a fresh history, as in Galaxy. */
export default function ArchitecturePanel(props: ArchitecturePanelProps): JSX.Element {
return <ArchitectureWorkspace key={props.projectName} {...props} />;
}
diff --git a/graph-ui/src/architecture/BehaviorJourney.test.tsx b/graph-ui/src/architecture/BehaviorJourney.test.tsx
index 04d7c6740..4e8c905db 100644
--- a/graph-ui/src/architecture/BehaviorJourney.test.tsx
+++ b/graph-ui/src/architecture/BehaviorJourney.test.tsx
@@ -70,26 +70,39 @@ describe('behavior journeys', () => {
expect([...container.querySelectorAll('[data-edge]')].map(item => item.getAttribute('data-edge'))).toEqual(['14', '15', '16', '17']);
expect(container.querySelector('[aria-label="Call-chain position"]')?.getAttribute('value')).toBe('5');
});
- it('double-clicking an operation requests its actual symbol and Back restores the previous scope', async () => {
- const props = await render(fixture());
+ it('double-clicking an operation requests its actual symbol as a hop from the start, and Back is the shared Back (K27)', async () => {
+ const onBack = vi.fn();
+ const props = await render(fixture(), { back: { target: 'Behavior · operation1', onBack } });
const button = container.querySelector('[data-node="journey-choice:2"]')!;
await act(async () => button.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })));
- expect(props.onRequest).toHaveBeenLastCalledWith(expect.objectContaining({ id: 2 }), undefined);
- await click('← Back');
- expect(props.onRequest).toHaveBeenLastCalledWith(expect.objectContaining({ id: 1 }), undefined);
+ expect(props.onRequest).toHaveBeenLastCalledWith(expect.objectContaining({ id: 2 }), undefined, { from: expect.objectContaining({ id: 1 }) });
+ const back = [...container.querySelectorAll<HTMLButtonElement>('.behavior-navigation button')].find(item => item.textContent === '← Back')!;
+ expect(back.title).toBe('Back to Behavior · operation1 (Alt+Left)');
+ await act(async () => back.click());
+ expect(onBack).toHaveBeenCalledOnce();
+ // A second hop still names the operation the hops started from.
+ const next = fixture(); next.entrypoints = [next.paths[0].nodes[1]];
+ next.paths = [{ ...next.paths[0], entrypoint_id: 2, nodes: next.paths[0].nodes.slice(1), edges: next.paths[0].edges.slice(1) }];
+ await render(next, { ...props, data: next, entryId: 2, from: fixture().entrypoints[0] });
+ await act(async () => container.querySelector('[data-node="journey-choice:3"]')!.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })));
+ expect(props.onRequest).toHaveBeenLastCalledWith(expect.objectContaining({ id: 3 }), undefined, { from: expect.objectContaining({ id: 1 }) });
+ // A start picked in the field begins anew.
+ await act(async () => { const select = container.querySelector<HTMLSelectElement>('[aria-label="Behavior entry point"]')!; select.value = '1'; select.dispatchEvent(new Event('change', { bubbles: true })); });
+ expect(props.onRequest).toHaveBeenLastCalledWith(expect.objectContaining({ id: 1 }), undefined, {});
});
it('clears inspection and returns from a followed operation to the original entry on empty background', async () => {
const clear = vi.fn(); const props = await render(fixture(), { onClearSelection: clear });
- await act(async () => container.querySelector('[data-node="journey-choice:2"]')!.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })));
const next = fixture(); next.entrypoints = [next.paths[0].nodes[1]];
next.paths = [{ ...next.paths[0], entrypoint_id: 2, nodes: next.paths[0].nodes.slice(1), edges: next.paths[0].edges.slice(1) }];
- await render(next, { ...props, data: next, entryId: 2 });
+ await render(next, { ...props, data: next, entryId: 2, from: fixture().entrypoints[0], back: { onBack: vi.fn() } });
await click('Empty background');
- expect(props.onRequest).toHaveBeenLastCalledWith(expect.objectContaining({ id: 1 }));
+ expect(props.onRequest).toHaveBeenLastCalledWith(expect.objectContaining({ id: 1 }), undefined, {});
expect(container.querySelector('[data-scene]')?.getAttribute('data-selected')).toBeNull();
expect(container.querySelector('[aria-label="Behavior evidence inspector"]')?.textContent).toContain('Select an operation or a call');
expect(clear).toHaveBeenCalledOnce();
- expect([...container.querySelectorAll('button')].find(item => item.textContent === '← Back')?.disabled).toBe(true);
+ const back = [...container.querySelectorAll<HTMLButtonElement>('button')].find(item => item.textContent === '← Back');
+ expect(back?.disabled).toBe(true);
+ expect(back?.title).toBe('Nothing to go back to yet');
});
it('shows exact argument expressions and declaration facts without inventing argument-to-parameter bindings', async () => {
const data = fixture();
diff --git a/graph-ui/src/architecture/BehaviorJourney.tsx b/graph-ui/src/architecture/BehaviorJourney.tsx
index 8c88f72f6..2bb87061b 100644
--- a/graph-ui/src/architecture/BehaviorJourney.tsx
+++ b/graph-ui/src/architecture/BehaviorJourney.tsx
@@ -1,7 +1,8 @@
import { lazy, Suspense, useEffect, useMemo, useRef, useState } from 'react';
import { behaviorJourney } from './behavior-journey-model';
import { projectionLimits, type SystemSceneModel } from './system-architecture-model';
-import { architectureText as text } from './strings';
+import { architectureHistoryText as historyText, architectureText as text } from './strings';
+import type { SharedBack } from './architecture-history';
import type { SystemProjection, SystemSymbol } from './system-architecture-source';
import BehaviorSourceEvidence, { type BehaviorSourceSnapshot } from './BehaviorSourceEvidence';
import { useSelectionEvidence, type SelectionEvidenceListener } from '../galaxy/selection-evidence';
@@ -12,13 +13,22 @@ export interface BehaviorJourneyProps {
project: string; generation?: string; data?: SystemProjection; entries: SystemSymbol[];
targets: (SystemSymbol & { distance: number })[]; entryId?: number; targetId?: number;
active: boolean; pending: boolean; error?: string; filter: string;
- onRequest: (entry: SystemSymbol | undefined, targetId?: number) => void;
+ onRequest: (entry: SystemSymbol | undefined, targetId?: number, detail?: BehaviorRequestDetail) => void;
+ /** The start the followed calls began from (K27); empty background returns there. */
+ from?: SystemSymbol;
+ /** The shared Architecture Back; without it the journey offers no Back of its own. */
+ back?: SharedBack;
+ /** Reports the start shown when none was requested, so a Back or Forward tooltip can name it (K27). */
+ onShownStart?: (name: string) => void;
onClearSelection?: () => void;
onSelectionEvidence?: SelectionEvidenceListener;
onRefresh: () => void; onSelectSymbol: (symbol: SystemSymbol) => void;
onNavigate: (path: string, line?: number, name?: string) => void;
}
+/** What a request carries besides start and destination: where followed calls began, and the destination's name. */
+export interface BehaviorRequestDetail { from?: SystemSymbol; targetName?: string }
+
/** Overlapping windows keep every operation legible and retain actual call adjacency. */
export function journeyPage(scene: SystemSceneModel, step: number, choices = false, pathWindow = 5): SystemSceneModel {
const size = choices ? 5 : Math.max(2, Math.min(5, pathWindow));
@@ -38,18 +48,16 @@ export function journeyPage(scene: SystemSceneModel, step: number, choices = fal
}
export default function BehaviorJourney({ project, generation, data, entries, targets, entryId, targetId, active, pending, error, filter,
- onRequest, onRefresh, onSelectSymbol, onNavigate, onClearSelection, onSelectionEvidence }: BehaviorJourneyProps) {
+ onRequest, onRefresh, onSelectSymbol, onNavigate, onClearSelection, onSelectionEvidence, from, back, onShownStart }: BehaviorJourneyProps) {
const [pathIndex, setPathIndex] = useState(0), [step, setStep] = useState(0);
const [branchPage, setBranchPage] = useState(0);
const [overview, setOverview] = useState(false);
const [selection, setSelection] = useState<{ node?: string; edge?: string }>();
const [planar, setPlanar] = useState(false), [resetKey, setResetKey] = useState(0);
- const [history, setHistory] = useState<{ entry: SystemSymbol; targetId?: number }[]>([]);
const visual = useRef<HTMLDivElement>(null);
const [pathWindow, setPathWindow] = useState(5);
const [sourceEvidence, setSourceEvidence] = useState<BehaviorSourceSnapshot>();
useEffect(() => { setSelection(undefined); setPathIndex(0); setStep(0); setBranchPage(0); }, [project, generation, entryId, targetId, filter]);
- useEffect(() => { setHistory([]); }, [project, generation]);
const journey = useMemo(() => data ? behaviorJourney(data, { entryId, targetId, pathIndex, filter }) : undefined,
[data, entryId, targetId, pathIndex, filter]);
const path = journey?.path;
@@ -78,6 +86,10 @@ export default function BehaviorJourney({ project, generation, data, entries, ta
.filter(item => item.id !== (entryId ?? journey?.entry?.id)).map(item => [item.id, item])).values()];
const entry = journey?.entry ?? entries.find(item => item.id === entryId);
const availableEntries = entry && !entries.some(item => item.id === entry.id) ? [entry, ...entries] : entries;
+ const reportShown = useRef(onShownStart);
+ reportShown.current = onShownStart;
+ const shownStart = entryId === undefined && !pending ? entry?.name : undefined;
+ useEffect(() => { if (shownStart !== undefined) reportShown.current?.(shownStart); }, [shownStart]);
const selectedTarget = targetOptions.find(item => item.id === targetId) ?? path?.nodes.at(-1);
const limits = data?.status === 'limited' ? projectionLimits(data) : [];
const sourceKey = caller ? JSON.stringify([project, generation, caller.qualified_name, call?.callsite?.file_path ?? caller.file_path, call?.callsite?.line ?? caller.start_line]) : undefined;
@@ -92,16 +104,22 @@ export default function BehaviorJourney({ project, generation, data, entries, ta
limitations: { analysis: data?.limits, warnings: data?.warnings, journey: journey.limits, counts: journey.counts,
interpretation: 'Static call evidence only. Call-chain depth is not execution order. Branch feasibility, parameter binding, runtime values and data transformation are not established.' },
} : undefined, active);
+ /** Empty background leaves a destination and returns from followed calls to where they began. */
function clearSelection() {
- const origin = history[0]?.entry ?? entry;
- setOverview(true); setSelection(undefined); setStep(0); setBranchPage(0); setPathIndex(0); setHistory([]);
+ const origin = from ?? entry;
+ setOverview(true); setSelection(undefined); setStep(0); setBranchPage(0); setPathIndex(0);
setResetKey(value => value + 1); onClearSelection?.();
- if (history.length || targetId !== undefined) onRequest(origin);
+ if (from || targetId !== undefined) onRequest(origin, undefined, {});
}
- function request(next: SystemSymbol | undefined, destination?: number, remember = true) {
+ /**
+ * Every request is a step of the shared Architecture history (K27). `origin` is where followed calls began:
+ * kept for a destination and for further hops, dropped for a start picked in the field.
+ */
+ function request(next: SystemSymbol | undefined, destination?: number, origin?: SystemSymbol) {
setOverview(false);
- if (remember && entry) setHistory(items => [...items.slice(-19), { entry, targetId }]);
- setSelection(undefined); setStep(0); setPathIndex(0); onRequest(next, destination);
+ setSelection(undefined); setStep(0); setPathIndex(0);
+ const targetName = destination === undefined ? undefined : targetOptions.find(item => item.id === destination)?.name;
+ onRequest(next, destination, { ...(origin && origin.id !== next?.id ? { from: origin } : {}), ...(targetName ? { targetName } : {}) });
}
function selectNode(id: string) {
setOverview(false);
@@ -126,7 +144,7 @@ export default function BehaviorJourney({ project, generation, data, entries, ta
}
function follow(id: string) {
const operation = allNodes.find(node => node.id === id)?.symbol;
- if (operation && operation.id !== entryId) request(operation);
+ if (operation && operation.id !== entryId) request(operation, undefined, from ?? entry);
}
return <section className="system-architecture behavior-journey" aria-label="Behavior" data-testid="behavior-journey" aria-busy={pending}>
<header className="behavior-heading"><div><span className="system-eyebrow">Behavior · source-guided exploration</span>
@@ -138,12 +156,12 @@ export default function BehaviorJourney({ project, generation, data, entries, ta
<label>Start <select aria-label="Behavior entry point" value={entry?.id ?? ''} onChange={event => request(availableEntries.find(item => item.id === Number(event.target.value)))}>
<option value="">Choose an operation…</option>{availableEntries.map(item => <option key={item.id} value={item.id}>{item.name} · {item.file_path ?? item.qualified_name}</option>)}
</select></label>
- <label>Reach <select aria-label="Behavior destination" value={targetId ?? ''} disabled={!entry || pending} onChange={event => request(entry, event.target.value ? Number(event.target.value) : undefined)}>
+ <label>Reach <select aria-label="Behavior destination" value={targetId ?? ''} disabled={!entry || pending} onChange={event => request(entry, event.target.value ? Number(event.target.value) : undefined, from)}>
<option value="">Explore immediate calls</option>{targetOptions.map(item => <option key={item.id} value={item.id}>{item.name} · {item.file_path ?? ''}</option>)}
</select></label>
</div>
- <div className="behavior-navigation"><button disabled={!history.length} onClick={() => { const previous = history.at(-1)!; setHistory(items => items.slice(0, -1)); request(previous.entry, previous.targetId, false); }}>← Back</button>
- {targetId !== undefined && <button onClick={() => request(entry)}>Immediate calls</button>}
+ <div className="behavior-navigation">{back && <button disabled={!back.target} title={back.target ? historyText.backTo(back.target) : historyText.noBack} onClick={back.onBack}>{historyText.inViewBack}</button>}
+ {targetId !== undefined && <button onClick={() => request(entry, undefined, from)}>Immediate calls</button>}
<span>{pending ? 'Updating this journey…' : path ? `${path.edges.length} call-chain hops · ${new Set(path.nodes.map(item => item.component_id)).size} components`
: text.directCallees(journey?.counts.directChoices ?? 0, journey?.counts.selfCalls ?? false)}</span>
<span className="behavior-static-badge" title="Graph relationships describe possible calls. They do not prove execution order, path feasibility or actual runtime values.">Static evidence</span>
@@ -179,7 +197,7 @@ export default function BehaviorJourney({ project, generation, data, entries, ta
<p>{call && callee ? caller.component_id === callee.component_id ? 'A call within the same component.' : `Crosses from ${components.get(caller.component_id)?.label ?? caller.component_id} into ${components.get(callee.component_id)?.label ?? callee.component_id}.`
: components.get(caller.component_id)?.label ?? caller.file_path}</p>
{call?.resolution && <p className="behavior-resolution">{call.resolution.strategy?.replaceAll('_', ' ') ?? 'Indexed resolution'}{call.resolution.candidates && call.resolution.candidates > 1 ? ` · ${call.resolution.candidates} candidate targets` : ''}</p>}
- <div className="behavior-inspector-actions">{symbol && symbol.id !== entryId && <button onClick={() => request(symbol)}>Follow calls from here</button>}
+ <div className="behavior-inspector-actions">{symbol && symbol.id !== entryId && <button onClick={() => request(symbol, undefined, from ?? entry)}>Follow calls from here</button>}
{symbol?.file_path && <button onClick={() => onNavigate(symbol.file_path!, symbol.start_line, symbol.name)}>Open definition ↗</button>}</div>
<div className="behavior-contract" aria-label="Indexed call contract">
{call?.arguments && <section><h4>Passed expressions</h4>{call.arguments.length ? <ol>{call.arguments.map((argument, index) => <li key={`${argument.i}:${index}`}><code>{argument.e}</code>
diff --git a/graph-ui/src/architecture/RoutesArchitecture.tsx b/graph-ui/src/architecture/RoutesArchitecture.tsx
index 9beb85fe4..e747dabd0 100644
--- a/graph-ui/src/architecture/RoutesArchitecture.tsx
+++ b/graph-ui/src/architecture/RoutesArchitecture.tsx
@@ -1,16 +1,30 @@
import { lazy, Suspense, useState, type ComponentProps } from 'react';
import SpatialArchitecture from './SpatialArchitecture';
+import type { RoutesPerspective } from './architecture-history';
+import { architectureText } from './strings';
import './container-map.css';
const ContainerMap = lazy(() => import('./ContainerMap'));
+const text = architectureText.routesPerspective;
+
+type Props = ComponentProps<typeof SpatialArchitecture> & {
+ /** Service map or Endpoints, lifted to the workspace for Back and Forward (K27). */
+ perspective?: RoutesPerspective;
+ onPerspective?: (perspective: RoutesPerspective) => void;
+};
/** The endpoint graph remains available independently of deployment metadata. */
-export default function RoutesArchitecture(props: ComponentProps<typeof SpatialArchitecture>) {
- const [mode, setMode] = useState<'services' | 'endpoints'>('services');
- const show = (next: 'services' | 'endpoints') => { if (mode !== next) props.onSelectionEvidence?.(undefined); setMode(next); };
- return <><nav className="container-mode" aria-label="Routes perspective">
- <button aria-pressed={mode === 'services'} onClick={() => show('services')}>Service map</button>
- <button aria-pressed={mode === 'endpoints'} onClick={() => show('endpoints')}>Endpoints</button>
- </nav>{mode === 'services' ? <Suspense fallback={<p role="status">Preparing service map…</p>}><ContainerMap
+export default function RoutesArchitecture({ perspective, onPerspective, ...props }: Props) {
+ const [own, setOwn] = useState<RoutesPerspective>('services');
+ const mode = perspective ?? own;
+ const show = (next: RoutesPerspective) => {
+ if (mode === next) return;
+ props.onSelectionEvidence?.(undefined);
+ if (onPerspective) onPerspective(next); else setOwn(next);
+ };
+ return <><nav className="container-mode" aria-label={text.label}>
+ <button aria-pressed={mode === 'services'} onClick={() => show('services')}>{text.services}</button>
+ <button aria-pressed={mode === 'endpoints'} onClick={() => show('endpoints')}>{text.endpoints}</button>
+ </nav>{mode === 'services' ? <Suspense fallback={<p role="status">{text.preparing}</p>}><ContainerMap
project={props.project} generation={props.generation} active={props.active} filter={props.filter} onNavigate={props.onNavigate} onClearSelection={props.onClearSelection} onSelectionEvidence={props.onSelectionEvidence}
onShowEndpoints={() => show('endpoints')} /></Suspense>
: <SpatialArchitecture {...props} />}</>;
diff --git a/graph-ui/src/architecture/SpatialArchitecture.tsx b/graph-ui/src/architecture/SpatialArchitecture.tsx
index 4319c9093..8c484541e 100644
--- a/graph-ui/src/architecture/SpatialArchitecture.tsx
+++ b/graph-ui/src/architecture/SpatialArchitecture.tsx
@@ -1,4 +1,6 @@
import { Component, Fragment, useEffect, useMemo, useState, type ReactNode } from 'react';
+import type { PlaceChange, SpatialPlace } from './architecture-history';
+import { useLiftedPlace, useOnIdentityChange } from './lifted-place';
import type { ArchitectureOverviewDto } from '../core/intelligence-provider';
import type { GraphData, GraphNode } from '../galaxy/types';
import { graphNodeEvidence, useSelectionEvidence, type SelectionEvidenceListener } from '../galaxy/selection-evidence';
@@ -25,6 +27,9 @@ interface Props {
onFilter?: (filter: string) => void;
onNavigate: (path: string, line?: number, name?: string) => void;
coverage?: CoverageIndex;
+ /** The opened area or file, the hotspot area and Plan or 3D, lifted to the workspace for Back and Forward (K27). */
+ place?: SpatialPlace;
+ onPlace?: PlaceChange<SpatialPlace>;
}
class SceneBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
@@ -44,16 +49,14 @@ const viewNotes: Record<SemanticView, string> = {
};
const relationKinds = ['CALLS', 'IMPORTS', 'USAGE', 'INHERITS', 'IMPLEMENTS', 'DATA_FLOWS'];
-export default function SpatialArchitecture({ project, generation, graph, overview, view, filter, active, graphNote, onSelect, onClearSelection, onSelectionEvidence, selectionPanel, onNavigate, onView, onFilter, coverage }: Props) {
- const [areaPath, setAreaPath] = useState<string>();
- const [filePath, setFilePath] = useState<string>();
+export default function SpatialArchitecture({ project, generation, graph, overview, view, filter, active, graphNote, onSelect, onClearSelection, onSelectionEvidence, selectionPanel, onNavigate, onView, onFilter, coverage, place: liftedPlace, onPlace }: Props) {
+ const [place, changePlace] = useLiftedPlace<SpatialPlace>(liftedPlace, onPlace, () => ({ planar: false }));
+ const { areaPath, filePath, hotspotArea, planar } = place;
const [entryChoice, setEntryChoice] = useState<{ node: GraphNode; generation?: string }>();
const [depth, setDepth] = useState(2);
const [relations, setRelations] = useState<string[]>([]);
- const [planar, setPlanar] = useState(false);
const { preferences, setPreferences } = useViewPreferences(project);
const { brickHeight: heightMetric, brickColor: colorMetric, fileVisibility, hotspotGravity: showHotspots } = preferences;
- const [hotspotArea, setHotspotArea] = useState<string>();
const [inventoryLimit, setInventoryLimit] = useState(24);
const [resetKey, setResetKey] = useState(0);
const [selection, setSelection] = useState<{ scope: string; node?: string; edge?: string }>();
@@ -61,7 +64,8 @@ export default function SpatialArchitecture({ project, generation, graph, overvi
const [routeRevision, setRouteRevision] = useState(0);
const [memberLimit, setMemberLimit] = useState(5);
const [includeTestRoutes, setIncludeTestRoutes] = useState(false);
- useEffect(() => { setHotspotArea(undefined); }, [project, generation]);
+ // A reindex clears the hotspot area; a view that mounts again keeps the place it is handed.
+ useOnIdentityChange(`${project}:${generation ?? ''}`, () => { if (hotspotArea) changePlace({ hotspotArea: undefined }, true); });
const routeKey = `${project}:${generation ?? ''}:${routeRevision}`;
useEffect(() => {
if (view !== 'routes' || !active) return;
@@ -126,12 +130,12 @@ export default function SpatialArchitecture({ project, generation, graph, overvi
if (node?.graphNode) onSelect?.(node.graphNode);
};
const openGroup = (node: SemanticNode) => {
- if (node.kind === 'area') { setAreaPath(node.areaPath); setFilePath(undefined); }
- else if (node.kind === 'file') setFilePath(node.filePath);
+ if (node.kind === 'area') changePlace({ areaPath: node.areaPath, filePath: undefined });
+ else if (node.kind === 'file') changePlace({ filePath: node.filePath });
if (view === 'routes' || view === 'hotspots') onView('overview');
setSelection(undefined);
};
- const clearScope = () => { setHotspotArea(undefined); setAreaPath(undefined); setFilePath(undefined); setSelection(undefined); setResetKey(value => value + 1); onClearSelection?.(); };
+ const clearScope = () => { changePlace({ hotspotArea: undefined, areaPath: undefined, filePath: undefined }); setSelection(undefined); setResetKey(value => value + 1); onClearSelection?.(); };
const openSource = (node: GraphNode) => node.file_path && onNavigate(node.file_path, node.start_line, node.name);
const inspectMember = (node: GraphNode) => {
const current = graph.nodes.find(candidate => candidate.qualified_name && candidate.qualified_name === node.qualified_name && candidate.file_path === node.file_path);
@@ -141,14 +145,14 @@ export default function SpatialArchitecture({ project, generation, graph, overvi
return <section className="spatial-architecture" data-testid="spatial-architecture" aria-label="Spatial architecture explorer">
<div className="spatial-heading"><div><span className="spatial-eyebrow">Repository atlas / {view === 'entryPoints' ? 'entry points' : view}</span><h2>{model.title}</h2><p>{viewNotes[view]}</p></div>
<div className="spatial-camera-controls" role="group" aria-label="Map camera">
- <button aria-pressed={!planar} onClick={() => setPlanar(false)}>3D</button><button aria-pressed={planar} onClick={() => setPlanar(true)}>Plan</button>
+ <button aria-pressed={!planar} onClick={() => changePlace({ planar: false })}>3D</button><button aria-pressed={planar} onClick={() => changePlace({ planar: true })}>Plan</button>
<button onClick={() => setResetKey(value => value + 1)}>Fit map</button>
</div>
</div>
<div className="spatial-controls">
{['overview', 'dependencies', 'entryPoints'].includes(view) && <div className="spatial-projection-modes" role="group" aria-label="Overview mode"><button aria-pressed={view !== 'entryPoints'} onClick={() => onView('overview')}>Structure</button><button aria-pressed={view === 'entryPoints'} onClick={() => onView('entryPoints')}>Entry points</button></div>}
{(view === 'overview' || view === 'dependencies') && <nav aria-label="Architecture location"><button onClick={clearScope}>{project}</button>
- {areaPath && areaLevels(areaPath).map((level, index, levels) => <Fragment key={level}><span>/</span><button onClick={() => { setAreaPath(level); setFilePath(undefined); setSelection(undefined); }}>{index ? level.slice(levels[index - 1].length + 1) : level}</button></Fragment>)}{filePath && <><span>/</span><span>{filePath.split('/').at(-1)}</span></>}
+ {areaPath && areaLevels(areaPath).map((level, index, levels) => <Fragment key={level}><span>/</span><button onClick={() => { changePlace({ areaPath: level, filePath: undefined }); setSelection(undefined); }}>{index ? level.slice(levels[index - 1].length + 1) : level}</button></Fragment>)}{filePath && <><span>/</span><span>{filePath.split('/').at(-1)}</span></>}
</nav>}
{view === 'entryPoints' && <><label>Start <select aria-label="Entry point" value={currentEntry?.id ?? ''} onChange={event => { const node = entries.find(node => node.id === Number(event.target.value)); setEntryChoice(node ? { node, generation } : undefined); setSelection(undefined); }}>
{!entries.length && <option value="">No indexed entry points</option>}{entries.map(node => <option key={node.id} value={node.id}>{node.name} · {node.file_path}</option>)}
@@ -197,7 +201,7 @@ export default function SpatialArchitecture({ project, generation, graph, overvi
{openedScope.measure && <details className="spatial-selection-details"><summary>{text.scopeMeasure(openedScope.measure.files, openedScope.measure.lines)}</summary><SourceMetricsDetails measure={openedScope.measure} catalog={catalog} /></details>}
<p>{text.openedScopeHint}</p>
</> : <><span className="spatial-eyebrow">{view === 'hotspots' ? 'Review areas' : 'Repository'}</span><h3>{view === 'hotspots' ? `${hotspotCatalog.findings.length} hotspot findings` : `${catalog.files.size.toLocaleString()} files`}</h3>
- {view === 'hotspots' ? <><p>Grouped by source area. Outside dependents are distinct files with direct incoming relationships in the loaded graph.</p><div className="spatial-area-summary" aria-label="Hotspots by source area">{areas.slice(0, 5).map(area => <button key={area.path} aria-pressed={hotspotArea === area.path} onClick={() => { setHotspotArea(area.path); setSelection(undefined); setResetKey(value => value + 1); }}><strong>{area.path}</strong><small>{area.findings} findings · {area.files} files</small><small>{area.dependentFiles} outside dependent files</small></button>)}</div>{areas.length > 5 && <details className="spatial-selection-details"><summary>{areas.length - 5} more areas</summary><div className="spatial-area-summary">{areas.slice(5).map(area => <button key={area.path} onClick={() => { setHotspotArea(area.path); setSelection(undefined); setResetKey(value => value + 1); }}><strong>{area.path}</strong><small>{area.findings} findings · {area.dependentFiles} outside dependent files</small></button>)}</div></details>}</>
+ {view === 'hotspots' ? <><p>Grouped by source area. Outside dependents are distinct files with direct incoming relationships in the loaded graph.</p><div className="spatial-area-summary" aria-label="Hotspots by source area">{areas.slice(0, 5).map(area => <button key={area.path} aria-pressed={hotspotArea === area.path} onClick={() => { changePlace({ hotspotArea: area.path }); setSelection(undefined); setResetKey(value => value + 1); }}><strong>{area.path}</strong><small>{area.findings} findings · {area.files} files</small><small>{area.dependentFiles} outside dependent files</small></button>)}</div>{areas.length > 5 && <details className="spatial-selection-details"><summary>{areas.length - 5} more areas</summary><div className="spatial-area-summary">{areas.slice(5).map(area => <button key={area.path} onClick={() => { changePlace({ hotspotArea: area.path }); setSelection(undefined); setResetKey(value => value + 1); }}><strong>{area.path}</strong><small>{area.findings} findings · {area.dependentFiles} outside dependent files</small></button>)}</div></details>}</>
: <p>Select a part or connection to inspect it. Open an area to explore its files.</p>}
</>}
<details className="spatial-node-list"><summary>Browse map · {model.nodes.length} parts</summary>{model.nodes.map(node => <button key={node.id} aria-pressed={selectedNode?.id === node.id} onClick={() => selectNode(node.id)}><span>{node.label}</span><small>{node.kind} · {node.count}</small></button>)}</details>
@@ -208,7 +212,7 @@ export default function SpatialArchitecture({ project, generation, graph, overvi
<details className="spatial-map-details"><summary>Browse files, connections and map details</summary>
<details className="spatial-file-inventory"><summary>File inventory · {catalog.files.size.toLocaleString()} known files</summary>
<p>Every returned file remains reachable here, even without connections or outside the 3D display limit. Unindexed folders may contain additional files that the index has not listed.</p>
- <div className="spatial-inventory-list">{inventoryFiles.slice(0, inventoryLimit).map(file => <article key={file.path}><button onClick={() => { setAreaPath(undefined); setFilePath(file.path); setSelection(undefined); onView('overview'); }}>{file.path}</button><small>{file.language} · {file.lines === undefined ? 'size unknown' : `${file.lines.toLocaleString()} indexed lines`} · {file.connection === 'connected' ? 'connected' : file.connection === 'none' ? 'no indexed connections' : 'connections unknown'}{coverage?.records.get(file.path) ? ` · ${coverage.records.get(file.path)!.state}` : ''}</small><button aria-label={`Read ${file.path}`} onClick={() => onNavigate(file.path, 1)}>Read source</button></article>)}</div>
+ <div className="spatial-inventory-list">{inventoryFiles.slice(0, inventoryLimit).map(file => <article key={file.path}><button onClick={() => { changePlace({ areaPath: undefined, filePath: file.path }); setSelection(undefined); onView('overview'); }}>{file.path}</button><small>{file.language} · {file.lines === undefined ? 'size unknown' : `${file.lines.toLocaleString()} indexed lines`} · {file.connection === 'connected' ? 'connected' : file.connection === 'none' ? 'no indexed connections' : 'connections unknown'}{coverage?.records.get(file.path) ? ` · ${coverage.records.get(file.path)!.state}` : ''}</small><button aria-label={`Read ${file.path}`} onClick={() => onNavigate(file.path, 1)}>Read source</button></article>)}</div>
<small>{Math.min(inventoryLimit, inventoryFiles.length)} / {inventoryFiles.length} files</small>{inventoryLimit < inventoryFiles.length && <button onClick={() => setInventoryLimit(value => value + 24)}>More files</button>}
{(overview.symbolKinds.find(kind => kind.kind === 'File')?.count ?? 0) > overview.files.length && <p className="spatial-notice">The file inventory query is limited. Additional files are available through the explorer tree.</p>}
{coverage?.truncations.map(note => <p key={note} className="spatial-notice">{note}</p>)}
diff --git a/graph-ui/src/architecture/SystemArchitecture.test.tsx b/graph-ui/src/architecture/SystemArchitecture.test.tsx
index c55096df5..103ff91b3 100644
--- a/graph-ui/src/architecture/SystemArchitecture.test.tsx
+++ b/graph-ui/src/architecture/SystemArchitecture.test.tsx
@@ -248,18 +248,27 @@ describe('system architecture workspace', () => {
expect(container.querySelector('[data-node="g:store"]')).toBeNull();
expect(container.querySelector('[data-node="g:context"]')).toBeNull();
});
- it('returns to immediate calls and restores the selected destination with Back', async () => {
+ it('returns to immediate calls, and its Back is the shared Architecture Back (K27)', async () => {
const loader = vi.fn<SystemArchitectureLoader>().mockImplementation(request => Promise.resolve(response(request.targetNodeId === 3 ? corridorFixture() : overviewFixture())));
- await render(loader, { view: 'behavior' });
+ const onBack = vi.fn();
+ await render(loader, { view: 'behavior', back: { target: 'Behavior · start → save', onBack } });
await choose('Behavior entry point', '1'); await choose('Behavior destination', '3');
await clickText('Immediate calls');
expect(container.querySelector<HTMLSelectElement>('[aria-label="Behavior destination"]')?.value).toBe('');
expect(container.querySelectorAll('[data-node]')).toHaveLength(2);
expect(container.textContent).toContain('DIRECT CALLS · UNORDERED');
- await clickText('← Back');
- expect(container.querySelector<HTMLSelectElement>('[aria-label="Behavior destination"]')?.value).toBe('3');
- expect(container.querySelectorAll('[data-node]')).toHaveLength(3);
- expect(container.querySelector('[data-testid="system-scene"]')?.getAttribute('data-focus')).toBe('');
+ const back = [...container.querySelectorAll<HTMLButtonElement>('.behavior-navigation button')].find(item => item.textContent === '← Back')!;
+ expect(back.title).toBe('Back to Behavior · start → save (Alt+Left)');
+ await act(async () => back.click());
+ expect(onBack).toHaveBeenCalledOnce();
+ await render(loader, { view: 'structure', back: { target: 'Overview', onBack } });
+ const structureBack = [...container.querySelectorAll<HTMLButtonElement>('.system-scope-actions button')].find(item => item.textContent === '← Back')!;
+ expect(structureBack.title).toBe('Back to Overview (Alt+Left)');
+ await act(async () => structureBack.click());
+ expect(onBack).toHaveBeenCalledTimes(2);
+ // Without a shared history (a view on its own) there is no second, local Back.
+ await render(loader, { view: 'structure', back: undefined });
+ expect([...container.querySelectorAll('button')].some(item => item.textContent === '← Back')).toBe(false);
});
it('filters whole paths without drawing disconnected remnants and restores the path without refetching', async () => {
const loader = vi.fn<SystemArchitectureLoader>().mockImplementation(request => Promise.resolve(response(request.targetNodeId === 3 ? corridorFixture() : overviewFixture())));
diff --git a/graph-ui/src/architecture/SystemArchitecture.tsx b/graph-ui/src/architecture/SystemArchitecture.tsx
index e1762847d..c89bcb9f7 100644
--- a/graph-ui/src/architecture/SystemArchitecture.tsx
+++ b/graph-ui/src/architecture/SystemArchitecture.tsx
@@ -8,6 +8,9 @@ import { connectionLoad } from '../graph/connection-load';
import { AtlasApi } from '../app/atlas-api';
import type { FlowSummary } from '../traces/trace-schemas';
import BehaviorJourney from './BehaviorJourney';
+import type { BehaviorPlace, PlaceChange, SharedBack, SystemPlace } from './architecture-history';
+import { architectureHistoryText as historyText } from './strings';
+import { useLiftedPlace, useOnIdentityChange } from './lifted-place';
import './system-architecture.css';
const Scene = lazy(() => import('./SystemArchitectureScene'));
@@ -18,6 +21,11 @@ export interface SystemArchitectureProps {
onNavigate: (path: string, line?: number, name?: string) => void;
loader?: SystemArchitectureLoader;
flowsLoader?: FlowsLoader;
+ /** Focus, expanded groups and the Behavior start, lifted to the workspace for Back and Forward (K27). */
+ place?: SystemPlace;
+ onPlace?: PlaceChange<SystemPlace>;
+ /** The shared Architecture Back; without it the view offers no Back of its own. */
+ back?: SharedBack;
}
/** Ranked call-graph flows (route handlers, call-graph roots) from /api/flows. */
export type FlowsLoader = (project: string) => Promise<FlowSummary[]>;
@@ -65,13 +73,16 @@ const connectionAllowed = (type: string, view: ConnectionView) => view === 'all'
|| (view === 'calls' ? ['CALLS', 'IMPORTS', 'HTTP_CALLS', 'ASYNC_CALLS'] : ['INHERITS', 'IMPLEMENTS']).includes(type);
/** Poll only while this view is active. A new request key hides stale results before its effect runs. */
-export default function SystemArchitecture({ project, generation, view, filter, active, graph, onSelect, onClearSelection, onSelectionEvidence, onNavigate, loader = loadSystemArchitecture, flowsLoader = loadFlows }: SystemArchitectureProps) {
- const [entryChoice, setEntryChoice] = useState<{ project: string; generation?: string; expectedGeneration?: string; id?: number; targetId?: number }>();
+export default function SystemArchitecture({ project, generation, view, filter, active, graph, onSelect, onClearSelection, onSelectionEvidence, onNavigate, loader = loadSystemArchitecture, flowsLoader = loadFlows, place: liftedPlace, onPlace, back }: SystemArchitectureProps) {
+ const [place, changePlace] = useLiftedPlace<SystemPlace>(liftedPlace, onPlace, () => ({ expanded: [] }));
+ const entryChoice = place.behavior;
+ /** A start the page picks itself (the suggestion, a reset) completes the current step instead of adding one. */
+ const setEntryChoice = (choice: BehaviorPlace | undefined, automatic = false) => changePlace({ behavior: choice }, automatic);
+ const focusId = place.focus?.id;
+ const expandedGroups = place.expanded;
const [entryChoices, setEntryChoices] = useState<{ project: string; generation?: string; analysisGeneration: string; entries: SystemSymbol[] }>();
const [snapshot, setSnapshot] = useState<{ project: string; generation?: string; analysisGeneration: string; data: SystemProjection }>();
const [targetCatalog, setTargetCatalog] = useState<{ project: string; generation?: string; source: number; analysisGeneration: string; targets: (SystemSymbol & { distance: number })[] }>();
- const [expandedGroups, setExpandedGroups] = useState<string[]>([]);
- const [scopeHistory, setScopeHistory] = useState<(string | undefined)[]>([]);
const [revision, setRevision] = useState(0);
const [reading, setReading] = useState<{ key: string; response?: SystemArchitectureResponse; error?: string }>();
const [cyclesOnly, setCyclesOnly] = useState(false);
@@ -83,7 +94,6 @@ export default function SystemArchitecture({ project, generation, view, filter,
const [listLimit, setListLimit] = useState(20);
const [resetKey, setResetKey] = useState(0);
const [planar, setPlanar] = useState(false);
- const [focusId, setFocusId] = useState<string>();
const [stepIndex, setStepIndex] = useState(0);
const [showConnectionLoad, setShowConnectionLoad] = useState(true);
const [flows, setFlows] = useState<{ project: string; generation?: string; entries: SystemSymbol[] }>();
@@ -104,7 +114,7 @@ export default function SystemArchitecture({ project, generation, view, filter,
// The numeric identity belongs to the projection that supplied the dropdown.
// A stale-entry rejection reopens the overview once, rather than reusing that ID.
if (response.status === 'failed' && requestedEntry !== undefined && expectedGeneration !== undefined && response.generation !== expectedGeneration) {
- setEntryChoice({ project, generation }); setEntryChoices(undefined); setTargetCatalog(undefined); setSnapshot(undefined); return;
+ setEntryChoice({ project, generation }, true); setEntryChoices(undefined); setTargetCatalog(undefined); setSnapshot(undefined); return;
}
setReading({ key: requestKey, response });
if (response.status === 'pending') timer = setTimeout(() => { void poll(); }, Math.min(5000, Math.max(500, response.retry_after_ms ?? 500)));
@@ -145,7 +155,11 @@ export default function SystemArchitecture({ project, generation, view, filter,
? queryData.behavior.reachable_targets : [];
const targets = matchingTargetCatalog?.targets ?? currentTargets;
const queryPending = !current?.error && current?.response?.status !== 'failed' && !queryData;
- useEffect(() => { setFocusId(undefined); setExpandedGroups([]); setScopeHistory([]); setSelection(undefined); }, [project, generation]);
+ // A new project or index clears focus and groups; a view that mounts again keeps the place it is handed.
+ useOnIdentityChange(`${project}:${generation ?? ''}`, () => {
+ setSelection(undefined);
+ if (place.focus || place.expanded.length) changePlace({ focus: undefined, expanded: [] }, true);
+ });
const structureData = useMemo(() => data ? { ...data, dependencies: data.dependencies.filter(edge => connectionAllowed(edge.type, connectionView)) } : undefined, [data, connectionView]);
const error = current?.error ?? (current?.response?.status === 'failed' ? current.response.error ?? 'Architecture analysis failed.' : undefined);
const chosenEntries = entryChoices?.project === project && entryChoices.generation === generation ? entryChoices.entries : data?.entrypoints ?? [];
@@ -169,7 +183,7 @@ export default function SystemArchitecture({ project, generation, view, filter,
useEffect(() => {
if (view !== 'behavior' || !data || (entryChoice?.project === project && entryChoice.generation === generation)) return;
const suggested = data.entrypoints.length ? suggestedBehaviorEntry(data.entrypoints) : suggestedBehaviorEntry(flowStarts, true);
- if (suggested) setEntryChoice({ project, generation, expectedGeneration: current?.response?.generation ?? snapshot?.analysisGeneration, id: suggested.id });
+ if (suggested) setEntryChoice({ project, generation, expectedGeneration: current?.response?.generation ?? snapshot?.analysisGeneration, id: suggested.id, name: suggested.name }, true);
}, [view, data, project, generation, entryChoice, current?.response?.generation, snapshot?.analysisGeneration, flowStarts]);
const returnedPaths = useMemo(() => {
const valid = queryData?.paths.filter(path => isContiguousPath(path)) ?? [];
@@ -263,11 +277,15 @@ export default function SystemArchitecture({ project, generation, view, filter,
const pathTarget = edge?.pathEdge && path?.nodes.find(symbol => symbol.id === edge.pathEdge!.target_id);
const pending = !error && !data;
function clearSelection() {
- setSelection(undefined); setFocusId(undefined); setScopeHistory([]); setExpandedGroups([]);
+ setSelection(undefined); changePlace({ focus: undefined, expanded: [] });
setResetKey(value => value + 1); onClearSelection?.();
}
- function focus(id: string | undefined) { setScopeHistory(previous => [...previous, focusId]); setFocusId(id); }
- function toggleGroup(id: string) { setExpandedGroups(previous => previous.includes(id) ? previous.filter(value => value !== id) : [...previous, id]); }
+ /** The name a Back or Forward tooltip gives a focus. */
+ const labelOf = (id: string) => model.nodes.find(item => item.id === id)?.label ?? data?.overview?.groups.find(item => item.id === id)?.label
+ ?? [...(data?.overview?.components ?? []), ...(data?.components ?? [])].find(item => item.id === id)?.label ?? id;
+ const toggled = (id: string) => expandedGroups.includes(id) ? expandedGroups.filter(value => value !== id) : [...expandedGroups, id];
+ function focus(id: string, expanded = expandedGroups) { changePlace({ focus: { id, label: labelOf(id) }, expanded }); }
+ function toggleGroup(id: string) { changePlace({ expanded: toggled(id) }); }
const selectedGroup = node?.group;
const corridorWitnesses: SystemWitness[] = view === 'behavior' ? (edge?.behaviorEdges ?? []).flatMap(evidence => {
const source = queryData?.behavior?.nodes.find(symbol => symbol.id === evidence.source_id);
@@ -294,11 +312,14 @@ export default function SystemArchitecture({ project, generation, view, filter,
const behaviorPage = view === 'behavior' ? <BehaviorJourney project={project} generation={projectionGeneration} data={queryData}
entries={entries} targets={targets} entryId={requestedEntry} targetId={requestedTarget} active={active} pending={queryPending}
error={error} filter={filter} onRefresh={() => setRevision(value => value + 1)} onNavigate={onNavigate} onSelectSymbol={selectSymbol} onClearSelection={onClearSelection} onSelectionEvidence={onSelectionEvidence}
- onRequest={(entry, targetId) => {
+ from={requestedEntry !== undefined ? entryChoice?.from : undefined} back={back}
+ onShownStart={name => { if (name !== place.shown) changePlace({ shown: name }, true); }}
+ onRequest={(entry, targetId, detail) => {
const analysisGeneration = projectionGeneration ?? sourceGeneration;
if (entry && analysisGeneration) setEntryChoices(previous => ({ project, generation, analysisGeneration,
entries: [...new Map([...(previous?.project === project && previous.generation === generation ? previous.entries : entries), entry].map(item => [item.id, item])).values()] }));
- setEntryChoice({ project, generation, id: entry?.id, targetId, expectedGeneration: analysisGeneration });
+ setEntryChoice({ project, generation, id: entry?.id, ...(entry ? { name: entry.name } : {}), targetId, expectedGeneration: analysisGeneration,
+ ...(targetId !== undefined && detail?.targetName ? { targetName: detail.targetName } : {}), ...(detail?.from ? { from: detail.from } : {}) });
}} /> : undefined;
if (behaviorPage) return behaviorPage;
return <section className="system-architecture" data-testid="system-architecture" aria-label={view === 'structure' ? 'System structure' : 'Behavior'} aria-busy={active && pending}>
@@ -306,7 +327,7 @@ export default function SystemArchitecture({ project, generation, view, filter,
<p>{view === 'structure' ? 'Inspect the parts and the code that connects them.' : 'Follow a question through the same system map.'}</p>
<button className="atlas-arch-action system-refresh" onClick={() => { setRevision(value => value + 1); setResetKey(value => value + 1); }}>Refresh analysis</button>
</div><div className="system-controls">
- <div className="system-scope-actions"><button disabled={!scopeHistory.length} onClick={() => { setFocusId(scopeHistory.at(-1)); setScopeHistory(previous => previous.slice(0, -1)); }}>← Back</button>
+ <div className="system-scope-actions">{back && <button disabled={!back.target} title={back.target ? historyText.backTo(back.target) : historyText.noBack} onClick={back.onBack}>{historyText.inViewBack}</button>}
<button disabled={!focusId} onClick={clearSelection}>Whole system</button></div>
{view === 'structure' && <label>Connections <select aria-label="Connection view" value={connectionView} onChange={event => { setConnectionView(event.target.value as ConnectionView); setCyclesOnly(false); }}>
<option value="calls">Calls &amp; imports</option><option value="types">Type relationships</option><option value="all">All relationships</option>
@@ -316,12 +337,13 @@ export default function SystemArchitecture({ project, generation, view, filter,
{view === 'structure' && <label><input type="checkbox" checked={includeTests} onChange={event => { setIncludeTests(event.target.checked); setSelection(undefined); }} />Include test components</label>}
{view === 'behavior' && <span className="system-small">Calls &amp; imports · all code groups</span>}
{view === 'behavior' && <label>From <select aria-label="Behavior entry point" value={requestedEntry ?? ''} onChange={event => setEntryChoice({ project, generation,
- expectedGeneration: entryChoices?.analysisGeneration ?? current?.response?.generation, id: event.target.value ? Number(event.target.value) : undefined })}>
+ expectedGeneration: entryChoices?.analysisGeneration ?? current?.response?.generation, id: event.target.value ? Number(event.target.value) : undefined,
+ name: entries.find(item => item.id === Number(event.target.value))?.name })}>
<option value="">{path ? `Suggested · ${path.nodes[0].name}${path.nodes[0].file_path ? ` · ${path.nodes[0].file_path}` : ''}` : 'Choose an entry point'}</option>{entries.map(entry => <option key={entry.id} value={entry.id}>{entry.name}{entry.file_path ? ` · ${entry.file_path}` : ''}</option>)}
</select></label>}
{view === 'behavior' && (data?.behavior || requestedEntry !== undefined) && <label>To <select aria-label="Behavior destination" disabled={requestedEntry === undefined || (!targets.length && queryPending)} value={requestedTarget ?? ''}
- onChange={event => setEntryChoice({ project, generation, id: requestedEntry, targetId: event.target.value ? Number(event.target.value) : undefined,
- expectedGeneration: matchingTargetCatalog?.analysisGeneration ?? sourceGeneration })}>
+ onChange={event => setEntryChoice({ project, generation, id: requestedEntry, name: entryChoice?.name, targetId: event.target.value ? Number(event.target.value) : undefined,
+ targetName: targets.find(item => item.id === Number(event.target.value))?.name, expectedGeneration: matchingTargetCatalog?.analysisGeneration ?? sourceGeneration })}>
<option value="">Choose a reachable operation…</option>{targets.map(target => <option key={target.id} value={target.id}>{target.name} · {target.file_path}</option>)}
</select></label>}
</div>
@@ -343,7 +365,7 @@ export default function SystemArchitecture({ project, generation, view, filter,
<div className="system-workspace"><div className="system-map">
{/* The reason for an empty projection outranks any filter that would also find nothing. */}
{model.nodes.length ? <Suspense fallback={<div className="system-scene-empty">Preparing 3D view…</div>}><Scene model={model} selectedNode={selectedSceneNode} selectedEdge={selection?.edge}
- onSelectNode={selectNode} onSelectEdge={selectEdge} onExpandNode={id => { toggleGroup(id); focus(id); }} onClearSelection={clearSelection} highlightedPathIndex={view === 'behavior' ? highlightedPathIndex : undefined} resetKey={resetKey} planar={planar} active={active} showConnectionLoad={showConnectionLoad} /></Suspense>
+ onSelectNode={selectNode} onSelectEdge={selectEdge} onExpandNode={id => focus(id, toggled(id))} onClearSelection={clearSelection} highlightedPathIndex={view === 'behavior' ? highlightedPathIndex : undefined} resetKey={resetKey} planar={planar} active={active} showConnectionLoad={showConnectionLoad} /></Suspense>
: view === 'structure' && projectionUnavailable(data) ? <UnavailableProjection limits={projectionLimits(data)} />
: <div className="system-scene-empty">{view === 'behavior' ? filter ? 'No source paths match this filter. Clear it to see the entry point’s returned paths.' : 'No connected source path is available for this entry point.' : cyclesOnly ? 'No component cycles match the current filters in the returned analysis.' : filter ? 'No matching components. Try a broader filter or include unconnected components.' : data.components.length && !includeUnconnected ? 'No connected components match the current view. Change the connection filter or include unconnected components.' : text.projectionEmpty}</div>}
<div className="system-map-caption"><span>{view === 'behavior' ? 'Arrows are indexed calls, not an execution timeline.' : 'Select to inspect · expand a group for its members'}{showConnectionLoad ? ' · rings show link load' : ''}</span>
@@ -372,8 +394,7 @@ export default function SystemArchitecture({ project, generation, view, filter,
{selectedGroup && <p className="system-small">{selectedGroup.component_count} code groups share this boundary. Grouping follows source organization; functional responsibilities are not inferred from its name.</p>}
{selectedGroup && <label className="system-member-picker">Browse members <select aria-label="Group member" value="" onChange={event => {
const id = event.target.value; if (!id) return;
- setExpandedGroups(previous => previous.includes(selectedGroup.id) ? previous : [...previous, selectedGroup.id]);
- focus(id); setSelection({ node: `member:${selectedGroup.id}:${id}` });
+ focus(id, expandedGroups.includes(selectedGroup.id) ? expandedGroups : [...expandedGroups, selectedGroup.id]); setSelection({ node: `member:${selectedGroup.id}:${id}` });
}}><option value="">Choose a component…</option>{(data.overview?.components ?? []).filter(item => selectedGroup.component_ids.includes(item.id)).map(item => <option key={item.id} value={item.id}>{item.label}</option>)}</select></label>}
<p>{selectedComponent.member_count.toLocaleString()} symbols across {selectedComponent.file_count.toLocaleString()} files.</p>
{(['incoming', 'outgoing'] as const).map(direction => <div className="system-neighbors" key={direction}><h4>{direction === 'incoming' ? 'Used by' : 'Uses'} <span>{neighbors[direction].size}</span></h4>
diff --git a/graph-ui/src/architecture/architecture-history.test.ts b/graph-ui/src/architecture/architecture-history.test.ts
new file mode 100644
index 000000000..ec8009f13
--- /dev/null
+++ b/graph-ui/src/architecture/architecture-history.test.ts
@@ -0,0 +1,124 @@
+/*
+ * Handtest K27: der Architecture-Eintrag im gemeinsamen Verlaufsmodell
+ * (src/graph/navigation-history.ts). Welcher Ort ein Schritt ist, wie er im
+ * Tooltip heisst und welcher Ort in der Liste der letzten Orte steht.
+ */
+import { describe, expect, it } from 'vitest';
+import {
+ NAVIGATION_HISTORY_LIMIT, emptyNavigationHistory, moveNavigation, peekNavigation, pushNavigation, replaceNavigation,
+ type NavigationHistory,
+} from '../graph/navigation-history';
+import {
+ architectureEntryDetail, architectureEntryLabel, architectureEntryName, architectureHistoryOptions, initialArchitecturePlace,
+ type ArchitectureHistoryEntry,
+} from './architecture-history';
+import type { SystemSymbol } from './system-architecture-source';
+
+const start = initialArchitecturePlace('overview');
+const at = (change: Partial<ArchitectureHistoryEntry>): ArchitectureHistoryEntry => ({ ...start, ...change });
+const key = architectureHistoryOptions.key;
+const recentKey = (entry: ArchitectureHistoryEntry) => architectureHistoryOptions.recentKey!(entry);
+const symbol = (id: number, name: string): SystemSymbol => ({ id, name, qualified_name: `django.${name}`, label: 'Function', file_path: `django/${name}.py`, component_id: 'django' });
+const behavior = (id: number, name: string, extra: Partial<NonNullable<ArchitectureHistoryEntry['system']['behavior']>> = {}) =>
+ at({ view: 'behavior', system: { expanded: [], behavior: { project: 'django-demo', id, name, ...extra } } });
+
+describe('the Architecture history entry (K27)', () => {
+ it('starts on the saved subtab with nothing opened', () => {
+ expect(initialArchitecturePlace('routes')).toEqual({ view: 'routes', spatial: { planar: false }, routes: 'services', filter: '', system: { expanded: [] } });
+ expect(initialArchitecturePlace('dependencies').view).toBe('overview');
+ });
+
+ it('is a new step for every subtab and for what each subtab opens', () => {
+ const views = ['overview', 'entryPoints', 'routes', 'hotspots', 'structure', 'behavior'] as const;
+ expect(new Set(views.map(view => key(at({ view }))))).toHaveProperty('size', views.length);
+ // Overview: the opened area and file, and Plan or 3D.
+ const django = at({ spatial: { planar: false, areaPath: 'django' } });
+ expect(key(django)).not.toBe(key(start));
+ expect(key(at({ spatial: { planar: false, areaPath: 'django', filePath: 'django/shortcuts.py' } }))).not.toBe(key(django));
+ expect(key(at({ spatial: { planar: true, areaPath: 'django' } }))).not.toBe(key(django));
+ // Routes: the perspective and the filter an opened route group sets.
+ const routes = at({ view: 'routes' });
+ expect(key({ ...routes, routes: 'endpoints' })).not.toBe(key(routes));
+ expect(key({ ...routes, routes: 'endpoints', filter: '/edit' })).not.toBe(key({ ...routes, routes: 'endpoints' }));
+ // System structure: the focus and the expanded groups, in any order.
+ const structure = at({ view: 'structure' });
+ const focused = { ...structure, system: { expanded: [], focus: { id: 'g:django', label: 'django' } } };
+ expect(key(focused)).not.toBe(key(structure));
+ expect(key({ ...structure, system: { expanded: ['g:a', 'g:b'] } })).toBe(key({ ...structure, system: { expanded: ['g:b', 'g:a'] } }));
+ expect(key({ ...structure, system: { expanded: ['g:a'] } })).not.toBe(key(structure));
+ // Behavior: the start and the destination ("Reach").
+ expect(key(behavior(7, 'handle'))).not.toBe(key(behavior(8, 'get_autocommit')));
+ expect(key(behavior(7, 'handle', { targetId: 9, targetName: 'save' }))).not.toBe(key(behavior(7, 'handle')));
+ });
+
+ it('merges what the screen does not show: other subtabs, names and where a hop came from', () => {
+ // What another subtab holds does not split an Overview step.
+ expect(key(at({ filter: '/edit' }))).toBe(key(start));
+ expect(key(at({ routes: 'endpoints' }))).toBe(key(start));
+ expect(key(at({ system: { expanded: ['g:a'], focus: { id: 'g:a', label: 'a' } } }))).toBe(key(start));
+ expect(key(at({ view: 'structure', spatial: { planar: true, areaPath: 'django' } }))).toBe(key(at({ view: 'structure' })));
+ // Names are for the tooltip; identity is the numeric start of this analysis.
+ expect(key(behavior(7, 'handle'))).toBe(key(behavior(7, 'renamed', { from: symbol(3, 'main'), generation: 'g2' })));
+ // A Service map does not draw Plan or 3D.
+ expect(key(at({ view: 'routes', spatial: { planar: true } }))).toBe(key(at({ view: 'routes' })));
+ expect(key(at({ view: 'routes', routes: 'endpoints', spatial: { planar: true } }))).not.toBe(key(at({ view: 'routes', routes: 'endpoints' })));
+ });
+
+ it('names the target of Back and Forward', () => {
+ expect(architectureEntryLabel(start)).toBe('Overview');
+ expect(architectureEntryLabel(at({ spatial: { planar: false, areaPath: 'django' } }))).toBe('Overview · django');
+ expect(architectureEntryLabel(at({ spatial: { planar: true, areaPath: 'django', filePath: 'django/shortcuts.py' } }))).toBe('Overview · django/shortcuts.py · Plan');
+ expect(architectureEntryLabel(at({ view: 'entryPoints' }))).toBe('Overview · Entry points');
+ expect(architectureEntryLabel(at({ view: 'routes' }))).toBe('Routes · Service map');
+ expect(architectureEntryLabel(at({ view: 'routes', routes: 'endpoints', filter: '/edit' }))).toBe('Routes · Endpoints · /edit');
+ expect(architectureEntryLabel(at({ view: 'hotspots', spatial: { planar: false, hotspotArea: 'django/db' } }))).toBe('Hotspots · django/db');
+ expect(architectureEntryLabel(at({ view: 'structure', system: { expanded: ['g:django'], focus: { id: 'g:django', label: 'django' } } })))
+ .toBe('System structure · django · 1 group open');
+ expect(architectureEntryLabel(at({ view: 'structure', system: { expanded: ['g:a', 'g:b'] } }))).toBe('System structure · 2 groups open');
+ expect(architectureEntryLabel(at({ view: 'behavior' }))).toBe('Behavior');
+ expect(architectureEntryLabel(behavior(7, 'handle', { targetId: 9, targetName: 'save' }))).toBe('Behavior · handle → save');
+ expect(architectureEntryLabel(behavior(8, 'get_autocommit', { from: symbol(7, 'handle') }))).toBe('Behavior · get_autocommit · followed from handle');
+ // Without a requested start the tooltip names the start the journey showed.
+ expect(architectureEntryLabel(at({ view: 'behavior', system: { expanded: [], shown: 'main', behavior: { project: 'django-demo' } } }))).toBe('Behavior · main');
+ expect(architectureEntryLabel(at({ view: 'behavior', system: { expanded: [], shown: 'main', behavior: { project: 'django-demo', id: 7, name: 'handle' } } }))).toBe('Behavior · handle');
+ expect(key(at({ view: 'behavior', system: { expanded: [], shown: 'main' } }))).toBe(key(at({ view: 'behavior' })));
+ expect(architectureEntryName(behavior(7, 'handle'))).toBe('Behavior');
+ expect(architectureEntryDetail(behavior(7, 'handle'))).toBe('handle');
+ expect(architectureEntryDetail(start)).toBe('');
+ });
+
+ it('keeps one recent place per subtab location, whatever its Plan or expanded groups', () => {
+ expect(recentKey(at({ spatial: { planar: true } }))).toBe(recentKey(start));
+ expect(recentKey(at({ spatial: { planar: false, areaPath: 'django' } }))).not.toBe(recentKey(start));
+ const structure = at({ view: 'structure', system: { expanded: [], focus: { id: 'g:django', label: 'django' } } });
+ expect(recentKey({ ...structure, system: { ...structure.system, expanded: ['g:django'] } })).toBe(recentKey(structure));
+ expect(recentKey(behavior(7, 'handle'))).not.toBe(recentKey(behavior(8, 'get_autocommit')));
+ });
+
+ it('runs on the one shared model: bounded, merged, forward branch dropped, recent places', () => {
+ const options = architectureHistoryOptions;
+ const push = (history: NavigationHistory<ArchitectureHistoryEntry>, ...entries: ArchitectureHistoryEntry[]) =>
+ entries.reduce((next, entry) => pushNavigation(next, entry, options), history);
+ const django = at({ spatial: { planar: false, areaPath: 'django' } });
+ let history = push(emptyNavigationHistory<ArchitectureHistoryEntry>(), start, django, django, at({ view: 'routes' }), at({ view: 'routes', filter: '' }));
+ expect(history.entries.map(architectureEntryLabel)).toEqual(['Overview', 'Overview · django', 'Routes · Service map']);
+ history = moveNavigation(moveNavigation(history, -1, options), -1, options);
+ history = push(history, at({ view: 'structure' }));
+ expect(history.entries.map(architectureEntryLabel)).toEqual(['Overview', 'System structure']);
+ expect(peekNavigation(history, 1)).toBeUndefined();
+ const many = Array.from({ length: NAVIGATION_HISTORY_LIMIT + 10 }, (_, index) => behavior(index + 1, `operation${index + 1}`));
+ history = push(history, ...many);
+ expect(history.entries).toHaveLength(NAVIGATION_HISTORY_LIMIT);
+ expect(history.recent).toHaveLength(8);
+ expect(architectureEntryLabel(history.recent[0]!)).toBe(`Behavior · operation${NAVIGATION_HISTORY_LIMIT + 10}`);
+ });
+
+ it('lets an automatic pick replace the step it completes instead of adding one', () => {
+ const options = architectureHistoryOptions;
+ const empty = at({ view: 'behavior' });
+ let history = pushNavigation(pushNavigation(emptyNavigationHistory<ArchitectureHistoryEntry>(), start, options), empty, options);
+ history = replaceNavigation(history, behavior(1, 'main'), options);
+ expect(history.entries.map(architectureEntryLabel)).toEqual(['Overview', 'Behavior · main']);
+ expect(history.recent.map(architectureEntryLabel)).toEqual(['Behavior · main', 'Overview']);
+ });
+});
diff --git a/graph-ui/src/architecture/architecture-history.ts b/graph-ui/src/architecture/architecture-history.ts
new file mode 100644
index 000000000..0d7122190
--- /dev/null
+++ b/graph-ui/src/architecture/architecture-history.ts
@@ -0,0 +1,120 @@
+/**
+ * The Architecture entry for Back and Forward (hand test K27): which place the
+ * workspace shows, without what it loaded for it.
+ *
+ * One entry is the subtab and what that subtab has opened: in Overview the area
+ * or file and Plan or 3D, in Routes the perspective and the route filter (an
+ * opened route group is that filter), in System structure the focus and the
+ * expanded groups, in Behavior the start, the destination and where a followed
+ * call began. It holds identities and names only, never projections, scenes or
+ * cameras, so nothing grows with the session. The model behind it is the one
+ * Galaxy uses (src/graph/navigation-history.ts); the concept is in
+ * docs/development/pr-2068-galaxy-history.md.
+ */
+import type { NavigationHistoryOptions } from '../graph/navigation-history';
+import type { ArchitectureView } from './architecture-model';
+import type { SystemSymbol } from './system-architecture-source';
+import { architectureHistoryText as text, architectureText } from './strings';
+
+export type RoutesPerspective = 'services' | 'endpoints';
+
+/** Overview, Entry points, Hotspots and Endpoints draw the same map (SpatialArchitecture). */
+export interface SpatialPlace { areaPath?: string; filePath?: string; hotspotArea?: string; planar: boolean }
+
+/**
+ * A Behavior start as SystemArchitecture requests it. The numeric identity
+ * belongs to one analysis snapshot, which `generation` and `expectedGeneration`
+ * guard; the names are for the tooltip.
+ */
+export interface BehaviorPlace {
+ project: string; generation?: string; expectedGeneration?: string;
+ id?: number; name?: string; targetId?: number; targetName?: string;
+ /** The start a followed call ("follow calls", double-click) began from; empty background returns there. */
+ from?: SystemSymbol;
+}
+
+export interface SystemPlace {
+ focus?: { id: string; label: string }; expanded: readonly string[]; behavior?: BehaviorPlace;
+ /** The start Behavior shows when none was requested (the server picks one, or the first entry point): for the tooltip only. */
+ shown?: string;
+}
+
+export interface ArchitectureHistoryEntry {
+ view: ArchitectureView;
+ spatial: SpatialPlace;
+ routes: RoutesPerspective;
+ /** The Routes filter, as far as it is a step: a route group or typing that paused. */
+ filter: string;
+ system: SystemPlace;
+}
+
+/** A part of the place handed to a view, and how it reports a change; `automatic` marks one the page made itself. */
+export type PlaceChange<T> = (change: Partial<T>, automatic?: boolean) => void;
+
+/** What System structure and Behavior need for the shared Back in their own toolbar. */
+export interface SharedBack { target?: string; onBack: () => void }
+
+export function initialArchitecturePlace(view: ArchitectureView): ArchitectureHistoryEntry {
+ return { view: view === 'dependencies' ? 'overview' : view, spatial: { planar: false }, routes: 'services', filter: '', system: { expanded: [] } };
+}
+
+/** What the subtab of an entry shows, without Plan or 3D and without expanded groups. */
+function location(entry: ArchitectureHistoryEntry): unknown[] {
+ const { spatial, system } = entry;
+ switch (entry.view) {
+ case 'overview': case 'dependencies': return [spatial.areaPath ?? null, spatial.filePath ?? null];
+ case 'hotspots': return [spatial.hotspotArea ?? null];
+ case 'routes': return [entry.routes, entry.filter];
+ case 'structure': return [system.focus?.id ?? null];
+ case 'behavior': return [system.behavior?.id ?? null, system.behavior?.targetId ?? null];
+ default: return [];
+ }
+}
+
+/** Whether the subtab of an entry draws the shared map with its Plan and 3D switch. */
+function drawsMap(entry: ArchitectureHistoryEntry): boolean {
+ return entry.view !== 'structure' && entry.view !== 'behavior' && (entry.view !== 'routes' || entry.routes === 'endpoints');
+}
+
+const viewOf = (entry: ArchitectureHistoryEntry): ArchitectureView => (entry.view === 'dependencies' ? 'overview' : entry.view);
+
+export const architectureHistoryOptions: NavigationHistoryOptions<ArchitectureHistoryEntry> = {
+ key: (entry) => JSON.stringify([viewOf(entry), ...location(entry), drawsMap(entry) && entry.spatial.planar,
+ entry.view === 'structure' ? [...entry.system.expanded].sort() : null]),
+ recentKey: (entry) => JSON.stringify([viewOf(entry), ...location(entry)]),
+};
+
+/** The subtab an entry stands on, as the tab names it. Entry points is a mode within Overview. */
+export function architectureEntryName(entry: ArchitectureHistoryEntry): string {
+ return architectureText.views[viewOf(entry) === 'entryPoints' ? 'overview' : viewOf(entry)];
+}
+
+function details(entry: ArchitectureHistoryEntry): string[] {
+ const { spatial, system } = entry;
+ const parts: (string | undefined)[] = [];
+ switch (viewOf(entry)) {
+ case 'overview': parts.push(spatial.filePath ?? spatial.areaPath); break;
+ case 'entryPoints': parts.push(architectureText.views.entryPoints); break;
+ case 'hotspots': parts.push(spatial.hotspotArea); break;
+ case 'routes': parts.push(architectureText.routesPerspective[entry.routes], entry.filter.trim() || undefined); break;
+ case 'structure': parts.push(system.focus?.label, system.expanded.length ? text.groupsOpen(system.expanded.length) : undefined); break;
+ case 'behavior': {
+ const start = system.behavior?.id === undefined ? system.behavior?.name ?? system.shown : system.behavior.name;
+ const target = system.behavior?.targetId === undefined ? undefined : system.behavior.targetName;
+ parts.push(start && target ? text.reach(start, target) : start, system.behavior?.from ? text.followedFrom(system.behavior.from.name) : undefined);
+ break;
+ }
+ }
+ if (drawsMap(entry) && spatial.planar) parts.push(text.plan);
+ return parts.filter((part): part is string => Boolean(part));
+}
+
+/** What a place shows besides its subtab, for the line under the name in the Recent list. Empty at the top of a subtab. */
+export function architectureEntryDetail(entry: ArchitectureHistoryEntry): string {
+ return details(entry).join(text.separator);
+}
+
+/** How an entry is named in a Back or Forward tooltip: "Overview · django". */
+export function architectureEntryLabel(entry: ArchitectureHistoryEntry): string {
+ return [architectureEntryName(entry), ...details(entry)].join(text.separator);
+}
diff --git a/graph-ui/src/architecture/architecture.css b/graph-ui/src/architecture/architecture.css
index e5ff9fc01..064eb889c 100644
--- a/graph-ui/src/architecture/architecture.css
+++ b/graph-ui/src/architecture/architecture.css
@@ -45,6 +45,30 @@
}
.atlas-arch-tab[aria-pressed="true"] { color: var(--atlas-fg); border-bottom-color: var(--atlas-phosphor); }
.atlas-arch-tab:hover { color: var(--atlas-fg); background: var(--atlas-panel); }
+/* K27: the tabs and one Back, Forward and Recent for the whole workspace share a row. The menu sits outside the scrolling tab strip. */
+.atlas-arch-tabrow { display: flex; align-items: center; gap: 12px; border-bottom: 1px solid var(--atlas-line); margin-bottom: 16px; }
+.atlas-arch-tabrow > .atlas-arch-tabs { flex: 1 1 auto; min-width: 0; border-bottom: 0; margin-bottom: 0; }
+.atlas-arch-history { display: flex; align-items: center; gap: 4px; flex: none; position: relative; }
+.atlas-arch-history > button, .atlas-arch-recent > summary {
+ border: 1px solid var(--atlas-line); border-radius: 7px; background: var(--atlas-panel); color: var(--atlas-fg);
+ min-width: 32px; min-height: 30px; padding: 3px 8px; line-height: 1.4;
+}
+.atlas-arch-history > button:hover:not(:disabled), .atlas-arch-recent > summary:hover { background: var(--atlas-panel-raised); border-color: var(--atlas-dim); }
+.atlas-arch-history > button:disabled { opacity: 0.45; }
+.atlas-arch-recent { position: relative; }
+.atlas-arch-recent > summary { display: block; cursor: pointer; list-style: none; text-align: center; white-space: nowrap; color: var(--atlas-dim); }
+.atlas-arch-recent > summary::-webkit-details-marker { display: none; }
+.atlas-arch-recent-menu {
+ position: absolute; top: calc(100% + 6px); right: 0; z-index: 30; width: min(24rem, calc(100vw - 3rem)); max-height: 20rem; overflow: auto;
+ margin: 0; padding: 6px; list-style: none; border: 1px solid var(--atlas-line); border-radius: 8px; background: var(--atlas-panel); box-shadow: 0 8px 24px #0006;
+}
+.atlas-arch-recent-menu button {
+ width: 100%; display: flex; flex-direction: column; align-items: flex-start; gap: 1px; text-align: left;
+ border: 0; border-radius: 6px; background: transparent; color: var(--atlas-fg); padding: 5px 8px;
+}
+.atlas-arch-recent-menu button:hover:not(:disabled) { background: var(--atlas-panel-raised); }
+.atlas-arch-recent-menu button span { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 11px; color: var(--atlas-dim); }
+.atlas-arch-recent-menu button[aria-current="true"] { opacity: 0.6; }
.atlas-arch-toolbar { margin-bottom: 24px; gap: 10px; }
.atlas-arch-filter { position: relative; flex: 1; max-width: 370px; }
.atlas-arch-filter svg { color: var(--atlas-dim); left: 11px; position: absolute; top: 10px; pointer-events: none; }
diff --git a/graph-ui/src/architecture/lifted-place.ts b/graph-ui/src/architecture/lifted-place.ts
new file mode 100644
index 000000000..48fc57779
--- /dev/null
+++ b/graph-ui/src/architecture/lifted-place.ts
@@ -0,0 +1,32 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import type { PlaceChange } from './architecture-history';
+
+/**
+ * A view's part of the Architecture place (K27). The workspace passes it in so
+ * that Back and Forward can restore it; a view rendered on its own keeps it as
+ * its own state. Either way the view reads one value and reports changes one way.
+ */
+export function useLiftedPlace<T extends object>(lifted: T | undefined, onChange: PlaceChange<T> | undefined, initial: () => T): [T, PlaceChange<T>] {
+ const [own, setOwn] = useState(initial);
+ const change = useCallback<PlaceChange<T>>((partial, automatic) => {
+ if (onChange) onChange(partial, automatic);
+ else setOwn(current => ({ ...current, ...partial }));
+ }, [onChange]);
+ return [lifted ?? own, change];
+}
+
+/**
+ * Runs `reset` when the identity changes after the first render, never on mount.
+ * A view that mounts again (switching subtabs, or Back into it) must keep the
+ * place it is handed instead of clearing it as if the index had changed.
+ */
+export function useOnIdentityChange(identity: string, reset: () => void): void {
+ const seen = useRef(identity);
+ const latest = useRef(reset);
+ latest.current = reset;
+ useEffect(() => {
+ if (seen.current === identity) return;
+ seen.current = identity;
+ latest.current();
+ }, [identity]);
+}
diff --git a/graph-ui/src/architecture/strings.ts b/graph-ui/src/architecture/strings.ts
index c3c9e09b9..65035afec 100644
--- a/graph-ui/src/architecture/strings.ts
+++ b/graph-ui/src/architecture/strings.ts
@@ -88,6 +88,8 @@ export const architectureText = {
compareFailed: 'Could not read that project. Its index may be unavailable.',
},
showEndpoints: 'Show endpoints →',
+ /** Routes: the two perspectives, also the names a Back or Forward tooltip gives them. */
+ routesPerspective: { label: 'Routes perspective', services: 'Service map', endpoints: 'Endpoints', preparing: 'Preparing service map…' },
/** Behavior: the callees of the start operation; a call to itself is named, not counted. */
directCallees: (count: number, selfCalls: boolean) => `${count.toLocaleString()} direct callees with returned evidence${selfCalls ? ' · also calls itself' : ''}`,
/** Behavior: the page of direct calls, the same calls the "direct callees" count names. */
@@ -97,3 +99,32 @@ export const architectureText = {
scopeMeasure: (files: number, lines?: number) => `${files.toLocaleString()} files · ${lines === undefined ? 'unknown' : lines.toLocaleString()} indexed lines`,
openedScopeHint: 'Select a part or connection to inspect it. The location above leads back to the repository.',
};
+
+/**
+ * Back and Forward for the whole Architecture workspace (hand test K27). The
+ * same rules and the same model as Galaxy (K2, src/graph/navigation-history.ts);
+ * a tooltip names the place a step leads to, for example "Back to Overview · django".
+ */
+export const architectureHistoryText = {
+ /** The accessible name of the Back, Forward and Recent group. */
+ group: 'Architecture history',
+ 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',
+ /** System structure and Behavior keep their own Back button; it takes the same step as the one above. */
+ inViewBack: '← Back',
+ recent: 'Recent',
+ recentGlyph: '▾',
+ recentTitle: 'Jump straight to a recently visited place in Architecture, as it was last seen',
+ recentList: 'Recently visited places',
+ separator: ' · ',
+ plan: 'Plan',
+ groupsOpen: (count: number) => (count === 1 ? '1 group open' : `${count} groups open`),
+ reach: (start: string, target: string) => `${start} → ${target}`,
+ followedFrom: (name: string) => `followed from ${name}`,
+};
diff --git a/graph-ui/src/architecture/system-architecture.css b/graph-ui/src/architecture/system-architecture.css
index 66ec47064..5fc416ac9 100644
--- a/graph-ui/src/architecture/system-architecture.css
+++ b/graph-ui/src/architecture/system-architecture.css
@@ -4,7 +4,8 @@
.atlas-architecture[data-system-view] .atlas-arch-heading h1 { font-size: 24px; line-height: 1.2; margin: 0 0 5px; }
.atlas-architecture[data-system-view] .atlas-arch-heading p { margin: 0; font-size: 12px; }
.atlas-architecture[data-system-view] .atlas-arch-project { display: none; }
-.atlas-architecture[data-system-view] .atlas-arch-tabs { margin-bottom: 10px; gap: 5px; }
+.atlas-architecture[data-system-view] .atlas-arch-tabrow { margin-bottom: 10px; }
+.atlas-architecture[data-system-view] .atlas-arch-tabs { gap: 5px; }
.atlas-architecture[data-system-view] .atlas-arch-tab { padding: 7px 10px; }
.atlas-architecture[data-system-view] .atlas-arch-toolbar { margin-bottom: 12px; gap: 8px; }
.system-toolbar, .system-reading-status, .system-map-caption { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; justify-content: space-between; }
diff --git a/graph-ui/src/architecture/use-architecture-history.ts b/graph-ui/src/architecture/use-architecture-history.ts
new file mode 100644
index 000000000..a2f3b4815
--- /dev/null
+++ b/graph-ui/src/architecture/use-architecture-history.ts
@@ -0,0 +1,146 @@
+/**
+ * Back and Forward for the Architecture workspace (hand test K27), wired the
+ * way Galaxy wires K2: the current place is state, every change of its key is
+ * a step in the shared bounded model, and a restored entry pushes nothing.
+ *
+ * Three refinements Architecture needs and Galaxy does not:
+ *
+ * - Typing in the Routes filter becomes one step once it pauses
+ * (`FILTER_STEP_MS`), not one step per key. A navigation while typing first
+ * records what the field showed.
+ * - A change the page makes itself (the suggested Behavior start, a reset
+ * after reindexing) replaces the current step instead of adding one, so Back
+ * never lands on a state the page would immediately fill in again.
+ * - Alt+Left and Alt+Right act only while this workspace is the active one,
+ * never while typing and never while another surface takes the keys.
+ *
+ * Rules and limits: src/graph/navigation-history.ts and
+ * docs/development/pr-2068-galaxy-history.md.
+ */
+import { useCallback, useEffect, useRef, useState } from 'react';
+import {
+ emptyNavigationHistory, moveNavigation, peekNavigation, pushNavigation, refreshNavigation, replaceNavigation, type NavigationHistory,
+} from '../graph/navigation-history';
+import { isTypingTarget } from '../app/keyboard';
+import { architectureHistoryOptions as options, type ArchitectureHistoryEntry } from './architecture-history';
+
+/** Typing in the Routes filter becomes a step once it pauses this long. */
+export const FILTER_STEP_MS = 600;
+
+type Update = (current: ArchitectureHistoryEntry) => ArchitectureHistoryEntry;
+
+export interface ArchitectureHistory {
+ place: ArchitectureHistoryEntry;
+ /** What the filter field shows, including typing that is not a step yet. */
+ filter: string;
+ history: NavigationHistory<ArchitectureHistoryEntry>;
+ back?: ArchitectureHistoryEntry;
+ forward?: ArchitectureHistoryEntry;
+ /** A navigation; `automatic` marks a change the page made itself. Stable across renders. */
+ navigate: (update: Update, automatic?: boolean) => void;
+ type: (filter: string) => void;
+ go: (step: -1 | 1) => void;
+ /** A recent place is a new navigation: it is pushed and drops the forward branch. */
+ jump: (entry: ArchitectureHistoryEntry) => void;
+}
+
+export interface ArchitectureHistoryKeys {
+ active: boolean;
+ escapeTaken: boolean;
+ /** Called before Back, Forward or a recent jump replaces the place. */
+ onRestore?: (from: ArchitectureHistoryEntry, to: ArchitectureHistoryEntry) => void;
+}
+
+export function useArchitectureHistory(initial: () => ArchitectureHistoryEntry, { active, escapeTaken, onRestore }: ArchitectureHistoryKeys): ArchitectureHistory {
+ const [place, setPlace] = useState(initial);
+ const [draft, setDraft] = useState<string>();
+ const [history, setHistory] = useState(() => emptyNavigationHistory<ArchitectureHistoryEntry>());
+ const latest = useRef(place);
+ latest.current = place;
+ const typed = useRef<string | undefined>(undefined);
+ const restoringKey = useRef<string | undefined>(undefined);
+ /** An automatic change: the key it was computed from and the key it leads to. */
+ const automaticStep = useRef<{ base: string; next: string } | undefined>(undefined);
+ const restore = useRef(onRestore);
+ restore.current = onRestore;
+ const key = options.key(place);
+
+ useEffect(() => {
+ const entry = latest.current;
+ const restoring = restoringKey.current;
+ restoringKey.current = undefined;
+ if (restoring === key) return;
+ const automatic = automaticStep.current;
+ if (automatic?.next === key) {
+ automaticStep.current = undefined;
+ setHistory((current) => replaceNavigation(current, entry, options));
+ return;
+ }
+ // Computed from this very state and not rendered yet: it still belongs to the next step.
+ if (automatic && automatic.base !== key) automaticStep.current = undefined;
+ setHistory((current) => pushNavigation(current, entry, options));
+ }, [key]);
+ // The current step keeps the newest details of its place (a name known only later); after the push above, so a new key is never a refresh.
+ useEffect(() => { setHistory((current) => refreshNavigation(current, place, options)); }, [place]);
+
+ const clearDraft = useCallback(() => { typed.current = undefined; setDraft(undefined); }, []);
+
+ const navigate = useCallback((update: Update, automatic = false) => {
+ const text = automatic ? undefined : typed.current;
+ if (text !== undefined) {
+ clearDraft();
+ // What the field showed is a step of its own, before the navigation that leaves it.
+ setHistory((current) => pushNavigation(current, { ...latest.current, filter: text }, options));
+ }
+ setPlace((current) => {
+ const result = update(text === undefined ? current : { ...current, filter: text });
+ if (automatic) {
+ const before = options.key(current), after = options.key(result);
+ if (after !== before) automaticStep.current = { base: before, next: after };
+ }
+ return result;
+ });
+ }, [clearDraft]);
+
+ const type = useCallback((value: string) => { typed.current = value; setDraft(value); }, []);
+ useEffect(() => {
+ if (draft === undefined) return;
+ const timer = setTimeout(() => {
+ clearDraft();
+ setPlace((current) => ({ ...current, filter: draft }));
+ }, FILTER_STEP_MS);
+ return () => clearTimeout(timer);
+ }, [draft, clearDraft]);
+
+ const apply = useCallback((entry: ArchitectureHistoryEntry) => {
+ restore.current?.(latest.current, entry);
+ clearDraft();
+ automaticStep.current = undefined;
+ setPlace(entry);
+ }, [clearDraft]);
+ const go = useCallback((step: -1 | 1) => {
+ const entry = peekNavigation(history, step);
+ if (entry === undefined) return;
+ restoringKey.current = options.key(entry);
+ setHistory((current) => moveNavigation(current, step, options));
+ apply(entry);
+ }, [history, apply]);
+ const jump = useCallback((entry: ArchitectureHistoryEntry) => apply(entry), [apply]);
+
+ useEffect(() => {
+ if (!active || 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();
+ go(step);
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [active, escapeTaken, history, go]);
+
+ return { place, filter: draft ?? place.filter, history, back: peekNavigation(history, -1), forward: peekNavigation(history, 1), navigate, type, go, jump };
+}
diff --git a/graph-ui/src/graph/navigation-history.test.ts b/graph-ui/src/graph/navigation-history.test.ts
index 6ff5b4b31..eb7919018 100644
--- a/graph-ui/src/graph/navigation-history.test.ts
+++ b/graph-ui/src/graph/navigation-history.test.ts
@@ -5,6 +5,8 @@ import {
moveNavigation,
peekNavigation,
pushNavigation,
+ refreshNavigation,
+ replaceNavigation,
type NavigationHistory,
type NavigationHistoryOptions,
} from './navigation-history';
@@ -65,4 +67,36 @@ describe('bounded back and forward history', () => {
expect(capped.recent).toHaveLength(8);
expect(capped.recent[0]!.root).toBe('R11');
});
+
+ it('replaces the current step for a change the page makes on its own, keeping the forward branch (K27)', () => {
+ let history = push(emptyNavigationHistory<Entry>(), { root: 'A', depth: 1 }, { root: 'B', depth: 1 }, { root: 'C', depth: 1 });
+ history = moveNavigation(history, -1, options);
+ history = replaceNavigation(history, { root: 'B2', depth: 1 }, options);
+ expect(keys(history)).toEqual(['A@1', 'B2@1', 'C@1']);
+ expect(history.index).toBe(1);
+ expect(peekNavigation(history, 1)).toEqual({ root: 'C', depth: 1 });
+ // The replaced place leaves the recent list with it.
+ expect(history.recent.map((entry) => entry.root)).toEqual(['B2', 'C', 'A']);
+ // Equal to the current step: nothing changes. Equal to the step before: the two merge.
+ expect(replaceNavigation(history, { root: 'B2', depth: 1 }, options)).toBe(history);
+ expect(keys(replaceNavigation(history, { root: 'A', depth: 1 }, options))).toEqual(['A@1', 'C@1']);
+ expect(replaceNavigation(history, { root: 'A', depth: 1 }, options).index).toBe(0);
+ // Without a current step it is an ordinary first step.
+ expect(keys(replaceNavigation(emptyNavigationHistory<Entry>(), { root: 'A', depth: 1 }, options))).toEqual(['A@1']);
+ });
+
+ it('refreshes the current step with newer details of the same place, without a step or reordering (K27)', () => {
+ interface Named extends Entry { name?: string }
+ const named: NavigationHistoryOptions<Named> = options;
+ let history = [{ root: 'A', depth: 1 }, { root: 'B', depth: 1 }].reduce((next, entry) => pushNavigation(next, entry, named), emptyNavigationHistory<Named>());
+ const fresher = { root: 'B', depth: 1, name: 'Bee' };
+ history = refreshNavigation(history, fresher, named);
+ expect(history.entries).toEqual([{ root: 'A', depth: 1 }, fresher]);
+ expect(history.index).toBe(1);
+ expect(history.recent).toEqual([fresher, { root: 'A', depth: 1 }]);
+ // Another key is a step, not a refresh; the same object changes nothing.
+ expect(refreshNavigation(history, { root: 'C', depth: 1 }, named)).toBe(history);
+ expect(refreshNavigation(history, fresher, named)).toBe(history);
+ expect(refreshNavigation(emptyNavigationHistory<Named>(), fresher, named).entries).toEqual([]);
+ });
});
diff --git a/graph-ui/src/graph/navigation-history.ts b/graph-ui/src/graph/navigation-history.ts
index cdda112ef..d33929ae4 100644
--- a/graph-ui/src/graph/navigation-history.ts
+++ b/graph-ui/src/graph/navigation-history.ts
@@ -1,7 +1,7 @@
/**
* Ein begrenzter Verlauf mit Zurueck und Vor, wie beim Blaettern (K2).
*
- * Rein und ohne React, damit Galaxy und spaeter Architecture (K27) dasselbe
+ * Rein und ohne React, damit Galaxy (K2) und 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:
@@ -61,6 +61,50 @@ export function pushNavigation<T>(history: NavigationHistory<T>, entry: T, optio
return { entries, index: entries.length - 1, recent: visit(history.recent, entry, options) };
}
+/**
+ * Den aktuellen Eintrag ersetzen statt einen Schritt abzulegen (K27): fuer
+ * das, was die Seite von selbst einstellt, etwa den vorgeschlagenen
+ * Behavior-Start oder ein Zuruecksetzen nach dem Neuindizieren. Waere das ein
+ * eigener Schritt, fuehrte Zurueck auf den leeren Zustand, die Seite stellte
+ * ihn sofort wieder ein, und Zurueck kaeme nie darueber hinaus.
+ *
+ * Der Vorwaertszweig bleibt. Der ersetzte Ort verlaesst die Liste der letzten
+ * Orte, wenn er dort vorn steht. Gleicht der neue Eintrag dem davor, fallen
+ * beide zusammen, wie bei `pushNavigation`. Ohne aktuellen Eintrag ist es ein
+ * gewoehnlicher erster Schritt.
+ */
+export function replaceNavigation<T>(history: NavigationHistory<T>, entry: T, options: NavigationHistoryOptions<T>): NavigationHistory<T> {
+ const current = history.entries[history.index];
+ if (current === undefined) return pushNavigation(history, entry, options);
+ if (options.key(current) === options.key(entry)) return history;
+ const replaced = options.recentKey?.(current);
+ const front = history.recent[0];
+ const recent = replaced !== undefined && front !== undefined && options.recentKey?.(front) === replaced ? history.recent.slice(1) : history.recent;
+ const previous = history.entries[history.index - 1];
+ if (previous !== undefined && options.key(previous) === options.key(entry)) {
+ const entries = [...history.entries.slice(0, history.index), ...history.entries.slice(history.index + 1)];
+ return { entries, index: history.index - 1, recent: visit(recent, previous, options) };
+ }
+ const entries = [...history.entries.slice(0, history.index), entry, ...history.entries.slice(history.index + 1)];
+ return { entries, index: history.index, recent: visit(recent, entry, options) };
+}
+
+/**
+ * Den aktuellen Eintrag durch einen gleichen (gleicher Schluessel) mit neueren
+ * Angaben ersetzen (K27), etwa einem Namen, der erst nach dem Schritt bekannt
+ * wird. Kein neuer Schritt und kein Umsortieren der letzten Orte; dort steht
+ * der Ort danach mit seinem neuesten Stand. Ein anderer Schluessel ist ein
+ * Schritt und kein Auffrischen: dann bleibt alles, wie es ist.
+ */
+export function refreshNavigation<T>(history: NavigationHistory<T>, entry: T, options: NavigationHistoryOptions<T>): NavigationHistory<T> {
+ const current = history.entries[history.index];
+ if (current === undefined || current === entry || options.key(current) !== options.key(entry)) return history;
+ const entries = history.entries.map((item, at) => (at === history.index ? entry : item));
+ const place = options.recentKey?.(entry);
+ const recent = place === undefined ? history.recent : history.recent.map((item) => (options.recentKey?.(item) === place ? entry : item));
+ return { entries, index: history.index, recent };
+}
+
/** 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];