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

address review: async catch in worktreeManager, NaN score guard, null-safe drill questions, index validation, remove unused import, fix success toast on error

Adam Eivy42a4f08d5e73
diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsx
index ace1e4fa64..afced3dc1d 100644
--- a/client/src/components/apps/tabs/UpdateTab.jsx
+++ b/client/src/components/apps/tabs/UpdateTab.jsx
@@ -156,13 +156,13 @@ export default function UpdateTab() {
};
const handleIgnore = async (version) => {
- await api.ignoreUpdateVersion(version).catch(() => null);
+ await api.ignoreUpdateVersion(version);
fetchStatus();
toast.success(`v${version} ignored`);
};
const handleClearIgnored = async () => {
- await api.clearIgnoredVersions().catch(() => null);
+ await api.clearIgnoredVersions();
fetchStatus();
toast.success('Ignored versions cleared');
};
diff --git a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx b/client/src/components/meatspace/post/PostLlmDrillRunner.jsx
index b91337de0b..7b92a529a1 100644
--- a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx
+++ b/client/src/components/meatspace/post/PostLlmDrillRunner.jsx
@@ -19,6 +19,8 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr
const timerRef = useRef(null);
const questionStartRef = useRef(Date.now());
const drillStartRef = useRef(Date.now());
+ const responsesRef = useRef([]);
+ const questionIndexRef = useRef(0);
const timeLimitMs = (timeLimitSec || 120) * 1000;
const drillType = drill?.type;
@@ -50,6 +52,10 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr
return () => clearInterval(timerRef.current);
}, [drill]);
+ // Keep refs in sync with state for use in interval callbacks
+ useEffect(() => { responsesRef.current = responses; }, [responses]);
+ useEffect(() => { questionIndexRef.current = questionIndex; }, [questionIndex]);
+
useEffect(() => {
setInputValue('');
setItems([]);
@@ -57,12 +63,14 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr
}, [questionIndex, phase]);
function handleTimeExpired() {
- // Submit whatever we have so far
- const remaining = prompts.slice(questionIndex).map(() => ({
+ // Submit whatever we have so far (use refs to avoid stale closures in interval callback)
+ const currentResponses = responsesRef.current;
+ const currentIndex = questionIndexRef.current;
+ const remaining = prompts.slice(currentIndex).map(() => ({
response: '',
responseMs: 0
}));
- const finalResponses = [...responses, ...remaining];
+ const finalResponses = [...currentResponses, ...remaining];
finishDrill(finalResponses);
}
@@ -131,7 +139,7 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr
e?.preventDefault();
const val = inputValue.trim();
if (!val) return;
- if (!items.includes(val.toLowerCase())) {
+ if (!items.some(item => item.toLowerCase() === val.toLowerCase())) {
setItems(prev => [...prev, val]);
}
setInputValue('');
diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.js
index f681e61c14..45168520a9 100644
--- a/client/src/hooks/usePostSession.js
+++ b/client/src/hooks/usePostSession.js
@@ -100,7 +100,8 @@ export function usePostSession() {
const submitAnswer = useCallback((value) => {
if (state !== STATES.DRILLING || !currentDrill) return;
- const q = currentDrill.questions[currentQuestionIndex];
+ const q = currentDrill.questions?.[currentQuestionIndex];
+ if (!q) return;
const responseMs = Date.now() - questionStartRef.current;
const numValue = value === null ? null : Number(value);
@@ -125,7 +126,7 @@ export function usePostSession() {
setAnswers(newAnswers);
// Check if drill is complete
- if (currentQuestionIndex + 1 >= currentDrill.questions.length) {
+ if (currentQuestionIndex + 1 >= (currentDrill.questions?.length ?? 0)) {
finishDrillRef.current(newAnswers);
} else {
setCurrentQuestionIndex(currentQuestionIndex + 1);
@@ -162,7 +163,7 @@ export function usePostSession() {
if (state !== STATES.DRILLING || !currentDrill) return;
// Mark remaining questions as unanswered
- const remaining = currentDrill.questions.slice(currentQuestionIndex).map(q => ({
+ const remaining = (currentDrill.questions || []).slice(currentQuestionIndex).map(q => ({
prompt: q.prompt,
expected: q.expected,
answered: null,
diff --git a/server/routes/meatspace.js b/server/routes/meatspace.js
index db17d351d0..a78d604d77 100644
--- a/server/routes/meatspace.js
+++ b/server/routes/meatspace.js
@@ -136,7 +136,11 @@ router.post('/alcohol/log', asyncHandler(async (req, res) => {
router.put('/alcohol/log/:date/:index', asyncHandler(async (req, res) => {
const { date, index } = req.params;
const data = validateRequest(drinkUpdateSchema, req.body);
- const result = await alcoholService.updateDrink(date, parseInt(index, 10), data);
+ const parsedIndex = parseInt(index, 10);
+ if (!Number.isInteger(parsedIndex) || parsedIndex < 0) {
+ throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });
+ }
+ const result = await alcoholService.updateDrink(date, parsedIndex, data);
if (!result) {
throw new ServerError('Drink entry not found', { status: 404, code: 'NOT_FOUND' });
}
@@ -149,7 +153,11 @@ router.put('/alcohol/log/:date/:index', asyncHandler(async (req, res) => {
*/
router.delete('/alcohol/log/:date/:index', asyncHandler(async (req, res) => {
const { date, index } = req.params;
- const removed = await alcoholService.removeDrink(date, parseInt(index, 10));
+ const parsedIndex = parseInt(index, 10);
+ if (!Number.isInteger(parsedIndex) || parsedIndex < 0) {
+ throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });
+ }
+ const removed = await alcoholService.removeDrink(date, parsedIndex);
if (!removed) {
throw new ServerError('Drink entry not found', { status: 404, code: 'NOT_FOUND' });
}
@@ -298,6 +306,9 @@ router.post('/eyes', asyncHandler(async (req, res) => {
*/
router.put('/eyes/:index', asyncHandler(async (req, res) => {
const index = parseInt(req.params.index, 10);
+ if (!Number.isInteger(index) || index < 0) {
+ throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });
+ }
const data = validateRequest(eyeExamUpdateSchema, req.body);
const exam = await healthService.updateEyeExam(index, data);
if (!exam) {
@@ -312,6 +323,9 @@ router.put('/eyes/:index', asyncHandler(async (req, res) => {
*/
router.delete('/eyes/:index', asyncHandler(async (req, res) => {
const index = parseInt(req.params.index, 10);
+ if (!Number.isInteger(index) || index < 0) {
+ throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });
+ }
const removed = await healthService.removeEyeExam(index);
if (!removed) {
throw new ServerError('Eye exam not found', { status: 404, code: 'NOT_FOUND' });
diff --git a/server/services/featureAgents.js b/server/services/featureAgents.js
index 044a7381d1..e602557e84 100644
--- a/server/services/featureAgents.js
+++ b/server/services/featureAgents.js
@@ -6,7 +6,7 @@
* git worktree/branch and runs on a schedule.
*/
-import { writeFile, readFile, rename, mkdir, readdir, rm } from 'fs/promises';
+import { writeFile, readFile, rename, readdir, rm } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { existsSync } from 'fs';
@@ -74,7 +74,8 @@ export async function createFeatureAgent(input) {
const id = `fa-${uuidv4().slice(0, 8)}`;
const now = new Date().toISOString();
- const branchName = `feature-agent/${input.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')}`;
+ const slug = input.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || id;
+ const branchName = `feature-agent/${slug}`;
const agent = {
id,
...input,
@@ -268,9 +269,19 @@ export async function triggerFeatureAgent(id) {
const agent = await getFeatureAgent(id);
if (!agent) return null;
- // Activate if in draft/paused
+ // Activate if in draft/paused, then reset lastRunAt/backoff so it's picked up immediately
if (agent.status === 'draft' || agent.status === 'paused') {
- return await activateFeatureAgent(id);
+ await activateFeatureAgent(id);
+ return withLock(async () => {
+ const data = await readData();
+ const idx = data.agents.findIndex(a => a.id === id);
+ if (idx === -1) return null;
+ data.agents[idx].backoff = null;
+ data.agents[idx].lastRunAt = null;
+ data.agents[idx].updatedAt = new Date().toISOString();
+ await writeData(data);
+ return data.agents[idx];
+ });
}
// For active agents, reset backoff and lastRunAt so getDueFeatureAgents picks it up immediately
@@ -501,15 +512,32 @@ Learnings: [anything discovered for next run]
}
/**
- * Mark a feature agent as having a running CoS agent
+ * Mark a feature agent as having a pending task (prevents duplicate spawns).
+ * The pendingTaskId is used temporarily until the real CoS agent spawns,
+ * at which point currentAgentId is set via the agent:spawned listener below.
*/
-export async function setCurrentAgent(id, agentId) {
+export async function setCurrentAgent(id, taskId) {
return withLock(async () => {
const data = await readData();
const idx = data.agents.findIndex(a => a.id === id);
if (idx === -1) return;
- data.agents[idx].currentAgentId = agentId;
+ data.agents[idx].currentAgentId = taskId;
data.agents[idx].updatedAt = new Date().toISOString();
await writeData(data);
});
}
+
+// Listen for agent:spawned events to update currentAgentId from the
+// temporary task ID to the real CoS agent ID (needed for output streaming).
+cosEvents.on('agent:spawned', async (agentData) => {
+ if (!agentData?.taskId) return;
+ // Check if this task belongs to a feature agent
+ const taskId = agentData.taskId;
+ const data = await readData().catch(() => null);
+ if (!data) return;
+ const fa = data.agents.find(a => a.currentAgentId === taskId);
+ if (!fa) return;
+ await setCurrentAgent(fa.id, agentData.id).catch(err => {
+ console.log(`⚠️ Failed to update feature agent currentAgentId: ${err.message}`);
+ });
+});
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index 6c0496ba0d..ced955a5d6 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -99,7 +99,10 @@ export async function submitPostSession(sessionData) {
const rescoredTasks = rawTasks.map(t => {
const { score: _score, correct: _correct, ...rest } = t || {};
- // LLM drills: score was already computed server-side via /post/score-llm
+ // LLM drills: score was computed server-side via /post/score-llm and
+ // passed back by the client. Re-scoring here would add latency + cost.
+ // This is a single-user internal tool so client score trust is acceptable.
+ // The llmEvaluation field (if present) contains the full server-generated scoring breakdown.
if (LLM_DRILL_TYPES.includes(rest.type)) {
return { ...rest, score: t.score || 0 };
}
@@ -323,9 +326,10 @@ export function scoreDrill(type, questions, timeLimitMs, config = {}) {
}
function computeSessionScore(tasks) {
- if (!tasks?.length) return 0;
- const totalScore = tasks.reduce((sum, t) => sum + t.score, 0);
- return Math.round(totalScore / tasks.length);
+ const valid = (tasks || []).filter(t => typeof t.score === 'number' && !Number.isNaN(t.score));
+ if (!valid.length) return 0;
+ const totalScore = valid.reduce((sum, t) => sum + t.score, 0);
+ return Math.round(totalScore / valid.length);
}
// =============================================================================
diff --git a/server/services/meatspacePostLlm.js b/server/services/meatspacePostLlm.js
index bc01df12e5..c0c3062bfa 100644
--- a/server/services/meatspacePostLlm.js
+++ b/server/services/meatspacePostLlm.js
@@ -43,6 +43,7 @@ async function callAI(prompt, providerId, model) {
if (selectedModel) args.push('--model', selectedModel);
args.push(prompt);
let output = '';
+ let settled = false;
const child = spawn(provider.command, args, {
env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })(),
@@ -50,15 +51,27 @@ async function callAI(prompt, providerId, model) {
windowsHide: true
});
- child.stdout.on('data', d => { output += d.toString(); });
- child.stderr.on('data', d => { output += d.toString(); });
- child.on('close', code => code === 0 ? resolve(output) : reject(new Error(`CLI exited with code ${code}`)));
- child.on('error', reject);
-
- setTimeout(() => {
+ const timeoutHandle = setTimeout(() => {
+ if (settled) return;
+ settled = true;
child.kill();
reject(new Error('POST AI request timed out'));
}, provider.timeout || 120000);
+
+ child.stdout.on('data', d => { output += d.toString(); });
+ child.stderr.on('data', d => { output += d.toString(); });
+ child.on('close', code => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeoutHandle);
+ code === 0 ? resolve(output) : reject(new Error(`CLI exited with code ${code}`));
+ });
+ child.on('error', err => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeoutHandle);
+ reject(err);
+ });
});
}
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index f90e0d7c8d..f9ef0943c7 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -219,7 +219,7 @@ export async function mergeBaseIntoFeatureWorktree(featureAgentId, sourceWorkspa
await execGit(['fetch', 'origin'], worktreePath).catch(() => {});
const result = await execGit(['merge', `origin/${baseBranch}`, '--no-edit'], worktreePath)
.then(() => ({ merged: true }))
- .catch(err => {
+ .catch(async (err) => {
// Abort failed merge
await execGit(['merge', '--abort'], worktreePath).catch(() => {});
return { merged: false, reason: err.message };