Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: label goal tree nodes and fit camera to graph bounds (#3280)
[._.]/ Adam Eivya2d470f15498
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ae3b5ce0df..64f100f99a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -93,3 +93,7 @@## Stacker News stewardship- **[issue-3302] Safe Stacker News community stewardship** — Add independent account rules and effective account/territory schedules, editable ownership-aware communities, removable encrypted credentials, constrained GraphQL reads and reviewed publishing, conservative local text/vision analysis with safe image normalization, fixed-origin identity-verified browser handoffs, target-bound Review Hub approvals, and an auditable action ledger in Comms.++## Goals++- **[issue-3280] The goal tree now names every goal instead of showing bare dots.** The Tree view rendered a dozen unlabelled coloured spheres whose identity was only revealed on hover — which doesn't exist on a touch device — so it conveyed strictly less than the list view beside it. Each node now carries its title on a camera-facing label sized by goal type, fading out as you pull back so a zoomed-out graph doesn't turn into a wall of words, with a Labels toggle (on by default) to quiet a dense tree. The camera also frames itself to the whole graph on open and whenever a filter or search reshapes it, so no goal starts off-screen with its edges running into empty space.diff --git a/client/src/components/goals/GoalsTreeView.jsx b/client/src/components/goals/GoalsTreeView.jsxindex cd57350069..66c2d4edfd 100644--- a/client/src/components/goals/GoalsTreeView.jsx+++ b/client/src/components/goals/GoalsTreeView.jsx@@ -1,11 +1,25 @@-import { useState, useEffect, useMemo, useRef, useCallback } from 'react';-import { Canvas } from '@react-three/fiber';-import { OrbitControls } from '@react-three/drei';+import { Suspense, useState, useEffect, useMemo, useRef, useCallback } from 'react';+import { Canvas, useFrame, useThree } from '@react-three/fiber';+import { Billboard, OrbitControls, Text } from '@react-three/drei';import * as THREE from 'three';-import { Search, Plus, Wand2, X, Check, Star, Crown } from 'lucide-react';+import { Search, Plus, Wand2, X, Check, Star, Crown, Type } from 'lucide-react';import toast from '../ui/Toast';import * as api from '../../services/api';import { layoutGoalNodes } from './goalTreeLayout';+import {+ DIMMED_LABEL_OPACITY,+ GOAL_LABEL_FONT_URL,+ computeGraphBounds,+ fitCameraToBounds,+ goalLabelColor,+ goalLabelFontSize,+ goalLabelOffsetY,+ goalLabelText,+ goalNodeRadius,+ labelFadeRange,+ labelOpacityForDistance,+ orbitDistanceLimits+} from './goalTreeScene';import GoalDetailPanel, { CATEGORY_CONFIG, HORIZON_OPTIONS, GOAL_TYPE_CONFIG, DEFAULT_NEW_GOAL } from './GoalDetailPanel';import { applyOrganizationSuggestion } from './applyOrganization';import useProviderModels from '../../hooks/useProviderModels';@@ -79,12 +93,102 @@ function GoalEdges({ edges, selectedId }) {);}-function GoalScene({ graph, selectedId, adjacentIds, onSelect, onHover }) {+// Labels are decoration over the nodes — they must never eat a click meant for+// the sphere underneath (or, once faded to invisible, swallow one from nothing).+const noRaycast = () => null;+const labelWorldPos = new THREE.Vector3();++// A persistent, camera-facing goal title. Opacity is driven imperatively from the+// frame loop: a per-frame setState would re-render the whole scene 60x a second,+// and troika reads `fillOpacity` off the instance at draw time, so mutating it+// needs no sync() and no React round-trip.+function GoalLabel({ node, dimmed, fadeRange }) {+ const groupRef = useRef();+ const textRef = useRef();+ const stateRef = useRef({ dimmed, fadeRange });+ stateRef.current = { dimmed, fadeRange };++ useFrame(({ camera }) => {+ const group = groupRef.current;+ const text = textRef.current;+ if (!group || !text) return;+ const { dimmed: isDimmed, fadeRange: range } = stateRef.current;+ const distance = camera.position.distanceTo(group.getWorldPosition(labelWorldPos));+ const opacity = labelOpacityForDistance(distance, range) * (isDimmed ? DIMMED_LABEL_OPACITY : 1);+ group.visible = opacity > 0.02;+ text.fillOpacity = opacity;+ text.outlineOpacity = opacity;+ });++ const label = goalLabelText(node.title);+ if (!label) return null;+ const fontSize = goalLabelFontSize(node);++ return (+ <Billboard ref={groupRef} position={[node.x, node.y + goalLabelOffsetY(node), node.z]}>+ <Text+ ref={textRef}+ font={GOAL_LABEL_FONT_URL}+ fontSize={fontSize}+ color={goalLabelColor(node)}+ anchorX="center"+ anchorY="bottom"+ textAlign="center"+ maxWidth={fontSize * 12}+ outlineWidth={fontSize * 0.1}+ outlineColor="#000000"+ raycast={noRaycast}+ >+ {label}+ </Text>+ </Billboard>+ );+}++// Frames the whole graph on mount and whenever the node set changes (a filter or+// search rebuilds the layout), so no goal starts outside the viewport.+function GoalCameraRig({ bounds, fitKey, onFit }) {+ const camera = useThree(state => state.camera);+ const controls = useThree(state => state.controls);+ // Read through a ref: re-running the fit on every `bounds` identity change would+ // yank the camera back after an unrelated refetch. `fitKey` is the real trigger.+ const boundsRef = useRef(bounds);+ boundsRef.current = bounds;++ useEffect(() => {+ if (!camera) return;+ const fit = fitCameraToBounds(boundsRef.current, { fov: camera.fov, aspect: camera.aspect });+ if (!fit) return;+ camera.position.set(...fit.position);+ camera.updateProjectionMatrix();+ if (controls?.target) {+ controls.target.set(...fit.target);+ controls.update();+ } else {+ // OrbitControls registers itself as the default controls a tick after mount;+ // until then, aim the camera directly so the first frame is already framed.+ camera.lookAt(...fit.target);+ }+ onFit(fit.distance);+ }, [camera, controls, fitKey, onFit]);++ return null;+}++function GoalScene({ graph, selectedId, adjacentIds, onSelect, onHover, showLabels }) {const sphereGeo = useMemo(() => new THREE.SphereGeometry(1, 16, 12), []);const octaGeo = useMemo(() => new THREE.OctahedronGeometry(1, 0), []);const selNode = selectedId ? graph.idMap.get(selectedId) : null;- const selRadius = selNode ? (selNode.goalType === 'apex' ? 1.6 : selNode.goalType === 'sub-apex' ? 1.1 : 0.5 + (selNode.urgency ?? 0.3) * 0.6) : 0;+ const selRadius = selNode ? goalNodeRadius(selNode) : 0;++ const bounds = useMemo(() => computeGraphBounds(graph.nodes), [graph.nodes]);+ const fitKey = useMemo(() => graph.nodes.map(n => n.id).join('|'), [graph.nodes]);+ const orbitLimits = useMemo(() => orbitDistanceLimits(bounds), [bounds]);++ const [fitDistance, setFitDistance] = useState(null);+ const handleFit = useCallback((distance) => setFitDistance(distance), []);+ const fadeRange = useMemo(() => labelFadeRange(fitDistance), [fitDistance]);return (<>@@ -92,12 +196,14 @@ function GoalScene({ graph, selectedId, adjacentIds, onSelect, onHover }) {<pointLight position={[50, 50, 50]} intensity={0.8} /><pointLight position={[-30, -30, -30]} intensity={0.3} />+ <GoalCameraRig bounds={bounds} fitKey={fitKey} onFit={handleFit} />+<GoalEdges edges={graph.edges} selectedId={selectedId} />{graph.nodes.map(node => {const isApex = node.goalType === 'apex';const isSubApex = node.goalType === 'sub-apex';- const radius = isApex ? 1.6 : isSubApex ? 1.1 : 0.5 + (node.urgency ?? 0.3) * 0.6;+ const radius = goalNodeRadius(node);const cat = CATEGORY_CONFIG[node.category] || CATEGORY_CONFIG.mastery;const color = isApex ? '#fbbf24' : isSubApex ? '#c084fc' : cat.hex;const isSelected = node.id === selectedId;@@ -124,13 +230,34 @@ function GoalScene({ graph, selectedId, adjacentIds, onSelect, onHover }) {);})}+ {/* Own Suspense boundary: drei's <Text> suspends until the font loads, and+ the Canvas-level boundary would blank the WHOLE scene while it does. */}+ {showLabels && (+ <Suspense fallback={null}>+ {graph.nodes.map(node => (+ <GoalLabel+ key={`label-${node.id}`}+ node={node}+ dimmed={Boolean(selectedId && node.id !== selectedId && !adjacentIds?.has(node.id))}+ fadeRange={fadeRange}+ />+ ))}+ </Suspense>+ )}+{selNode && (<mesh geometry={sphereGeo} position={[selNode.x, selNode.y, selNode.z]} scale={selRadius + 0.2}><meshBasicMaterial color="#ffffff" transparent opacity={0.15} wireframe /></mesh>)}- <OrbitControls enableDamping dampingFactor={0.05} minDistance={5} maxDistance={150} />+ <OrbitControls+ makeDefault+ enableDamping+ dampingFactor={0.05}+ minDistance={orbitLimits.min}+ maxDistance={orbitLimits.max}+ /></>);}@@ -248,6 +375,9 @@ export default function GoalsTreeView({ data, onRefresh }) {const [categoryFilters, setCategoryFilters] = useState(() =>Object.fromEntries(Object.keys(CATEGORY_CONFIG).map(k => [k, true])));+ // Names on by default: without them the tree is a field of unlabelled dots and+ // reads as strictly less than the list view next to it (#3280).+ const [showLabels, setShowLabels] = useState(true);const [showNewGoal, setShowNewGoal] = useState(false);const [newGoal, setNewGoal] = useState({ ...DEFAULT_NEW_GOAL });const [organizing, setOrganizing] = useState(false);@@ -372,6 +502,20 @@ export default function GoalsTreeView({ data, onRefresh }) {</button>);})}+ <button+ onClick={() => setShowLabels(v => !v)}+ aria-pressed={showLabels}+ aria-label="Labels"+ title={showLabels ? 'Hide goal names' : 'Show goal names'}+ className={`flex items-center gap-1 px-1.5 sm:px-2 py-1 rounded-lg text-xs font-medium border transition-colors ${+ showLabels+ ? 'bg-port-accent/20 text-port-accent border-transparent'+ : 'bg-port-card/60 text-gray-600 border-port-border'+ }`}+ >+ <Type className="w-3 h-3" />+ <span className="hidden sm:inline">Labels</span>+ </button><buttononClick={() => setShowNewGoal(!showNewGoal)}className="flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium bg-port-accent text-white"@@ -523,6 +667,7 @@ export default function GoalsTreeView({ data, onRefresh }) {adjacentIds={adjacentIds}onSelect={handleSelect}onHover={handleHover}+ showLabels={showLabels}/></Canvas>) : (diff --git a/client/src/components/goals/GoalsTreeView.test.jsx b/client/src/components/goals/GoalsTreeView.test.jsxnew file mode 100644index 0000000000..ab7a92d600--- /dev/null+++ b/client/src/components/goals/GoalsTreeView.test.jsx@@ -0,0 +1,87 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, act } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++// jsdom has no WebGL context, so the three.js stack can't mount. The stub drops+// `children` deliberately: rendering the scene would mount <mesh>/<bufferGeometry>+// as unknown DOM elements and hand back HTMLElements where three.js objects are+// expected. The scene's own maths are covered by goalTreeScene.test.js instead —+// this file covers the chrome around the canvas.+vi.mock('@react-three/fiber', () => ({+ Canvas: () => <div data-testid="goal-tree-canvas" />,+ useFrame: () => {},+ useThree: () => null,+}));+vi.mock('@react-three/drei', () => ({+ OrbitControls: () => null,+ Billboard: () => null,+ Text: () => null,+}));++vi.mock('../../services/api', () => ({+ createGoal: vi.fn(),+ organizeGoals: vi.fn(),+}));+vi.mock('../../hooks/useProviderModels', () => ({+ default: () => ({+ providers: [], selectedProviderId: '', selectedModel: '', availableModels: [],+ setSelectedProviderId: vi.fn(), setSelectedModel: vi.fn(), loading: false,+ }),+}));++import GoalsTreeView from './GoalsTreeView';++// Invented placeholder goals — never real records from a running install.+const DATA = {+ flat: [+ { id: 'g1', title: 'Sail across an ocean', category: 'mastery', horizon: 'lifetime', goalType: 'apex' },+ { id: 'g2', title: 'Learn celestial navigation', category: 'mastery', horizon: '5-year', parentId: 'g1' },+ { id: 'g3', title: 'Restore the boat', category: 'creative', horizon: '3-year', parentId: 'g1' },+ ],+};++const renderTree = async (data = DATA) => {+ render(<GoalsTreeView data={data} onRefresh={vi.fn()} />);+ await act(async () => {});+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe('labels toggle', () => {+ // The bug this guards (#3280): the tree rendered unlabelled dots whose identity+ // was only reachable by hovering — which does not exist on a touch device. Names+ // must be on by DEFAULT; the toggle only exists to quiet a dense graph.+ it('defaults to showing goal names', async () => {+ await renderTree();+ expect(screen.getByRole('button', { name: /labels/i })).toHaveAttribute('aria-pressed', 'true');+ });++ it('turns labels off and back on', async () => {+ const user = userEvent.setup();+ await renderTree();+ const toggle = screen.getByRole('button', { name: /labels/i });++ await user.click(toggle);+ expect(toggle).toHaveAttribute('aria-pressed', 'false');++ await user.click(toggle);+ expect(toggle).toHaveAttribute('aria-pressed', 'true');+ });++ it('names the control for screen readers and touch, where the text is hidden', async () => {+ await renderTree();+ // The word "Labels" is `hidden sm:inline`, so on a phone the icon is all+ // that renders — the accessible name has to come from aria-label.+ expect(screen.getByRole('button', { name: /labels/i })).toHaveAttribute('aria-label', 'Labels');+ });+});++describe('empty state', () => {+ it('skips the canvas when there is nothing to lay out', async () => {+ await renderTree({ flat: [] });+ expect(screen.queryByTestId('goal-tree-canvas')).not.toBeInTheDocument();+ expect(screen.getByText(/no goals to display/i)).toBeInTheDocument();+ });+});diff --git a/client/src/components/goals/goalTreeScene.js b/client/src/components/goals/goalTreeScene.jsnew file mode 100644index 0000000000..ddc9557abe--- /dev/null+++ b/client/src/components/goals/goalTreeScene.js@@ -0,0 +1,148 @@+// Pure presentation math for the 3D goal tree scene (#3280): node geometry, the+// persistent per-node title labels, and framing the camera to the whole graph so+// nothing starts off-screen. No React / three.js imports — GoalsTreeView and the+// tests share these, and jsdom can't run WebGL, so all the reasoning lives here.++// Bundled with the app (client/public/fonts). troika (drei's <Text>) falls back+// to a jsdelivr CDN font lookup when no `font` is given, and PortOS installs run+// on a private network with no guaranteed internet egress — so always pass one.+export const GOAL_LABEL_FONT_URL = '/fonts/GeistPixel-Square.ttf';++const APEX_RADIUS = 1.6;+const SUB_APEX_RADIUS = 1.1;+const DEFAULT_URGENCY = 0.3;++// Sphere/octahedron radius a node renders at. Drives the scene mesh scale, the+// selection halo, the label offset AND the camera fit, so it lives in one place.+export function goalNodeRadius(node) {+ if (node?.goalType === 'apex') return APEX_RADIUS;+ if (node?.goalType === 'sub-apex') return SUB_APEX_RADIUS;+ return 0.5 + (node?.urgency ?? DEFAULT_URGENCY) * 0.6;+}++export const LABEL_FONT_SIZE = { apex: 1.4, 'sub-apex': 1, standard: 0.72 };++export function goalLabelFontSize(node) {+ return LABEL_FONT_SIZE[node?.goalType] ?? LABEL_FONT_SIZE.standard;+}++// Tinted toward the node's own colour but kept light — a label has to be READ+// against the dark canvas, so the category hex (which the sphere already carries)+// would cost too much contrast.+export const LABEL_COLORS = { apex: '#fde68a', 'sub-apex': '#e9d5ff', standard: '#e5e7eb' };++export function goalLabelColor(node) {+ return LABEL_COLORS[node?.goalType] ?? LABEL_COLORS.standard;+}++export const LABEL_MAX_CHARS = 32;++// A goal title is free text and can run for a sentence; an unbounded label turns+// the graph into a wall of words. Clip to a readable stem — the hover tooltip and+// the detail panel still carry the full title.+export function goalLabelText(title, maxChars = LABEL_MAX_CHARS) {+ const text = typeof title === 'string' ? title.trim() : '';+ if (text.length <= maxChars) return text;+ return `${text.slice(0, Math.max(maxChars - 1, 0)).trimEnd()}…`;+}++// Sit the label clear of the node it names (anchored at its bottom edge).+export function goalLabelOffsetY(node) {+ return goalNodeRadius(node) + goalLabelFontSize(node) * 0.75;+}++// A single node (or a tight cluster) shouldn't slam the camera into the geometry.+export const MIN_BOUNDS_RADIUS = 4;++// Axis-aligned extents of the laid-out graph, padded by each node's own radius so+// the outermost sphere is fully inside the box rather than tangent to it.+export function computeGraphBounds(nodes) {+ const list = Array.isArray(nodes) ? nodes.filter(Boolean) : [];+ if (!list.length) return null;++ const min = [Infinity, Infinity, Infinity];+ const max = [-Infinity, -Infinity, -Infinity];++ for (const node of list) {+ const radius = goalNodeRadius(node);+ const coords = [node.x, node.y, node.z];+ for (let axis = 0; axis < 3; axis++) {+ // A layout bug (or a NaN horizon) must not poison the whole fit into NaN+ // and blank the view — treat a non-finite coordinate as the origin.+ const value = Number.isFinite(coords[axis]) ? coords[axis] : 0;+ if (value - radius < min[axis]) min[axis] = value - radius;+ if (value + radius > max[axis]) max[axis] = value + radius;+ }+ }++ const center = min.map((lo, i) => (lo + max[i]) / 2);+ const size = min.map((lo, i) => max[i] - lo);+ const radius = Math.max(Math.hypot(...size) / 2, MIN_BOUNDS_RADIUS);+ return { center, size, radius };+}++export const CAMERA_FIT_PADDING = 1.2;+export const MIN_FIT_DISTANCE = 12;+// Slightly above the graph looking down the +Z axis — the same three-quarter+// framing the old hardcoded [0, 15, 40] camera used, now scaled to the graph.+const VIEW_DIRECTION = [0, 0.35, 1];++// Where to put the camera so the whole bounding sphere is inside the frustum.+// Both the vertical AND horizontal half-angles are solved and the LARGER distance+// wins, so a portrait phone (aspect < 1, narrow horizontal FOV) pulls back far+// enough instead of clipping the graph's left and right edges.+export function fitCameraToBounds(bounds, { fov = 60, aspect = 1, padding = CAMERA_FIT_PADDING } = {}) {+ if (!bounds) return null;++ const safeFov = Number.isFinite(fov) && fov > 0 && fov < 180 ? fov : 60;+ const safeAspect = Number.isFinite(aspect) && aspect > 0 ? aspect : 1;+ const safePadding = Number.isFinite(padding) && padding > 0 ? padding : CAMERA_FIT_PADDING;++ const verticalHalf = (safeFov * Math.PI) / 360;+ const horizontalHalf = Math.atan(Math.tan(verticalHalf) * safeAspect);++ const distance = safePadding * Math.max(+ bounds.radius / Math.sin(verticalHalf),+ bounds.radius / Math.sin(horizontalHalf),+ MIN_FIT_DISTANCE+ );++ const length = Math.hypot(...VIEW_DIRECTION);+ const direction = VIEW_DIRECTION.map(component => component / length);++ return {+ distance,+ target: [...bounds.center],+ position: bounds.center.map((component, axis) => component + direction[axis] * distance)+ };+}++// Orbit limits derived from the graph itself rather than the fitted camera, so a+// graph wider than the old fixed 150 ceiling can't be clamped back in on the very+// first controls.update() — which would undo the fit we just applied.+export function orbitDistanceLimits(bounds) {+ const radius = bounds?.radius ?? MIN_BOUNDS_RADIUS;+ return { min: Math.min(5, radius * 0.5), max: Math.max(150, radius * 8) };+}++export const LABEL_FADE_NEAR_SCALE = 1.15;+export const LABEL_FADE_FAR_SCALE = 2.2;++// Labels stay fully legible at (and inside) the framed distance and fade out as+// the user pulls back, so a zoomed-out graph doesn't become label soup.+export function labelFadeRange(fitDistance) {+ const distance = Number.isFinite(fitDistance) && fitDistance > 0 ? fitDistance : MIN_FIT_DISTANCE;+ return { near: distance * LABEL_FADE_NEAR_SCALE, far: distance * LABEL_FADE_FAR_SCALE };+}++export function labelOpacityForDistance(distance, range) {+ const { near, far } = range ?? labelFadeRange();+ if (!Number.isFinite(distance)) return 1;+ if (distance <= near) return 1;+ if (!(far > near) || distance >= far) return 0;+ return (far - distance) / (far - near);+}++// A label on a node the selection dimmed keeps just enough presence to read the+// surrounding structure without competing with the selected branch.+export const DIMMED_LABEL_OPACITY = 0.2;diff --git a/client/src/components/goals/goalTreeScene.test.js b/client/src/components/goals/goalTreeScene.test.jsnew file mode 100644index 0000000000..68110207a0--- /dev/null+++ b/client/src/components/goals/goalTreeScene.test.js@@ -0,0 +1,253 @@+import { describe, it, expect } from 'vitest';+import {+ CAMERA_FIT_PADDING,+ LABEL_MAX_CHARS,+ MIN_BOUNDS_RADIUS,+ MIN_FIT_DISTANCE,+ computeGraphBounds,+ fitCameraToBounds,+ goalLabelColor,+ goalLabelFontSize,+ goalLabelOffsetY,+ goalLabelText,+ goalNodeRadius,+ labelFadeRange,+ labelOpacityForDistance,+ orbitDistanceLimits+} from './goalTreeScene';++const node = (over = {}) => ({ id: 'g1', title: 'Ship the thing', x: 0, y: 0, z: 0, ...over });++describe('goalNodeRadius', () => {+ it('sizes apex and sub-apex above standard goals', () => {+ expect(goalNodeRadius(node({ goalType: 'apex' }))).toBeGreaterThan(goalNodeRadius(node({ goalType: 'sub-apex' })));+ expect(goalNodeRadius(node({ goalType: 'sub-apex' }))).toBeGreaterThan(goalNodeRadius(node()));+ });++ it('scales a standard goal with urgency and falls back for a missing one', () => {+ expect(goalNodeRadius(node({ urgency: 1 }))).toBeGreaterThan(goalNodeRadius(node({ urgency: 0 })));+ // `?? 0.3`, not `|| 0.3` — a legitimately zero urgency must stay zero.+ expect(goalNodeRadius(node({ urgency: 0 }))).toBe(0.5);+ expect(goalNodeRadius(node())).toBe(goalNodeRadius(node({ urgency: 0.3 })));+ });+});++describe('goalLabelText', () => {+ it('passes a short title through untouched', () => {+ expect(goalLabelText('Learn to sail')).toBe('Learn to sail');+ });++ it('clips a long title to a readable stem with an ellipsis', () => {+ const long = 'Build an entirely self-sufficient off-grid workshop by the lake';+ const clipped = goalLabelText(long);+ expect(clipped.length).toBeLessThanOrEqual(LABEL_MAX_CHARS);+ expect(clipped.endsWith('…')).toBe(true);+ expect(long.startsWith(clipped.slice(0, -1).trimEnd())).toBe(true);+ });++ it('trims surrounding whitespace and returns empty for a missing title', () => {+ expect(goalLabelText(' Run a marathon ')).toBe('Run a marathon');+ expect(goalLabelText(undefined)).toBe('');+ expect(goalLabelText(null)).toBe('');+ expect(goalLabelText(42)).toBe('');+ });+});++describe('label sizing', () => {+ it('reads apex and sub-apex larger than a standard goal', () => {+ expect(goalLabelFontSize(node({ goalType: 'apex' }))).toBeGreaterThan(goalLabelFontSize(node({ goalType: 'sub-apex' })));+ expect(goalLabelFontSize(node({ goalType: 'sub-apex' }))).toBeGreaterThan(goalLabelFontSize(node()));+ expect(goalLabelFontSize(node({ goalType: 'nonsense' }))).toBe(goalLabelFontSize(node()));+ });++ it('lifts every label clear of the sphere it names', () => {+ for (const goalType of ['apex', 'sub-apex', 'standard', undefined]) {+ const n = node({ goalType, urgency: 1 });+ expect(goalLabelOffsetY(n)).toBeGreaterThan(goalNodeRadius(n));+ }+ });++ it('gives apex and sub-apex their own colours', () => {+ const colors = new Set(['apex', 'sub-apex', 'standard'].map(t => goalLabelColor(node({ goalType: t }))));+ expect(colors.size).toBe(3);+ expect(goalLabelColor(node({ goalType: 'nonsense' }))).toBe(goalLabelColor(node()));+ });+});++describe('computeGraphBounds', () => {+ it('returns null when there is nothing to frame', () => {+ expect(computeGraphBounds([])).toBeNull();+ expect(computeGraphBounds(undefined)).toBeNull();+ expect(computeGraphBounds([null])).toBeNull();+ });++ it('centres on the extents and covers every node radius', () => {+ const bounds = computeGraphBounds([+ node({ id: 'a', x: -10, y: 0, z: 0 }),+ node({ id: 'b', x: 10, y: 4, z: -6 })+ ]);+ expect(bounds.center[0]).toBeCloseTo(0);+ expect(bounds.center[1]).toBeCloseTo(2);+ expect(bounds.center[2]).toBeCloseTo(-3);+ // Width spans the two nodes PLUS both radii, not just centre-to-centre.+ expect(bounds.size[0]).toBeGreaterThan(20);+ });++ it('floors the radius so a single node does not slam the camera into it', () => {+ expect(computeGraphBounds([node()]).radius).toBe(MIN_BOUNDS_RADIUS);+ });++ it('treats a non-finite coordinate as the origin instead of poisoning the fit', () => {+ const bounds = computeGraphBounds([node({ x: Number.NaN }), node({ id: 'b', x: 20 })]);+ expect(bounds.center.every(Number.isFinite)).toBe(true);+ expect(bounds.radius).toBeGreaterThan(0);+ });+});++// Camera-space projection of a world point, mirroring what three.js does: build+// the camera basis from the look direction and world up, then check the point+// against the frustum half-angles. This is the actual "no node starts off-screen"+// assertion — jsdom can't render, so the geometry is verified here instead.+const sub = (a, b) => a.map((v, i) => v - b[i]);+const dot = (a, b) => a.reduce((sum, v, i) => sum + v * b[i], 0);+const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];+const norm = (a) => { const l = Math.hypot(...a); return a.map(v => v / l); };++function isVisible(point, fit, { fov, aspect }) {+ const forward = norm(sub(fit.target, fit.position));+ const right = norm(cross(forward, [0, 1, 0]));+ const up = cross(right, forward);+ const v = sub(point, fit.position);+ const depth = dot(v, forward);+ if (depth <= 0) return false;+ const verticalHalf = (fov * Math.PI) / 360;+ const horizontalHalf = Math.atan(Math.tan(verticalHalf) * aspect);+ return Math.abs(dot(v, up)) <= depth * Math.tan(verticalHalf)+ && Math.abs(dot(v, right)) <= depth * Math.tan(horizontalHalf);+}++describe('fitCameraToBounds', () => {+ const spread = [+ node({ id: 'apex', goalType: 'apex', x: 0, y: 0, z: 0 }),+ node({ id: 'n', x: 0, y: 2, z: -32 }),+ node({ id: 's', x: 0, y: -2, z: 32 }),+ node({ id: 'e', x: 40, y: 1, z: 0 }),+ node({ id: 'w', x: -40, y: -1, z: 0 })+ ];++ it('returns null when there are no bounds', () => {+ expect(fitCameraToBounds(null, { fov: 60, aspect: 1.6 })).toBeNull();+ });++ it('frames every node inside the frustum on a landscape viewport', () => {+ const view = { fov: 60, aspect: 1600 / 900 };+ const bounds = computeGraphBounds(spread);+ const fit = fitCameraToBounds(bounds, view);+ for (const n of spread) {+ expect(isVisible([n.x, n.y, n.z], fit, view)).toBe(true);+ }+ });++ it('frames every node inside the frustum on a portrait phone', () => {+ // The regression this guards: solving only the VERTICAL half-angle. A phone's+ // horizontal FOV is much narrower, so the graph's east/west nodes clip off the+ // sides of the screen even though the fit "succeeded".+ const view = { fov: 60, aspect: 375 / 812 };+ const bounds = computeGraphBounds(spread);+ const fit = fitCameraToBounds(bounds, view);+ for (const n of spread) {+ expect(isVisible([n.x, n.y, n.z], fit, view)).toBe(true);+ }+ });++ it('pulls further back as the viewport narrows', () => {+ const bounds = computeGraphBounds(spread);+ const wide = fitCameraToBounds(bounds, { fov: 60, aspect: 2 });+ const narrow = fitCameraToBounds(bounds, { fov: 60, aspect: 0.5 });+ expect(narrow.distance).toBeGreaterThan(wide.distance);+ });++ it('aims at the graph centre and sits `distance` away from it', () => {+ const bounds = computeGraphBounds([node({ x: 100, y: 20, z: -50 })]);+ const fit = fitCameraToBounds(bounds, { fov: 60, aspect: 1 });+ expect(fit.target).toEqual(bounds.center);+ expect(Math.hypot(...sub(fit.position, fit.target))).toBeCloseTo(fit.distance);+ // Framed from above and in front, matching the previous fixed camera angle.+ expect(fit.position[1]).toBeGreaterThan(fit.target[1]);+ expect(fit.position[2]).toBeGreaterThan(fit.target[2]);+ });++ it('keeps a floor distance for a tiny graph', () => {+ const fit = fitCameraToBounds({ center: [0, 0, 0], size: [0, 0, 0], radius: 0.1 }, { fov: 60, aspect: 1 });+ expect(fit.distance).toBeCloseTo(MIN_FIT_DISTANCE * CAMERA_FIT_PADDING);+ });++ it('falls back to sane optics rather than returning NaN', () => {+ const bounds = computeGraphBounds(spread);+ for (const view of [{ fov: 0, aspect: 0 }, { fov: Number.NaN, aspect: Number.NaN }, { fov: 200, aspect: -3 }]) {+ const fit = fitCameraToBounds(bounds, { ...view, padding: Number.NaN });+ expect(Number.isFinite(fit.distance)).toBe(true);+ expect(fit.position.every(Number.isFinite)).toBe(true);+ }+ expect(Number.isFinite(fitCameraToBounds(bounds).distance)).toBe(true);+ });+});++describe('orbitDistanceLimits', () => {+ it('never clamps a graph that needs more than the old fixed 150 ceiling', () => {+ const bounds = computeGraphBounds([node({ x: -400 }), node({ id: 'b', x: 400 })]);+ const fit = fitCameraToBounds(bounds, { fov: 60, aspect: 1 });+ expect(orbitDistanceLimits(bounds).max).toBeGreaterThan(fit.distance);+ });++ it('keeps a usable zoom-in floor for a small graph', () => {+ const limits = orbitDistanceLimits(computeGraphBounds([node()]));+ expect(limits.min).toBeGreaterThan(0);+ expect(limits.min).toBeLessThanOrEqual(5);+ expect(limits.max).toBe(150);+ });++ it('degrades to defaults with no bounds', () => {+ expect(orbitDistanceLimits(null).max).toBe(150);+ });+});++describe('labelOpacityForDistance', () => {+ const range = labelFadeRange(100);++ it('is fully opaque at and inside the framed distance', () => {+ expect(labelOpacityForDistance(0, range)).toBe(1);+ expect(labelOpacityForDistance(100, range)).toBe(1);+ expect(labelOpacityForDistance(range.near, range)).toBe(1);+ });++ it('fades to nothing as the camera pulls back past the far threshold', () => {+ expect(labelOpacityForDistance(range.far, range)).toBe(0);+ expect(labelOpacityForDistance(range.far + 500, range)).toBe(0);+ const mid = labelOpacityForDistance((range.near + range.far) / 2, range);+ expect(mid).toBeCloseTo(0.5);+ });++ it('decreases monotonically across the fade band', () => {+ const step = (range.far - range.near) / 8;+ let previous = 1;+ for (let d = range.near; d <= range.far; d += step) {+ const opacity = labelOpacityForDistance(d, range);+ expect(opacity).toBeLessThanOrEqual(previous);+ previous = opacity;+ }+ });++ it('stays legible rather than blank for a bad distance or range', () => {+ expect(labelOpacityForDistance(Number.NaN, range)).toBe(1);+ expect(labelOpacityForDistance(1, undefined)).toBe(1);+ // Degenerate band (near === far) must not divide by zero.+ expect(labelOpacityForDistance(10, { near: 5, far: 5 })).toBe(0);+ });++ it('scales the fade band with the framed distance, not a fixed world size', () => {+ expect(labelFadeRange(500).near).toBeGreaterThan(labelFadeRange(50).near);+ expect(labelFadeRange(0).near).toBeGreaterThan(0);+ expect(labelFadeRange(undefined).far).toBeGreaterThan(labelFadeRange(undefined).near);+ });+});