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
address review: typed error codes, ARIA on LayoutPicker, optimistic revert, layout-changed event
Adam Eivy506842637910
diff --git a/client/src/components/CmdKSearch.jsx b/client/src/components/CmdKSearch.jsxindex 9ae39f079e..5ea6c0443a 100644--- a/client/src/components/CmdKSearch.jsx+++ b/client/src/components/CmdKSearch.jsx@@ -179,6 +179,10 @@ export default function CmdKSearch() {search: (item) => { navigate(item.url); close(); },layout: async (item) => {await setActiveDashboardLayout(item.layoutId);+ // Notify any mounted Dashboard to re-fetch — navigate('/') is a+ // no-op if the user is already on the dashboard, and we otherwise+ // wouldn't see the new active layout until next mount.+ window.dispatchEvent(new CustomEvent('portos:dashboard-layout-changed'));navigate('/');toast.success(`Switched to "${item.layoutName}"`);close();diff --git a/client/src/components/dashboard/LayoutPicker.jsx b/client/src/components/dashboard/LayoutPicker.jsxindex 8dc0ed3af5..cc29bd7374 100644--- a/client/src/components/dashboard/LayoutPicker.jsx+++ b/client/src/components/dashboard/LayoutPicker.jsx@@ -17,25 +17,34 @@ export default function LayoutPicker({ layouts, activeLayoutId, onSelect, onEdit<div ref={ref} className="relative"><buttononClick={() => setOpen((v) => !v)}- className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-card border border-port-border hover:border-gray-600 transition-colors text-sm text-gray-300 hover:text-white min-h-[40px]"+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-card border border-port-border hover:border-gray-600 transition-colors text-sm text-gray-300 hover:text-white min-h-[40px] focus:outline-hidden focus:ring-2 focus:ring-port-accent focus:ring-offset-2 focus:ring-offset-port-bg"title="Switch dashboard layout"+ aria-label={`Dashboard layout: ${active?.name || 'none'}`}+ aria-expanded={open}+ aria-haspopup="menu">- <LayoutGrid size={14} />+ <LayoutGrid size={14} aria-hidden="true" /><span className="hidden sm:inline">{active?.name || 'Layout'}</span></button>{open && (- <div className="absolute right-0 mt-1 w-56 bg-port-card border border-port-border rounded-lg shadow-2xl overflow-hidden z-50">+ <div+ role="menu"+ aria-label="Dashboard layout menu"+ className="absolute right-0 mt-1 w-56 bg-port-card border border-port-border rounded-lg shadow-2xl overflow-hidden z-50"+ ><div className="py-1">{layouts.map((l) => (<buttonkey={l.id}+ role="menuitemradio"+ aria-checked={l.id === activeLayoutId}onClick={() => { onSelect(l.id); setOpen(false); }}className={`w-full text-left flex items-center gap-2 px-3 py-2 text-sm hover:bg-white/5 ${l.id === activeLayoutId ? 'text-white' : 'text-gray-300'}`}>- {l.id === activeLayoutId ? <Check size={14} className="text-port-success" /> : <span className="w-3.5" />}+ {l.id === activeLayoutId ? <Check size={14} className="text-port-success" aria-hidden="true" /> : <span className="w-3.5" aria-hidden="true" />}<span className="flex-1 truncate">{l.name}</span>{l.builtIn && <span className="text-[10px] text-gray-500 uppercase">Built-in</span>}</button>@@ -43,10 +52,11 @@ export default function LayoutPicker({ layouts, activeLayoutId, onSelect, onEdit</div><div className="border-t border-port-border"><button+ role="menuitem"onClick={() => { setOpen(false); onEdit(); }}className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-300 hover:bg-white/5 hover:text-white">- <Pencil size={14} />+ <Pencil size={14} aria-hidden="true" /><span>Edit layouts…</span></button></div>diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsxindex 7a4f6bcafc..37a0b015d0 100644--- a/client/src/pages/Dashboard.jsx+++ b/client/src/pages/Dashboard.jsx@@ -41,12 +41,21 @@ export default function Dashboard() {}, [fetchData]);useEffect(() => {- api.getDashboardLayouts()+ const fetchLayouts = () => api.getDashboardLayouts().then((data) => {setLayouts(data.layouts);setActiveLayoutId(data.activeLayoutId);}).catch((err) => setError(`Layouts: ${err.message}`));++ fetchLayouts();++ // External switchers (the ⌘K palette) fire this event after writing+ // to the server so the Dashboard re-syncs even when already on `/`+ // (where navigate('/') would be a no-op and no remount happens).+ const handleLayoutChanged = () => fetchLayouts();+ window.addEventListener('portos:dashboard-layout-changed', handleLayoutChanged);+ return () => window.removeEventListener('portos:dashboard-layout-changed', handleLayoutChanged);}, []);const sortedApps = useMemo(() =>@@ -84,8 +93,14 @@ export default function Dashboard() {);const selectLayout = async (id) => {+ const previousId = activeLayoutId;setActiveLayoutId(id);- await api.setActiveDashboardLayout(id);+ // Revert optimistic state on failure — request() toasts the error+ // centrally, but the picker can't stay showing the wrong selection.+ await api.setActiveDashboardLayout(id).catch((err) => {+ setActiveLayoutId(previousId);+ throw err;+ });};const saveLayout = async ({ id, name, widgets }) => {diff --git a/server/routes/dashboardLayouts.js b/server/routes/dashboardLayouts.jsindex 7dd2961306..89a8e781a5 100644--- a/server/routes/dashboardLayouts.js+++ b/server/routes/dashboardLayouts.js@@ -23,15 +23,27 @@ const setActiveSchema = z.object({id: z.string().min(1).max(60),});+// Map service error codes to HTTP statuses. Any other error (I/O, parse,+// write failures) bubbles through asyncHandler as 500 — do NOT collapse+// unknown errors into 404, that hides real server problems.+const SERVICE_ERROR_STATUS = {+ [svc.ERR_NOT_FOUND]: 404,+ [svc.ERR_BUILTIN_PROTECTED]: 400,+};++const mapServiceError = (err) => {+ const status = SERVICE_ERROR_STATUS[err?.code];+ if (status) return new ServerError(err.message, { status });+ return err;+};+router.get('/', asyncHandler(async (_req, res) => {res.json(await svc.getState());}));router.put('/active', asyncHandler(async (req, res) => {const { id } = validateRequest(setActiveSchema, req.body ?? {});- const state = await svc.setActiveLayout(id).catch((err) => {- throw new ServerError(err.message, { status: 404 });- });+ const state = await svc.setActiveLayout(id).catch((err) => { throw mapServiceError(err); });res.json(state);}));@@ -41,9 +53,7 @@ router.put('/:id', asyncHandler(async (req, res) => {}));router.delete('/:id', asyncHandler(async (req, res) => {- const state = await svc.deleteLayout(String(req.params.id)).catch((err) => {- throw new ServerError(err.message, { status: err.message.includes('Cannot delete') ? 400 : 404 });- });+ const state = await svc.deleteLayout(String(req.params.id)).catch((err) => { throw mapServiceError(err); });res.json(state);}));diff --git a/server/routes/dashboardLayouts.test.js b/server/routes/dashboardLayouts.test.jsindex a1057c4781..15cefe6059 100644--- a/server/routes/dashboardLayouts.test.js+++ b/server/routes/dashboardLayouts.test.js@@ -4,6 +4,8 @@ import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';vi.mock('../services/dashboardLayouts.js', () => ({+ ERR_NOT_FOUND: 'NOT_FOUND',+ ERR_BUILTIN_PROTECTED: 'BUILTIN_PROTECTED',getState: vi.fn(),setActiveLayout: vi.fn(),saveLayout: vi.fn(),@@ -49,12 +51,20 @@ describe('PUT /api/dashboard/layouts/active', () => {});it('404s on unknown layout', async () => {- svc.setActiveLayout.mockRejectedValue(new Error('Unknown layout id: nope'));+ svc.setActiveLayout.mockRejectedValue(Object.assign(new Error('Unknown layout id: nope'), { code: 'NOT_FOUND' }));const res = await request(makeApp()).put('/api/dashboard/layouts/active').send({ id: 'nope' });expect(res.status).toBe(404);});++ it('500s (bubbles) on unexpected service errors — does not collapse to 404', async () => {+ svc.setActiveLayout.mockRejectedValue(new Error('disk full'));+ const res = await request(makeApp())+ .put('/api/dashboard/layouts/active')+ .send({ id: 'default' });+ expect(res.status).toBe(500);+ });});describe('PUT /api/dashboard/layouts/:id', () => {@@ -89,8 +99,14 @@ describe('DELETE /api/dashboard/layouts/:id', () => {});it('400s when trying to delete a built-in layout', async () => {- svc.deleteLayout.mockRejectedValue(new Error('Cannot delete built-in layout: default'));+ svc.deleteLayout.mockRejectedValue(Object.assign(new Error('Cannot delete built-in layout: default'), { code: 'BUILTIN_PROTECTED' }));const res = await request(makeApp()).delete('/api/dashboard/layouts/default');expect(res.status).toBe(400);});++ it('404s when deleting an unknown layout', async () => {+ svc.deleteLayout.mockRejectedValue(Object.assign(new Error('Unknown layout id: nope'), { code: 'NOT_FOUND' }));+ const res = await request(makeApp()).delete('/api/dashboard/layouts/nope');+ expect(res.status).toBe(404);+ });});diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.jsindex 0c7b7e67a4..7b998700e5 100644--- a/server/services/dashboardLayouts.js+++ b/server/services/dashboardLayouts.js@@ -15,8 +15,14 @@ import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.jsconst STATE_PATH = join(PATHS.data, 'dashboard-layouts.json');+// Service errors carry a `code` field so routes can map to HTTP status+// without string-matching on err.message (which breaks on rename/i18n).+export const ERR_NOT_FOUND = 'NOT_FOUND';+export const ERR_BUILTIN_PROTECTED = 'BUILTIN_PROTECTED';+const makeErr = (message, code) => Object.assign(new Error(message), { code });+// Widget ids are the contract between this file and the client registry —-// see client/src/components/dashboard/widgetRegistry.js. If a layout refers+// see client/src/components/dashboard/widgetRegistry.jsx. If a layout refers// to an unknown id, the client skips it gracefully.const DEFAULT_LAYOUTS = [{@@ -56,14 +62,23 @@ const DEFAULT_STATE = {layouts: DEFAULT_LAYOUTS,};+// Sanitize a single layout entry — protect against hand-edits that produce+// non-object elements, missing fields, or non-array widget lists.+const sanitizeLayout = (l) => {+ if (!l || typeof l !== 'object') return null;+ if (typeof l.id !== 'string' || !l.id) return null;+ if (typeof l.name !== 'string' || !l.name) return null;+ const widgets = Array.isArray(l.widgets) ? l.widgets.filter((w) => typeof w === 'string') : [];+ return { id: l.id, name: l.name, builtIn: !!l.builtIn, widgets };+};+export async function getState() {await ensureDir(PATHS.data);const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false });- // If the file exists but has drifted (missing fields, or user deleted all- // layouts), merge in defaults conservatively rather than returning junk.- const layouts = Array.isArray(raw.layouts) && raw.layouts.length > 0- ? raw.layouts- : DEFAULT_LAYOUTS;+ const sanitized = Array.isArray(raw.layouts)+ ? raw.layouts.map(sanitizeLayout).filter(Boolean)+ : [];+ const layouts = sanitized.length > 0 ? sanitized : DEFAULT_LAYOUTS;const activeLayoutId = layouts.find((l) => l.id === raw.activeLayoutId)? raw.activeLayoutId: layouts[0].id;@@ -73,7 +88,7 @@ export async function getState() {export async function setActiveLayout(id) {const state = await getState();if (!state.layouts.find((l) => l.id === id)) {- throw new Error(`Unknown layout id: ${id}`);+ throw makeErr(`Unknown layout id: ${id}`, ERR_NOT_FOUND);}const next = { ...state, activeLayoutId: id };await atomicWrite(STATE_PATH, next);@@ -94,8 +109,8 @@ export async function saveLayout(layout) {export async function deleteLayout(id) {const state = await getState();const target = state.layouts.find((l) => l.id === id);- if (!target) throw new Error(`Unknown layout id: ${id}`);- if (target.builtIn) throw new Error(`Cannot delete built-in layout: ${id}`);+ if (!target) throw makeErr(`Unknown layout id: ${id}`, ERR_NOT_FOUND);+ if (target.builtIn) throw makeErr(`Cannot delete built-in layout: ${id}`, ERR_BUILTIN_PROTECTED);const remaining = state.layouts.filter((l) => l.id !== id);// Guard against the pathological case where the JSON was hand-edited to// remove every built-in — fall back to reseeding defaults rather than