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: avoid cloning task history for live activity polls

[._.]/ Adam Eivy3d59c6eb8313
diff --git a/server/services/activeProcessing.js b/server/services/activeProcessing.js
index 42fe64c875..40f5eead62 100644
--- a/server/services/activeProcessing.js
+++ b/server/services/activeProcessing.js
@@ -8,12 +8,12 @@ import * as cos from './cos.js';
const LIVE_STATUSES = new Set(['queued', 'running']);
export async function getActiveProcessing() {
- const [capability, jobs, models, loadedModels, taskData, agents] = await Promise.all([
+ const [capability, jobs, models, loadedModels, pendingTaskIds, agents] = await Promise.all([
getCudaCapability(),
Promise.resolve(listJobs()).then((items) => items.filter((job) => LIVE_STATUSES.has(job.status))),
listGeneratingModelSummaries().catch(() => []),
getLoadedModels().catch(() => []),
- cos.getAllTasks().catch(() => ({ user: {}, cos: {} })),
+ cos.getPendingTaskIds().catch(() => []),
// `null` = the read FAILED, distinct from `[]` = read fine, no agents. The
// counts below degrade differently for the two, so they must stay separable.
cos.getAgents().catch(() => null),
@@ -33,8 +33,7 @@ export async function getActiveProcessing() {
// their tasks as queued, which would understate BOTH numbers at once.
const runningAgents = agents === null ? null : agents.filter((agent) => agent.status === 'running');
const claimedTaskIds = new Set((runningAgents || []).map((agent) => agent.taskId).filter(Boolean));
- const pendingTasks = [...(taskData.user?.tasks || []), ...(taskData.cos?.tasks || [])]
- .filter((task) => task.status === 'pending' && !claimedTaskIds.has(task.id)).length;
+ const pendingTasks = pendingTaskIds.filter((id) => !claimedTaskIds.has(id)).length;
const gpuBusy = Boolean(getRunningJob());
return {
updatedAt: new Date().toISOString(),
diff --git a/server/services/activeProcessing.test.js b/server/services/activeProcessing.test.js
index 1bd7c9d2b6..b85000e1ea 100644
--- a/server/services/activeProcessing.test.js
+++ b/server/services/activeProcessing.test.js
@@ -8,7 +8,7 @@ vi.mock('./mediaJobQueue/index.js', () => ({ listJobs: deps.jobs, getRunningJob:
vi.mock('./mediaJobQueue/sanitizeJob.js', () => ({ sanitizeJob: (job) => ({ id: job.id, kind: job.kind, status: job.status, params: { musicStudio: job.params.musicStudio } }) }));
vi.mock('./imageTo3d/models.js', () => ({ listGeneratingModelSummaries: deps.models }));
vi.mock('./ollamaManager.js', () => ({ getLoadedModels: deps.loaded }));
-vi.mock('./cos.js', () => ({ getAllTasks: deps.tasks, getStatus: deps.status, getAgents: deps.agents }));
+vi.mock('./cos.js', () => ({ getPendingTaskIds: deps.tasks, getStatus: deps.status, getAgents: deps.agents }));
const { getActiveProcessing } = await import('./activeProcessing.js');
@@ -24,7 +24,7 @@ describe('active processing snapshot', () => {
deps.running.mockReturnValue({ kind: 'audio' });
deps.models.mockResolvedValue([{ id: 'mesh-1', name: 'Fake mesh' }, { id: 'mesh-2', name: '' }]);
deps.loaded.mockResolvedValue([{ id: 'model-1', name: 'Fake model' }]);
- deps.tasks.mockResolvedValue({ user: { tasks: [{ id: 'task-1', status: 'pending' }] }, cos: { tasks: [{ id: 'cos-task-1', status: 'completed' }] } });
+ deps.tasks.mockResolvedValue(['task-1']);
deps.status.mockResolvedValue({ activeAgents: 99 });
deps.agents.mockResolvedValue([
{ id: 'agent-1', status: 'running', taskId: 'task-a' },
@@ -46,7 +46,7 @@ describe('active processing snapshot', () => {
deps.running.mockReturnValue(null);
deps.models.mockResolvedValue([]);
deps.loaded.mockResolvedValue([]);
- deps.tasks.mockResolvedValue({ user: {}, cos: {} });
+ deps.tasks.mockResolvedValue([]);
deps.status.mockResolvedValue({ activeAgents: 0 });
deps.agents.mockResolvedValue([]);
const snapshot = await getActiveProcessing();
@@ -74,17 +74,14 @@ describe('queued agent count', () => {
});
it('does not count a pending task a running agent already holds', async () => {
- deps.tasks.mockResolvedValue({
- user: { tasks: [{ id: 'task-spawning', status: 'pending' }, { id: 'task-waiting', status: 'pending' }] },
- cos: { tasks: [] },
- });
+ deps.tasks.mockResolvedValue(['task-spawning', 'task-waiting']);
deps.agents.mockResolvedValue([{ id: 'agent-1', status: 'running', taskId: 'task-spawning' }]);
const snapshot = await getActiveProcessing();
expect(snapshot.agents).toEqual({ active: 1, queued: 1 });
});
it('still counts a pending task whose agent already completed', async () => {
- deps.tasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [{ id: 'cos-task-1', status: 'pending' }] } });
+ deps.tasks.mockResolvedValue(['cos-task-1']);
deps.agents.mockResolvedValue([{ id: 'agent-1', status: 'completed', taskId: 'cos-task-1' }]);
const snapshot = await getActiveProcessing();
expect(snapshot.agents).toEqual({ active: 0, queued: 1 });
@@ -95,7 +92,7 @@ describe('queued agent count', () => {
// numbers at once — so the failure path falls back to getStatus()'s own tally.
it('falls back to the status tally when the agent read fails, without dropping pending tasks', async () => {
deps.status.mockResolvedValue({ activeAgents: 3 });
- deps.tasks.mockResolvedValue({ user: { tasks: [{ id: 'task-1', status: 'pending' }] }, cos: { tasks: [] } });
+ deps.tasks.mockResolvedValue(['task-1']);
deps.agents.mockRejectedValue(new Error('state unreadable'));
const snapshot = await getActiveProcessing();
expect(snapshot.agents).toEqual({ active: 3, queued: 1 });
@@ -105,7 +102,7 @@ describe('queued agent count', () => {
// ...and a successful read of an EMPTY list still means zero, not the fallback.
it('reports zero active from an empty agent list without waiting for status', async () => {
deps.status.mockImplementation(() => new Promise(() => {}));
- deps.tasks.mockResolvedValue({ user: { tasks: [{ id: 'task-1', status: 'pending' }] }, cos: { tasks: [] } });
+ deps.tasks.mockResolvedValue(['task-1']);
deps.agents.mockResolvedValue([]);
const snapshot = await getActiveProcessing();
expect(snapshot.agents).toEqual({ active: 0, queued: 1 });
@@ -113,7 +110,7 @@ describe('queued agent count', () => {
});
it('preserves pending tasks when both agent and fallback status reads fail', async () => {
- deps.tasks.mockResolvedValue({ user: { tasks: [{ id: 'task-1', status: 'pending' }] }, cos: { tasks: [] } });
+ deps.tasks.mockResolvedValue(['task-1']);
deps.agents.mockRejectedValue(new Error('state unreadable'));
deps.status.mockRejectedValue(new Error('status unavailable'));
const snapshot = await getActiveProcessing();
diff --git a/server/services/cos.js b/server/services/cos.js
index 009644cfbb..3306be32d3 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -87,6 +87,7 @@ export { runHealthCheck, getHealthStatus };
// emits `tasks:changed`; init() below turns that into tryImmediateSpawn /
// dequeueNextTask so the spawn-side logic stays here, not in the store.
import { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks } from './cosTaskStore.js';
+export { getPendingTaskIds } from './cosTaskStore.js';
export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks };
import { ensureInstanceId } from './instances.js';
import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner, getSkipReason } from './cosTaskClaim.js';
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 9105938a04..30a8b3997a 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -222,6 +222,24 @@ export async function getAllTasks() {
return { user: userTasks, cos: cosTasks };
}
+/**
+ * Lightweight live-activity input. Derive once per task-file snapshot, so a
+ * three-second poll never clones prompts or groups completed history.
+ * Keep duplicates and source order, matching getAllTasks() counting semantics.
+ */
+export async function getPendingTaskIds() {
+ const { config } = await loadState();
+ const sources = await Promise.all([config.userTasksFile, config.cosTasksFile].map(async (file) => {
+ const filePath = join(ROOT_DIR, file);
+ if (!existsSync(filePath)) return [];
+ const snapshot = await readTaskSnapshot(filePath);
+ snapshot.pendingIds ??= snapshot.tasks.filter(task => task.status === 'pending').map(task => task.id);
+ return snapshot.pendingIds;
+ }));
+ // Never expose the cached arrays to callers.
+ return sources.flat();
+}
+
/**
* Alias for backward compatibility
*/
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 7c4ba59cc2..072e5c415e 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -96,6 +96,7 @@ import {
getUserTasks,
getCosTasks,
getAllTasks,
+ getPendingTaskIds,
getTasks,
getTaskById,
addTask,
@@ -188,6 +189,29 @@ describe('cosTaskStore.getUserTasks / getCosTasks', () => {
// that every invalidation signal fires, and that a cached read can never leak a
// caller's in-place mutations into the next reader.
describe('cosTaskStore parsed-task cache (#3497)', () => {
+ it('projects pending IDs without cloning task payloads and refreshes after writes and external edits', async () => {
+ expect(await getPendingTaskIds()).toEqual([]);
+ const user = await addTask({ description: 'Example user task' }, 'user');
+ const internal = await addTask({ description: 'Example internal task' }, 'internal');
+ const clone = vi.spyOn(globalThis, 'structuredClone');
+ const ids = await getPendingTaskIds();
+ expect(ids).toEqual([user.id, internal.id]);
+ ids.push('caller-only');
+ const parses = mock.parseCalls;
+ expect(await getPendingTaskIds()).toEqual([user.id, internal.id]);
+ expect(mock.parseCalls).toBe(parses);
+ expect(clone).not.toHaveBeenCalled();
+ clone.mockRestore();
+
+ await updateTask(user.id, { status: 'completed' }, 'user');
+ expect(await getPendingTaskIds()).toEqual([internal.id]);
+ mock.files.set(COS_FILE, mock.files.get(COS_FILE).replace('- [ ]', '- [x]'));
+ mock.mtimes.set(COS_FILE, mock.mtimes.get(COS_FILE) + 5000);
+ expect(await getPendingTaskIds()).toEqual([]);
+ mock.files.delete(USER_FILE);
+ expect(await getPendingTaskIds()).toEqual([]);
+ });
+
it('serves a cached parse while the file is unchanged', async () => {
await addTask({ description: 'cached thing' }, 'user');
mock.parseCalls = 0;