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([issue-813]): address review (claude+codex)

[._.]/ Adam Eivyb6dd27c84ba9
diff --git a/client/src/hooks/useCityData.js b/client/src/hooks/useCityData.js
index 6d58139d2d..cd5413ddb1 100644
--- a/client/src/hooks/useCityData.js
+++ b/client/src/hooks/useCityData.js
@@ -3,7 +3,7 @@ import * as api from '../services/api';
import socket from '../services/socket';
import { useAutoRefetch } from './useAutoRefetch';
import { METRICS as HEALTH_TOWER_METRICS } from '../utils/cityHealthTower';
-import { applyAiStatusEvent } from '../utils/cityAiCore';
+import { applyAiStatusEvent, pruneAiOps, AI_CORE } from '../utils/cityAiCore';
import { coalesce } from '../utils/coalesce';
// Metric keys the vitals-tower landmark renders — fetched as the latest-value snapshot.
@@ -37,6 +37,10 @@ export const useCityData = () => {
const [aiActivity, setAiActivity] = useState({ ops: {}, lastStartTs: 0 });
const [loading, setLoading] = useState(true);
const logIdRef = useRef(0);
+ // One-shot timer that prunes expired AI Core ops. `ai:status` is purely event-driven, so
+ // without this a `done` afterglow (or a flare) beam would linger until the next event —
+ // the render derivations check the clock but nothing re-renders to advance it.
+ const aiPruneTimerRef = useRef(null);
const fetchApps = useCallback(async () => {
const data = await api.getApps().catch(() => []);
@@ -251,10 +255,31 @@ export const useCityData = () => {
// (start → model:loading → model:loaded → complete/error) globally. Track the in-flight
// set so the central spire glows/beams with live model activity; the pure reducer adds
// on non-terminal phases, drops on complete/error, and prunes stale ops.
- const handleAiStatus = (event) => setAiActivity(prev => ({
- ops: applyAiStatusEvent(prev.ops, event),
- lastStartTs: event?.phase === 'start' ? Date.now() : prev.lastStartTs,
- }));
+ // Prune expired ops and re-arm while any remain, so a `done` afterglow beam fades after
+ // afterglowMs and a stranded in-flight op clears at opMaxAgeMs — without depending on a
+ // further `ai:status` event to advance the clock. Tick at the afterglow cadence (the
+ // shorter window); pruneAiOps returns the same ref when nothing expired, short-circuiting
+ // the setState to no re-render.
+ const scheduleAiPrune = () => {
+ if (aiPruneTimerRef.current) clearTimeout(aiPruneTimerRef.current);
+ aiPruneTimerRef.current = setTimeout(() => {
+ let remaining = 0;
+ setAiActivity(prev => {
+ const ops = pruneAiOps(prev.ops);
+ remaining = Object.keys(ops).length;
+ return ops === prev.ops ? prev : { ...prev, ops };
+ });
+ if (remaining > 0) scheduleAiPrune();
+ }, AI_CORE.afterglowMs + 100);
+ };
+
+ const handleAiStatus = (event) => {
+ setAiActivity(prev => ({
+ ops: applyAiStatusEvent(prev.ops, event),
+ lastStartTs: event?.phase === 'start' ? Date.now() : prev.lastStartTs,
+ }));
+ scheduleAiPrune();
+ };
socket.on('ai:status', handleAiStatus);
// Subscribe but do NOT unsubscribe on cleanup. The cos:* and notifications:*
@@ -279,6 +304,7 @@ export const useCityData = () => {
socket.off('voice:error', handleVoiceError);
socket.off('voice:idle', handleVoiceIdle);
socket.off('ai:status', handleAiStatus);
+ if (aiPruneTimerRef.current) clearTimeout(aiPruneTimerRef.current);
coalescedFetchAll.cancel(); // drop any pending trailing refetch on unmount
};
}, [fetchAll, fetchApps, fetchBackup, coalescedFetchAll]);
diff --git a/client/src/utils/cityAiCore.js b/client/src/utils/cityAiCore.js
index 3a28817468..80cf424149 100644
--- a/client/src/utils/cityAiCore.js
+++ b/client/src/utils/cityAiCore.js
@@ -64,10 +64,11 @@ export function tierColor(tier) {
const TIER_RANK = { light: 1, medium: 2, heavy: 3 };
// Coerce a finite, non-negative tokens/sec from an event; otherwise null ("unknown").
-// Keeps "the provider didn't report usage" distinct from a measured zero.
+// Keeps "the provider didn't report usage" distinct from a measured zero. Only an actual
+// number counts — `null`/`undefined`/`''` (which `Number()` would coerce to 0/NaN) are
+// "unknown", per the sentinel-vs-empty convention.
function readTokensPerSec(v) {
- const n = Number(v);
- return Number.isFinite(n) && n >= 0 ? n : null;
+ return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : null;
}
// True while an op should still draw a beam: in flight (within opMaxAgeMs), or just
@@ -122,9 +123,31 @@ export function applyAiStatusEvent(ops, event, now = Date.now()) {
return next;
}
+// True when `child` is `parent` itself or a path nested under it — a boundary-aware check so
+// `/repos/app` does NOT match the sibling `/repos/app-other`. Compares on a trailing-slash
+// normalized form. Pure.
+function isPathUnder(child, parent) {
+ if (!child || !parent) return false;
+ if (child === parent) return true;
+ const base = parent.endsWith('/') ? parent : `${parent}/`;
+ return child.startsWith(base);
+}
+
+// Drop every op past its window (in-flight or afterglow). Returns the SAME reference when
+// nothing changed so callers can skip a no-op state update; otherwise a new pruned object.
+// Used by a one-shot timer so a `done`/flare beam fades on schedule even when no further
+// `ai:status` event arrives to trigger the reducer. Pure.
+export function pruneAiOps(ops, now = Date.now()) {
+ const entries = Object.entries(ops || {});
+ const kept = entries.filter(([, op]) => opWithinWindow(op, now));
+ if (kept.length === entries.length) return ops;
+ return Object.fromEntries(kept);
+}
+
// Map an op's building association to an app id. Prefers an explicit `appId`; otherwise
-// matches the longest `repoPath` prefix of the op's `workspacePath` (a CoS-agent worktree
-// lives under its app's repo). Returns null when nothing matches. Pure.
+// matches the app whose `repoPath` is the longest path-boundary prefix of the op's
+// `workspacePath` (a CoS-agent worktree lives under its app's repo). Returns null when
+// nothing matches. Pure.
export function resolveOpAppId(op, apps = []) {
if (op?.appId) return op.appId;
const wp = op?.workspacePath;
@@ -132,7 +155,7 @@ export function resolveOpAppId(op, apps = []) {
let best = null;
let bestLen = -1;
for (const app of apps) {
- if (app?.repoPath && wp.startsWith(app.repoPath) && app.repoPath.length > bestLen) {
+ if (app?.repoPath && isPathUnder(wp, app.repoPath) && app.repoPath.length > bestLen) {
best = app.id;
bestLen = app.repoPath.length;
}
diff --git a/client/src/utils/cityAiCore.test.js b/client/src/utils/cityAiCore.test.js
index cc558eed33..fe9391f7ff 100644
--- a/client/src/utils/cityAiCore.test.js
+++ b/client/src/utils/cityAiCore.test.js
@@ -8,6 +8,7 @@ import {
resolveOpAppId,
beamThickness,
computeAiCoreBeams,
+ pruneAiOps,
} from './cityAiCore';
const NOW = 1_000_000;
@@ -201,6 +202,11 @@ describe('resolveOpAppId', () => {
it('matches the longest repoPath prefix of workspacePath', () => {
expect(resolveOpAppId({ workspacePath: '/repos/proj/packages/web/src' }, apps)).toBe('inner');
expect(resolveOpAppId({ workspacePath: '/repos/proj/docs' }, apps)).toBe('outer');
+ expect(resolveOpAppId({ workspacePath: '/repos/proj' }, apps)).toBe('outer'); // exact match
+ });
+ it('does not match a sibling path that merely shares a prefix', () => {
+ // /repos/proj-other is NOT under /repos/proj — boundary-aware, not raw startsWith.
+ expect(resolveOpAppId({ workspacePath: '/repos/proj-other/src' }, apps)).toBeNull();
});
it('returns null when nothing matches', () => {
expect(resolveOpAppId({ workspacePath: '/elsewhere' }, apps)).toBeNull();
@@ -209,6 +215,41 @@ describe('resolveOpAppId', () => {
});
});
+describe('readTokensPerSec sentinel (via afterglow retention)', () => {
+ it('treats null / empty-string throughput as unknown, not a measured zero', () => {
+ // A terminal event with no real throughput must drop the op (unknown), not keep it as
+ // a zero-throughput afterglow.
+ let ops = applyAiStatusEvent({}, ev('a', 'start', 'm'), NOW);
+ ops = applyAiStatusEvent(ops, ev('a', 'complete', 'm', { tokensPerSec: null }), NOW + 1);
+ expect(Object.keys(ops)).toEqual([]);
+ ops = applyAiStatusEvent({}, ev('b', 'start', 'm'), NOW);
+ ops = applyAiStatusEvent(ops, ev('b', 'complete', 'm', { tokensPerSec: '' }), NOW + 1);
+ expect(Object.keys(ops)).toEqual([]);
+ });
+ it('keeps a genuine zero-throughput afterglow distinct from unknown', () => {
+ let ops = applyAiStatusEvent({}, ev('a', 'start', 'm'), NOW);
+ ops = applyAiStatusEvent(ops, ev('a', 'complete', 'm', { tokensPerSec: 0 }), NOW + 1);
+ expect(ops.a?.done).toBe(true);
+ expect(ops.a.tokensPerSec).toBe(0);
+ });
+});
+
+describe('pruneAiOps', () => {
+ it('returns the same reference when nothing expired', () => {
+ const ops = { a: { id: 'a', ts: NOW } };
+ expect(pruneAiOps(ops, NOW)).toBe(ops);
+ });
+ it('drops expired in-flight and afterglow ops', () => {
+ const ops = {
+ live: { id: 'live', ts: NOW },
+ stale: { id: 'stale', ts: NOW - AI_CORE.opMaxAgeMs - 1 },
+ glow: { id: 'glow', done: true, ts: NOW - AI_CORE.afterglowMs - 1 },
+ };
+ const pruned = pruneAiOps(ops, NOW);
+ expect(Object.keys(pruned)).toEqual(['live']);
+ });
+});
+
describe('beamThickness', () => {
it('renders base thickness for unknown / null throughput', () => {
expect(beamThickness(null)).toBe(AI_CORE.beamThicknessBase);
diff --git a/server/lib/aiProvider.js b/server/lib/aiProvider.js
index 1e01fb5a7f..8359ab6ba0 100644
--- a/server/lib/aiProvider.js
+++ b/server/lib/aiProvider.js
@@ -210,7 +210,9 @@ export async function callProviderAISimple(provider, model, prompt, options = {}
const elapsedSec = () => ((Date.now() - startMs) / 1000).toFixed(1);
// Token-throughput extras for the completion event — `tokensPerSec` powers the AI Core
// beam thickness. Omitted entirely when the provider didn't report token usage so the
- // client can distinguish "unknown" from a real zero.
+ // client can distinguish "unknown" from a real zero. This is a coarse end-to-end rate
+ // (elapsed since the op started, so on the model-load / LM-Studio-retry paths it folds in
+ // load + retry time and reads slightly low) — adequate for a relative beam-width cue.
const throughput = (tokens) => {
if (!Number.isFinite(tokens)) return {};
const secs = Math.max((Date.now() - startMs) / 1000, 0.001);
diff --git a/server/services/jiraReports.js b/server/services/jiraReports.js
index fae8e56940..861a84c8e5 100644
--- a/server/services/jiraReports.js
+++ b/server/services/jiraReports.js
@@ -80,7 +80,7 @@ function ticketSummary(ticket, extraFields = []) {
* with ticket keys inline so the UI can link them.
* Falls back to a plain bullet list if AI is unavailable.
*/
-async function generateNarrativeSummary(appName, completed, inProgress, blocked, todo) {
+async function generateNarrativeSummary(appName, completed, inProgress, blocked, todo, appId) {
const sections = [];
if (completed.length > 0) {
sections.push(`COMPLETED (last 7 days):\n${completed.map(t => `- ${t.key}: ${t.summary}`).join('\n')}`);
@@ -135,7 +135,10 @@ ${ticketData}`;
for (const provider of candidates) {
const aiResult = await callProviderAISimple(provider, provider.lightModel || provider.defaultModel, prompt, {
temperature: 0.3,
- max_tokens: 1500
+ max_tokens: 1500,
+ // Associate this call with the app it's reporting on so the CyberCity AI Core aims
+ // its activity beam at that building.
+ appId
}).catch(err => ({ error: err.message }));
if (!aiResult.error) return aiResult.text.trim();
@@ -202,7 +205,7 @@ export async function generateReport(appId, app) {
t.status?.toLowerCase().includes('block') ||
(t.priority === 'Highest' && t.statusCategory === 'To Do')
);
- const statusSummary = await generateNarrativeSummary(app.name, recentlyCompleted, inProgress, blocked, todo);
+ const statusSummary = await generateNarrativeSummary(app.name, recentlyCompleted, inProgress, blocked, todo, appId);
const report = {
appId,