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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: auto-complete CoS review items when agent finishes successfully
Adam Eivy05180fcd8973
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d7fb709ab6..63bda92fba 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,6 +8,10 @@## Fixed+- **Review Hub: CoS-spawned tasks lingered as "pending" forever.** The review service emitted a `cos`-type item every time `cosEvents.emit('task:ready', ...)` fired, but nothing closed the loop when the agent actually finished — so the user saw a permanent backlog of "CoS Actions" they had to manually tick off, even for tasks the agent completed unattended. `server/services/review.js` now also listens for `agent:completed` and auto-completes any pending review item whose `metadata.referenceId` matches the agent's `taskId` when `result.success` is truthy (failures stay pending so the user still sees them). Mirrors the existing `memory:approval-needed` → `memory:approved`/`rejected` dismiss pattern. Refactored the helper into a single `updateStatusByReferenceId(id, status)` so dismiss and complete share the loop. Added two tests against the registered `agent:completed` listener (success → complete; failure → no-op). Files: `server/services/review.js`, `server/services/review.test.js`.++- **Review Hub: only had a "Mark All Read" (dismiss) bulk action.** Added a green "Complete All" button next to the renamed "Dismiss All" so the user can clear a queue of finished items as completed (correct status for things that were actually done) instead of dismissing them (which means "ignored"). File: `client/src/pages/Review.jsx`.+- **Flux i2i: portrait iPhone photos came out rotated 90°.** Modern browsers honor the EXIF Orientation tag when rendering `<img>`, so the upload thumbnail looked right — but mflux/PIL reads raw pixel data and ignores EXIF, so a portrait iPhone photo (Orientation=6 or 8) landed sideways in the generated output. The init image picker now passes the file through `createImageBitmap({ imageOrientation: 'from-image' })` and re-encodes via canvas before upload, baking the rotation into the actual pixels and stripping the EXIF tag. Any image decoder downstream now sees the same orientation the browser displayed. File: `client/src/pages/ImageGen.jsx`.- **Multipart upload server crash: `Cannot read properties of null (reading 'write')`.** Streaming multipart parser (`server/lib/multipart.js`) crashed with an uncaught `TypeError` when the request stream's `'end'` event fired while a file part's `ws.end()` flush was still in flight. After consuming a part boundary, `endPart()` synchronously nulled `writeStream` but kept `state` at `STATE_BODY` until the async `ws.end` callback ran. If `req.on('end')` fired during that window, the end handler called `tick()`, which re-entered `STATE_BODY`, found another boundary in the trailing buffer, and called `writePartChunk()` → `writeStream.write(chunk)` on a `null` stream → process-killing `uncaughtException`. Fix: `tick()` now returns early when `pendingFlush > 0`; the existing `endPart` callback already re-invokes `tick()` once the flush completes and state has advanced. Added a regression test that defers the mocked `ws.end()` callback so the bug reproduces without the fix. File: `server/lib/multipart.js`.diff --git a/client/src/pages/Review.jsx b/client/src/pages/Review.jsxindex 6d7ce65704..eec0b417e3 100644--- a/client/src/pages/Review.jsx+++ b/client/src/pages/Review.jsx@@ -114,11 +114,14 @@ export default function Review() {setEditingId(null);};- const handleMarkAllRead = async () => {+ const applyToAllPending = (apiFn) => {const pendingItems = items.filter(i => i.status === 'pending');- await Promise.all(pendingItems.map(i => api.dismissReviewItem(i.id).catch(() => null)));+ return Promise.all(pendingItems.map(i => apiFn(i.id).catch(() => null)));};+ const handleMarkAllRead = () => applyToAllPending(api.dismissReviewItem);+ const handleCompleteAll = () => applyToAllPending(api.completeReviewItem);+const grouped = items.reduce((acc, item) => {if (!acc[item.type]) acc[item.type] = [];acc[item.type].push(item);@@ -171,12 +174,22 @@ export default function Review() {<option value="all">All</option></select>{pendingCount > 0 && (- <button- onClick={handleMarkAllRead}- className="px-3 py-2 text-sm bg-port-border/50 hover:bg-port-border rounded-lg text-gray-300 transition-colors"- >- Mark All Read- </button>+ <>+ <button+ onClick={handleCompleteAll}+ className="px-3 py-2 text-sm bg-port-success/10 hover:bg-port-success/20 border border-port-success/30 rounded-lg text-port-success transition-colors"+ title="Mark all pending items as completed"+ >+ Complete All+ </button>+ <button+ onClick={handleMarkAllRead}+ className="px-3 py-2 text-sm bg-port-border/50 hover:bg-port-border rounded-lg text-gray-300 transition-colors"+ title="Dismiss all pending items"+ >+ Dismiss All+ </button>+ </>)}</div></div>diff --git a/server/services/review.js b/server/services/review.jsindex c03b4e6cda..59b63bc8f4 100644--- a/server/services/review.js+++ b/server/services/review.js@@ -238,17 +238,28 @@ cosEvents.on('memory:approval-needed', (data) => {}});-async function dismissByReferenceId(referenceId) {+async function updateStatusByReferenceId(referenceId, status) {+ if (!ITEM_STATUSES.includes(status)) {+ const err = new Error(`Invalid status: ${status}`);+ err.status = 400;+ throw err;+ }+const items = await loadItems();const matching = items.filter(i => i.metadata?.referenceId === referenceId && i.status === 'pending');+ if (matching.length === 0) return;+ const now = new Date().toISOString();for (const item of matching) {- item.status = 'dismissed';- item.updatedAt = new Date().toISOString();- reviewEvents.emit('item:updated', item);+ item.status = status;+ item.updatedAt = now;}- if (matching.length > 0) await saveItems(items);+ await saveItems(items);+ for (const item of matching) reviewEvents.emit('item:updated', item);}+const dismissByReferenceId = (referenceId) => updateStatusByReferenceId(referenceId, 'dismissed');+const completeByReferenceId = (referenceId) => updateStatusByReferenceId(referenceId, 'completed');+cosEvents.on('memory:approved', (data) => {if (data?.id) dismissByReferenceId(data.id).catch(err => console.error(`❌ Failed to dismiss approved memory review item: ${err.message}`));});@@ -265,3 +276,17 @@ cosEvents.on('task:ready', (data) => {metadata: { taskId: data?.id, referenceId: data?.id }}).catch(err => console.error(`❌ Failed to create review item: ${err.message}`));});++// When a CoS agent finishes a task, auto-resolve the matching review item so+// the user isn't asked to manually mark something complete that an agent+// already handled. Success → complete; failure stays pending so the user can+// see and act on it.+cosEvents.on('agent:completed', (agent) => {+ const taskId = agent?.taskId;+ if (!taskId) return;+ if (agent.result?.success) {+ completeByReferenceId(taskId).catch(err =>+ console.error(`❌ Failed to auto-complete review item for task ${taskId}: ${err.message}`)+ );+ }+});diff --git a/server/services/review.test.js b/server/services/review.test.jsindex 8bdc0c8fe8..f2c84c7b4e 100644--- a/server/services/review.test.js+++ b/server/services/review.test.js@@ -9,7 +9,10 @@ vi.mock('fs/promises', () => ({const emit = vi.fn();const reviewEvents = { emit };-const cosEvents = { on: vi.fn() };+const registeredHandlers = {};+const cosEvents = {+ on: vi.fn((event, handler) => { registeredHandlers[event] = handler; })+};vi.mock('./cosEvents.js', () => ({ cosEvents }));@@ -182,4 +185,40 @@ describe('review service', () => {expect(briefing.content).toContain('No CoS daily briefing found yet');});});++ describe('cosEvents bridge', () => {+ it('auto-completes the matching review item when an agent finishes successfully', async () => {+ const handler = registeredHandlers['agent:completed'];+ expect(handler).toBeDefined();++ const items = [+ { id: 'r1', type: 'cos', status: 'pending', metadata: { referenceId: 'task-42', taskId: 'task-42' } },+ { id: 'r2', type: 'cos', status: 'pending', metadata: { referenceId: 'task-99', taskId: 'task-99' } }+ ];+ readFile.mockResolvedValue(JSON.stringify(items));++ handler({ taskId: 'task-42', result: { success: true } });+ // Wait a tick for the async chain inside the handler to flush+ await new Promise(r => setImmediate(r));++ const written = atomicWrite.mock.calls[0][1];+ const updated = written.find(i => i.id === 'r1');+ const untouched = written.find(i => i.id === 'r2');+ expect(updated.status).toBe('completed');+ expect(untouched.status).toBe('pending');+ });++ it('does not auto-complete when the agent failed', async () => {+ const handler = registeredHandlers['agent:completed'];+ const items = [+ { id: 'r1', type: 'cos', status: 'pending', metadata: { referenceId: 'task-42', taskId: 'task-42' } }+ ];+ readFile.mockResolvedValue(JSON.stringify(items));++ handler({ taskId: 'task-42', result: { success: false, error: 'boom' } });+ await new Promise(r => setImmediate(r));++ expect(atomicWrite).not.toHaveBeenCalled();+ });+ });});