Skip to content

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

fix: pick brain-graph nodes by screen-space proximity on touch so a tap hits a finger-sized target (#4114)

[._.]/ Adam Eivy7ecc5d22912e
diff --git a/.changelog/next/fixed-issue-4114.md b/.changelog/next/fixed-issue-4114.md
new file mode 100644
index 0000000000..7e082f603b
--- /dev/null
+++ b/.changelog/next/fixed-issue-4114.md
@@ -0,0 +1 @@
+- Brain graph: tapping a node on a phone now picks the nearest node within a finger-sized radius instead of requiring a direct hit on its ~10px sphere
diff --git a/client/src/components/brain/tabs/BrainGraph.jsx b/client/src/components/brain/tabs/BrainGraph.jsx
index 0cebd66f7b..f6a01b06fd 100644
--- a/client/src/components/brain/tabs/BrainGraph.jsx
+++ b/client/src/components/brain/tabs/BrainGraph.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useMemo, useRef, useCallback, memo } from 'react';
-import { Canvas } from '@react-three/fiber';
+import { Canvas, useThree } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import * as THREE from 'three';
import {AlertTriangle, Zap, RefreshCw, X, ChevronRight, ArrowLeft, Compass, Info} from 'lucide-react';
@@ -7,6 +7,7 @@ import toast from '../../ui/Toast';
import * as api from '../../../services/api';
import { BRAIN_TYPE_HEX, DESTINATIONS } from '../constants';
import { buildGraph } from '../../../lib/graphSimulation';
+import { pickNearestNodeByScreenDistance, isTapGesture } from '../../../lib/graphPicking';
import { pushFocus, popFocus, currentFocusId } from '../../../lib/brainGraphFocus';
import EntityCombobox from '../../EntityCombobox';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
@@ -96,12 +97,34 @@ function GraphEdges({ simEdges, selectedId }) {
// move over the canvas (it tracks the tooltip position), and every prop here is
// already identity-stable across that render — so without memo each move
// reconciles a <mesh> per node for nothing.
-const GraphScene = memo(function GraphScene({ graph, selectedId, adjacentIds, onSelect, onFocus, onHover }) {
+const GraphScene = memo(function GraphScene({ graph, selectedId, adjacentIds, onSelect, onFocus, onHover, pickRef, touchGestureRef }) {
const sphereGeo = useMemo(() => new THREE.SphereGeometry(1, 16, 12), []);
+ const { camera, size } = useThree();
const selNode = selectedId ? graph.idMap.get(selectedId) : null;
const selRadius = selNode ? 0.4 + (selNode.importance ?? 0.5) * 0.8 : 0;
+ // Publish a live screen-space pick to the DOM wrapper, which owns the touch
+ // gesture (see the tap handler in BrainGraph). The camera object is stable
+ // across orbiting, so the matrices are read at tap time, not captured here.
+ useEffect(() => {
+ if (!pickRef) return;
+ pickRef.current = (point) => {
+ camera.updateMatrixWorld();
+ const viewProjection = new THREE.Matrix4()
+ .multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)
+ .elements;
+ return pickNearestNodeByScreenDistance({
+ nodes: graph.simNodes,
+ viewProjection,
+ width: size.width,
+ height: size.height,
+ point
+ });
+ };
+ return () => { pickRef.current = null; };
+ }, [camera, graph, size.width, size.height, pickRef]);
+
return (
<>
<ambientLight intensity={0.4} />
@@ -123,7 +146,16 @@ const GraphScene = memo(function GraphScene({ graph, selectedId, adjacentIds, on
geometry={sphereGeo}
scale={radius}
position={[node.x, node.y, node.z]}
- onClick={(e) => { e.stopPropagation(); onSelect(node); }}
+ // Touch selection is owned by the wrapper's threshold pick, which
+ // fires on `pointerup` — ahead of the compatibility `click` r3f
+ // raycasts here — so a tap that lands on a mesh must not toggle the
+ // same node a second time. `click` is a MouseEvent with no
+ // `pointerType` after a touch, hence the recorded gesture ref.
+ onClick={(e) => {
+ e.stopPropagation();
+ if (touchGestureRef?.current) return;
+ onSelect(node);
+ }}
onDoubleClick={(e) => { e.stopPropagation(); onFocus(node); }}
onPointerOver={(e) => { e.stopPropagation(); onHover(node); }}
onPointerOut={() => onHover(null)}
@@ -171,6 +203,11 @@ export default function BrainGraph() {
const graphRef = useRef(null);
const dragStartRef = useRef(null);
+ // Set by GraphScene: (point in canvas-local px) => node | null.
+ const pickRef = useRef(null);
+ // True while the in-flight gesture came from a finger, so the mesh raycast
+ // and onPointerMissed can stand down for the threshold pick below.
+ const touchGestureRef = useRef(false);
const focusId = currentFocusId(focusTrail);
@@ -284,8 +321,10 @@ export default function BrainGraph() {
return () => { cancelled = true; };
}, [selectedNode]);
+ // A null node clears the selection (an empty-space tap); re-selecting the
+ // current node toggles it off.
const handleSelect = useCallback((node) => {
- setSelectedNode(prev => prev?.id === node.id ? null : node);
+ setSelectedNode(prev => (node && prev?.id !== node.id ? node : null));
}, []);
const handleHover = useCallback((node) => {
@@ -303,14 +342,39 @@ export default function BrainGraph() {
return () => window.removeEventListener('keydown', onKey);
}, [selectedNode]);
+ // Mouse only: a touch tap is resolved by handlePointerUp below (which also
+ // owns clearing on an empty-space tap), and would otherwise be undone here by
+ // the compatibility `click` r3f fires afterwards.
const handlePointerMissed = useCallback((e) => {
- const start = dragStartRef.current;
- if (!start) return;
- if (Math.abs(e.clientX - start.x) < 5 && Math.abs(e.clientY - start.y) < 5) {
+ if (touchGestureRef.current) return;
+ if (isTapGesture(dragStartRef.current, { x: e.clientX, y: e.clientY })) {
setSelectedNode(null);
}
}, []);
+ const handlePointerDown = useCallback((e) => {
+ // A second finger is a pinch-zoom or two-finger pan, never a tap — drop the
+ // recorded start so neither the threshold pick nor the miss-clear can fire
+ // for it (both gate on `isTapGesture`, which is false without a start).
+ const secondFinger = touchGestureRef.current && !e.isPrimary;
+ dragStartRef.current = secondFinger ? null : { x: e.clientX, y: e.clientY };
+ touchGestureRef.current = e.pointerType === 'touch';
+ }, []);
+
+ // Touch selection. The raw mesh raycast needs the ray to hit a ~10px sphere;
+ // instead project every node and take the nearest within a finger-sized
+ // radius (see lib/graphPicking.js). Runs on `pointerup` on the wrapper, which
+ // bubbles after the canvas' own pointerup and before the `click` r3f picks
+ // with — so this result is what sticks. Mouse input is untouched.
+ const handlePointerUp = useCallback((e) => {
+ if (!touchGestureRef.current) return;
+ const end = { x: e.clientX, y: e.clientY };
+ if (!isTapGesture(dragStartRef.current, end)) return; // an orbit drag
+ const rect = e.currentTarget.getBoundingClientRect();
+ const picked = pickRef.current?.({ x: end.x - rect.left, y: end.y - rect.top }) ?? null;
+ handleSelect(picked);
+ }, [handleSelect]);
+
// refresh:true re-embeds already-mapped records — the recovery path for
// memory entries that diverged before synced-in records were re-vectorized
// automatically (issue #1080). onlyMissing:true embeds just the records that
@@ -527,7 +591,8 @@ export default function BrainGraph() {
desktop, floors at 240px so it stays usable on a short viewport. */}
<div
className="relative bg-port-card border border-port-border rounded-lg overflow-hidden h-[clamp(240px,45vh,500px)]"
- onPointerDown={(e) => { dragStartRef.current = { x: e.clientX, y: e.clientY }; }}
+ onPointerDown={handlePointerDown}
+ onPointerUp={handlePointerUp}
onPointerMove={(e) => setTooltipPos({ x: e.clientX, y: e.clientY })}
>
{graph && (
@@ -545,6 +610,8 @@ export default function BrainGraph() {
onSelect={handleSelect}
onFocus={focusNode}
onHover={handleHover}
+ pickRef={pickRef}
+ touchGestureRef={touchGestureRef}
/>
</Canvas>
)}
diff --git a/client/src/components/brain/tabs/BrainGraph.test.jsx b/client/src/components/brain/tabs/BrainGraph.test.jsx
index 809e219f72..9555e1811a 100644
--- a/client/src/components/brain/tabs/BrainGraph.test.jsx
+++ b/client/src/components/brain/tabs/BrainGraph.test.jsx
@@ -9,6 +9,9 @@ import userEvent from '@testing-library/user-event';
// back are HTMLElements without the three.js geometry API.
vi.mock('@react-three/fiber', () => ({
Canvas: () => <div data-testid="graph-canvas" />,
+ // GraphScene reads the live camera through this; it is never rendered here,
+ // but the named import has to resolve.
+ useThree: () => ({ camera: null, size: { width: 0, height: 0 } }),
}));
vi.mock('@react-three/drei', () => ({ OrbitControls: () => null }));
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index a0c91c65ec..248ef7f5c1 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -74,6 +74,7 @@ grep -i "what you want to do" client/src/lib/README.md
| Module | Purpose |
|---|---|
| `brainGraphFocus.js` | Pure focus-trail (breadcrumb) transitions for BrainGraph re-focus navigation. |
+| `graphPicking.js` | Screen-space touch picking for the 3D brain graph (#4114). `projectToScreen(point, viewProjection, width, height)` projects a world point to canvas-local pixels (y down, `null` when the point sits on or behind the camera plane); `pickNearestNodeByScreenDistance({ nodes, viewProjection, width, height, point, threshold })` returns the node whose projected centre is nearest the tap within `TOUCH_PICK_THRESHOLD_PX` (44px — a max-importance sphere only projects to ~38px at `OrbitControls minDistance`, so a tap anywhere inside a node still lands), tie-broken by depth then array order; `isTapGesture(start, end, slop)` separates a tap from an orbit drag (`TAP_SLOP_PX`). Takes the 16 flattened column-major `THREE.Matrix4` elements rather than a camera, so it stays three.js-free and unit-testable — jsdom has no WebGL context and therefore no raycast to exercise. |
| `graphSimulation.js` | 3D force simulation parameters for BrainGraph / CyberCity. |
| `goalFeatureMap.js` | Deterministic goal `category` → PortOS feature-area deep-link map (Daily Driver). `getGoalFeatureAreas(goal)` honors the per-goal `featureAreas` override, else the category default. Mirrored byte-for-byte from `server/lib/`. |
diff --git a/client/src/lib/graphPicking.js b/client/src/lib/graphPicking.js
new file mode 100644
index 0000000000..b878c5d253
--- /dev/null
+++ b/client/src/lib/graphPicking.js
@@ -0,0 +1,100 @@
+// Screen-space picking for the 3D brain graph (#4114).
+//
+// The raw three.js raycast picks a node only when the ray actually hits its
+// sphere. A low-importance node projects to roughly a 10px disc on a phone —
+// well under the ~44px touch-target guidance — so a tap lands on a neighbour or
+// on nothing. On touch we therefore project every node to screen space and take
+// the nearest one within a finger-sized radius instead of hitting the mesh.
+//
+// Pure and three.js-free: it takes the flattened view-projection matrix (the
+// 16 column-major elements of `THREE.Matrix4`, i.e. `projectionMatrix *
+// matrixWorldInverse`) rather than a camera, so the whole pick is unit-testable
+// in jsdom, where no WebGL context (and therefore no raycast) exists.
+
+// Apple HIG / WCAG 2.5.5 both put the comfortable minimum touch target at ~44px.
+// Used here as the max distance from the tap point to a node's projected CENTRE,
+// which is deliberately more generous than a 44px-wide target: the pick is
+// nearest-wins, so a wider net never steals a tap from a closer node, it only
+// rescues taps that would otherwise select nothing. It also stays at or above
+// the largest radius a node can project to — `OrbitControls minDistance={10}`
+// bounds a max-importance sphere (r = 1.2 world units) near ~38px — so a tap
+// anywhere inside a node still selects it, exactly as the raycast did.
+export const TOUCH_PICK_THRESHOLD_PX = 44;
+
+// A tap that drags further than this is an orbit gesture, not a selection.
+export const TAP_SLOP_PX = 8;
+
+/**
+ * Project a world-space point to canvas-local screen pixels (y grows downward,
+ * matching `clientY - rect.top`).
+ *
+ * @param {{x:number,y:number,z:number}} point world position
+ * @param {ArrayLike<number>} viewProjection 16 column-major matrix elements
+ * @param {number} width canvas CSS width
+ * @param {number} height canvas CSS height
+ * @returns {{x:number,y:number,depth:number}|null} null when the point sits on
+ * or behind the camera plane (clip w <= 0), where the perspective divide
+ * flips the projection and would otherwise report a bogus on-screen position.
+ */
+export const projectToScreen = (point, viewProjection, width, height) => {
+ const e = viewProjection;
+ const { x, y, z } = point;
+ const w = e[3] * x + e[7] * y + e[11] * z + e[15];
+ if (!(w > 0)) return null;
+ const ndcX = (e[0] * x + e[4] * y + e[8] * z + e[12]) / w;
+ const ndcY = (e[1] * x + e[5] * y + e[9] * z + e[13]) / w;
+ const ndcZ = (e[2] * x + e[6] * y + e[10] * z + e[14]) / w;
+ return {
+ x: (ndcX * 0.5 + 0.5) * width,
+ y: (-ndcY * 0.5 + 0.5) * height,
+ depth: ndcZ
+ };
+};
+
+/**
+ * Nearest node to a tap, in screen space, within `threshold` pixels.
+ *
+ * Ranking is by projected-centre distance; an exact tie goes to the node nearer
+ * the camera (smaller NDC depth), then to the earlier entry — so the same tap on
+ * the same layout always resolves to the same node.
+ *
+ * @returns {object|null} the picked node from `nodes`, or null when nothing is
+ * within the threshold (the caller treats that as "tapped empty space").
+ */
+export const pickNearestNodeByScreenDistance = ({
+ nodes,
+ viewProjection,
+ width,
+ height,
+ point,
+ threshold = TOUCH_PICK_THRESHOLD_PX
+}) => {
+ if (!nodes?.length || !viewProjection || !point || !(width > 0) || !(height > 0)) return null;
+
+ let best = null;
+ let bestDistance = Infinity;
+ let bestDepth = Infinity;
+
+ for (const node of nodes) {
+ const screen = projectToScreen(node, viewProjection, width, height);
+ if (!screen) continue;
+ const distance = Math.hypot(screen.x - point.x, screen.y - point.y);
+ if (distance > threshold) continue;
+ if (distance < bestDistance || (distance === bestDistance && screen.depth < bestDepth)) {
+ best = node;
+ bestDistance = distance;
+ bestDepth = screen.depth;
+ }
+ }
+
+ return best;
+};
+
+/**
+ * True when a pointer gesture stayed put enough to read as a tap rather than an
+ * orbit drag. `start`/`end` are client coordinates.
+ */
+export const isTapGesture = (start, end, slop = TAP_SLOP_PX) =>
+ !!start && !!end
+ && Math.abs(end.x - start.x) <= slop
+ && Math.abs(end.y - start.y) <= slop;
diff --git a/client/src/lib/graphPicking.test.js b/client/src/lib/graphPicking.test.js
new file mode 100644
index 0000000000..3511e944b2
--- /dev/null
+++ b/client/src/lib/graphPicking.test.js
@@ -0,0 +1,135 @@
+import { describe, it, expect } from 'vitest';
+import * as THREE from 'three';
+import {
+ projectToScreen,
+ pickNearestNodeByScreenDistance,
+ isTapGesture,
+ TOUCH_PICK_THRESHOLD_PX
+} from './graphPicking.js';
+
+const WIDTH = 800;
+const HEIGHT = 400;
+
+// A real perspective camera looking down -Z from z=80, matching BrainGraph's
+// Canvas defaults. Only Matrix4 math runs here — no renderer, no WebGL.
+const viewProjectionAt = (position = [0, 0, 80]) => {
+ const camera = new THREE.PerspectiveCamera(50, WIDTH / HEIGHT, 0.1, 1000);
+ camera.position.set(...position);
+ camera.lookAt(0, 0, 0);
+ camera.updateMatrixWorld();
+ camera.updateProjectionMatrix();
+ return new THREE.Matrix4()
+ .multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)
+ .elements;
+};
+
+const VP = viewProjectionAt();
+
+describe('projectToScreen', () => {
+ it('maps the point the camera looks at to the centre of the canvas', () => {
+ const screen = projectToScreen({ x: 0, y: 0, z: 0 }, VP, WIDTH, HEIGHT);
+ expect(screen.x).toBeCloseTo(WIDTH / 2, 6);
+ expect(screen.y).toBeCloseTo(HEIGHT / 2, 6);
+ });
+
+ it('grows y downward, matching clientY', () => {
+ const above = projectToScreen({ x: 0, y: 10, z: 0 }, VP, WIDTH, HEIGHT);
+ expect(above.y).toBeLessThan(HEIGHT / 2);
+ });
+
+ it('returns null for a point behind the camera', () => {
+ expect(projectToScreen({ x: 0, y: 0, z: 200 }, VP, WIDTH, HEIGHT)).toBeNull();
+ });
+
+ it('reports a nearer point with a smaller depth', () => {
+ const near = projectToScreen({ x: 0, y: 0, z: 20 }, VP, WIDTH, HEIGHT);
+ const far = projectToScreen({ x: 0, y: 0, z: -20 }, VP, WIDTH, HEIGHT);
+ expect(near.depth).toBeLessThan(far.depth);
+ });
+});
+
+describe('pickNearestNodeByScreenDistance', () => {
+ // Screen position of a world point, for building tap coordinates.
+ const at = (world) => projectToScreen(world, VP, WIDTH, HEIGHT);
+
+ const pick = (nodes, point, threshold) => pickNearestNodeByScreenDistance({
+ nodes, viewProjection: VP, width: WIDTH, height: HEIGHT, point, threshold
+ });
+
+ it('picks the nearest node to the tap', () => {
+ const nodes = [
+ { id: 'far', x: 6, y: 0, z: 0 },
+ { id: 'near', x: 1, y: 0, z: 0 },
+ ];
+ expect(pick(nodes, at({ x: 0, y: 0, z: 0 }))?.id).toBe('near');
+ });
+
+ it('selects a node the tap misses outright, within the touch threshold', () => {
+ const node = { id: 'n1', x: 0, y: 0, z: 0 };
+ const centre = at(node);
+ // 30px away — nowhere near the ~5px disc the raycast would have required.
+ const picked = pick([node], { x: centre.x + 30, y: centre.y });
+ expect(picked?.id).toBe('n1');
+ });
+
+ it('returns null when every node is outside the threshold', () => {
+ const node = { id: 'n1', x: 0, y: 0, z: 0 };
+ const centre = at(node);
+ const picked = pick([node], { x: centre.x + TOUCH_PICK_THRESHOLD_PX + 1, y: centre.y });
+ expect(picked).toBeNull();
+ });
+
+ it('breaks an exact distance tie toward the node nearer the camera', () => {
+ // Same screen position (both on the camera axis), different depth.
+ const nodes = [
+ { id: 'behind', x: 0, y: 0, z: -20 },
+ { id: 'front', x: 0, y: 0, z: 20 },
+ ];
+ expect(pick(nodes, at({ x: 0, y: 0, z: 0 }))?.id).toBe('front');
+ // Order-independent: the depth tie-break, not array order, decides.
+ expect(pick([...nodes].reverse(), at({ x: 0, y: 0, z: 0 }))?.id).toBe('front');
+ });
+
+ it('excludes nodes behind the camera even when they project onto the tap', () => {
+ const nodes = [{ id: 'behind-camera', x: 0, y: 0, z: 200 }];
+ expect(pick(nodes, { x: WIDTH / 2, y: HEIGHT / 2 })).toBeNull();
+ });
+
+ it('prefers an in-front node over one behind the camera at the same tap', () => {
+ const nodes = [
+ { id: 'behind-camera', x: 0, y: 0, z: 200 },
+ { id: 'visible', x: 0, y: 0, z: 0 },
+ ];
+ expect(pick(nodes, { x: WIDTH / 2, y: HEIGHT / 2 })?.id).toBe('visible');
+ });
+
+ it('honours a caller-supplied threshold', () => {
+ const node = { id: 'n1', x: 0, y: 0, z: 0 };
+ const centre = at(node);
+ const point = { x: centre.x + 20, y: centre.y };
+ expect(pick([node], point, 10)).toBeNull();
+ expect(pick([node], point, 40)?.id).toBe('n1');
+ });
+
+ it('returns null for empty or unusable inputs instead of throwing', () => {
+ const point = { x: 0, y: 0 };
+ expect(pick([], point)).toBeNull();
+ expect(pick(undefined, point)).toBeNull();
+ expect(pick([{ id: 'n1', x: 0, y: 0, z: 0 }], null)).toBeNull();
+ expect(pickNearestNodeByScreenDistance({
+ nodes: [{ id: 'n1', x: 0, y: 0, z: 0 }], viewProjection: VP, width: 0, height: 0, point
+ })).toBeNull();
+ });
+});
+
+describe('isTapGesture', () => {
+ it('accepts a still pointer and rejects a drag', () => {
+ expect(isTapGesture({ x: 100, y: 100 }, { x: 103, y: 96 })).toBe(true);
+ expect(isTapGesture({ x: 100, y: 100 }, { x: 140, y: 100 })).toBe(false);
+ expect(isTapGesture({ x: 100, y: 100 }, { x: 100, y: 140 })).toBe(false);
+ });
+
+ it('is false without a recorded start', () => {
+ expect(isTapGesture(null, { x: 0, y: 0 })).toBe(false);
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index f7dcbde6e1..b2aef058a6 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -53,6 +53,7 @@ export * from './wrImageDefaults.js';
// === Graph & sim ===
export * from './brainGraphFocus.js';
+export * from './graphPicking.js';
export * from './graphSimulation.js';
export * from './goalFeatureMap.js';