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

make the Brain graph tab usable on a phone

[._.]/ Adam Eivy3b39488d6332
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0b1a89789e..a17e95b955 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -15,6 +15,7 @@
## Fixed
- The Chief of Staff status panel's Learning card no longer spills its skipped-task count outside the card on mobile. The "(3 skipped)" note used to sit beside the success rate on one line, where it was too wide to fit a narrow card and rendered past the border; it now sits on its own line under the percentage and truncates if it can't fit.
+- The Brain **Graph** tab is now usable on a phone. The graph canvas sizes itself to the viewport instead of a fixed 500px (which overflowed a landscape phone entirely and left no room to scroll past a canvas that swallows drags), the controls bar stacks into readable rows instead of cramming a breadcrumb, seven type filters, and both buttons into one line, and the type filters wrap with a proper tap target. The legend — ten rows that blanketed a phone-sized graph — now shows automatically only when there's room for it and collapses behind a "Legend" toggle everywhere else, including a landscape phone (which is wide enough to look like a desktop but far too short). The hover tooltip no longer flashes under your finger advertising a double-click that touch can't do (tap the node and use the detail panel's "Explore connections" instead), and it no longer runs off the right edge in a narrow window. "Explore connections" moved out of a cramped side column onto its own full-width row, above the record text so it stays reachable on a long entry.
- [issue-2669] Sharing, Messages, and Calendar screens no longer show two stacked error toasts when a share/subscribe/export/save/sync action fails — the custom-catch callers now pass `{ silent: true }` so only their own toast fires, not the shared `request()` helper's default one too. Swept the Messages/calendar/sharing feature area (both ConfigTabs, InboxTab, ReviewTab, ShareToButton, and the Sharing page) and threaded a backward-compatible `options` arg into the affected API wrappers (`evaluateMessages`, `enableGmailApi`, `getGoogleAuthUrl`, `create/updateMessageAccount`, `create/updateCalendarAccount`, `updateSubcalendars`, `saveGoogleAuthCredentials`, `start/runGoogleAutoConfig`, `confirmDailyReviewEvent`).
- Creative Director projects that use the Antigravity provider no longer get stuck on "Planning." The agent now reliably receives its instructions instead of launching and sitting idle at an empty prompt (it waits for Antigravity's input box to be ready before sending, the same way the Claude provider does), so planning actually runs to completion.
- A Creative Director project no longer wedges in "Planning" when its agent is interrupted or crashes mid-run. The stuck run is now cleaned up as soon as the dead agent is detected, so the project can retry on its own instead of waiting for the next server restart.
diff --git a/PLAN.md b/PLAN.md
index 8c381fd130..7d26d061ea 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -136,6 +136,13 @@ by `/do:replan --issues`:
- [ ] **Re-derive POST day keys from timestamps at read time (or re-normalize on timezone change).** #2681 made POST records store their `date` in the user's configured timezone (writers) and read "today" in that zone (readers: `getPostStats`/`getPostProgress`/`getUnifiedActivityStreak`/`getTrainingStats`/`getMorseProgress`, plus the client). Migration 192 re-keys existing records once. The residual gap: a stored `date` is frozen in the zone that was active when it was written, so if the user *changes* `settings.timezone` after accumulating history, the old day keys disagree with the new-zone readers (a session saved as `2026-07-15` in LA reads as incomplete-today after switching to UTC). The reminder path (`meatspacePostReminder.js` `firePostReminderIfIncomplete`) is already immune because it derives the day from each record's `startedAt`/`timestamp` at read time via `isOnLocalDay(instant, tz)` — NOT the stored `date`. Two fix options: (a) apply that same read-time derivation in the streak/stats/history readers — map each record to `{ ...r, date: localDay(r.startedAt||r.completedAt||r.timestamp, tz) }` before it reaches `computePostStreaks`/aggregation, making the stored `date` a cache the readers ignore (comprehensive, no re-normalization ever needed, but touches every reader + the pure-helper integration and needs careful test updates); or (b) subscribe to the `settings:updated` timezone-change event (there's already `timezoneUpdatedAt` infra) and re-run migration-192-style normalization through the services' load/save paths (must NOT raw-write the files — that bypasses service caches, see the "sync direct-write bypasses cache" precedent). Deferred from #2681 review (codex r6, P2) — an uncommon tz-change-after-history scenario whose correct fix is a sizable, separately-reviewable refactor against real POST data; the steady-state configured-tz behavior shipped in #2681 is fully covered. Note: codex's r6 claim that the reminder recomputes `startedAt` in UTC is factually wrong — it already uses `getUserTimezone()`.
+### Brain Graph touch-interaction follow-ups
+
+- [ ] **Give 3D graph nodes a finger-sized hit target.** `client/src/components/brain/tabs/BrainGraph.jsx` `GraphScene` raycasts against the node `<mesh>` spheres directly (radius `0.4 + importance * 0.8`), so on a phone a low-importance node is a ~10px target — well under the ~44px touch guidance, and tapping usually selects a neighbour or nothing. Options: an invisible larger companion sphere per node that carries the pointer handlers (cheap, but doubles the mesh count and overlapping halos make "nearest wins" ambiguous in a dense cluster), or a custom nearest-node-within-threshold pick in screen space on tap. Deferred from the mobile-responsive pass because it changes the 3D pick model (not layout) and wants real-device validation — jsdom/headless can't exercise a WebGL raycast, and the layout fixes stand on their own.
+- [ ] **Stop feeding the tooltip position on pointer moves that can't show a tooltip.** `client/src/components/brain/tabs/BrainGraph.jsx` sets `onPointerMove={(e) => setTooltipPos({ x: e.clientX, y: e.clientY })}` on the canvas container, so every mouse/finger move re-renders `BrainGraph` — even though `hoveredNode` is null for most moves (sparse spheres, and every orbit-drag), and on touch the tooltip is now `pointer-coarse:hidden` and can *never* paint, making it 100% waste on the weakest hardware. Memoizing `GraphScene` (done) already bails the ~200-element mesh subtree out of those renders, so what's left is the component's own render. The gate must use a **ref**, not `hoveredNode` state: r3f attaches its raycasting listener to the Canvas's own inner div while React delegates `onPointerMove` at the app root, so on the event that enters a node the `onPointerMove` closure still sees `hoveredNode === null` and would skip the position update the tooltip needs — stranding the first frame at a stale position (or `{0,0}` on the first-ever hover, if the user enters a node and holds still). Safest shape: have `GraphScene`'s `onPointerOver` pass `e.clientX/e.clientY` up so `handleHover` seeds `tooltipPos` at enter time, then gate the move handler on `hoveredRef.current`. Deferred from the mobile-responsive pass because it's an unverifiable path here — the tooltip only appears on a WebGL raycast hover, which neither jsdom (the test stubs `<Canvas>`) nor a headless run can exercise, and a wrong ordering assumption regresses the very tooltip the pass was fixing. Needs real-device/browser validation.
+- [ ] **Give `MemoryGraph.jsx` the same mobile treatment as BrainGraph.** `client/src/components/cos/tabs/MemoryGraph.jsx` is a near-literal fork of BrainGraph's canvas shell — same `Canvas`+`OrbitControls`, same `buildGraph` from `lib/graphSimulation`, same `dragStartRef`/`onPointerMove`→`setTooltipPos` wiring — and still carries all three defects the Brain Graph mobile pass fixed: `style={{ height: '500px' }}` (line ~219), the always-on `absolute bottom-3 left-3` legend (line ~241), and the unclamped `max-w-xs` tooltip at `left: tooltipPos.x + 12, top: tooltipPos.y - 12` (line ~267). `/cos` is in `Layout.jsx`'s `isFullWidth` list, so it has the same landscape-overflow exposure. Do NOT extract a shared `<GraphCanvasShell>` — only two call sites and the surrounding chrome has genuinely diverged (BrainGraph has a breadcrumb, seven type filters, search, embeddings banner, detail panel; MemoryGraph has a stats bar); port the fixes across instead. Deferred from the Brain Graph pass to keep that PR scoped to the page the work was requested for.
+- [ ] **Decide the touch scroll story for the graph canvas.** R3F sets `touch-action: none` on the canvas, so the graph is a dead zone for page scrolling — a one-finger drag rotates the camera and never scrolls. The mobile pass bounded the damage by making the canvas viewport-relative (`h-[clamp(240px,45vh,500px)]`), leaving the bars above and detail panel below as scrollable surfaces, but a user who starts a swipe on the canvas still can't scroll. Considered and rejected for this PR: the map-embed pattern (one finger scrolls, two fingers rotate, via OrbitControls `touches={{ ONE: … }}`) — it would make rotating the graph, which is the feature's whole point, a two-hand gesture. Worth revisiting with a real device: possibly a "drag to rotate / two-finger to scroll" hint on first touch, or an explicit fullscreen mode where the canvas legitimately owns all gestures.
+
### PortOS-update / CoS-agent mutual-exclusion follow-up
- [ ] **Gate every CoS spawn engine on `updateInProgress` so a scheduled/autopilot spawn can't start during a PortOS self-update.** The update flow now blocks `POST /api/update/execute` when a CoS agent is live or mid-spawn (`server/routes/update.js` `countActiveCosAgents`, fast-fail + post-lock re-check via `getActiveAgentIds()` + `spawningTasks`), and the Update tab suppresses restart buttons while agents run. Residual: an agent that begins spawning *after* the route's post-lock re-check but before `update.sh` reaches its `pm2 delete` (a multi-second window covering git pull / submodules / npm install) is still severed. Fully closing it means having the spawn side consult the update lock: add a synchronous in-memory `isUpdateInProgress()` mirror to `server/services/updateChecker.js` (kept in lockstep with the persisted flag in `setUpdateInProgress`) and have the CoS spawn engines skip-and-requeue (return the existing `SPAWN_DEDUP_SKIP`-style no-op, leaving the task queued for after the restart) when it's set. **This must cover ALL spawn engines, not just `spawnAgentForTask`** — per the CoS autonomous-spawn precedent, gating one chokepoint gives false confidence; audit `dequeueNextTask` / `evaluateTasks` / `executeScheduledJob` and the Creative Director / on-demand bridges (grep the spawn call sites in `server/services/agentLifecycle.js` + `subAgentSpawner.js` + `cos*.js`). Deferred from the codex review of this PR (r2 P1) because it's a CoS-subsystem change spanning multiple spawn paths that deserves its own focused PR + tests; the 409 guard, post-lock re-check, and the orphan reaper bound the residual exposure in the meantime.
diff --git a/client/src/components/brain/tabs/BrainGraph.jsx b/client/src/components/brain/tabs/BrainGraph.jsx
index 4cdda75512..e561b1880e 100644
--- a/client/src/components/brain/tabs/BrainGraph.jsx
+++ b/client/src/components/brain/tabs/BrainGraph.jsx
@@ -1,8 +1,8 @@
-import { useState, useEffect, useMemo, useRef, useCallback } from 'react';
+import { useState, useEffect, useMemo, useRef, useCallback, memo } from 'react';
import { Canvas } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import * as THREE from 'three';
-import {AlertTriangle, Zap, RefreshCw, X, ChevronRight, ArrowLeft, Compass} from 'lucide-react';
+import {AlertTriangle, Zap, RefreshCw, X, ChevronRight, ArrowLeft, Compass, Info} from 'lucide-react';
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
import { BRAIN_TYPE_HEX, DESTINATIONS } from '../constants';
@@ -20,6 +20,11 @@ const EDGE_COLORS = {
const BRAIN_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories', 'goals', 'journals'];
+// Widest the hover tooltip renders. Single source for both its max-width and
+// the clamp that keeps it inside the viewport — as a CSS class plus a mirrored
+// constant the two silently drift apart.
+const TOOLTIP_WIDTH = 320;
+
// Per-type API getters for detail panel
const TYPE_GETTERS = {
people: api.getBrainPerson,
@@ -70,7 +75,11 @@ function GraphEdges({ simEdges, selectedId }) {
);
}
-function GraphScene({ graph, selectedId, adjacentIds, onSelect, onFocus, onHover }) {
+// Memoized: the container's onPointerMove re-renders BrainGraph on every mouse
+// 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 sphereGeo = useMemo(() => new THREE.SphereGeometry(1, 16, 12), []);
const selNode = selectedId ? graph.idMap.get(selectedId) : null;
@@ -120,7 +129,7 @@ function GraphScene({ graph, selectedId, adjacentIds, onSelect, onFocus, onHover
<OrbitControls enableDamping dampingFactor={0.05} minDistance={10} maxDistance={200} />
</>
);
-}
+});
export default function BrainGraph() {
const [graphData, setGraphData] = useState(null);
@@ -137,6 +146,8 @@ export default function BrainGraph() {
const [searchValue, setSearchValue] = useState('');
const [focusTrail, setFocusTrail] = useState([]);
const [embeddingStatus, setEmbeddingStatus] = useState(null);
+ // Mobile-only: the legend is always shown from `sm` up (CSS, not this flag).
+ const [legendOpen, setLegendOpen] = useState(false);
const [typeFilters, setTypeFilters] = useState(() =>
Object.fromEntries(BRAIN_TYPES.map(t => [t, true]))
);
@@ -193,6 +204,15 @@ export default function BrainGraph() {
await loadView(null, { trail: [] });
}, [loadView]);
+ // The search index covers every brain record (unbounded, unlike the loaded
+ // view), so keep a stable mapping — rebuilt inline it re-allocated the whole
+ // list on every tooltip-position render and re-ran the combobox's filters.
+ const searchItems = useMemo(() => searchIndex.map(n => ({
+ id: n.id,
+ name: n.label,
+ subtitle: DESTINATIONS[n.brainType]?.label || n.brainType
+ })), [searchIndex]);
+
// Filter the (already bounded) loaded nodes by type toggles.
const filteredData = useMemo(() => {
if (!graphData?.nodes?.length) return null;
@@ -336,15 +356,15 @@ export default function BrainGraph() {
<div className="h-full overflow-y-auto p-3 sm:p-4 space-y-3">
{/* No-embeddings banner */}
{graphData && !graphData.hasEmbeddings && (
- <div className="flex items-center justify-between bg-port-warning/10 border border-port-warning/30 rounded-lg px-4 py-2.5">
- <div className="flex items-center gap-2 text-sm text-port-warning">
- <AlertTriangle size={16} />
- No embeddings found. Sync brain data to CoS memory to enable semantic similarity edges.
+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 bg-port-warning/10 border border-port-warning/30 rounded-lg px-3 sm:px-4 py-2.5">
+ <div className="flex items-start gap-2 text-sm text-port-warning">
+ <AlertTriangle size={16} className="shrink-0 mt-0.5" />
+ <span>No embeddings found. Sync brain data to CoS memory to enable semantic similarity edges.</span>
</div>
<button
onClick={() => handleSync({ onlyMissing: true })}
disabled={syncing}
- className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium bg-port-warning/20 text-port-warning border border-port-warning/30 rounded-lg hover:bg-port-warning/30 transition-colors disabled:opacity-50"
+ className="flex items-center justify-center gap-1.5 self-start sm:self-auto shrink-0 px-3 py-1.5 min-h-[36px] text-xs font-medium bg-port-warning/20 text-port-warning border border-port-warning/30 rounded-lg hover:bg-port-warning/30 transition-colors disabled:opacity-50"
>
{syncing ? <BrailleSpinner /> : <Zap size={14} />}
{syncing ? 'Syncing...' : 'Sync Now'}
@@ -356,21 +376,24 @@ export default function BrainGraph() {
loaded view) and focus its neighborhood. */}
<div className="flex items-center gap-2">
<EntityCombobox
- items={searchIndex.map(n => ({ id: n.id, name: n.label, subtitle: DESTINATIONS[n.brainType]?.label || n.brainType }))}
+ items={searchItems}
value={searchValue}
onChange={setSearchValue}
onPick={(item) => { focusNode({ id: item.id, label: item.name }); setSearchValue(''); }}
inputId="brain-graph-search"
noun="memory"
placeholder="Search memories to explore…"
- className="flex-1 min-w-[200px]"
+ // min-w-0 (not the default 200px floor) so the field still shrinks
+ // beside the "N missing" button on a ~320px screen instead of
+ // overflowing the row.
+ className="flex-1 min-w-0"
/>
{missingCount > 0 && (
<button
onClick={() => handleSync({ onlyMissing: true })}
disabled={syncing}
title={`${missingCount} of ${embeddingStatus?.total ?? '?'} records have no embedding yet — embed just those (fast)`}
- className="flex items-center gap-1.5 px-3 py-2 min-h-[36px] text-xs whitespace-nowrap bg-port-warning/15 text-port-warning border border-port-warning/30 rounded-lg hover:bg-port-warning/25 transition-colors disabled:opacity-50"
+ className="flex items-center gap-1.5 shrink-0 px-3 py-2 min-h-[36px] text-xs whitespace-nowrap bg-port-warning/15 text-port-warning border border-port-warning/30 rounded-lg hover:bg-port-warning/25 transition-colors disabled:opacity-50"
>
{syncing ? <BrailleSpinner /> : <Zap size={14} />}
{missingCount} missing · Embed
@@ -378,16 +401,18 @@ export default function BrainGraph() {
)}
</div>
- {/* Breadcrumb trail + controls bar */}
- <div className="flex items-center gap-3 bg-port-card border border-port-border rounded-lg px-4 py-2 flex-wrap">
- {/* Breadcrumb */}
- <div className="flex items-center gap-1 text-xs min-w-0">
+ {/* Breadcrumb trail + controls bar. Below `sm` this stacks into three
+ rows (trail / filters / stats+actions) — as one flex row the seven
+ type filters shoved the breadcrumb and buttons into a jumble. */}
+ <div className="bg-port-card border border-port-border rounded-lg px-3 sm:px-4 py-2 space-y-2 sm:space-y-0 sm:flex sm:flex-wrap sm:items-center sm:gap-3">
+ {/* Breadcrumb — scrolls sideways rather than wrapping a deep trail */}
+ <div className="flex items-center gap-1 text-xs min-w-0 overflow-x-auto">
{focusTrail.length > 0 && (
<button
onClick={goBack}
title="Back"
aria-label="Back"
- className="flex items-center gap-1 px-2 py-1 text-gray-400 hover:text-white rounded transition-colors"
+ className="flex items-center gap-1 shrink-0 px-2 py-1 text-gray-400 hover:text-white rounded transition-colors"
>
<ArrowLeft size={13} />
</button>
@@ -395,7 +420,7 @@ export default function BrainGraph() {
<button
onClick={goToOverview}
disabled={focusTrail.length === 0}
- className={`px-1.5 py-1 rounded transition-colors ${focusTrail.length === 0 ? 'text-white font-medium' : 'text-gray-400 hover:text-white'}`}
+ className={`shrink-0 px-1.5 py-1 rounded transition-colors ${focusTrail.length === 0 ? 'text-white font-medium' : 'text-gray-400 hover:text-white'}`}
>
Overview
</button>
@@ -409,12 +434,13 @@ export default function BrainGraph() {
))}
</div>
- {/* Type filter checkboxes */}
- <div className="flex items-center gap-3 ml-auto">
+ {/* Type filter checkboxes — wrap on mobile (seven of them never fit a
+ phone row) with a taller tap target than the 12px swatch alone. */}
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 sm:ml-auto">
{BRAIN_TYPES.map(type => {
const dest = DESTINATIONS[type];
return (
- <label key={type} className="flex items-center gap-1.5 cursor-pointer text-sm">
+ <label key={type} className="flex items-center gap-1.5 cursor-pointer select-none text-sm py-1.5 sm:py-0 min-h-[32px] sm:min-h-0">
<input
type="checkbox"
checked={typeFilters[type]}
@@ -433,29 +459,32 @@ export default function BrainGraph() {
})}
</div>
- {/* Stats + re-layout */}
- <span className="text-sm text-gray-400">
- {filteredData?.nodes?.length || 0} nodes &middot; {filteredData?.edges?.length || 0} edges
- </span>
- <button
- onClick={() => { setSelectedNode(null); setLayoutKey(k => k + 1); }}
- className="px-3 py-1.5 min-h-[36px] text-xs bg-port-border text-gray-400 hover:text-white rounded-lg transition-colors"
- >
- Re-layout
- </button>
- {/* Recovery action (issue #1080): re-embed already-synced records whose
- memory copy may be stale. Confirmed first — it re-embeds every record
- and can run for many minutes. The cheaper "Embed missing" above is the
- usual path; this is the heavy reset. */}
- <button
- onClick={() => setConfirmingRefresh(true)}
- disabled={syncing || confirmingRefresh}
- title="Re-embed ALL brain records, including ones synced from peers. Slow — use 'Embed missing' for the common case."
- className="flex items-center gap-1.5 px-3 py-1.5 min-h-[36px] text-xs bg-port-border text-gray-400 hover:text-white rounded-lg transition-colors disabled:opacity-50"
- >
- {syncing ? <BrailleSpinner /> : <RefreshCw size={14} />}
- Refresh all
- </button>
+ {/* Stats + actions — kept together so they share a row on mobile
+ instead of each wrapping onto a line of their own. */}
+ <div className="flex items-center gap-2 sm:gap-3">
+ <span className="text-xs sm:text-sm text-gray-400 mr-auto sm:mr-0">
+ {filteredData?.nodes?.length || 0} nodes &middot; {filteredData?.edges?.length || 0} edges
+ </span>
+ <button
+ onClick={() => { setSelectedNode(null); setLayoutKey(k => k + 1); }}
+ className="px-3 py-1.5 min-h-[36px] text-xs bg-port-border text-gray-400 hover:text-white rounded-lg transition-colors"
+ >
+ Re-layout
+ </button>
+ {/* Recovery action (issue #1080): re-embed already-synced records whose
+ memory copy may be stale. Confirmed first — it re-embeds every record
+ and can run for many minutes. The cheaper "Embed missing" above is the
+ usual path; this is the heavy reset. */}
+ <button
+ onClick={() => setConfirmingRefresh(true)}
+ disabled={syncing || confirmingRefresh}
+ title="Re-embed ALL brain records, including ones synced from peers. Slow — use 'Embed missing' for the common case."
+ className="flex items-center gap-1.5 px-3 py-1.5 min-h-[36px] text-xs bg-port-border text-gray-400 hover:text-white rounded-lg transition-colors disabled:opacity-50"
+ >
+ {syncing ? <BrailleSpinner /> : <RefreshCw size={14} />}
+ Refresh all
+ </button>
+ </div>
</div>
{confirmingRefresh && (
@@ -469,10 +498,13 @@ export default function BrainGraph() {
/>
)}
- {/* 3D Canvas */}
+ {/* 3D Canvas. Viewport-relative rather than a flat 500px: the canvas is a
+ touch-action:none dead zone for page scrolling, so on a phone (and
+ especially in landscape, where 500px overflowed the whole viewport) it
+ has to leave room to scroll past. Caps at the original 500px on
+ 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"
- style={{ height: '500px' }}
+ 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 }; }}
onPointerMove={(e) => setTooltipPos({ x: e.clientX, y: e.clientY })}
>
@@ -522,35 +554,61 @@ export default function BrainGraph() {
</button>
)}
- {/* Legend */}
- <div className="absolute bottom-3 left-3 bg-port-bg/90 border border-port-border rounded-lg p-3 text-xs space-y-1.5 pointer-events-none">
- {BRAIN_TYPES.map(t => (
- <div key={t} className="flex items-center gap-2">
- <span className="inline-block w-2.5 h-2.5 rounded-full" style={{ backgroundColor: BRAIN_TYPE_HEX[t] }} />
- <span className="text-gray-400">{DESTINATIONS[t]?.label || t}</span>
- </div>
- ))}
- <div className="border-t border-port-border pt-1.5 mt-1.5 space-y-1">
- <div className="flex items-center gap-2">
- <span className="inline-block w-4 h-0 border-t" style={{ borderColor: EDGE_COLORS.similar }} />
- <span className="text-gray-500">similar</span>
- </div>
- <div className="flex items-center gap-2">
- <span className="inline-block w-4 h-0 border-t" style={{ borderColor: EDGE_COLORS.shared_tag }} />
- <span className="text-gray-500">shared tag</span>
- </div>
- <div className="flex items-center gap-2">
- <span className="inline-block w-4 h-0 border-t" style={{ borderColor: EDGE_COLORS.linked }} />
- <span className="text-gray-500">linked</span>
+ {/* Legend. Ten rows blanket a phone-sized canvas, so below `sm` it
+ collapses behind a toggle and expands upward from the corner (the
+ type filters above already carry the same colour→label mapping; the
+ edge colours are only here, so it stays reachable rather than
+ hidden). Unchanged at `sm` and up. */}
+ <div className="absolute bottom-3 left-3 z-10 flex flex-col items-start gap-1.5">
+ <div
+ data-testid="graph-legend"
+ className={`${legendOpen ? 'block' : 'hidden'} sm:block bg-port-bg/90 border border-port-border rounded-lg p-3 text-xs space-y-1.5 pointer-events-none`}
+ >
+ {BRAIN_TYPES.map(t => (
+ <div key={t} className="flex items-center gap-2">
+ <span className="inline-block w-2.5 h-2.5 rounded-full" style={{ backgroundColor: BRAIN_TYPE_HEX[t] }} />
+ <span className="text-gray-400">{DESTINATIONS[t]?.label || t}</span>
+ </div>
+ ))}
+ <div className="border-t border-port-border pt-1.5 mt-1.5 space-y-1">
+ <div className="flex items-center gap-2">
+ <span className="inline-block w-4 h-0 border-t" style={{ borderColor: EDGE_COLORS.similar }} />
+ <span className="text-gray-500">similar</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <span className="inline-block w-4 h-0 border-t" style={{ borderColor: EDGE_COLORS.shared_tag }} />
+ <span className="text-gray-500">shared tag</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <span className="inline-block w-4 h-0 border-t" style={{ borderColor: EDGE_COLORS.linked }} />
+ <span className="text-gray-500">linked</span>
+ </div>
</div>
</div>
+ <button
+ onClick={() => setLegendOpen(o => !o)}
+ aria-expanded={legendOpen}
+ className="sm:hidden flex items-center gap-1.5 px-2.5 py-1.5 min-h-[32px] text-[11px] bg-port-bg/90 border border-port-border text-gray-400 hover:text-white rounded-lg transition-colors"
+ >
+ <Info size={12} />
+ Legend
+ </button>
</div>
- {/* Tooltip */}
+ {/* Hover tooltip. Suppressed on a coarse pointer: there is no hover to
+ preview with — a tap selects the node and the detail panel below
+ already shows the same record — and it would otherwise flash under
+ the user's own finger advertising a double-click touch can't do.
+ Position is clamped so it can't run off the right edge of a narrow
+ window, where `x + 12` alone would clip the label. */}
{hoveredNode && (
<div
- className="fixed z-50 pointer-events-none bg-port-bg border border-port-border rounded-lg px-3 py-2 shadow-lg max-w-xs"
- style={{ left: tooltipPos.x + 12, top: tooltipPos.y - 12 }}
+ className="fixed z-50 pointer-events-none pointer-coarse:hidden bg-port-bg border border-port-border rounded-lg px-3 py-2 shadow-lg"
+ style={{
+ maxWidth: TOOLTIP_WIDTH,
+ left: Math.max(8, Math.min(tooltipPos.x + 12, window.innerWidth - TOOLTIP_WIDTH - 8)),
+ top: Math.max(8, tooltipPos.y - 12)
+ }}
>
<div className="flex items-center gap-2 mb-1">
<span
@@ -571,8 +629,8 @@ export default function BrainGraph() {
{/* Detail panel */}
{selectedNode && (
- <div className="bg-port-card border border-port-border rounded-lg p-4">
- <div className="flex items-start justify-between gap-3 mb-3">
+ <div className="bg-port-card border border-port-border rounded-lg p-3 sm:p-4">
+ <div className="flex items-start justify-between gap-2 sm:gap-3 mb-3">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-2">
<span
@@ -619,26 +677,29 @@ export default function BrainGraph() {
<p className="text-sm text-gray-300">{selectedNode.summary}</p>
)}
</div>
- <div className="flex flex-col items-end gap-2 shrink-0">
- <button
- onClick={() => setSelectedNode(null)}
- title="Clear selection (Esc)"
- aria-label="Clear selection"
- className="text-gray-500 hover:text-white transition-colors p-1"
- >
- &times;
- </button>
- {selectedNode.id !== focusId && (
- <button
- onClick={() => focusNode(selectedNode)}
- className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs bg-port-accent/20 text-port-accent border border-port-accent/30 rounded-lg hover:bg-port-accent/30 transition-colors whitespace-nowrap"
- >
- <Compass size={13} />
- Explore connections
- </button>
- )}
- </div>
+ <button
+ onClick={() => setSelectedNode(null)}
+ title="Clear selection (Esc)"
+ aria-label="Clear selection"
+ className="shrink-0 text-gray-500 hover:text-white transition-colors p-1"
+ >
+ &times;
+ </button>
</div>
+
+ {/* "Explore connections" sits on its own row rather than in a column
+ beside the body: as a fixed ~160px sidebar it squeezed the record
+ text to a sliver on a phone. Full-width on mobile (it's the touch
+ stand-in for double-clicking a node), inline from `sm` up. */}
+ {selectedNode.id !== focusId && (
+ <button
+ onClick={() => focusNode(selectedNode)}
+ className="flex items-center justify-center sm:justify-start gap-1.5 w-full sm:w-auto mb-3 px-2.5 py-2 sm:py-1.5 min-h-[36px] text-xs bg-port-accent/20 text-port-accent border border-port-accent/30 rounded-lg hover:bg-port-accent/30 transition-colors whitespace-nowrap"
+ >
+ <Compass size={13} />
+ Explore connections
+ </button>
+ )}
{connectedNodes.length > 0 && (
<div>
<p className="text-xs text-gray-500 mb-2">{connectedNodes.length} connections</p>
diff --git a/client/src/components/brain/tabs/BrainGraph.test.jsx b/client/src/components/brain/tabs/BrainGraph.test.jsx
new file mode 100644
index 0000000000..a2701a15e9
--- /dev/null
+++ b/client/src/components/brain/tabs/BrainGraph.test.jsx
@@ -0,0 +1,95 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, act } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+// The three.js stack can't run in jsdom (no WebGL context), and none of it is
+// under test here — this file covers the responsive chrome AROUND the canvas.
+// The stub deliberately drops `children`: rendering the scene would mount
+// <bufferGeometry>/<mesh> as unknown DOM elements, and the r3f refs they hand
+// back are HTMLElements without the three.js geometry API.
+vi.mock('@react-three/fiber', () => ({
+ Canvas: () => <div data-testid="graph-canvas" />,
+}));
+vi.mock('@react-three/drei', () => ({ OrbitControls: () => null }));
+
+vi.mock('../../../services/api', () => ({
+ getBrainGraph: vi.fn(),
+ getBrainGraphSearchIndex: vi.fn(),
+ getEmbeddingsStatus: vi.fn(),
+ syncBrainData: vi.fn(),
+ getBrainPerson: vi.fn(),
+ getBrainProject: vi.fn(),
+ getBrainIdea: vi.fn(),
+ getBrainAdminItem: vi.fn(),
+ getBrainMemory: vi.fn(),
+ getBrainGoal: vi.fn(),
+ getBrainJournalEntry: vi.fn(),
+}));
+
+import * as api from '../../../services/api';
+import BrainGraph from './BrainGraph';
+
+const GRAPH = {
+ hasEmbeddings: true,
+ nodes: [
+ { id: 'n1', label: 'Alpha', brainType: 'ideas', importance: 0.5, summary: 'first' },
+ { id: 'n2', label: 'Beta', brainType: 'goals', importance: 0.5, summary: 'second' },
+ ],
+ edges: [{ source: 'n1', target: 'n2', type: 'linked', weight: 0.9 }],
+};
+
+const renderGraph = async () => {
+ render(<BrainGraph />);
+ // Settle the mount-effect fetches inside act (see src/test/setup.js).
+ await act(async () => {});
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.getBrainGraph.mockResolvedValue(GRAPH);
+ api.getBrainGraphSearchIndex.mockResolvedValue({ nodes: [] });
+ api.getEmbeddingsStatus.mockResolvedValue({ missing: 0, total: 2 });
+});
+
+// The legend is ten rows tall and sits over the canvas, which blankets a
+// phone-sized graph — so on mobile it hides behind a toggle. It must stay
+// reachable (the edge colours appear nowhere else) rather than be dropped.
+describe('legend disclosure', () => {
+ it('starts collapsed and expands when the mobile toggle is pressed', async () => {
+ const user = userEvent.setup();
+ await renderGraph();
+
+ const toggle = screen.getByRole('button', { name: /legend/i });
+ expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ // `hidden` is the mobile-collapsed state — the panel stays in the DOM, and
+ // `sm:block` re-shows it on desktop regardless of this flag.
+ expect(screen.getByTestId('graph-legend')).toHaveClass('hidden');
+
+ await user.click(toggle);
+
+ expect(toggle).toHaveAttribute('aria-expanded', 'true');
+ expect(screen.getByTestId('graph-legend')).not.toHaveClass('hidden');
+ });
+
+ it('keeps the edge-colour key reachable — it appears nowhere else in the tab', async () => {
+ await renderGraph();
+ // The type colours are duplicated by the filter row, but similar/shared
+ // tag/linked only exist here, so the mobile collapse must not drop them.
+ for (const label of ['similar', 'shared tag', 'linked']) {
+ expect(screen.getByText(label)).toBeInTheDocument();
+ }
+ });
+});
+
+describe('canvas sizing', () => {
+ it('sizes the canvas relative to the viewport, not a fixed pixel height', async () => {
+ await renderGraph();
+ const shell = screen.getByTestId('graph-canvas').parentElement;
+ // The regression guarded here is a fixed height (the old
+ // `style={{ height: '500px' }}`), which overflowed a landscape phone and
+ // left no room to scroll past a canvas that swallows drags. The exact
+ // clamp values are free to be tuned, so only assert it's viewport-relative.
+ expect(shell.style.height).toBe('');
+ expect(shell.className).toMatch(/h-\[clamp\([^\]]*vh[^\]]*\)\]/);
+ });
+});