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([issue-711]): address claude+codex iter-2 review
Adam Eivyc7e6ff07ab21
diff --git a/client/src/components/WhileAwayWidget.jsx b/client/src/components/WhileAwayWidget.jsxindex 4660ef1203..a210ee5673 100644--- a/client/src/components/WhileAwayWidget.jsx+++ b/client/src/components/WhileAwayWidget.jsx@@ -22,8 +22,8 @@ const LAST_SEEN_KEY = 'portos.whileAway.lastSeen';const readLastSeen = () => {// localStorage access can throw in private-mode / storage-disabled /// security-error contexts — never let that crash the dashboard render.- // (Same guard idiom as utils/timeWindow.js.)- if (typeof window === 'undefined' || !window.localStorage) return null;+ // Even *reading* the `window.localStorage` property can throw in some+ // sandboxed iframes, so it's acquired inside the try (not before it).let raw = null;try { raw = window.localStorage.getItem(LAST_SEEN_KEY); }catch { return null; }@@ -37,9 +37,9 @@ const readLastSeen = () => {};const writeLastSeen = (iso) => {- // A write failure (quota / disabled) must not break "Mark as seen" — the- // subsequent refetch still runs; the window just isn't persisted this time.- if (typeof window === 'undefined' || !window.localStorage) return;+ // A write failure (quota / disabled / property-access throw) must not break+ // "Mark as seen" — the subsequent refetch still runs; the window just isn't+ // persisted this time.try { window.localStorage.setItem(LAST_SEEN_KEY, iso); }catch { /* private mode / quota — graceful no-op */ }};@@ -71,14 +71,17 @@ export default function WhileAwayWidget() {// The marker captured at fetch time, so "Mark as seen" and the header label// reflect the window we actually queried (not a value that drifted since).const sinceRef = useRef(null);+ // A socket-driven refresh can land after the widget unmounts — guard the+ // async setState so it doesn't fire into the void (CLAUDE.md unmount rule).+ const mountedRef = useRef(true);const load = useCallback(() => {const since = readLastSeen();sinceRef.current = since;return api.getCosWhileAwayActivity(since, { silent: true })- .then((res) => setData(res))+ .then((res) => { if (mountedRef.current) setData(res); }).catch(() => null)- .finally(() => setLoading(false));+ .finally(() => { if (mountedRef.current) setLoading(false); });}, []);useEffect(() => {@@ -87,7 +90,10 @@ export default function WhileAwayWidget() {// refresh on completion so the card stays live (mirrors ReviewHubCard).const refresh = () => load();socket.on('cos:agent:completed', refresh);- return () => socket.off('cos:agent:completed', refresh);+ return () => {+ mountedRef.current = false;+ socket.off('cos:agent:completed', refresh);+ };}, [load]);const markSeen = () => {@@ -135,6 +141,7 @@ export default function WhileAwayWidget() {onClick={markSeen}className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs bg-port-bg border border-port-border hover:border-port-accent/50 text-gray-300 rounded-lg transition-colors shrink-0 min-h-[36px]"title="Reset the window to now"+ aria-label="Mark as seen — reset the window to now"><Eye size={13} /><span className="hidden sm:inline">Mark as seen</span>diff --git a/client/src/components/dashboard/widgetRegistry.jsx b/client/src/components/dashboard/widgetRegistry.jsxindex c7d1ce55ac..5517206d0a 100644--- a/client/src/components/dashboard/widgetRegistry.jsx+++ b/client/src/components/dashboard/widgetRegistry.jsx@@ -36,7 +36,7 @@ const HourlyActivityWidget = lazyWithReload(() => import('./builtins/HourlyActi//// `module` is optional micrographic chrome — when set, the dashboard// renders a SchematicLabel ("MODULE.04 // ALERTS ●") as a tab on the-// widget's top border. Six widgets carry this by default; the rest are+// widget's top border. Several widgets carry this by default; the rest are// label-free so the dashboard doesn't turn into a wall of HUD chrome.export const WIDGETS = [{ id: 'quick-brain', label: 'Quick Brain Capture', Component: QuickBrainCapture, width: 'half', defaultH: 3 },diff --git a/scripts/migrations/070-seed-while-away-widget.js b/scripts/migrations/070-seed-while-away-widget.jsindex 9e00118ea9..cf3e12c42a 100644--- a/scripts/migrations/070-seed-while-away-widget.js+++ b/scripts/migrations/070-seed-while-away-widget.js@@ -22,7 +22,7 @@ const WIDGET_H = 5;// DEFAULT_LAYOUTS — edits here must match that file or fresh installs +// migrated installs diverge. `agent-watch` gives the card a wider slot.const PREFERRED_SLOTS = {- default: { x: 9, y: 14, w: WIDGET_W, h: WIDGET_H },+ default: { x: 9, y: 15, w: WIDGET_W, h: 3 },'agent-watch': { x: 6, y: 3, w: 6, h: WIDGET_H },};const TARGET_LAYOUT_IDS = Object.keys(PREFERRED_SLOTS);@@ -45,9 +45,17 @@ function pickGridEntry(grid, layoutId) {if (!collidesWith(grid, candidate)) return candidate;}// Fall back to a clean row below everything else if the preferred slot is- // occupied (a user rearranged the layout but kept the built-in id).+ // occupied (a user rearranged the layout but kept the built-in id). Carry+ // the layout's preferred width/height so a collided agent-watch heal still+ // gets the intended 6-wide card, not the bare WIDGET_W default.const bottom = grid.reduce((max, it) => Math.max(max, (it.y ?? 0) + (it.h ?? 0)), 0);- return { id: WIDGET_ID, x: 0, y: bottom, w: WIDGET_W, h: WIDGET_H };+ return {+ id: WIDGET_ID,+ x: 0,+ y: bottom,+ w: preferred?.w ?? WIDGET_W,+ h: preferred?.h ?? WIDGET_H+ };}function applyToLayout(layout) {diff --git a/scripts/migrations/070-seed-while-away-widget.test.js b/scripts/migrations/070-seed-while-away-widget.test.jsindex f5d8da2009..2b23b828aa 100644--- a/scripts/migrations/070-seed-while-away-widget.test.js+++ b/scripts/migrations/070-seed-while-away-widget.test.js@@ -55,7 +55,7 @@ describe('migration 070 — seed while-away widget into default + agent-watch laconst def = after.layouts.find((l) => l.id === 'default');expect(def.widgets).toContain('while-away');- expect(def.grid.find((g) => g.id === 'while-away')).toEqual({ id: 'while-away', x: 9, y: 14, w: 3, h: 5 });+ expect(def.grid.find((g) => g.id === 'while-away')).toEqual({ id: 'while-away', x: 9, y: 15, w: 3, h: 3 });const watch = after.layouts.find((l) => l.id === 'agent-watch');expect(watch.widgets).toContain('while-away');@@ -142,4 +142,28 @@ describe('migration 070 — seed while-away widget into default + agent-watch laexpect(newEntry.x).toBe(0);expect(newEntry.y).toBeGreaterThanOrEqual(19);});++ it('keeps the agent-watch preferred width (6) when the slot is occupied', async () => {+ writeJson(layoutsPath, {+ activeLayoutId: 'agent-watch',+ layouts: [+ {+ id: 'agent-watch',+ name: 'Agent Watch',+ builtIn: true,+ widgets: ['system-health'],+ // Occupies the preferred slot (x:6,y:3) so the fallback path runs.+ grid: [{ id: 'system-health', x: 6, y: 3, w: 6, h: 5 }],+ },+ ],+ });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(1);+ const after = readJson(layoutsPath);+ const newEntry = after.layouts[0].grid.find((g) => g.id === 'while-away');+ expect(newEntry).toBeDefined();+ // Fallback must carry the layout's preferred width, not the bare default.+ expect(newEntry.w).toBe(6);+ expect(newEntry.h).toBe(5);+ });});diff --git a/server/routes/cos.test.js b/server/routes/cos.test.jsindex 03044a30ca..3d79f63294 100644--- a/server/routes/cos.test.js+++ b/server/routes/cos.test.js@@ -48,6 +48,7 @@ vi.mock('../services/cos.js', () => ({getScript: vi.fn(),forceSpawnTask: vi.fn(),getTodayActivity: vi.fn(),+ getWhileAwayActivity: vi.fn(),getRecentTasks: vi.fn()}));@@ -1073,4 +1074,37 @@ describe('CoS Routes', () => {expect(response.body.stats.completed).toBe(5);});});++ describe('GET /api/cos/activity/while-away', () => {+ it('passes a valid ISO since through to the service', async () => {+ cos.getWhileAwayActivity.mockResolvedValue({ stats: { completed: 3 } });+ const since = '2026-06-01T00:00:00.000Z';++ const response = await request(app).get(`/api/cos/activity/while-away?since=${encodeURIComponent(since)}`);++ expect(response.status).toBe(200);+ expect(response.body.stats.completed).toBe(3);+ expect(cos.getWhileAwayActivity).toHaveBeenCalledWith(since);+ });++ it('tolerates a garbage since (200 + service fallback, not 400)', async () => {+ cos.getWhileAwayActivity.mockResolvedValue({ stats: { completed: 0 } });++ const response = await request(app).get('/api/cos/activity/while-away?since=not-a-date');++ expect(response.status).toBe(200);+ // Malformed value is dropped to undefined so the service applies its+ // own 24h fallback rather than the route 400-ing the dashboard card.+ expect(cos.getWhileAwayActivity).toHaveBeenCalledWith(undefined);+ });++ it('works with no since param', async () => {+ cos.getWhileAwayActivity.mockResolvedValue({ stats: { completed: 1 } });++ const response = await request(app).get('/api/cos/activity/while-away');++ expect(response.status).toBe(200);+ expect(cos.getWhileAwayActivity).toHaveBeenCalledWith(undefined);+ });+ });});diff --git a/server/routes/cosReportRoutes.js b/server/routes/cosReportRoutes.jsindex 0dc50aaded..6b4b140967 100644--- a/server/routes/cosReportRoutes.js+++ b/server/routes/cosReportRoutes.js@@ -14,11 +14,15 @@ import { validateRequest } from '../lib/validation.js';const router = Router();// `since` is the client's last-visit marker (ISO-8601). Optional and tolerant:-// an absent/garbage value is clamped server-side to a 24h fallback, so we only-// reject a malformed datetime to keep the contract honest — we don't 400 on-// omission.+// `getWhileAwayActivity` already clamps an absent/garbage/future marker to a+// 24h fallback, so a malformed value preprocesses to `undefined` (let the+// service apply its fallback) rather than 400-ing the dashboard card into a+// blank state. A valid datetime string passes through unchanged.const whileAwayQuerySchema = z.object({- since: z.string().datetime({ offset: true }).optional()+ since: z.preprocess(+ (v) => (typeof v === 'string' && !Number.isNaN(Date.parse(v)) ? v : undefined),+ z.string().optional()+ )});// GET /api/cos/reports - List all reportsdiff --git a/server/services/cosReports.js b/server/services/cosReports.jsindex 313327b4e6..5efcb9c754 100644--- a/server/services/cosReports.js+++ b/server/services/cosReports.js@@ -12,6 +12,17 @@ import { loadState, ensureDirectories, REPORTS_DIR, isDaemonRunning } from './coimport { getAgentsByDate } from './cosAgents.js';import { formatDuration, safeJSONParse } from '../lib/fileUtils.js';+// A completed agent's work duration in ms: prefer the recorded `result.duration`,+// else derive from completedAt − startedAt. Clamped to >=0 so a clock-skewed+// record (completedAt < startedAt) can't surface a negative duration.+function agentDurationMs(a) {+ const d = a.result?.duration+ || (a.completedAt && a.startedAt+ ? new Date(a.completedAt).getTime() - new Date(a.startedAt).getTime()+ : 0);+ return d > 0 ? d : 0;+}+export async function generateReport(date = null) {const reportDate = date || new Date().toISOString().split('T')[0];const state = await loadState();@@ -117,12 +128,8 @@ export async function getTodayActivity() {const succeeded = todayAgents.filter(a => a.result?.success);const failed = todayAgents.filter(a => !a.result?.success);- // Calculate total time worked (sum of agent durations, fallback to completedAt - startedAt)- const totalDurationMs = todayAgents.reduce((sum, a) => {- const duration = a.result?.duration- || (a.completedAt && a.startedAt ? new Date(a.completedAt).getTime() - new Date(a.startedAt).getTime() : 0);- return sum + (duration > 0 ? duration : 0);- }, 0);+ // Calculate total time worked (sum of agent durations)+ const totalDurationMs = todayAgents.reduce((sum, a) => sum + agentDurationMs(a), 0);// Get currently running agentsconst runningAgents = Object.values(state.agents).filter(a => a.status === 'running');@@ -138,8 +145,7 @@ export async function getTodayActivity() {taskId: a.taskId,description: a.metadata?.taskDescription?.substring(0, 100) || a.taskId,taskType: a.metadata?.analysisType || a.metadata?.taskType || 'task',- duration: a.result?.duration- || (a.completedAt && a.startedAt ? new Date(a.completedAt).getTime() - new Date(a.startedAt).getTime() : 0),+ duration: agentDurationMs(a),completedAt: a.completedAt})).sort((a, b) => new Date(b.completedAt) - new Date(a.completedAt))@@ -180,18 +186,8 @@ function summarizeAwayActivity(agents, sinceIso) {const succeeded = agents.filter(a => a.result?.success);const failed = agents.filter(a => !a.result?.success);- // Clamp to >=0 so a clock-skewed completedAt < startedAt can't produce a- // negative duration in either the per-card field or the rollup.- const durationOf = (a) => {- const d = a.result?.duration- || (a.completedAt && a.startedAt- ? new Date(a.completedAt).getTime() - new Date(a.startedAt).getTime()- : 0);- return d > 0 ? d : 0;- };-const toCard = (a) => {- const durationMs = durationOf(a);+ const durationMs = agentDurationMs(a);return {id: a.id,taskId: a.taskId,@@ -208,7 +204,7 @@ function summarizeAwayActivity(agents, sinceIso) {// Most-recent first so the freshest work tops each list.const byRecency = (a, b) => new Date(b.completedAt) - new Date(a.completedAt);- const totalDurationMs = agents.reduce((sum, a) => sum + durationOf(a), 0);+ const totalDurationMs = agents.reduce((sum, a) => sum + agentDurationMs(a), 0);return {sinceIso,diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.jsindex 43f92f7e44..3931a12a8d 100644--- a/server/services/dashboardLayouts.js+++ b/server/services/dashboardLayouts.js@@ -108,10 +108,12 @@ const DEFAULT_LAYOUTS = [{ id: 'quick-stats', x: 3, y: 10, w: 3, h: 3 },{ id: 'goal-progress', x: 6, y: 10, w: 3, h: 4 },{ id: 'network-exposure', x: 9, y: 10, w: 3, h: 5 },- // Row 14–17: lower-priority + cos+ // Row 14–17: lower-priority + cos. while-away fills the x9–11 column+ // in rows 15–17 — below network-exposure (ends at row 14) and above+ // hourly-activity (starts at row 18), so it overlaps neither.{ id: 'decision-log', x: 0, y: 14, w: 4, h: 2 },{ id: 'cos', x: 4, y: 14, w: 5, h: 4 },- { id: 'while-away', x: 9, y: 14, w: 3, h: 5 },+ { id: 'while-away', x: 9, y: 15, w: 3, h: 3 },// Row 18+: full-width visualizations + apps{ id: 'hourly-activity', x: 0, y: 18, w: 12, h: 3 },{ id: 'apps', x: 0, y: 21, w: 12, h: 8 },diff --git a/server/services/dashboardLayouts.test.js b/server/services/dashboardLayouts.test.jsindex be26f9cc9f..19efcf9df1 100644--- a/server/services/dashboardLayouts.test.js+++ b/server/services/dashboardLayouts.test.js@@ -175,4 +175,28 @@ describe('dashboardLayouts service', () => {expect(existsSync(STATE_FILE)).toBe(false);});});++ describe('built-in layout grids have no overlapping cells', () => {+ // Regression: a hand-tuned grid edit can place two widgets in the same+ // rows/cols, so fresh installs render stacked cards. Every built-in+ // layout's grid rectangles must be pairwise non-overlapping.+ const rectsOverlap = (a, b) =>+ a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;++ it('no two grid items overlap in any seeded built-in layout', async () => {+ const state = await svc.getState();+ const collisions = [];+ for (const layout of state.layouts) {+ const grid = layout.grid || [];+ for (let i = 0; i < grid.length; i += 1) {+ for (let j = i + 1; j < grid.length; j += 1) {+ if (rectsOverlap(grid[i], grid[j])) {+ collisions.push(`${layout.id}: ${grid[i].id} ∩ ${grid[j].id}`);+ }+ }+ }+ }+ expect(collisions).toEqual([]);+ });+ });});