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: crash and hang guards — async timer callbacks, fetch timeouts, SSE write guard

[._.]/ Adam Eivy4c538463997b
diff --git a/server/lib/aiToolkit/internal/antigravity.js b/server/lib/aiToolkit/internal/antigravity.js
new file mode 100644
index 0000000000..cd1b9aa2c6
--- /dev/null
+++ b/server/lib/aiToolkit/internal/antigravity.js
@@ -0,0 +1,59 @@
+/**
+ * Antigravity provider constants and argument helpers for the aiToolkit.
+ *
+ * Duplicated from server/lib/antigravity.js so the toolkit stays self-contained
+ * (no imports out to sibling PortOS modules). Keep in sync with upstream.
+ */
+
+export const ANTIGRAVITY_CLI_ID = 'antigravity-cli';
+export const ANTIGRAVITY_TUI_ID = 'antigravity-tui';
+export const LEGACY_GEMINI_CLI_ID = 'gemini-cli';
+export const LEGACY_GEMINI_TUI_ID = 'gemini-tui';
+export const ANTIGRAVITY_CONFIGURED_DEFAULT = 'antigravity-configured-default';
+
+export function isAntigravityCommand(command) {
+ return command === 'agy' || command === 'antigravity';
+}
+
+export function isAntigravityCliProvider(provider) {
+ return provider?.id === ANTIGRAVITY_CLI_ID || isAntigravityCommand(provider?.command);
+}
+
+export function stripAntigravityUnsupportedArgs(args = []) {
+ const out = [];
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--yolo') continue;
+ if (arg === '--model' || arg === '-m' || arg === '--output-format' || arg === '-o') {
+ i += 1;
+ continue;
+ }
+ if (
+ typeof arg === 'string'
+ && (arg.startsWith('--model=') || arg.startsWith('-m=') || arg.startsWith('--output-format=') || arg.startsWith('-o='))
+ ) {
+ continue;
+ }
+ out.push(arg);
+ }
+ return out;
+}
+
+export function ensureAntigravityPrintArgs(args = []) {
+ const out = stripAntigravityUnsupportedArgs(args);
+ if (!out.some((arg) => arg === '--print' || arg === '-p' || arg === '--prompt')) {
+ out.unshift('--print');
+ }
+ if (!out.includes('--dangerously-skip-permissions') && !out.includes('--sandbox')) {
+ out.push('--dangerously-skip-permissions');
+ }
+ return out;
+}
+
+export function ensureAntigravityTuiArgs(args = []) {
+ const out = stripAntigravityUnsupportedArgs(args);
+ if (!out.includes('--dangerously-skip-permissions') && !out.includes('--sandbox')) {
+ out.push('--dangerously-skip-permissions');
+ }
+ return out;
+}
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 34a7d6d397..7be8b50ebb 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -13,7 +13,7 @@ import {
ensureAntigravityTuiArgs,
LEGACY_GEMINI_CLI_ID,
LEGACY_GEMINI_TUI_ID,
-} from '../antigravity.js';
+} from './internal/antigravity.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const DEFAULT_SAMPLE_PATH = join(__dirname, 'defaults/providers.sample.json');
@@ -379,7 +379,8 @@ export function createProviderService(config = {}) {
if (provider.type === 'api') {
const modelsUrl = `${provider.endpoint}/models`;
const response = await fetch(modelsUrl, {
- headers: provider.apiKey ? { 'Authorization': `Bearer ${provider.apiKey}` } : {}
+ headers: provider.apiKey ? { 'Authorization': `Bearer ${provider.apiKey}` } : {},
+ signal: AbortSignal.timeout(10000),
}).catch(err => ({ ok: false, error: err.message }));
if (!response.ok) {
@@ -435,7 +436,7 @@ export function createProviderService(config = {}) {
async _refreshAPIProviderModels(provider) {
if (provider.endpoint?.includes('ollama') || provider.endpoint?.includes(':11434')) {
const ollamaUrl = `${provider.endpoint}/api/tags`;
- const response = await fetch(ollamaUrl).catch(() => null);
+ const response = await fetch(ollamaUrl, { signal: AbortSignal.timeout(8000) }).catch(() => null);
if (response?.ok) {
const data = await response.json().catch(() => null);
@@ -452,7 +453,7 @@ export function createProviderService(config = {}) {
headers['Authorization'] = `Bearer ${provider.apiKey}`;
}
- const response = await fetch(modelsUrl, { headers }).catch(() => null);
+ const response = await fetch(modelsUrl, { headers, signal: AbortSignal.timeout(8000) }).catch(() => null);
if (!response?.ok) {
throw new Error(`HTTP ${response?.status || 'error'}`);
diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.js
index c881b3bd7f..a7db88b601 100644
--- a/server/lib/aiToolkit/providers.test.js
+++ b/server/lib/aiToolkit/providers.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { mkdir, rm, writeFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
@@ -455,4 +455,116 @@ describe('Provider Service', () => {
expect(antigravityTui.args).toEqual(['--dangerously-skip-permissions']);
});
});
+
+ describe('testProvider — network layer (api type)', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('returns success shape when the api endpoint responds ok', async () => {
+ const models = { data: [{ id: 'gpt-5' }, { id: 'gpt-4' }] };
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => models,
+ }));
+
+ const p = await providerService.createProvider({
+ name: 'Test API',
+ type: 'api',
+ endpoint: 'https://api.example.com/v1',
+ apiKey: 'sk-test',
+ });
+
+ const result = await providerService.testProvider(p.id);
+ expect(result.success).toBe(true);
+ expect(result.models).toEqual(['gpt-5', 'gpt-4']);
+ expect(result.endpoint).toBe('https://api.example.com/v1');
+ });
+
+ it('returns failure shape when fetch rejects (e.g. timeout / network error)', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new DOMException('The operation was aborted.', 'TimeoutError')));
+
+ const p = await providerService.createProvider({
+ name: 'Stalled API',
+ type: 'api',
+ endpoint: 'https://stalled.example.com/v1',
+ });
+
+ const result = await providerService.testProvider(p.id);
+ expect(result.success).toBe(false);
+ expect(typeof result.error).toBe('string');
+ expect(result.error).toMatch(/API not reachable/);
+ });
+
+ it('returns failure shape when server responds with non-ok status', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: false,
+ status: 401,
+ }));
+
+ const p = await providerService.createProvider({
+ name: 'Unauthorized API',
+ type: 'api',
+ endpoint: 'https://auth.example.com/v1',
+ });
+
+ const result = await providerService.testProvider(p.id);
+ expect(result.success).toBe(false);
+ expect(result.error).toMatch(/API not reachable/);
+ });
+ });
+
+ describe('_refreshAPIProviderModels — network layer', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('uses data.models shape for Ollama endpoint', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ models: [{ name: 'llama3.2' }, { name: 'mistral' }] }),
+ }));
+
+ const p = await providerService.createProvider({
+ name: 'Ollama',
+ type: 'api',
+ endpoint: 'http://localhost:11434',
+ });
+
+ const updated = await providerService.refreshProviderModels(p.id);
+ expect(updated).not.toBeNull();
+ expect(updated.models).toEqual(['llama3.2', 'mistral']);
+ });
+
+ it('uses data.data shape for generic OpenAI-compatible endpoint', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ data: [{ id: 'model-a' }, { id: 'model-b' }] }),
+ }));
+
+ const p = await providerService.createProvider({
+ name: 'Generic API',
+ type: 'api',
+ endpoint: 'https://api.generic.com/v1',
+ apiKey: 'sk-key',
+ });
+
+ const updated = await providerService.refreshProviderModels(p.id);
+ expect(updated).not.toBeNull();
+ expect(updated.models).toEqual(['model-a', 'model-b']);
+ });
+
+ it('returns null when the generic endpoint rejects (timeout / unreachable)', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new DOMException('The operation was aborted.', 'TimeoutError')));
+
+ const p = await providerService.createProvider({
+ name: 'Unreachable API',
+ type: 'api',
+ endpoint: 'https://dead.example.com/v1',
+ });
+
+ const result = await providerService.refreshProviderModels(p.id);
+ expect(result).toBeNull();
+ });
+ });
});
diff --git a/server/routes/logs.js b/server/routes/logs.js
index 5ebaeb7302..643dae6c56 100644
--- a/server/routes/logs.js
+++ b/server/routes/logs.js
@@ -63,6 +63,7 @@ router.get('/:processName', asyncHandler(async (req, res) => {
let buffer = '';
const sendLine = (line, type = 'log') => {
+ if (res.writableEnded || res.destroyed) return;
if (line.trim()) {
res.write(`event: ${type}\ndata: ${JSON.stringify({
line,
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 0bd40424f7..8ba2f57fee 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -447,10 +447,14 @@ export async function spawnDirectly({
// If no output after 3 seconds, transition from initializing to working to show progress
const initializationTimeout = setTimeout(async () => {
- if (!hasStartedWorking && activeAgents.has(agentId)) {
- hasStartedWorking = true;
- await updateAgent(agentId, { metadata: { phase: 'working' } });
- emitLog('info', `Agent ${agentId} working (after initialization delay)...`, { agentId, phase: 'working' });
+ try {
+ if (!hasStartedWorking && activeAgents.has(agentId)) {
+ hasStartedWorking = true;
+ await updateAgent(agentId, { metadata: { phase: 'working' } });
+ emitLog('info', `Agent ${agentId} working (after initialization delay)...`, { agentId, phase: 'working' });
+ }
+ } catch (err) {
+ console.error(`❌ agentCliSpawning init timeout failed for ${agentId}: ${err.message}`);
}
}, 3000);
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index e3bd407cdc..4a28a96a88 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -312,6 +312,71 @@ describe('stream error containment', () => {
expect(logged).toBe(true);
});
+ describe('initialization timeout — 3-second phase transition', () => {
+ it('calls updateAgent with working phase after 3s when agent has not started working', async () => {
+ const { activeAgents } = await import('./agentState.js');
+ const agents = cosAgentsMocks;
+
+ const spawnPromise = spawnDirectly(minimalArgs);
+ // Yield two microtask rounds so the getClaudeSettingsEnv await resolves and
+ // the setTimeout is registered before we seed activeAgents.
+ await new Promise((r) => setTimeout(r, 10));
+
+ // Manually seed the activeAgents map so the guard inside the timeout passes.
+ activeAgents.set(minimalArgs.agentId, { process: fakeProcess });
+
+ // Wait past the 3-second threshold using real timers.
+ await new Promise((r) => setTimeout(r, 3100));
+
+ expect(agents.updateAgent).toHaveBeenCalledWith(
+ minimalArgs.agentId,
+ { metadata: { phase: 'working' } }
+ );
+
+ // Clean up: close the fake process so spawnDirectly can settle.
+ activeAgents.delete(minimalArgs.agentId);
+ fakeProcess.emit('close', 0);
+ await spawnPromise.catch(() => {});
+ }, 10000);
+
+ it('does NOT crash when updateAgent rejects inside the timeout callback', async () => {
+ const { activeAgents } = await import('./agentState.js');
+ // spawnDirectly calls updateAgent once synchronously (PID update at line ~406)
+ // before the 3-second setTimeout fires. Allow that first call to resolve
+ // normally so spawnDirectly doesn't throw before the timeout test begins;
+ // then reject the SECOND call (the phase-transition inside the timeout).
+ cosAgentsMocks.updateAgent
+ .mockResolvedValueOnce(undefined) // PID update — let it pass
+ .mockRejectedValueOnce(new Error('db write failed')); // timeout update — reject
+
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const unhandledRejections = [];
+ const onUnhandled = (reason) => unhandledRejections.push(reason);
+ process.on('unhandledRejection', onUnhandled);
+
+ const spawnPromise = spawnDirectly(minimalArgs);
+ await new Promise((r) => setTimeout(r, 10));
+
+ activeAgents.set(minimalArgs.agentId, { process: fakeProcess });
+
+ // Wait for the timeout to fire and its async body to finish.
+ await new Promise((r) => setTimeout(r, 3100));
+
+ process.off('unhandledRejection', onUnhandled);
+
+ expect(unhandledRejections).toHaveLength(0);
+ const logged = consoleSpy.mock.calls.some(
+ (args) => typeof args[0] === 'string' && args[0].startsWith('❌ agentCliSpawning init timeout failed')
+ );
+ expect(logged).toBe(true);
+
+ activeAgents.delete(minimalArgs.agentId);
+ fakeProcess.emit('close', 0);
+ await spawnPromise.catch(() => {});
+ consoleSpy.mockRestore();
+ }, 10000);
+ });
+
it('threads the ordered reviewers list (not a stale singular `reviewer`) into worktree cleanup', async () => {
const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);
const args = {
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 02b193d659..2d79808c9a 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -465,11 +465,15 @@ export async function spawnViaRunner(agentId, task, opts) {
// If no output after 3 seconds, transition from initializing to working to show progress
agentInfo.initializationTimeout = setTimeout(async () => {
- const agent = runnerAgents.get(agentId);
- if (agent && !agent.hasStartedWorking) {
- agent.hasStartedWorking = true;
- await updateAgent(agentId, { metadata: { phase: 'working' } });
- emitLog('info', `Agent ${agentId} working (after initialization delay)...`, { agentId, phase: 'working' });
+ try {
+ const agent = runnerAgents.get(agentId);
+ if (agent && !agent.hasStartedWorking) {
+ agent.hasStartedWorking = true;
+ await updateAgent(agentId, { metadata: { phase: 'working' } });
+ emitLog('info', `Agent ${agentId} working (after initialization delay)...`, { agentId, phase: 'working' });
+ }
+ } catch (err) {
+ console.error(`❌ agentLifecycle init timeout failed for ${agentId}: ${err.message}`);
}
}, 3000);
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index a5bbf0e0e6..bbdde584dd 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -364,7 +364,8 @@ async function upgradeOllamaMacApp(emit) {
emit('Looking up the latest Ollama release on GitHub…')
const release = await fetch('https://api.github.com/repos/ollama/ollama/releases/latest', {
- headers: { 'User-Agent': 'PortOS', Accept: 'application/vnd.github+json' }
+ headers: { 'User-Agent': 'PortOS', Accept: 'application/vnd.github+json' },
+ signal: AbortSignal.timeout(15000),
}).then((r) => (r.ok ? r.json() : null)).catch(() => null)
if (!release) return { success: false, error: 'Could not reach GitHub to look up the latest Ollama release.' }
@@ -384,16 +385,19 @@ async function upgradeOllamaMacApp(emit) {
await mkdir(tmpDir, { recursive: true })
emit(`Downloading Ollama ${release.tag_name} (${Math.round(asset.size / 1024 / 1024)} MB)…`)
+ // No timeout signal here: it would cover the entire multi-hundred-MB body
+ // stream, turning slow links into mid-download aborts. User-triggered and
+ // recoverable, so an unbounded stream is the lesser evil.
const dl = await fetch(asset.browser_download_url).catch((err) => ({ _err: err.message }))
if (dl._err || !dl?.ok || !dl.body) {
await rm(tmpDir, { recursive: true, force: true }).catch(() => {})
return { success: false, error: `Download failed: ${dl?._err || dl?.statusText || 'no response body'}` }
}
- await pipeline(Readable.fromWeb(dl.body), createWriteStream(zipPath))
- .catch(async (err) => {
- await rm(tmpDir, { recursive: true, force: true }).catch(() => {})
- throw err
- })
+ const pipeErr = await pipeline(Readable.fromWeb(dl.body), createWriteStream(zipPath)).then(() => null, (err) => err)
+ if (pipeErr) {
+ await rm(tmpDir, { recursive: true, force: true }).catch(() => {})
+ return { success: false, error: `Download failed: ${pipeErr.message}` }
+ }
emit('Stopping running Ollama…')
await ollamaManager.stopServer().catch(() => null)
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index 049b8e25c3..8d59d9c97c 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -1222,6 +1222,10 @@ export async function mergeIssuesFromSync(remoteIssues, { source = { via: 'sync'
const state = await readState();
const localById = new Map(state.issues.map((i) => [i.id, i]));
let changed = 0;
+ // Track only the issue IDs that were inserted or overwritten so we persist
+ // the changed subset rather than every issue in the store (avoids unbounded
+ // Promise.all / EMFILE on large catalogs).
+ const changedIds = new Set();
for (const remote of remoteIssues) {
if (!remote || typeof remote !== 'object' || !isStr(remote.id)) continue;
// Drop issues whose parent series is locally ephemeral, BEFORE any
@@ -1251,6 +1255,7 @@ export async function mergeIssuesFromSync(remoteIssues, { source = { via: 'sync'
// subscription, so peerSync never seeds an `issue`-keyed base hash —
// this merge path (and the importer) own it.
await setSyncBaseHash('issue', sanitized.id, contentHashForRecord('issue', sanitized));
+ changedIds.add(sanitized.id);
changed++;
} else if (local.ephemeral === true) {
// Local-ephemeral issues are immune to inbound merges. See
@@ -1265,6 +1270,7 @@ export async function mergeIssuesFromSync(remoteIssues, { source = { via: 'sync'
// throws into the merge (convergence wins).
await maybeJournalBeforeOverwrite({ kind: 'issue', id: sanitized.id, local, remote: sanitized, source });
localById.set(sanitized.id, sanitized);
+ changedIds.add(sanitized.id);
// Renumber on EITHER direction of the transition: a delete leaves
// a gap, a resurrection (deleted→live) reintroduces a previously-
// compacted number and can collide with live siblings until some
@@ -1287,10 +1293,21 @@ export async function mergeIssuesFromSync(remoteIssues, { source = { via: 'sync'
// tombstoned (gap) or resurrected (collision) an issue. renumberInline
// skips tombstones, so the resulting numbering is always contiguous
// across live issues. Single renumber per series, all inside the queue.
+ // renumberInline updates state.issues in-place; collect the renumbered
+ // issue ids so they are also persisted.
for (const seriesId of seriesNeedingRenumber) {
+ const before = new Map(state.issues.map((i) => [i.id, i.number]));
await renumberInline(state, seriesId, null);
+ for (const i of state.issues) {
+ if (i.seriesId === seriesId && i.number !== before.get(i.id)) {
+ changedIds.add(i.id);
+ }
+ }
}
- await saveIssuesNow(state.issues);
+ // Persist only the issues that were actually changed/renumbered, not the
+ // entire catalog — avoids EMFILE + write-amplification on large stores.
+ const changedIssues = state.issues.filter((i) => changedIds.has(i.id));
+ await saveIssuesNow(changedIssues);
// Re-emit a series-updated for each touched series so any active share
// subscription re-exports the post-merge issue set.
for (const seriesId of seriesNeedingRenumber) {
diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.js
index 7072febf30..b6cb2c1e9c 100644
--- a/server/services/pipeline/issues.test.js
+++ b/server/services/pipeline/issues.test.js
@@ -939,6 +939,84 @@ describe('pipeline issues service', () => {
});
});
+ describe('mergeIssuesFromSync — changed-only persistence and multi-series correctness', () => {
+ it('merges issues from two different series correctly', async () => {
+ const a = await svc.createIssue({ seriesId: 'ser-multi-1', title: 'A1' });
+ const b = await svc.createIssue({ seriesId: 'ser-multi-2', title: 'B1' });
+
+ const laterTs = new Date(Date.now() + 60_000).toISOString();
+ const result = await svc.mergeIssuesFromSync([
+ { ...a, title: 'A1 updated', updatedAt: laterTs },
+ { ...b, title: 'B1 updated', updatedAt: laterTs },
+ ]);
+
+ expect(result).toEqual({ applied: true, count: 2 });
+ const updatedA = await svc.getIssue(a.id);
+ const updatedB = await svc.getIssue(b.id);
+ expect(updatedA.title).toBe('A1 updated');
+ expect(updatedB.title).toBe('B1 updated');
+ });
+
+ it('persists only changed issues — unchanged ones are not written', async () => {
+ const changed = await svc.createIssue({ seriesId: 'ser-persist-check', title: 'Changed' });
+ const unchanged = await svc.createIssue({ seriesId: 'ser-persist-check', title: 'Unchanged' });
+
+ const { atomicWrite } = await import('../../lib/fileUtils.js');
+ const writesBefore = atomicWrite.mock.calls.length;
+
+ const laterTs = new Date(Date.now() + 60_000).toISOString();
+ await svc.mergeIssuesFromSync([
+ { ...changed, title: 'Changed - remote edit', updatedAt: laterTs },
+ // unchanged issue: same updatedAt → LWW skips it
+ ]);
+
+ const issueWritesAfter = atomicWrite.mock.calls
+ .slice(writesBefore)
+ .map(([path]) => path)
+ .filter((p) => p.includes('pipeline-issues'));
+
+ // The changed issue must have been written.
+ expect(issueWritesAfter.some((p) => p.includes(changed.id))).toBe(true);
+ // The unchanged issue must NOT have been written (B8 fix: only changed subset).
+ expect(issueWritesAfter.some((p) => p.includes(unchanged.id))).toBe(false);
+ // Only 1 issue-record write (the changed one), not 2.
+ expect(issueWritesAfter.length).toBe(1);
+ });
+
+ it('includes renumbered siblings in the persisted set after a delete-transition merge', async () => {
+ const x = await svc.createIssue({ seriesId: 'ser-renum-persist', title: 'X' });
+ const y = await svc.createIssue({ seriesId: 'ser-renum-persist', title: 'Y' });
+ const z = await svc.createIssue({ seriesId: 'ser-renum-persist', title: 'Z' });
+ expect([x.number, y.number, z.number]).toEqual([1, 2, 3]);
+
+ const { atomicWrite } = await import('../../lib/fileUtils.js');
+ const writesBefore = atomicWrite.mock.calls.length;
+
+ const laterTs = new Date(Date.now() + 60_000).toISOString();
+ // Delete Y via sync — should renumber Z from #3 to #2.
+ await svc.mergeIssuesFromSync([{ ...y, deleted: true, deletedAt: laterTs, updatedAt: laterTs }]);
+
+ const issueWritesAfter = atomicWrite.mock.calls
+ .slice(writesBefore)
+ .map(([path]) => path)
+ .filter((p) => p.includes('pipeline-issues'));
+
+ // Y (the changed issue) must be persisted.
+ expect(issueWritesAfter.some((p) => p.includes(y.id))).toBe(true);
+ // Z was renumbered from #3 to #2 — its record must also be persisted.
+ expect(issueWritesAfter.some((p) => p.includes(z.id))).toBe(true);
+ // X was not renumbered (number=1 doesn't change) — must NOT be written.
+ expect(issueWritesAfter.some((p) => p.includes(x.id))).toBe(false);
+ // Total issue-record writes: Y + Z = 2, not 3 (all issues).
+ expect(issueWritesAfter.length).toBe(2);
+
+ // Verify final state.
+ const live = await svc.listIssues({ seriesId: 'ser-renum-persist' });
+ expect(live.map((i) => i.title).sort()).toEqual(['X', 'Z']);
+ expect(live.map((i) => i.number).sort((a, b) => a - b)).toEqual([1, 2]);
+ });
+ });
+
describe('pruneTombstonedIssues', () => {
it('removes tombstones older than the cutoff and leaves newer ones + live records', async () => {
const live = await svc.createIssue({ seriesId: 'ser-prune', title: 'Live' });
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index c8ebf7c88f..f18048e5f4 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -19,6 +19,7 @@ import { join } from 'path';
import { cosEvents, emitLog } from './cosEvents.js';
import { DAY, ensureDir, HOUR, readJSONFile, PATHS, safeDate } from '../lib/fileUtils.js';
import { isPlainObject } from '../lib/objects.js';
+import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';
import { getAdaptiveCooldownMultiplier } from './taskLearning.js';
import { isTaskTypeEnabledForApp, getAppTaskTypeInterval, getActiveApps, getAppTaskTypeOverrides, clearAllPrWatcherState } from './apps.js';
import { loadState, isImprovementEnabled } from './cosState.js';
@@ -1037,7 +1038,7 @@ export async function getScheduleStatus() {
const isEnabledForApp = (override) => override?.enabled === true;
const appOverrides = {};
let enabledAppCount = 0;
- const allOverrides = await Promise.all(activeApps.map(app => getAppTaskTypeOverrides(app.id)));
+ const allOverrides = await mapWithConcurrency(activeApps, 8, (app) => getAppTaskTypeOverrides(app.id));
for (let i = 0; i < activeApps.length; i++) {
const override = allOverrides[i][taskType];
if (override) {
diff --git a/server/sockets/voice.js b/server/sockets/voice.js
index 9d61da78ad..037e2ecbc6 100644
--- a/server/sockets/voice.js
+++ b/server/sockets/voice.js
@@ -223,17 +223,22 @@ export const registerVoiceHandlers = (socket) => {
// dictation off and surface the error instead. Disabling is always
// allowed — it's a clean-up path that can run regardless of config.
socket.on('voice:dictation:set', async (payload) => {
- const { enabled, date } = payload && typeof payload === 'object' ? payload : {};
- if (enabled && !(await ensureEnabled('dictation'))) {
- // Ensure UI and server agree that dictation is off after a blocked
- // enable, otherwise the UI can silently drift into "dictating" state.
- state.dictation = { enabled: false, date: null };
- socket.emit('voice:dictation', { enabled: false });
- return;
+ try {
+ const { enabled, date } = payload && typeof payload === 'object' ? payload : {};
+ if (enabled && !(await ensureEnabled('dictation'))) {
+ // Ensure UI and server agree that dictation is off after a blocked
+ // enable, otherwise the UI can silently drift into "dictating" state.
+ state.dictation = { enabled: false, date: null };
+ socket.emit('voice:dictation', { enabled: false });
+ return;
+ }
+ const normalizedDate = isIsoDate(date) ? date : (state.dictation.date || null);
+ state.dictation = { enabled: !!enabled, date: enabled ? normalizedDate : null };
+ socket.emit('voice:dictation', { enabled: state.dictation.enabled, date: state.dictation.date });
+ } catch (err) {
+ console.error(`❌ voice:dictation:set failed: ${err.message}`);
+ socket.emit('voice:error', { stage: 'dictation', message: err.message });
}
- const normalizedDate = isIsoDate(date) ? date : (state.dictation.date || null);
- state.dictation = { enabled: !!enabled, date: enabled ? normalizedDate : null };
- socket.emit('voice:dictation', { enabled: state.dictation.enabled, date: state.dictation.date });
});
// Client pushes the current page's DOM index whenever voice is enabled
diff --git a/server/sockets/voice.test.js b/server/sockets/voice.test.js
index bde2360652..45085f3d83 100644
--- a/server/sockets/voice.test.js
+++ b/server/sockets/voice.test.js
@@ -1,5 +1,18 @@
-import { describe, it, expect } from 'vitest';
-import { truncateOnWordBoundary, registerVoiceHandlers } from './voice.js';
+import { describe, it, expect, vi } from 'vitest';
+
+// Force the enabled-gate open so the validation tests below deterministically
+// exercise the size/text guards (ensureEnabled runs BEFORE every guard; with
+// the real config loader the file read fails in this harness and its error
+// would mask the guard under test).
+vi.mock(import('../services/voice/config.js'), async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ getVoiceConfig: vi.fn(async () => ({ enabled: true })),
+ };
+});
+
+const { truncateOnWordBoundary, registerVoiceHandlers } = await import('./voice.js');
// Minimal fake socket: records on() handlers so tests can fire inbound events,
// and captures emit() calls. No real Socket.IO needed — the voice:ui:index /
@@ -123,3 +136,59 @@ describe('voice:screenshot:result socket handler', () => {
expect(() => socket.fire('voice:screenshot:result', { requestId: 'missing', dataUrl: 'data:image/png;base64,AAAA' })).not.toThrow();
});
});
+
+describe('voice:turn validation', () => {
+ it('emits voice:error when audio exceeds MAX_AUDIO_BYTES', async () => {
+ // MAX_AUDIO_BYTES = 8 * 1024 * 1024. Build a Buffer just over the limit.
+ const MAX_AUDIO_BYTES = 8 * 1024 * 1024;
+ const socket = makeFakeSocket();
+ registerVoiceHandlers(socket);
+ const oversized = Buffer.alloc(MAX_AUDIO_BYTES + 1);
+ await socket.fire('voice:turn', { audio: oversized, mimeType: 'audio/wav' });
+ const errors = socket.emitted.filter((e) => e.event === 'voice:error');
+ expect(errors).toHaveLength(1);
+ expect(errors[0].payload.stage).toBe('turn');
+ expect(errors[0].payload.message).toBe(`audio too large (${MAX_AUDIO_BYTES + 1} > ${MAX_AUDIO_BYTES} bytes)`);
+ });
+
+ it('emits voice:error when audio is missing', async () => {
+ const socket = makeFakeSocket();
+ registerVoiceHandlers(socket);
+ await socket.fire('voice:turn', { mimeType: 'audio/wav' });
+ const errors = socket.emitted.filter((e) => e.event === 'voice:error');
+ expect(errors).toHaveLength(1);
+ expect(errors[0].payload).toEqual({ stage: 'turn', message: 'audio is required' });
+ });
+});
+
+describe('voice:text validation', () => {
+ it('emits voice:error for text exceeding MAX_TEXT_LEN', async () => {
+ const MAX_TEXT_LEN = 4000;
+ const socket = makeFakeSocket();
+ registerVoiceHandlers(socket);
+ const longText = 'x'.repeat(MAX_TEXT_LEN + 1);
+ await socket.fire('voice:text', { text: longText });
+ const errors = socket.emitted.filter((e) => e.event === 'voice:error');
+ expect(errors).toHaveLength(1);
+ expect(errors[0].payload.stage).toBe('text');
+ expect(errors[0].payload.message).toBe(`text too long (${MAX_TEXT_LEN + 1} > ${MAX_TEXT_LEN} chars)`);
+ });
+
+ it('emits voice:error for empty text payload', async () => {
+ const socket = makeFakeSocket();
+ registerVoiceHandlers(socket);
+ await socket.fire('voice:text', { text: '' });
+ const errors = socket.emitted.filter((e) => e.event === 'voice:error');
+ expect(errors).toHaveLength(1);
+ expect(errors[0].payload).toEqual({ stage: 'text', message: 'text is required' });
+ });
+
+ it('emits voice:error when text field is absent', async () => {
+ const socket = makeFakeSocket();
+ registerVoiceHandlers(socket);
+ await socket.fire('voice:text', {});
+ const errors = socket.emitted.filter((e) => e.event === 'voice:error');
+ expect(errors).toHaveLength(1);
+ expect(errors[0].payload).toEqual({ stage: 'text', message: 'text is required' });
+ });
+});