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
feat([issue-1967]): add tabbed, wider, deep-linkable layout to the slide-in Drawer
[._.]/ Adam Eivy2c370fbe4949
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex bc9665f040..eb7bdfb1bc 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -127,3 +127,4 @@- **[self-improvement] CoS's auto-approved error-investigation tasks now require human review, matching the rest of the codebase's error-driven task creators** — two task creators auto-approved an unsupervised agent to start editing code from thin diagnostic evidence: `autoFixer.js`'s `createAutoFixTask` (triggered by `severity: 'critical'` or `canAutoFix`, covering bare `uncaughtException`/`unhandledRejection` — no repro steps, no live process state, since the process already crashed) and `agentManagement.js`'s orphan-retry investigation task (triggered after repeated agent-orphaning, an infra/process-flakiness signal rather than a diagnosed code bug). Every other error-driven task creator (`createAIProviderInvestigationTask`, `handleErrorRecovery`, `agentErrorAnalysis.js`'s `createInvestigationTask`) already required approval first; these two were the outliers, and both shipped with zero test coverage for this branch. CoS's own `learning.json` history bears this out — this task class runs rarely and has a materially worse success rate than the reviewed-first paths. Flipped both to `approvalRequired: true` and added coverage for the previously-untested branches (approval flag, trigger conditions, skip paths, dedupe).- **[issue-1956] Extracted a shared SIGTERM→grace→SIGKILL kill-escalation helper for spawn-based jobs** — the identical "SIGTERM, then after 8s escalate to SIGKILL if the tracked child hasn't exited" cancel block was copy-pasted across seven job-cancel paths (`musicVideo/render.js`, `videoTimeline/local.js`, `imageGen/local.js`, `imageGen/codex.js`, `videoGen/local.js`, `loraTraining/index.js`, `trackYoutubeImport.js`). It now lives in one place — `killWithEscalation(proc, { label, stillRunning, delayMs=8000 })` (`server/lib/killWithEscalation.js`) — which preserves each site's exact guard (`job.process === proc` / `activeProcess === proc` / `activeProcs.get(id) === proc`), its exit check (`exitCode === null && signalCode === null`), and its emoji-prefixed single-line warning, while wrapping the out-of-request-lifecycle `setTimeout` callback in try/catch and unref'ing the timer (codex passes `delayMs: 5000`). Behavior-preserving consolidation; covered by a new `killWithEscalation.test.js`. (#1956)+- **[issue-1967] The slide-in `Drawer` primitive gained a tabbed, wider, deep-linkable layout** — the shared right-side config drawer (`client/src/components/Drawer.jsx`) was a single flat scroll in a fixed ~520px panel, so large config surfaces (Edit App, Media Generation Settings, CoS task config) became page-length scrolls. It now takes a `size` prop (`sm`/`md`/`lg`/`xl`, the last two using more of a wide viewport via extra breakpoints; the old `widthClass` stays as a back-compat escape hatch), an optional `tabs` layout that renders a sticky `TabPills` bar under the header (collapsing to a `<select>` on mobile) with a per-tab scroll region that resets on switch, and a `bodyClassName` hook for multi-column tab bodies. A new `useDrawerTab(paramName, defaultTab, tabIds?)` hook backs the active tab with a caller-named URL search param so the open section is shareable/bookmarkable and degrades to the default on a stale link. Fully back-compat — omit `tabs` and it's the original flat drawer (existing EditAppDrawer/SyncDetailDrawer tests unchanged). This is the foundation for the drawer-UX epic (#1966); the per-surface migrations (#1968–#1973) build on it. (Closes #1967)diff --git a/client/src/components/Drawer.jsx b/client/src/components/Drawer.jsxindex ab8e1b8880..4af0370092 100644--- a/client/src/components/Drawer.jsx+++ b/client/src/components/Drawer.jsx@@ -1,26 +1,62 @@-import { useEffect } from 'react';+import { useEffect, useState } from 'react';import { X } from 'lucide-react';import { useScrollLock } from '../hooks/useScrollLock';+import TabPills from './ui/TabPills';-// Right-side slide-in panel for "settings over a feature page" pattern.-// Mobile (<sm): full width. Desktop: ~520px. Backdrop click + Esc close it.-// Caller controls open state — typically driven by a URL search param so the-// view stays deep-linkable per the project convention.+// Right-side slide-in panel for the "settings over a feature page" pattern.+// Mobile (<sm): full width. Desktop: a `size` bracket (see SIZE below). Backdrop+// click + Esc close it. Caller controls open state — typically driven by a URL+// search param so the view stays deep-linkable per the project convention.// Long-lived forms (e.g. the app-edit drawer) can opt out of accidental// dismissal via closeOnEsc / closeOnBackdrop so an Esc keystroke mid-edit// doesn't discard the form.+//+// Large config surfaces should group their fields into `tabs` instead of one+// page-length scroll: pass `tabs={[{ id, label, icon?, count? }]}` plus+// `activeTab` / `onTabChange` (drive them from a URL param via `useDrawerTab`+// for deep-linkability) and render only the active tab's fields as `children`.+// The drawer then renders a sticky TabPills bar under the header (collapsing to+// a <select> on mobile) and gives each tab its own scroll region that resets on+// switch — so no single tab is ever page-length. Omit `tabs` and it stays the+// original flat-scroll drawer. `bodyClassName` opts a tab into a multi-column+// layout on wide sizes (e.g. `lg:grid lg:grid-cols-2 lg:gap-x-6`).++// Desktop width brackets. Mobile is always `w-full`. `lg`/`xl` intentionally use+// more of the viewport (via extra breakpoints) so wide config forms can lay out+// in columns instead of a cramped single column inside a wide panel.+const SIZE = {+ sm: 'sm:w-[520px]',+ md: 'sm:w-[640px]',+ lg: 'sm:w-[720px] lg:w-[880px]',+ xl: 'sm:w-[720px] lg:w-[960px] xl:w-[1100px]',+};+export default function Drawer({open,onClose,title,children,- widthClass = 'sm:w-[520px]',+ size = 'sm',+ widthClass, // escape hatch: overrides `size` when provided (back-compat)+ tabs = null, // [{ id, label, icon?, count? }] enables the tabbed layout+ activeTab, // controlled active tab id (falls back to uncontrolled)+ onTabChange, // (id) => void — required for the controlled form+ bodyClassName = '', // extra classes on the scroll region (e.g. multi-column grid)closeOnEsc = true,closeOnBackdrop = true,- closeLabel = 'Close settings'+ closeLabel = 'Close settings',}) {useScrollLock(open);+ const tabList = Array.isArray(tabs) ? tabs.filter(Boolean) : null;+ const hasTabs = !!(tabList && tabList.length);++ // Support both controlled (activeTab + onTabChange) and uncontrolled tabs, so a+ // caller that doesn't care about deep-linking still gets working tab switching.+ const [internalTab, setInternalTab] = useState(hasTabs ? tabList[0].id : undefined);+ const currentTab = hasTabs ? (activeTab ?? internalTab) : undefined;+ const changeTab = onTabChange || setInternalTab;+useEffect(() => {if (!open || !closeOnEsc) return;const onKey = (e) => { if (e.key === 'Escape') onClose(); };@@ -30,6 +66,9 @@ export default function Drawer({if (!open) return null;+ const resolvedWidth = widthClass || SIZE[size] || SIZE.sm;+ const bodyClasses = `flex-1 overflow-y-auto p-4 ${bodyClassName}`.trim();+return (<><div@@ -41,7 +80,7 @@ export default function Drawer({role="dialog"aria-modal="true"aria-label={title}- className={`fixed inset-y-0 right-0 z-50 w-full ${widthClass} bg-port-card border-l border-port-border shadow-2xl flex flex-col`}+ className={`fixed inset-y-0 right-0 z-50 w-full ${resolvedWidth} bg-port-card border-l border-port-border shadow-2xl flex flex-col`}><header className="flex items-center justify-between px-4 py-3 border-b border-port-border"><h2 className="text-base font-medium text-white truncate min-w-0 pr-2">{title}</h2>@@ -54,9 +93,36 @@ export default function Drawer({<X className="w-5 h-5" /></button></header>- <div className="flex-1 overflow-y-auto p-4">- {children}- </div>+ {hasTabs && (+ <div className="px-4 pt-3 shrink-0 border-b border-port-border">+ <TabPills+ tabs={tabList}+ activeTab={currentTab}+ onChange={changeTab}+ mobileDropdown+ mobileSelectId="drawer-tab-select"+ ariaLabel={title ? `${title} sections` : 'Sections'}+ controlsIdPrefix="drawer-tabpanel"+ />+ </div>+ )}+ {hasTabs ? (+ // key on the tab id so switching tabs remounts the panel and resets its+ // scroll position — no single accumulated page-length scroll.+ <div+ key={currentTab}+ id={`drawer-tabpanel-${currentTab}`}+ role="tabpanel"+ aria-labelledby={`tab-${currentTab}`}+ className={bodyClasses}+ >+ {children}+ </div>+ ) : (+ <div className={bodyClasses}>+ {children}+ </div>+ )}</aside></>);diff --git a/client/src/components/Drawer.test.jsx b/client/src/components/Drawer.test.jsxnew file mode 100644index 0000000000..2f4300d46a--- /dev/null+++ b/client/src/components/Drawer.test.jsx@@ -0,0 +1,113 @@+import { describe, it, expect, vi } from 'vitest';+import { render, screen, fireEvent, within } from '@testing-library/react';+import Drawer from './Drawer';++const TABS = [+ { id: 'general', label: 'General' },+ { id: 'ports', label: 'Ports & TLS' },+ { id: 'jira', label: 'JIRA' },+];++describe('Drawer', () => {+ it('renders nothing when closed', () => {+ const { container } = render(<Drawer open={false} onClose={() => {}} title="X">body</Drawer>);+ expect(container).toBeEmptyDOMElement();+ });++ it('renders title, children and an accessible dialog when open', () => {+ render(<Drawer open onClose={() => {}} title="Edit App"><p>form body</p></Drawer>);+ const dialog = screen.getByRole('dialog');+ expect(dialog).toHaveAttribute('aria-modal', 'true');+ expect(dialog).toHaveAttribute('aria-label', 'Edit App');+ expect(screen.getByText('form body')).toBeInTheDocument();+ });++ describe('size variants (back-compat)', () => {+ it('defaults to the original sm (~520px) width', () => {+ render(<Drawer open onClose={() => {}} title="X">b</Drawer>);+ expect(screen.getByRole('dialog').className).toContain('sm:w-[520px]');+ });++ it('applies wider brackets for lg/xl', () => {+ const { rerender } = render(<Drawer open onClose={() => {}} title="X" size="lg">b</Drawer>);+ expect(screen.getByRole('dialog').className).toContain('lg:w-[880px]');+ rerender(<Drawer open onClose={() => {}} title="X" size="xl">b</Drawer>);+ expect(screen.getByRole('dialog').className).toContain('xl:w-[1100px]');+ });++ it('honors an explicit widthClass escape hatch over size', () => {+ render(<Drawer open onClose={() => {}} title="X" size="lg" widthClass="sm:w-[640px]">b</Drawer>);+ const cls = screen.getByRole('dialog').className;+ expect(cls).toContain('sm:w-[640px]');+ expect(cls).not.toContain('lg:w-[880px]');+ });+ });++ describe('close behavior', () => {+ it('closes on backdrop click and Esc by default', () => {+ const onClose = vi.fn();+ render(<Drawer open onClose={onClose} title="X">b</Drawer>);+ fireEvent.click(document.querySelector('[aria-hidden="true"]'));+ fireEvent.keyDown(window, { key: 'Escape' });+ expect(onClose).toHaveBeenCalledTimes(2);+ });++ it('opts out of Esc and backdrop dismissal for long-lived forms', () => {+ const onClose = vi.fn();+ render(<Drawer open onClose={onClose} title="X" closeOnEsc={false} closeOnBackdrop={false}>b</Drawer>);+ fireEvent.click(document.querySelector('[aria-hidden="true"]'));+ fireEvent.keyDown(window, { key: 'Escape' });+ expect(onClose).not.toHaveBeenCalled();+ });++ it('fires onClose from the header close button', () => {+ const onClose = vi.fn();+ render(<Drawer open onClose={onClose} title="X">b</Drawer>);+ fireEvent.click(screen.getByRole('button', { name: 'Close settings' }));+ expect(onClose).toHaveBeenCalledTimes(1);+ });+ });++ describe('tabbed layout', () => {+ it('renders no tablist when tabs are omitted', () => {+ render(<Drawer open onClose={() => {}} title="X">b</Drawer>);+ expect(screen.queryByRole('tablist')).not.toBeInTheDocument();+ expect(screen.getByText('b').closest('[role="tabpanel"]')).toBeNull();+ });++ it('renders a tablist and a labelled tabpanel when tabs are provided (uncontrolled)', () => {+ render(<Drawer open onClose={() => {}} title="Edit App" tabs={TABS}><div>panel body</div></Drawer>);+ expect(screen.getByRole('tablist')).toBeInTheDocument();+ const panel = screen.getByRole('tabpanel');+ expect(within(panel).getByText('panel body')).toBeInTheDocument();+ // defaults to the first tab+ expect(panel).toHaveAttribute('id', 'drawer-tabpanel-general');+ });++ it('switches tabs internally when uncontrolled', () => {+ render(<Drawer open onClose={() => {}} title="X" tabs={TABS}>body</Drawer>);+ // TabPills renders a mobile <select> plus the desktop tab buttons.+ fireEvent.click(screen.getByRole('tab', { name: 'JIRA' }));+ expect(screen.getByRole('tabpanel')).toHaveAttribute('id', 'drawer-tabpanel-jira');+ });++ it('is controllable via activeTab + onTabChange', () => {+ const onTabChange = vi.fn();+ const { rerender } = render(+ <Drawer open onClose={() => {}} title="X" tabs={TABS} activeTab="ports" onTabChange={onTabChange}>body</Drawer>+ );+ expect(screen.getByRole('tabpanel')).toHaveAttribute('id', 'drawer-tabpanel-ports');+ fireEvent.click(screen.getByRole('tab', { name: 'JIRA' }));+ expect(onTabChange).toHaveBeenCalledWith('jira');+ // controlled: nothing changes until the parent updates activeTab+ expect(screen.getByRole('tabpanel')).toHaveAttribute('id', 'drawer-tabpanel-ports');+ rerender(<Drawer open onClose={() => {}} title="X" tabs={TABS} activeTab="jira" onTabChange={onTabChange}>body</Drawer>);+ expect(screen.getByRole('tabpanel')).toHaveAttribute('id', 'drawer-tabpanel-jira');+ });++ it('applies bodyClassName to the scroll region for multi-column layouts', () => {+ render(<Drawer open onClose={() => {}} title="X" tabs={TABS} bodyClassName="lg:grid lg:grid-cols-2">body</Drawer>);+ expect(screen.getByRole('tabpanel').className).toContain('lg:grid-cols-2');+ });+ });+});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex dd78521e62..1ce02bd075 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -88,6 +88,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useCmdKSearch` | `⌘K` open/close state. | Anywhere that needs to toggle the palette. || `useContainerWidth` | `[ref, width]` via ResizeObserver. | Layout responds to a specific container's width. || `useCooldownTick` | 1-second ticker over a `{ id: epochMs }` cooldown map; fires `onAllExpired` once when every deadline passes. | Rate-limit countdown labels that need to refetch when the last cooldown clears (agents tabs pattern). |+| `useDrawerTab` | Deep-linkable `[activeTab, setActiveTab]` for a tabbed `<Drawer>`, backed by a caller-named URL search param (falls back to a default on stale/missing). | A tabbed config drawer whose open section should be shareable/bookmarkable — use with `<Drawer tabs>`; don't re-roll the search-param plumbing. || `useFieldDraft` | Local input draft that commits on blur. | Bible-editor-style single-field input that must dedupe sibling races. || `useRowDraft` | Multi-column row draft (analogue of `useFieldDraft`). | Multi-column row that commits as a unit. || `usePendingListRows` | List-of-rows where a new row is held client-side until a required column fills, then promoted to `onChange`. | Editable list whose nameless rows would otherwise be dropped by the server sanitizer (WardrobeSection, CharacterDetailEditor list sections). |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex d005538d94..aa3e857e10 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -95,6 +95,7 @@ export * from './useArmedAction.js';export * from './useAutoRefetch.js';export * from './useCmdKSearch.js';export * from './useCooldownTick.js';+export { default as useDrawerTab } from './useDrawerTab.js';export * from './useKeyboardHelp.js';export * from './useLockToggle.js';export * from './useScrollLock.js';diff --git a/client/src/hooks/useDrawerTab.js b/client/src/hooks/useDrawerTab.jsnew file mode 100644index 0000000000..89c984d0cb--- /dev/null+++ b/client/src/hooks/useDrawerTab.js@@ -0,0 +1,34 @@+import { useCallback } from 'react';+import { useSearchParams } from 'react-router-dom';++// Deep-linkable active-tab state for a tabbed <Drawer>, backed by a URL search+// param so the open section is shareable, bookmarkable, and reload-safe — the+// same "URL is the source of truth for what's open" convention the rest of the+// app follows. Returns `[activeTab, setActiveTab]`.+//+// The caller owns the param name (a page may host more than one drawer, e.g.+// `?settingsTab=backend`) and passes the tab id list so a stale/hand-edited+// deep link degrades to `defaultTab` instead of a blank panel. Writing the+// default tab (or null) drops the param entirely so a pristine URL stays clean;+// every write uses `replace` so flipping tabs doesn't pile history entries.+//+// Tabs live in a search param — not a route `:tab` segment (that's `useValidTab`)+// — because a drawer is an overlay on top of an already-routed page and can't own+// a path segment.+export default function useDrawerTab(paramName, defaultTab, tabIds = null) {+ const [searchParams, setSearchParams] = useSearchParams();+ const raw = searchParams.get(paramName);+ const valid = raw != null && (tabIds == null || tabIds.includes(raw));+ const activeTab = valid ? raw : defaultTab;++ const setActiveTab = useCallback((id) => {+ setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ if (id == null || id === defaultTab) next.delete(paramName);+ else next.set(paramName, id);+ return next;+ }, { replace: true });+ }, [setSearchParams, paramName, defaultTab]);++ return [activeTab, setActiveTab];+}diff --git a/client/src/hooks/useDrawerTab.test.jsx b/client/src/hooks/useDrawerTab.test.jsxnew file mode 100644index 0000000000..b927271681--- /dev/null+++ b/client/src/hooks/useDrawerTab.test.jsx@@ -0,0 +1,70 @@+import { describe, it, expect } from 'vitest';+import { renderHook, act } from '@testing-library/react';+import { MemoryRouter, useLocation } from 'react-router-dom';+import useDrawerTab from './useDrawerTab';++// MemoryRouter so `useSearchParams` resolves; `useLocation` lets the assertions+// read back the resulting URL — the deep-link contract this hook defines.+const renderWithRouter = (args, initial = '/x') => {+ const wrapper = ({ children }) => (+ <MemoryRouter initialEntries={[initial]}>{children}</MemoryRouter>+ );+ return renderHook(() => ({+ pair: useDrawerTab(...args),+ location: useLocation(),+ }), { wrapper });+};++const IDS = ['general', 'ports', 'jira'];++describe('useDrawerTab', () => {+ it('returns the default tab when the param is absent', () => {+ const { result } = renderWithRouter(['tab', 'general', IDS]);+ expect(result.current.pair[0]).toBe('general');+ });++ it('reads the active tab from the URL param', () => {+ const { result } = renderWithRouter(['tab', 'general', IDS], '/x?tab=jira');+ expect(result.current.pair[0]).toBe('jira');+ });++ it('falls back to the default for a stale/invalid param', () => {+ const { result } = renderWithRouter(['tab', 'general', IDS], '/x?tab=nope');+ expect(result.current.pair[0]).toBe('general');+ });++ it('accepts any value when no tabIds allow-list is given', () => {+ const { result } = renderWithRouter(['tab', 'general'], '/x?tab=anything');+ expect(result.current.pair[0]).toBe('anything');+ });++ it('writes the param when switching to a non-default tab', () => {+ const { result } = renderWithRouter(['tab', 'general', IDS]);+ act(() => result.current.pair[1]('ports'));+ expect(result.current.pair[0]).toBe('ports');+ expect(result.current.location.search).toBe('?tab=ports');+ });++ it('drops the param when switching back to the default tab', () => {+ const { result } = renderWithRouter(['tab', 'general', IDS], '/x?tab=jira');+ act(() => result.current.pair[1]('general'));+ expect(result.current.pair[0]).toBe('general');+ expect(result.current.location.search).toBe('');+ });++ it('preserves unrelated query params when writing the tab', () => {+ const { result } = renderWithRouter(['tab', 'general', IDS], '/x?settings=1');+ act(() => result.current.pair[1]('jira'));+ expect(result.current.location.search).toContain('settings=1');+ expect(result.current.location.search).toContain('tab=jira');+ });++ it('lets two drawers on one page use distinct param names', () => {+ const { result } = renderWithRouter(['imgTab', 'backend', ['backend', 'local']], '/x?tab=jira');+ // The other drawer's `tab` param must not leak into this one.+ expect(result.current.pair[0]).toBe('backend');+ act(() => result.current.pair[1]('local'));+ expect(result.current.location.search).toContain('tab=jira');+ expect(result.current.location.search).toContain('imgTab=local');+ });+});