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
feat([issue-817]): add CyberCity activity-heatmap tiles and task-flow river
[._.]/ Adam Eivy4f53b86ad8e6
diff --git a/client/src/components/city/CityActivityHeatmap.jsx b/client/src/components/city/CityActivityHeatmap.jsxnew file mode 100644index 0000000000..3f54d52b72--- /dev/null+++ b/client/src/components/city/CityActivityHeatmap.jsx@@ -0,0 +1,59 @@+import { useMemo, useRef } from 'react';+import { useFrame } from '@react-three/fiber';+import { computeActivityHeatmap } from '../../utils/cityActivityHeatmap';++// CyberCity productivity-district activity heatmap (issue #817): a GitHub-style contribution+// grid laid out as a field of thin ground tiles framing the streak monument. Each tile is one+// day; its glow scales with that day's completed-task count relative to the busiest day in the+// window. Today's tile reads accent-blue. Active tiles breathe on the highest quality presets;+// the static glow keeps the field legible when the pulse is dropped. Data comes from the+// activity calendar (`GET /api/cos/productivity/calendar`). Mirrors CityProductivityDistrict.+export default function CityActivityHeatmap({ calendarData, settings }) {+ const heatmap = useMemo(() => computeActivityHeatmap(calendarData), [calendarData]);+ const groupRef = useRef();++ // Honor the quality dial: drop the per-tile shimmer on the lowest preset, keep the static+ // glow so the contribution field stays readable.+ const animate = (settings?.particleDensity ?? 1) >= 0.5;++ useFrame(({ clock }) => {+ if (!animate || !groupRef.current) return;+ // A gentle traveling wave across the field so active tiles shimmer like data flowing in.+ const t = clock.getElapsedTime();+ for (const tile of groupRef.current.children) {+ const base = tile.userData.baseIntensity;+ if (!base) continue;+ const phase = tile.userData.phase || 0;+ const wave = 0.85 + ((Math.sin(t * 1.4 + phase * 6.283) + 1) / 2) * 0.3;+ tile.material.emissiveIntensity = base * wave;+ }+ });++ if (!heatmap.present) return null;++ const { origin, tileSize, tileHeight, tiles } = heatmap;++ return (+ <group position={origin}>+ <group ref={groupRef}>+ {tiles.map((tile) => (+ <mesh+ key={tile.key}+ position={[tile.x, tileHeight / 2, tile.z]}+ userData={{ baseIntensity: tile.tasks > 0 ? tile.intensity : 0, phase: tile.x + tile.z }}+ >+ <boxGeometry args={[tileSize, tileHeight, tileSize]} />+ <meshStandardMaterial+ color={tile.color}+ emissive={tile.color}+ emissiveIntensity={tile.intensity}+ metalness={0.3}+ roughness={0.6}+ toneMapped={false}+ />+ </mesh>+ ))}+ </group>+ </group>+ );+}diff --git a/client/src/components/city/CityScene.jsx b/client/src/components/city/CityScene.jsxindex f6e59c28b6..acc7cd5d36 100644--- a/client/src/components/city/CityScene.jsx+++ b/client/src/components/city/CityScene.jsx@@ -19,6 +19,8 @@ import CityBackupVault from './CityBackupVault';import CityTaskQueue from './CityTaskQueue';import CityHealthTower from './CityHealthTower';import CityProductivityDistrict from './CityProductivityDistrict';+import CityActivityHeatmap from './CityActivityHeatmap';+import CityTaskFlowRiver from './CityTaskFlowRiver';import CityGoalMonuments from './CityGoalMonuments';import CityArtifacts from './CityArtifacts';import CityVoiceMarker from './CityVoiceMarker';@@ -34,7 +36,7 @@ import CityEnergyOverlay from './CityEnergyOverlay';import PlayerController from './PlayerController';import CameraTransition from './CameraTransition';-export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus, reviewCounts, instances, backupStatus, cosTasks, healthMetrics, voiceState, aiActivity, productivityData, goals, character, chronotype, settings, playSfx, keysRef, dimmedAppIds }) {+export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus, reviewCounts, instances, backupStatus, cosTasks, healthMetrics, voiceState, aiActivity, productivityData, activityCalendar, goals, character, chronotype, settings, playSfx, keysRef, dimmedAppIds }) {const [positions, setPositions] = useState(null);const [proximityApp, setProximityApp] = useState(null);const [transitioning, setTransitioning] = useState(false);@@ -88,6 +90,8 @@ export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus,<CityTaskQueue cosTasks={cosTasks} settings={settings} /><CityHealthTower healthMetrics={healthMetrics} settings={settings} /><CityProductivityDistrict productivityData={productivityData} settings={settings} />+ <CityActivityHeatmap calendarData={activityCalendar} settings={settings} />+ <CityTaskFlowRiver cosTasks={cosTasks} productivityData={productivityData} calendarData={activityCalendar} settings={settings} /><CityGoalMonuments goals={goals} settings={settings} /><CityArtifacts character={character} goals={goals} productivityData={productivityData} settings={settings} /><CityVoiceMarker voiceState={voiceState} settings={settings} />diff --git a/client/src/components/city/CityTaskFlowRiver.jsx b/client/src/components/city/CityTaskFlowRiver.jsxnew file mode 100644index 0000000000..3d76200fdc--- /dev/null+++ b/client/src/components/city/CityTaskFlowRiver.jsx@@ -0,0 +1,89 @@+import { useMemo, useRef } from 'react';+import { useFrame } from '@react-three/fiber';+import { computeTaskQueue } from '../../utils/cityTaskQueue';+import { computeTaskFlowRiver } from '../../utils/cityTaskFlowRiver';++// CyberCity task-flow river (issue #817): an animated channel running from the task-queue+// warehouse to the productivity district, tying queued work to completed throughput. The+// channel WIDTH tracks the live backlog (more pending/in-progress/blocked work → broader) and+// the flow SPEED tracks recent throughput / queue drain. Flow nodes travel warehouse→monument+// along the channel; they animate only on the higher quality presets, while the channel bed+// itself stays drawn so the link between the two districts is always legible. Mirrors+// CityProductivityDistrict / CityTaskQueue.+export default function CityTaskFlowRiver({ cosTasks, productivityData, calendarData, settings }) {+ const river = useMemo(() => {+ const queue = computeTaskQueue(cosTasks);+ // Recent throughput: prefer the calendar window total (steady multi-day signal), fall+ // back to today's completed count from the quick-summary so the river still flows before+ // the calendar fetch lands.+ const calendarTotal = calendarData && typeof calendarData === 'object'+ ? calendarData?.summary?.totalTasks+ : undefined;+ const todayCompleted = productivityData && typeof productivityData === 'object'+ ? productivityData?.today?.completed+ : undefined;+ const throughput = typeof calendarTotal === 'number' ? calendarTotal : todayCompleted;+ return computeTaskFlowRiver(queue, throughput);+ }, [cosTasks, productivityData, calendarData]);++ const nodesRef = useRef();++ // Honor the quality dial: drop the traveling flow nodes on the lowest preset; the channel+ // bed remains so the districts stay visually linked.+ const animate = (settings?.particleDensity ?? 1) >= 0.5;++ useFrame(({ clock }) => {+ if (!animate || !nodesRef.current || !river.flowing) return;+ const t = clock.getElapsedTime();+ const half = river.length / 2;+ for (const node of nodesRef.current.children) {+ const phase = node.userData.phase || 0;+ // Flow runs warehouse(-half) → monument(+half) along the channel's local +x. Wrap with+ // a fractional cycle so nodes stream continuously; speed scales with throughput.+ const frac = (phase + t * river.speed * 0.12) % 1;+ node.position.x = -half + frac * river.length;+ }+ });++ const { center, angle, length, width, color, particles } = river;++ return (+ // Center the channel between the two districts and rotate it to align local +x with the+ // warehouse→monument axis. A slight lift keeps the bed from z-fighting the ground plane.+ <group position={[center[0], 0.06, center[2]]} rotation={[0, angle, 0]}>+ {/* Channel bed — a flat ribbon laid on the ground along the district axis */}+ <mesh rotation={[-Math.PI / 2, 0, 0]}>+ <planeGeometry args={[length, width]} />+ <meshStandardMaterial+ color={color}+ emissive={color}+ emissiveIntensity={0.12 + river.speedLevel * 0.18}+ transparent+ opacity={0.32}+ metalness={0.2}+ roughness={0.7}+ toneMapped={false}+ />+ </mesh>++ {/* Traveling flow nodes — brighter, faster current means more energy moving downstream */}+ <group ref={nodesRef}>+ {particles.map((p) => (+ <mesh+ key={p.index}+ position={[-length / 2 + p.phase * length, 0.18, 0]}+ userData={{ phase: p.phase }}+ >+ <boxGeometry args={[width * 0.5, 0.22, Math.min(width * 0.7, 1.4)]} />+ <meshStandardMaterial+ color={color}+ emissive={color}+ emissiveIntensity={0.6 + river.speedLevel * 0.6}+ toneMapped={false}+ />+ </mesh>+ ))}+ </group>+ </group>+ );+}diff --git a/client/src/pages/CyberCity.jsx b/client/src/pages/CyberCity.jsxindex 0739f29cb1..52897bb89d 100644--- a/client/src/pages/CyberCity.jsx+++ b/client/src/pages/CyberCity.jsx@@ -68,6 +68,14 @@ function CyberCityInner() {60_000,);+ // Activity calendar drives the productivity district's heatmap ground tiles and feeds the+ // task-flow river's throughput signal. Low-frequency: the daily contribution grid changes+ // slowly. Same last-good-snapshot semantics as productivityData.+ const { data: activityCalendar } = useAutoRefetch(+ () => api.getCosActivityCalendar(12, { silent: true }),+ 120_000,+ );+// Life goals drive the goal-monument district. Same pattern as productivityData —// `useAutoRefetch` keeps the last-good snapshot on transient failures.const { data: goalsData } = useAutoRefetch(@@ -127,6 +135,7 @@ function CyberCityInner() {voiceState={voiceState}aiActivity={aiActivity}productivityData={productivityData}+ activityCalendar={activityCalendar}goals={goalsData}character={character}chronotype={chronotypeData}diff --git a/client/src/utils/cityActivityHeatmap.js b/client/src/utils/cityActivityHeatmap.jsnew file mode 100644index 0000000000..db3825778f--- /dev/null+++ b/client/src/utils/cityActivityHeatmap.js@@ -0,0 +1,107 @@+// Pure, deterministic helpers for CyberCity's productivity-district activity heatmap+// (roadmap 2.6 follow-up, issue #817): a GitHub-style contribution grid rendered as a field+// of ground tiles laid out around the streak monument. Each tile is one day; its glow scales+// with that day's completed-task count relative to the busiest day in the window. The grid+// matches the calendar payload's shape exactly — weeks run left→right (x), day-of-week runs+// front→back (z) — so the field reads like the contribution chart on the productivity tab.+// No three.js / React imports so the topology is unit-testable (mirrors cityProductivity.js).++import { MONUMENT } from './cityProductivity';++export const HEATMAP = {+ // Anchored just east of the monument plinth so the grid frames the obelisk without+ // overlapping its footprint. Monument lives at MONUMENT.position ([-48, 0, 28]).+ origin: [MONUMENT.position[0] + MONUMENT.baseWidth * 1.4, 0, MONUMENT.position[2] - 12],+ tileSize: 1.6, // square footprint of each day tile+ tileGap: 0.4, // gap between adjacent tiles+ tileHeight: 0.18, // a thin slab so the field stays low to the ground+ maxWeeks: 14, // cap columns so the field never sprawls past the district (calendar default is 12)+};++const ACTIVE_COLOR = '#22c55e'; // port-success — completed work, GitHub-contribution green+const TODAY_COLOR = '#3b82f6'; // port-accent — highlight the current day+const EMPTY_COLOR = '#1a2030'; // near port-card — a quiet, unlit "no activity" tile++const clamp01 = (n) => Math.max(0, Math.min(1, n));++// Coerce to a finite, positive count or 0. Tile counts are never negative and a garbage+// value should read as "no activity," not crash the field.+function countOrZero(value) {+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;+}++// Map a day's task count to a 0..1 intensity against the window's busiest day. A zero-task+// day is 0 (drawn dim/empty); the busiest day(s) reach 1. A 0/garbage `maxTasks` falls back+// to 1 so a single active day still lights up rather than dividing by zero.+export function tileLevel(tasks, maxTasks) {+ const t = countOrZero(tasks);+ if (t === 0) return 0;+ const max = countOrZero(maxTasks);+ return clamp01(t / (max || 1));+}++// Full derived view-model for the component. `calendarData` is the `getActivityCalendar`+// payload (`{ weeks: [[{ date, dayOfWeek, tasks, isToday, isFuture, ... }]], maxTasks,+// summary, currentStreak }`). A missing/non-object payload, or one with no usable weeks,+// yields `present: false` and an empty tile list so the field simply doesn't render rather+// than crashing.+export function computeActivityHeatmap(calendarData) {+ const payload = calendarData && typeof calendarData === 'object' ? calendarData : {};+ const rawWeeks = Array.isArray(payload.weeks) ? payload.weeks : [];+ // Keep only the most recent `maxWeeks` columns so the field stays inside the district.+ const weeks = rawWeeks.slice(-HEATMAP.maxWeeks);+ const maxTasks = countOrZero(payload.maxTasks) || 1;++ const { tileSize, tileGap, tileHeight } = HEATMAP;+ const step = tileSize + tileGap;++ const tiles = [];+ let activeCount = 0;+ let totalTasks = 0;++ weeks.forEach((week, weekIndex) => {+ const days = Array.isArray(week) ? week : [];+ days.forEach((day) => {+ const dayObj = day && typeof day === 'object' ? day : {};+ // Future days in the trailing partial week aren't real activity — skip them so the+ // grid doesn't render a row of empty tiles past today.+ if (dayObj.isFuture) return;+ const dow = typeof dayObj.dayOfWeek === 'number' && Number.isFinite(dayObj.dayOfWeek)+ ? dayObj.dayOfWeek+ : 0;+ const tasks = countOrZero(dayObj.tasks);+ const level = tileLevel(tasks, maxTasks);+ const isToday = dayObj.isToday === true;+ if (tasks > 0) {+ activeCount += 1;+ totalTasks += tasks;+ }+ tiles.push({+ key: dayObj.date || `${weekIndex}-${dow}`,+ // Weeks run along x (columns), day-of-week runs along z (front→back rows).+ x: weekIndex * step,+ z: dow * step,+ tasks,+ level,+ isToday,+ // Empty days sit dark; active days glow green, scaled by level; today gets an accent.+ color: tasks === 0 ? EMPTY_COLOR : isToday ? TODAY_COLOR : ACTIVE_COLOR,+ // Emissive intensity: empty tiles barely glow; active tiles ramp with level; today+ // always reads clearly even on a light day.+ intensity: tasks === 0 ? 0.04 : isToday ? Math.max(0.5, 0.25 + level * 0.7) : 0.18 + level * 0.6,+ });+ });+ });++ return {+ origin: HEATMAP.origin,+ tileSize,+ tileHeight,+ present: tiles.length > 0,+ weekCount: weeks.length,+ tiles,+ activeCount,+ totalTasks,+ maxTasks,+ };+}diff --git a/client/src/utils/cityActivityHeatmap.test.js b/client/src/utils/cityActivityHeatmap.test.jsnew file mode 100644index 0000000000..8b4e0de849--- /dev/null+++ b/client/src/utils/cityActivityHeatmap.test.js@@ -0,0 +1,132 @@+import { describe, it, expect } from 'vitest';+import { HEATMAP, tileLevel, computeActivityHeatmap } from './cityActivityHeatmap';++// Minimal calendar payload mirroring getActivityCalendar's shape: weeks of 7 days.+function makeCalendar(taskGrid, { maxTasks, todayIndex } = {}) {+ let flat = 0;+ const weeks = taskGrid.map((week, wi) =>+ week.map((tasks, dow) => {+ const idx = flat++;+ return {+ date: `2026-w${wi}-d${dow}`,+ dayOfWeek: dow,+ tasks,+ successes: tasks,+ failures: 0,+ successRate: 100,+ isToday: idx === todayIndex,+ isFuture: false,+ };+ })+ );+ const computedMax = Math.max(1, ...taskGrid.flat());+ return { weeks, maxTasks: maxTasks ?? computedMax };+}++describe('tileLevel', () => {+ it('maps tasks/maxTasks into 0..1', () => {+ expect(tileLevel(5, 10)).toBe(0.5);+ expect(tileLevel(10, 10)).toBe(1);+ });++ it('treats a zero-task day as level 0', () => {+ expect(tileLevel(0, 10)).toBe(0);+ });++ it('clamps above the busiest day to 1', () => {+ expect(tileLevel(20, 10)).toBe(1);+ });++ it('falls back to max=1 (not divide-by-zero) for a single active day', () => {+ expect(tileLevel(3, 0)).toBe(1);+ expect(tileLevel(3, undefined)).toBe(1);+ });++ it('reads garbage / negative tasks as 0', () => {+ expect(tileLevel(undefined, 10)).toBe(0);+ expect(tileLevel(-4, 10)).toBe(0);+ expect(tileLevel('5', 10)).toBe(0);+ expect(tileLevel(NaN, 10)).toBe(0);+ });+});++describe('computeActivityHeatmap', () => {+ it('carries the anchored origin through unchanged', () => {+ const vm = computeActivityHeatmap(makeCalendar([[0, 0, 0, 0, 0, 0, 0]]));+ expect(vm.origin).toEqual(HEATMAP.origin);+ });++ it('builds one tile per non-future day with grid-aligned x/z', () => {+ const cal = makeCalendar([+ [0, 1, 2, 0, 0, 0, 0],+ [3, 0, 0, 0, 0, 0, 4],+ ]);+ const vm = computeActivityHeatmap(cal);+ expect(vm.present).toBe(true);+ expect(vm.tiles).toHaveLength(14);+ const step = HEATMAP.tileSize + HEATMAP.tileGap;+ // Week 1, day-of-week 6 (the "4-task" tile) sits at x=step, z=6*step.+ const last = vm.tiles.find((t) => t.tasks === 4);+ expect(last.x).toBeCloseTo(step);+ expect(last.z).toBeCloseTo(6 * step);+ });++ it('scales intensity by the busiest day and totals active days/tasks', () => {+ const cal = makeCalendar([[0, 2, 4, 0, 0, 0, 0]], { maxTasks: 4 });+ const vm = computeActivityHeatmap(cal);+ expect(vm.maxTasks).toBe(4);+ expect(vm.activeCount).toBe(2);+ expect(vm.totalTasks).toBe(6);+ const busiest = vm.tiles.find((t) => t.tasks === 4);+ const lighter = vm.tiles.find((t) => t.tasks === 2);+ expect(busiest.level).toBe(1);+ expect(lighter.level).toBe(0.5);+ expect(busiest.intensity).toBeGreaterThan(lighter.intensity);+ });++ it('draws empty days dim and dark, not glowing', () => {+ const vm = computeActivityHeatmap(makeCalendar([[0, 1, 0, 0, 0, 0, 0]]));+ const empty = vm.tiles.find((t) => t.tasks === 0);+ expect(empty.level).toBe(0);+ expect(empty.color).toBe('#1a2030');+ expect(empty.intensity).toBeLessThan(0.1);+ });++ it('accents today and keeps it legible even on a light day', () => {+ const cal = makeCalendar([[0, 1, 0, 0, 0, 0, 0]], { maxTasks: 10, todayIndex: 1 });+ const vm = computeActivityHeatmap(cal);+ const today = vm.tiles.find((t) => t.isToday);+ expect(today.color).toBe('#3b82f6'); // accent+ expect(today.intensity).toBeGreaterThanOrEqual(0.5);+ });++ it('skips future days in the trailing partial week', () => {+ const cal = makeCalendar([[1, 0, 0, 0, 0, 0, 0]]);+ cal.weeks[0][3].isFuture = true;+ cal.weeks[0][4].isFuture = true;+ const vm = computeActivityHeatmap(cal);+ expect(vm.tiles).toHaveLength(5); // 7 days minus 2 future+ });++ it('caps columns at maxWeeks, keeping the most recent', () => {+ const grid = Array.from({ length: 20 }, () => [1, 0, 0, 0, 0, 0, 0]);+ const vm = computeActivityHeatmap(makeCalendar(grid));+ expect(vm.weekCount).toBe(HEATMAP.maxWeeks);+ });++ it('handles missing / non-object / empty input as not-present without crashing', () => {+ for (const bad of [null, undefined, 'nope', 42, [], {}, { weeks: 'oops' }]) {+ const vm = computeActivityHeatmap(bad);+ expect(vm.present).toBe(false);+ expect(vm.tiles).toEqual([]);+ expect(vm.origin).toEqual(HEATMAP.origin);+ }+ });++ it('tolerates a non-object day or missing dayOfWeek', () => {+ const vm = computeActivityHeatmap({ weeks: [[null, { tasks: 2 }]], maxTasks: 2 });+ expect(vm.tiles).toHaveLength(2);+ // both fall back to dayOfWeek 0 → z 0+ expect(vm.tiles.every((t) => t.z === 0)).toBe(true);+ });+});diff --git a/client/src/utils/cityTaskFlowRiver.js b/client/src/utils/cityTaskFlowRiver.jsnew file mode 100644index 0000000000..4056b1a6be--- /dev/null+++ b/client/src/utils/cityTaskFlowRiver.js@@ -0,0 +1,129 @@+// Pure, deterministic helpers for CyberCity's task-flow river (roadmap 2.6 follow-up, issue+// #817): an animated flow that runs from the task-queue warehouse to the productivity+// district, visually tying queued work to completed throughput. The river's WIDTH tracks the+// live backlog (more pending/in-progress work → a broader channel) and its SPEED tracks+// recent throughput / queue drain (more recently-completed tasks relative to the backlog → a+// faster current). No three.js / React imports so the topology is unit-testable (mirrors+// cityProductivity.js / cityTaskQueue.js).++import { MONUMENT } from './cityProductivity';+import { TASK_QUEUE } from './cityTaskQueue';++export const RIVER = {+ // The channel runs warehouse → monument. Endpoints mirror the two districts it links.+ from: TASK_QUEUE.position, // task-queue warehouse (east)+ to: MONUMENT.position, // productivity-district monument (southwest)+ minWidth: 1.4, // a thin trickle when the queue is empty+ maxWidth: 7, // a broad channel at/above the backlog cap+ backlogCap: 12, // backlog count mapped to full width; beyond this stays capped+ minSpeed: 0.15, // a barely-moving current when nothing is draining+ maxSpeed: 1.6, // full-tilt flow when throughput is high+ throughputCap: 10, // recently-completed count mapped to full speed+ particleSpacing: 3.2, // world units between flow particles along the channel+};++const ACTIVE_COLOR = '#22c55e'; // port-success — work is draining (completing)+const QUEUED_COLOR = '#3b82f6'; // port-accent — backlog present, little draining+const BLOCKED_COLOR = '#f59e0b'; // port-warning — blocked work gumming up the flow+const IDLE_COLOR = '#475569'; // slate — empty channel, nothing moving++const clamp01 = (n) => Math.max(0, Math.min(1, n));++// Coerce to a finite, non-negative number or 0 — counts and throughput are never negative.+function nonNegOrZero(value) {+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;+}++// Map a backlog count to a 0..1 width level against the cap, clamped.+export function widthLevel(backlog, cap = RIVER.backlogCap) {+ const b = nonNegOrZero(backlog);+ const c = nonNegOrZero(cap) || 1;+ return clamp01(b / c);+}++// Map a recent-throughput count to a 0..1 speed level against the cap, clamped.+export function speedLevel(throughput, cap = RIVER.throughputCap) {+ const t = nonNegOrZero(throughput);+ const c = nonNegOrZero(cap) || 1;+ return clamp01(t / c);+}++// Euclidean distance on the ground plane (x/z) between the two endpoints.+function groundLength(from, to) {+ const dx = to[0] - from[0];+ const dz = to[2] - from[2];+ return Math.sqrt(dx * dx + dz * dz);+}++// Full derived view-model for the component. Inputs:+// - `taskQueue`: the `computeTaskQueue` view-model (`{ pending, inProgress, blocked, ... }`)+// — the live backlog that sets the channel width.+// - `recentThroughput`: a count of recently-completed tasks (e.g. the calendar window's+// `summary.totalTasks` or today's completed) that sets the current speed.+// Tolerates missing/garbage inputs by reading them as zero, yielding a thin, near-still,+// idle-slate channel that still renders as a quiet seam between the districts.+export function computeTaskFlowRiver(taskQueue, recentThroughput) {+ const queue = taskQueue && typeof taskQueue === 'object' ? taskQueue : {};+ const pending = nonNegOrZero(queue.pending);+ const inProgress = nonNegOrZero(queue.inProgress);+ const blocked = nonNegOrZero(queue.blocked);+ const backlog = pending + inProgress + blocked;+ const throughput = nonNegOrZero(recentThroughput);++ const wLevel = widthLevel(backlog);+ const sLevel = speedLevel(throughput);++ const width = RIVER.minWidth + wLevel * (RIVER.maxWidth - RIVER.minWidth);+ const speed = RIVER.minSpeed + sLevel * (RIVER.maxSpeed - RIVER.minSpeed);++ // Color reads the queue's dominant state, mirroring the warehouse: blocked work warns,+ // active draining flows green, a non-empty backlog sits accent-blue, an empty channel idles.+ let state;+ if (blocked > 0) state = 'blocked';+ else if (inProgress > 0) state = 'active';+ else if (pending > 0) state = 'queued';+ else state = 'idle';+ const color = state === 'blocked' ? BLOCKED_COLOR+ : state === 'active' ? ACTIVE_COLOR+ : state === 'queued' ? QUEUED_COLOR+ : IDLE_COLOR;++ const length = groundLength(RIVER.from, RIVER.to);+ // Rotation about Y so a unit segment laid along +x points from `from` toward `to`.+ const angle = Math.atan2(RIVER.to[0] - RIVER.from[0], RIVER.to[2] - RIVER.from[2]);+ const center = [+ (RIVER.from[0] + RIVER.to[0]) / 2,+ 0,+ (RIVER.from[2] + RIVER.to[2]) / 2,+ ];++ // Evenly-spaced flow particles along the channel; their count scales with length so the+ // current reads continuously regardless of how far apart the districts sit. Each carries a+ // 0..1 phase offset so the component can animate them flowing along the channel.+ const particleCount = Math.max(2, Math.round(length / RIVER.particleSpacing));+ const particles = [];+ for (let i = 0; i < particleCount; i++) {+ particles.push({ index: i, phase: i / particleCount });+ }++ return {+ from: RIVER.from,+ to: RIVER.to,+ center,+ angle,+ length,+ width,+ widthLevel: wLevel,+ speed,+ speedLevel: sLevel,+ backlog,+ pending,+ inProgress,+ blocked,+ throughput,+ state,+ color,+ flowing: state !== 'idle' && sLevel > 0,+ particles,+ };+}diff --git a/client/src/utils/cityTaskFlowRiver.test.js b/client/src/utils/cityTaskFlowRiver.test.jsnew file mode 100644index 0000000000..8aa1ee00a2--- /dev/null+++ b/client/src/utils/cityTaskFlowRiver.test.js@@ -0,0 +1,106 @@+import { describe, it, expect } from 'vitest';+import { MONUMENT } from './cityProductivity';+import { TASK_QUEUE } from './cityTaskQueue';+import {+ RIVER,+ widthLevel,+ speedLevel,+ computeTaskFlowRiver,+} from './cityTaskFlowRiver';++describe('widthLevel', () => {+ it('maps backlog/cap into 0..1', () => {+ expect(widthLevel(6, 12)).toBe(0.5);+ expect(widthLevel(12, 12)).toBe(1);+ });+ it('clamps above the cap and reads garbage as 0', () => {+ expect(widthLevel(99, 12)).toBe(1);+ expect(widthLevel(0, 12)).toBe(0);+ expect(widthLevel(undefined, 12)).toBe(0);+ expect(widthLevel(-3, 12)).toBe(0);+ });+});++describe('speedLevel', () => {+ it('maps throughput/cap into 0..1', () => {+ expect(speedLevel(5, 10)).toBe(0.5);+ expect(speedLevel(10, 10)).toBe(1);+ });+ it('clamps above the cap and reads garbage as 0', () => {+ expect(speedLevel(50, 10)).toBe(1);+ expect(speedLevel(undefined, 10)).toBe(0);+ expect(speedLevel('5', 10)).toBe(0);+ });+});++describe('computeTaskFlowRiver', () => {+ it('connects the warehouse to the monument', () => {+ const vm = computeTaskFlowRiver({ pending: 0 }, 0);+ expect(vm.from).toEqual(TASK_QUEUE.position);+ expect(vm.to).toEqual(MONUMENT.position);+ // Center is the midpoint of the two endpoints.+ expect(vm.center[0]).toBeCloseTo((TASK_QUEUE.position[0] + MONUMENT.position[0]) / 2);+ expect(vm.center[2]).toBeCloseTo((TASK_QUEUE.position[2] + MONUMENT.position[2]) / 2);+ // Length is the ground-plane distance between them.+ const dx = MONUMENT.position[0] - TASK_QUEUE.position[0];+ const dz = MONUMENT.position[2] - TASK_QUEUE.position[2];+ expect(vm.length).toBeCloseTo(Math.sqrt(dx * dx + dz * dz));+ });++ it('widens with backlog and quickens with throughput', () => {+ const empty = computeTaskFlowRiver({ pending: 0, inProgress: 0, blocked: 0 }, 0);+ const busy = computeTaskFlowRiver({ pending: 8, inProgress: 4, blocked: 0 }, 10);+ expect(busy.width).toBeGreaterThan(empty.width);+ expect(busy.speed).toBeGreaterThan(empty.speed);+ expect(busy.backlog).toBe(12);+ expect(busy.widthLevel).toBe(1); // 12 >= backlogCap+ expect(busy.speedLevel).toBe(1); // 10 >= throughputCap+ expect(busy.width).toBeCloseTo(RIVER.maxWidth);+ expect(busy.speed).toBeCloseTo(RIVER.maxSpeed);+ });++ it('floors width/speed for an empty, still channel', () => {+ const vm = computeTaskFlowRiver({ pending: 0 }, 0);+ expect(vm.width).toBeCloseTo(RIVER.minWidth);+ expect(vm.speed).toBeCloseTo(RIVER.minSpeed);+ expect(vm.flowing).toBe(false);+ expect(vm.state).toBe('idle');+ expect(vm.color).toBe('#475569');+ });++ it('colors by dominant queue state', () => {+ expect(computeTaskFlowRiver({ blocked: 1 }, 1).state).toBe('blocked');+ expect(computeTaskFlowRiver({ blocked: 1 }, 1).color).toBe('#f59e0b');+ expect(computeTaskFlowRiver({ inProgress: 2 }, 3).state).toBe('active');+ expect(computeTaskFlowRiver({ inProgress: 2 }, 3).color).toBe('#22c55e');+ expect(computeTaskFlowRiver({ pending: 2 }, 0).state).toBe('queued');+ expect(computeTaskFlowRiver({ pending: 2 }, 0).color).toBe('#3b82f6');+ });++ it('flows only when there is throughput and a non-idle state', () => {+ expect(computeTaskFlowRiver({ inProgress: 1 }, 4).flowing).toBe(true);+ // backlog present but nothing draining → not flowing+ expect(computeTaskFlowRiver({ pending: 5 }, 0).flowing).toBe(false);+ });++ it('emits evenly-phased particles scaled to channel length', () => {+ const vm = computeTaskFlowRiver({ pending: 3 }, 2);+ expect(vm.particles.length).toBeGreaterThanOrEqual(2);+ expect(vm.particles[0].phase).toBe(0);+ expect(vm.particles.every((p, i) => p.index === i)).toBe(true);+ expect(vm.particles.every((p) => p.phase >= 0 && p.phase < 1)).toBe(true);+ });++ it('handles missing / non-object inputs as an idle trickle without crashing', () => {+ for (const badQueue of [null, undefined, 'nope', 42, []]) {+ for (const badThroughput of [null, undefined, 'nope', -5, NaN]) {+ const vm = computeTaskFlowRiver(badQueue, badThroughput);+ expect(vm.state).toBe('idle');+ expect(vm.backlog).toBe(0);+ expect(vm.throughput).toBe(0);+ expect(vm.width).toBeCloseTo(RIVER.minWidth);+ expect(vm.from).toEqual(TASK_QUEUE.position);+ }+ }+ });+});