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

feat([issue-813]): aim CyberCity AI Core beams at the originating building

[._.]/ Adam Eivy612648459632
diff --git a/client/src/components/city/CityAiCore.jsx b/client/src/components/city/CityAiCore.jsx
index e327ea4662..452993f4bb 100644
--- a/client/src/components/city/CityAiCore.jsx
+++ b/client/src/components/city/CityAiCore.jsx
@@ -1,47 +1,79 @@
import { useMemo, useRef } from 'react';
+import * as THREE from 'three';
import { useFrame } from '@react-three/fiber';
import { Text } from '@react-three/drei';
import { PIXEL_FONT_URL } from './cityConstants';
-import { computeAiCore } from '../../utils/cityAiCore';
+import { computeAiCore, computeAiCoreBeams, AI_CORE } from '../../utils/cityAiCore';
// CyberCity's AI Core landmark (roadmap 2.1): a slender central spire above downtown from
// which all model activity radiates. The apex orb glows by the active model tier (cyan
// light → blue medium → violet heavy) and brightens with the number of in-flight calls;
// activity beams fan outward from the apex while AI work is happening, and a fast call
// still produces a brief flare. Idle, the core sits a dim slate. Driven by the live
-// `ai:status` op count threaded through useCityData.
+// `ai:status` ops threaded through useCityData.
//
-// `ai:status` carries no originating-building association, so beams radiate at fixed
-// angles rather than targeting a specific building (see issue follow-up).
-function Beam({ angle, length, apexY, color }) {
+// When a call originates from a managed app or CoS-agent workspace (its `ai:status` event
+// carries `appId` / `workspacePath`), its beam aims at that building's world position and
+// thickens with the call's tokens/sec; ops with no building association keep the generic
+// radial fan-out (roadmap 2.1, issue follow-up).
+
+// A radial beam: lies along +X from the apex, rotated about Y to its angle, tilted slightly
+// down so it reads as energy arcing out over the city.
+function RadialBeam({ angle, length, thickness, color }) {
const ref = useRef();
const { position, rotation } = useMemo(() => {
- // A beam lies along +X then is rotated about Y to its angle; tilt slightly downward
- // so it reads as energy arcing out over the city rather than a flat ray.
const tilt = -0.18;
return {
- position: [Math.cos(angle) * (length / 2), apexY - Math.sin(-tilt) * (length / 2), Math.sin(angle) * (length / 2)],
+ position: [Math.cos(angle) * (length / 2), -Math.sin(-tilt) * (length / 2), Math.sin(angle) * (length / 2)],
rotation: [0, -angle, tilt],
};
- }, [angle, length, apexY]);
+ }, [angle, length]);
useFrame(({ clock }) => {
if (!ref.current) return;
- // A pulse travels the beam: opacity breathes out of phase per angle so the beams
- // shimmer rather than blink in unison.
+ // A pulse travels the beam: opacity breathes out of phase per angle so beams shimmer.
const t = clock.getElapsedTime() * 3 + angle * 2;
ref.current.material.opacity = 0.25 + ((Math.sin(t) + 1) / 2) * 0.5;
});
return (
<mesh ref={ref} position={position} rotation={rotation}>
- <boxGeometry args={[length, 0.18, 0.18]} />
+ <boxGeometry args={[length, thickness, thickness]} />
<meshStandardMaterial color={color} emissive={color} emissiveIntensity={1} transparent opacity={0.4} toneMapped={false} depthWrite={false} />
</mesh>
);
}
-export default function CityAiCore({ aiActivity, settings }) {
+// A targeted beam: spans from the apex (group origin) to a building, given the apex-local
+// `target` vector. Orientation aligns the box's local +X axis with the apex→building
+// direction so a single box stretches cleanly along the line.
+function TargetedBeam({ target, thickness, color, seed }) {
+ const ref = useRef();
+ const { position, quaternion, length } = useMemo(() => {
+ const vec = new THREE.Vector3(target[0], target[1], target[2]);
+ const len = Math.max(vec.length(), 0.01);
+ const q = new THREE.Quaternion().setFromUnitVectors(
+ new THREE.Vector3(1, 0, 0),
+ vec.clone().normalize(),
+ );
+ return { position: vec.multiplyScalar(0.5).toArray(), quaternion: q, length: len };
+ }, [target]);
+
+ useFrame(({ clock }) => {
+ if (!ref.current) return;
+ const t = clock.getElapsedTime() * 3 + seed * 2;
+ ref.current.material.opacity = 0.3 + ((Math.sin(t) + 1) / 2) * 0.55;
+ });
+
+ return (
+ <mesh ref={ref} position={position} quaternion={quaternion}>
+ <boxGeometry args={[length, thickness, thickness]} />
+ <meshStandardMaterial color={color} emissive={color} emissiveIntensity={1} transparent opacity={0.45} toneMapped={false} depthWrite={false} />
+ </mesh>
+ );
+}
+
+export default function CityAiCore({ aiActivity, positions, apps, settings }) {
const core = useMemo(
() => computeAiCore(aiActivity?.ops, aiActivity?.lastStartTs ?? 0),
[aiActivity],
@@ -49,15 +81,17 @@ export default function CityAiCore({ aiActivity, settings }) {
const apexRef = useRef();
const animate = (settings?.particleDensity ?? 1) >= 0.5;
+ const { position, height, apexY, color } = core;
- // Even angular spread for however many beams are active right now.
+ // Per-op beams: targeted at the originating building when known, radial otherwise.
+ // While flaring with no live op (a fast call that already cleared) keep one radial pulse.
const beams = useMemo(() => {
- const out = [];
- for (let i = 0; i < core.beamCount; i++) {
- out.push({ angle: (i / Math.max(core.beamCount, 1)) * Math.PI * 2, key: i });
+ const computed = computeAiCoreBeams(aiActivity?.ops, positions, apps, apexY, color);
+ if (computed.length === 0 && core.flaring) {
+ return [{ key: 'flare', targeted: false, angle: 0, length: AI_CORE.radialLength, thickness: AI_CORE.beamThicknessBase, color }];
}
- return out;
- }, [core.beamCount]);
+ return computed;
+ }, [aiActivity, positions, apps, apexY, color, core.flaring]);
useFrame(({ clock }) => {
if (!animate || !apexRef.current) return;
@@ -67,9 +101,6 @@ export default function CityAiCore({ aiActivity, settings }) {
apexRef.current.material.emissiveIntensity = pulse * (core.intensity + 0.3);
});
- const { position, height, apexY, color } = core;
- const beamLength = 16;
-
return (
<group position={position}>
{/* Slender spire body — tapered so it reads as a tower, not a column */}
@@ -82,10 +113,12 @@ export default function CityAiCore({ aiActivity, settings }) {
<icosahedronGeometry args={[1.6, 1]} />
<meshStandardMaterial color={color} emissive={color} emissiveIntensity={core.intensity} toneMapped={false} />
</mesh>
- {/* Activity beams fan out from the apex while AI work is in flight */}
+ {/* Activity beams emanate from the apex while AI work is in flight */}
<group position={[0, apexY, 0]}>
- {beams.map(b => (
- <Beam key={b.key} angle={b.angle} length={beamLength} apexY={0} color={color} />
+ {beams.map((b, i) => (
+ b.targeted
+ ? <TargetedBeam key={b.key} target={b.target} thickness={b.thickness} color={b.color} seed={i} />
+ : <RadialBeam key={b.key} angle={b.angle} length={b.length} thickness={b.thickness} color={b.color} />
))}
</group>
{/* Label above the apex */}
diff --git a/client/src/components/city/CityScene.jsx b/client/src/components/city/CityScene.jsx
index 12576e4ea8..5122ec51f8 100644
--- a/client/src/components/city/CityScene.jsx
+++ b/client/src/components/city/CityScene.jsx
@@ -99,7 +99,7 @@ export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus,
<CitySeasonalDecor settings={settings} />
<CityEasterEggs character={character} goals={goals} productivityData={productivityData} settings={settings} />
<CityVoiceMarker voiceState={voiceState} settings={settings} />
- <CityAiCore aiActivity={aiActivity} settings={settings} />
+ <CityAiCore aiActivity={aiActivity} positions={positions} apps={apps} settings={settings} />
<CityGround settings={settings} />
<BuildingCluster
diff --git a/client/src/utils/cityAiCore.js b/client/src/utils/cityAiCore.js
index bceb99871d..f254e85fb7 100644
--- a/client/src/utils/cityAiCore.js
+++ b/client/src/utils/cityAiCore.js
@@ -5,9 +5,12 @@
// glow/beam state. No three.js / React imports so the logic is unit-testable (mirrors
// cityBackupVault.js).
//
-// Note: `ai:status` carries no agent/building association, so beams radiate generically
-// from the core rather than targeting the originating building — see issue note. Model
-// tier is a best-effort heuristic from the model name (the event has no explicit tier).
+// When a call originates on behalf of a managed app or CoS-agent workspace, the event
+// carries `appId` / `workspacePath`; `computeAiCoreBeams` maps that to the building's world
+// position and aims the beam there, scaling its thickness by the call's tokens/sec. Ops
+// with no building association (most PortOS-internal calls — taste summaries, embeddings)
+// keep the generic radial fan-out. Model tier is a best-effort heuristic from the model
+// name (the event has no explicit tier).
export const AI_CORE = {
position: [0, 0, 0], // city center — the spire rises above the building grid
@@ -19,6 +22,13 @@ export const AI_CORE = {
opMaxAgeMs: 60_000,
// How long after the last op start the core keeps its "just fired" flare.
flareMs: 1200,
+ // Generic (un-targeted) radial beam length, in world units.
+ radialLength: 16,
+ // Beam thickness clamps (world units). Un-measured ops use `beamThicknessBase`;
+ // measured throughput scales between base and max across `beamThicknessTopTokensPerSec`.
+ beamThicknessBase: 0.18,
+ beamThicknessMax: 0.6,
+ beamThicknessTopTokensPerSec: 200,
};
const TIER_COLORS = {
@@ -48,10 +58,18 @@ export function tierColor(tier) {
// Rank tiers so the core can pick the "loudest" active tier when several ops overlap.
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.
+function readTokensPerSec(v) {
+ const n = Number(v);
+ return Number.isFinite(n) && n >= 0 ? n : null;
+}
+
// Apply one `ai:status` event to the in-flight op map (plain object keyed by op id),
// returning a NEW object. Terminal phases remove the op; every other phase adds/updates
-// it with the event's model + a last-seen timestamp. Entries older than `opMaxAgeMs` are
-// pruned so a never-completed op can't wedge the core busy. Pure — `now` is injected.
+// it with the event's model, building association (`appId`/`workspacePath`), last-known
+// tokens/sec, and a last-seen timestamp. Entries older than `opMaxAgeMs` are pruned so a
+// never-completed op can't wedge the core busy. Pure — `now` is injected.
export function applyAiStatusEvent(ops, event, now = Date.now()) {
const next = {};
// Prune stale ops first.
@@ -64,10 +82,51 @@ export function applyAiStatusEvent(ops, event, now = Date.now()) {
delete next[id];
return next;
}
- next[id] = { id, model: event.model || null, tier: modelTier(event.model), ts: now };
+ const prev = next[id] || {};
+ next[id] = {
+ id,
+ model: event.model || prev.model || null,
+ tier: modelTier(event.model || prev.model),
+ // Association is stamped at start; carry it forward across intermediate phases even if
+ // a later event omits it.
+ appId: event.appId ?? prev.appId ?? null,
+ workspacePath: event.workspacePath ?? prev.workspacePath ?? null,
+ // Throughput typically only arrives on later phases; keep the last measured value.
+ tokensPerSec: readTokensPerSec(event.tokensPerSec) ?? prev.tokensPerSec ?? null,
+ ts: now,
+ };
return next;
}
+// 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.
+export function resolveOpAppId(op, apps = []) {
+ if (op?.appId) return op.appId;
+ const wp = op?.workspacePath;
+ if (!wp || !Array.isArray(apps)) return null;
+ let best = null;
+ let bestLen = -1;
+ for (const app of apps) {
+ if (app?.repoPath && wp.startsWith(app.repoPath) && app.repoPath.length > bestLen) {
+ best = app.id;
+ bestLen = app.repoPath.length;
+ }
+ }
+ return best;
+}
+
+// Map measured tokens/sec to a beam thickness, clamped between base and max. A null/unknown
+// throughput renders at the base thickness so an un-instrumented call still draws a beam.
+export function beamThickness(tokensPerSec) {
+ const base = AI_CORE.beamThicknessBase;
+ const max = AI_CORE.beamThicknessMax;
+ const tps = readTokensPerSec(tokensPerSec);
+ if (tps === null) return base;
+ const frac = Math.min(tps / AI_CORE.beamThicknessTopTokensPerSec, 1);
+ return base + (max - base) * frac;
+}
+
// Derive the core's view-model from the in-flight op map. `lastStartTs` (the timestamp of
// the most recent op start) drives a brief flare; `now` is injected for determinism.
export function computeAiCore(ops, lastStartTs = 0, now = Date.now()) {
@@ -95,3 +154,58 @@ export function computeAiCore(ops, lastStartTs = 0, now = Date.now()) {
intensity: busy ? 0.7 + Math.min(activeCount, 4) * 0.075 : flaring ? 0.6 : 0.25,
};
}
+
+// Build the per-beam descriptors the renderer draws from the apex. Each active op becomes
+// one beam: if it resolves to a building whose world position is known, the beam is
+// `targeted` and aims at that building (in apex-local space); otherwise it falls back to a
+// generic radial beam at an even angle. Thickness scales by the op's measured tokens/sec.
+//
+// ops — in-flight op map (from applyAiStatusEvent)
+// positions — Map<appId, { x, z }> of building world positions (CityScene's layout)
+// apps — app records (for workspacePath → app resolution)
+// apexY — world Y of the spire apex (beams originate here)
+// color — the core's active-tier color
+// now — injected for determinism
+//
+// Returns up to AI_CORE.maxBeams descriptors. Pure.
+export function computeAiCoreBeams(ops, positions, apps = [], apexY = AI_CORE.apexY, color, now = Date.now()) {
+ const active = Object.values(ops || {})
+ .filter(op => now - op.ts <= AI_CORE.opMaxAgeMs)
+ .slice(0, AI_CORE.maxBeams);
+
+ const getPos = (id) => {
+ if (!id || !positions) return null;
+ // Tolerate both a Map and a plain object so callers can pass either.
+ return typeof positions.get === 'function' ? positions.get(id) : positions[id];
+ };
+
+ // Radial fallback angles spread evenly across however many beams we draw, so a mix of
+ // targeted + radial beams still reads as a balanced fan.
+ const total = Math.max(active.length, 1);
+
+ return active.map((op, i) => {
+ const appId = resolveOpAppId(op, apps);
+ const pos = getPos(appId);
+ const thickness = beamThickness(op.tokensPerSec);
+ if (pos && Number.isFinite(pos.x) && Number.isFinite(pos.z)) {
+ // Apex-local target: building roof-ish height so the beam arcs down to the building.
+ return {
+ key: op.id,
+ targeted: true,
+ appId,
+ // Vector from the apex (group origin) to the building, in apex-local space.
+ target: [pos.x, -apexY + 4, pos.z],
+ thickness,
+ color,
+ };
+ }
+ return {
+ key: op.id,
+ targeted: false,
+ angle: (i / total) * Math.PI * 2,
+ length: AI_CORE.radialLength,
+ thickness,
+ color,
+ };
+ });
+}
diff --git a/client/src/utils/cityAiCore.test.js b/client/src/utils/cityAiCore.test.js
index b3539eca3b..2371a79cd8 100644
--- a/client/src/utils/cityAiCore.test.js
+++ b/client/src/utils/cityAiCore.test.js
@@ -5,6 +5,9 @@ import {
tierColor,
applyAiStatusEvent,
computeAiCore,
+ resolveOpAppId,
+ beamThickness,
+ computeAiCoreBeams,
} from './cityAiCore';
const NOW = 1_000_000;
@@ -140,3 +143,105 @@ describe('computeAiCore', () => {
expect(vm.beamCount).toBe(0);
});
});
+
+describe('applyAiStatusEvent building association', () => {
+ it('stamps appId / workspacePath / tokensPerSec from the event', () => {
+ const ops = applyAiStatusEvent({}, ev('a', 'start', 'gpt-4o', { appId: 'app-1', workspacePath: '/r/x', tokensPerSec: 90 }), NOW);
+ expect(ops.a.appId).toBe('app-1');
+ expect(ops.a.workspacePath).toBe('/r/x');
+ expect(ops.a.tokensPerSec).toBe(90);
+ });
+
+ it('carries association forward when a later phase omits it', () => {
+ let ops = applyAiStatusEvent({}, ev('a', 'start', 'm', { appId: 'app-1' }), NOW);
+ ops = applyAiStatusEvent(ops, ev('a', 'model:loading', 'm'), NOW + 100);
+ expect(ops.a.appId).toBe('app-1');
+ });
+
+ it('updates tokensPerSec when a later phase reports it, keeping last-known otherwise', () => {
+ let ops = applyAiStatusEvent({}, ev('a', 'start', 'm'), NOW);
+ expect(ops.a.tokensPerSec).toBeNull();
+ ops = applyAiStatusEvent(ops, ev('a', 'provider:starting', 'm', { tokensPerSec: 150 }), NOW + 10);
+ expect(ops.a.tokensPerSec).toBe(150);
+ ops = applyAiStatusEvent(ops, ev('a', 'provider:starting', 'm'), NOW + 20);
+ expect(ops.a.tokensPerSec).toBe(150); // preserved
+ });
+});
+
+describe('resolveOpAppId', () => {
+ const apps = [
+ { id: 'outer', repoPath: '/repos/proj' },
+ { id: 'inner', repoPath: '/repos/proj/packages/web' },
+ ];
+ it('prefers an explicit appId', () => {
+ expect(resolveOpAppId({ appId: 'x', workspacePath: '/repos/proj' }, apps)).toBe('x');
+ });
+ 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');
+ });
+ it('returns null when nothing matches', () => {
+ expect(resolveOpAppId({ workspacePath: '/elsewhere' }, apps)).toBeNull();
+ expect(resolveOpAppId({}, apps)).toBeNull();
+ expect(resolveOpAppId(null, apps)).toBeNull();
+ });
+});
+
+describe('beamThickness', () => {
+ it('renders base thickness for unknown / null throughput', () => {
+ expect(beamThickness(null)).toBe(AI_CORE.beamThicknessBase);
+ expect(beamThickness(undefined)).toBe(AI_CORE.beamThicknessBase);
+ expect(beamThickness('nope')).toBe(AI_CORE.beamThicknessBase);
+ });
+ it('scales toward max with throughput and clamps at the top', () => {
+ expect(beamThickness(0)).toBe(AI_CORE.beamThicknessBase);
+ expect(beamThickness(AI_CORE.beamThicknessTopTokensPerSec)).toBe(AI_CORE.beamThicknessMax);
+ expect(beamThickness(AI_CORE.beamThicknessTopTokensPerSec * 10)).toBe(AI_CORE.beamThicknessMax);
+ const mid = beamThickness(AI_CORE.beamThicknessTopTokensPerSec / 2);
+ expect(mid).toBeGreaterThan(AI_CORE.beamThicknessBase);
+ expect(mid).toBeLessThan(AI_CORE.beamThicknessMax);
+ });
+});
+
+describe('computeAiCoreBeams', () => {
+ const apps = [{ id: 'app-1', repoPath: '/repos/one' }];
+ const positions = new Map([['app-1', { x: 10, z: -6, district: 'downtown' }]]);
+
+ it('targets the building for an app-associated op (apex-local target vector)', () => {
+ const ops = { a: { id: 'a', appId: 'app-1', tokensPerSec: 200, ts: NOW } };
+ const beams = computeAiCoreBeams(ops, positions, apps, AI_CORE.apexY, '#fff', NOW);
+ expect(beams).toHaveLength(1);
+ expect(beams[0].targeted).toBe(true);
+ expect(beams[0].appId).toBe('app-1');
+ expect(beams[0].target).toEqual([10, -AI_CORE.apexY + 4, -6]);
+ expect(beams[0].thickness).toBe(AI_CORE.beamThicknessMax); // 200 tok/s → max
+ });
+
+ it('resolves a workspacePath op to its app building', () => {
+ const ops = { a: { id: 'a', workspacePath: '/repos/one/worktrees/x', ts: NOW } };
+ const beams = computeAiCoreBeams(ops, positions, apps, AI_CORE.apexY, '#fff', NOW);
+ expect(beams[0].targeted).toBe(true);
+ expect(beams[0].appId).toBe('app-1');
+ });
+
+ it('falls back to a radial beam when there is no building association', () => {
+ const ops = { a: { id: 'a', ts: NOW }, b: { id: 'b', appId: 'unknown', ts: NOW } };
+ const beams = computeAiCoreBeams(ops, positions, apps, AI_CORE.apexY, '#fff', NOW);
+ expect(beams).toHaveLength(2);
+ expect(beams.every(b => !b.targeted)).toBe(true);
+ expect(beams[0]).toMatchObject({ angle: 0, length: AI_CORE.radialLength });
+ });
+
+ it('accepts a plain-object position map and caps at maxBeams', () => {
+ const ops = {};
+ for (let i = 0; i < AI_CORE.maxBeams + 4; i++) ops[i] = { id: String(i), ts: NOW };
+ const beams = computeAiCoreBeams(ops, {}, apps, AI_CORE.apexY, '#fff', NOW);
+ expect(beams).toHaveLength(AI_CORE.maxBeams);
+ });
+
+ it('ignores stale ops past opMaxAgeMs', () => {
+ const ops = { a: { id: 'a', appId: 'app-1', ts: NOW } };
+ const beams = computeAiCoreBeams(ops, positions, apps, AI_CORE.apexY, '#fff', NOW + AI_CORE.opMaxAgeMs + 1);
+ expect(beams).toHaveLength(0);
+ });
+});
diff --git a/server/lib/aiProvider.js b/server/lib/aiProvider.js
index 3d718000b2..1e01fb5a7f 100644
--- a/server/lib/aiProvider.js
+++ b/server/lib/aiProvider.js
@@ -152,7 +152,14 @@ async function postChatCompletion(provider, model, prompt, { temperature, max_to
if (typeof content !== 'string') {
return { error: 'Provider returned a malformed (non-JSON or unexpected) response body' };
}
- return { text: content };
+ // OpenAI-compatible bodies report token counts under `usage`; surface the completion
+ // token count so the AI Core landmark can size its activity beam by output volume
+ // (tokens/sec). Absent on some providers — callers treat a missing count as "unknown".
+ const completionTokens = Number(data.usage?.completion_tokens);
+ return {
+ text: content,
+ tokens: Number.isFinite(completionTokens) ? completionTokens : undefined,
+ };
}
/**
@@ -168,9 +175,15 @@ async function postChatCompletion(provider, model, prompt, { temperature, max_to
* Pass `op` + `opLabel` to surface live status toasts in the UI via the
* `ai:status` Socket.IO channel. The op slug groups all phase events under
* one toast id so "loading model → calling → done" updates the same toast.
+ *
+ * Pass `appId` and/or `workspacePath` when the call originates on behalf of a
+ * managed app or CoS-agent workspace — the CyberCity AI Core aims its activity
+ * beam at that building (falling back to a generic radial beam when neither is
+ * supplied). Output token counts from the provider are reported on completion
+ * so the beam's thickness can track tokens/sec.
*/
export async function callProviderAISimple(provider, model, prompt, options = {}) {
- const { temperature = 0.3, max_tokens = 1000, op, opLabel } = options;
+ const { temperature = 0.3, max_tokens = 1000, op, opLabel, appId, workspacePath } = options;
if (provider.type !== 'api') {
return { error: 'This operation requires an API-based provider' };
}
@@ -187,12 +200,22 @@ export async function callProviderAISimple(provider, model, prompt, options = {}
providerId: provider.id,
providerName: provider.name,
model,
+ appId,
+ workspacePath,
silent: !op
});
const doneLabel = effectiveLabel.replace(/…$/, '');
const startMs = Date.now();
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.
+ const throughput = (tokens) => {
+ if (!Number.isFinite(tokens)) return {};
+ const secs = Math.max((Date.now() - startMs) / 1000, 0.001);
+ return { tokens, tokensPerSec: Math.round(tokens / secs) };
+ };
if (isOllamaProvider(provider)) {
statusOp.update('provider:starting', 'Starting Ollama if needed…', { providerId: provider.id });
@@ -206,7 +229,7 @@ export async function callProviderAISimple(provider, model, prompt, options = {}
const first = await postChatCompletion(provider, model, prompt, opts);
if (!first.error) {
- statusOp.complete(`${doneLabel} done (${elapsedSec()}s)`);
+ statusOp.complete(`${doneLabel} done (${elapsedSec()}s)`, throughput(first.tokens));
return { text: first.text };
}
@@ -216,7 +239,7 @@ export async function callProviderAISimple(provider, model, prompt, options = {}
statusOp.update('start', `Calling ${provider.name || provider.id} (${loaded})…`, { model: loaded });
const retry = await postChatCompletion(provider, loaded, prompt, opts);
if (!retry.error) {
- statusOp.complete(`${doneLabel} done (${elapsedSec()}s)`, { model: loaded });
+ statusOp.complete(`${doneLabel} done (${elapsedSec()}s)`, { model: loaded, ...throughput(retry.tokens) });
return { text: retry.text };
}
statusOp.error(retry.error, { model: loaded });
diff --git a/server/services/aiStatusEvents.js b/server/services/aiStatusEvents.js
index 5b76f6775c..fdca2b0411 100644
--- a/server/services/aiStatusEvents.js
+++ b/server/services/aiStatusEvents.js
@@ -38,6 +38,12 @@ const ICONS = {
* @param {string} [init.providerId]
* @param {string} [init.providerName]
* @param {string} [init.model]
+ * @param {string} [init.appId] — managed-app id this call works on behalf of
+ * @param {string} [init.workspacePath] — CoS-agent workspace this call works on behalf of
+ *
+ * `appId`/`workspacePath` let the CyberCity AI Core aim its activity beam at the
+ * originating building; ops with neither get the generic radial beam. Token counts
+ * (`tokens` / `tokensPerSec`) arrive later via the `complete` phase's `extra`.
*/
export function startAIOp(init) {
const id = randomUUID();
@@ -48,6 +54,8 @@ export function startAIOp(init) {
providerId: init.providerId,
providerName: init.providerName,
model: init.model,
+ appId: init.appId,
+ workspacePath: init.workspacePath,
silent: !!init.silent
};
diff --git a/server/services/aiStatusEvents.test.js b/server/services/aiStatusEvents.test.js
new file mode 100644
index 0000000000..d0984b62ca
--- /dev/null
+++ b/server/services/aiStatusEvents.test.js
@@ -0,0 +1,56 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { aiStatusEvents, startAIOp } from './aiStatusEvents.js';
+
+// Capture every emitted status event so we can assert which fields cross the
+// `ai:status` channel that the CyberCity AI Core landmark consumes.
+function captureEvents(fn) {
+ const events = [];
+ const handler = (e) => events.push(e);
+ aiStatusEvents.on('status', handler);
+ fn();
+ aiStatusEvents.off('status', handler);
+ return events;
+}
+
+describe('startAIOp building-association fields', () => {
+ it('propagates appId + workspacePath onto every phase event', () => {
+ const events = captureEvents(() => {
+ const op = startAIOp({
+ op: 'task-gen',
+ label: 'Generating tasks',
+ appId: 'app-42',
+ workspacePath: '/repos/widget',
+ });
+ op.update('model:loading', 'Loading…');
+ op.complete('Done');
+ });
+
+ expect(events).toHaveLength(3);
+ for (const e of events) {
+ expect(e.appId).toBe('app-42');
+ expect(e.workspacePath).toBe('/repos/widget');
+ }
+ expect(events.map(e => e.phase)).toEqual(['start', 'model:loading', 'complete']);
+ });
+
+ it('leaves appId/workspacePath undefined for unassociated internal ops', () => {
+ const [start] = captureEvents(() => {
+ startAIOp({ op: 'taste-summary', label: 'Summarizing taste' });
+ });
+ expect(start.appId).toBeUndefined();
+ expect(start.workspacePath).toBeUndefined();
+ });
+
+ it('carries token throughput on the completion event', () => {
+ const events = captureEvents(() => {
+ const op = startAIOp({ op: 'jira-report', label: 'Report', appId: 'app-1' });
+ op.complete('Done', { tokens: 480, tokensPerSec: 120 });
+ });
+ const complete = events.find(e => e.phase === 'complete');
+ expect(complete.tokens).toBe(480);
+ expect(complete.tokensPerSec).toBe(120);
+ // The start event has no token info yet.
+ const start = events.find(e => e.phase === 'start');
+ expect(start.tokens).toBeUndefined();
+ });
+});