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: keep the Run-on-App, Share, and Sync menus on screen via usePopoverPosition (#3844)
[._.]/ Adam Eivy8e496030a3a6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex dfe91e415a..25534ae0e9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -28,3 +28,4 @@- Notification panel placement now goes through the shared popover-positioning hook that the theme switcher beside it already used, so it clamps into the viewport and flips above/below on its own instead of relying on hand-written positioning.- The Code Review Defaults panel now names every CLI reviewer in its help text, generated from the reviewer roster itself — the sentence used to spell them out by hand and fell behind twice as new reviewers shipped, telling users their CLI reviewers ran a different way than they do.+- The remaining trigger-anchored dropdowns — "Run on App" on a scheduled task, and the Share and Sync buttons on series and universe cards — now use the same shared popover-positioning hook as the notification panel. "Run on App" opened a panel pinned to its button's left edge that merely got narrower on a phone rather than moving, so it ran off the right edge; the Share and Sync menus always opened downward even with no room below. All three now clamp into the viewport, flip when there is no room, and stay attached to their button as the page scrolls.diff --git a/client/src/components/cos/tabs/schedule/RunTaskButton.jsx b/client/src/components/cos/tabs/schedule/RunTaskButton.jsxindex 5fc4cb429f..bf6fb2130d 100644--- a/client/src/components/cos/tabs/schedule/RunTaskButton.jsx+++ b/client/src/components/cos/tabs/schedule/RunTaskButton.jsx@@ -1,6 +1,11 @@import { useState, useRef, useEffect } from 'react';+import { createPortal } from 'react-dom';import { Play, ChevronDown, Package } from 'lucide-react';import { triggerButtonClass } from './scheduleConstants';+import useClickOutside from '../../../../hooks/useClickOutside.js';+import usePopoverPosition, { VIEWPORT_PADDING } from '../../../../hooks/usePopoverPosition.js';++const MENU_WIDTH = 256; // w-64// Trigger an on-demand run. When the task targets managed apps, opens a picker// so the run carries app context; otherwise fires a plain global run. Shared by@@ -17,12 +22,23 @@ export default function RunTaskButton({ taskType, apps, onTrigger, disabledReasoconst activeApps = apps?.filter(app => !app.archived) || [];const disabled = !!disabledReason;- useEffect(() => {- if (!open) return;- const onClickOutside = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };- document.addEventListener('mousedown', onClickOutside);- return () => document.removeEventListener('mousedown', onClickOutside);- }, [open]);+ // The app list is portaled to <body> and placed in viewport coordinates. This+ // button sits mid-row on a task card, so the old `absolute bottom-full left-0`+ // panel ran off the right edge on a phone — `max-w` only narrowed it, it never+ // moved it back on-screen. The hook clamps into the viewport and flips below+ // the trigger when there is no room above. The rendered app count changes the+ // panel height, so it re-measures via contentDeps.+ const { triggerRef, popoverRef, style: menuStyle } = usePopoverPosition({+ open: open && !disabled,+ width: MENU_WIDTH,+ minWidth: 200,+ position: 'above',+ contentDeps: [activeApps.length]+ });++ // Both refs: the panel lives outside the trigger's subtree once portaled, so a+ // trigger-only containment check would read clicks on the panel as outside.+ useClickOutside([ref, popoverRef], open, () => setOpen(false));// Without this, an open dropdown survives a flip to disabled and pops back open when re-enabled.useEffect(() => {@@ -47,10 +63,11 @@ export default function RunTaskButton({ taskType, apps, onTrigger, disabledReaso}return (- <div className="relative" ref={ref}>+ <div ref={ref}>{/* Tooltip on the wrapper, not the button: most browsers skip hover events on disabled controls. */}<span title={disabledReason || 'Run this task on a specific app'} className="inline-block"><button+ ref={triggerRef}type="button"onClick={() => !disabled && setOpen(o => !o)}disabled={disabled}@@ -63,8 +80,17 @@ export default function RunTaskButton({ taskType, apps, onTrigger, disabledReaso<ChevronDown size={12} className={`transition-transform ${open ? 'rotate-180' : ''}`} /></button></span>- {open && !disabled && (- <div className="port-menu-surface absolute bottom-full left-0 mb-1 z-50 w-64 max-w-[calc(100vw-2rem)] max-h-64 overflow-y-auto border border-port-border rounded-lg shadow-lg">+ {open && !disabled && createPortal(+ <div+ ref={popoverRef}+ className="port-menu-surface fixed z-[100] max-h-64 overflow-y-auto border border-port-border rounded-lg shadow-lg"+ style={{+ left: menuStyle?.left ?? `${VIEWPORT_PADDING}px`,+ top: menuStyle?.top ?? `${VIEWPORT_PADDING}px`,+ width: menuStyle?.width ?? `${MENU_WIDTH}px`,+ visibility: menuStyle ? 'visible' : 'hidden'+ }}+ ><div className="p-2 border-b border-port-border"><span className="text-xs text-gray-400">Select an app to run {taskType} on:</span></div>@@ -84,7 +110,8 @@ export default function RunTaskButton({ taskType, apps, onTrigger, disabledReaso</button>))}</div>- </div>+ </div>,+ document.body)}</div>);diff --git a/client/src/components/cos/tabs/schedule/RunTaskButton.test.jsx b/client/src/components/cos/tabs/schedule/RunTaskButton.test.jsxnew file mode 100644index 0000000000..5a27be1541--- /dev/null+++ b/client/src/components/cos/tabs/schedule/RunTaskButton.test.jsx@@ -0,0 +1,63 @@+import { describe, it, expect, vi, afterEach } from 'vitest';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++import RunTaskButton from './RunTaskButton';++const APPS = [+ { id: 'app-1', name: 'Example App', repoPath: '~/code/example-app' },+ { id: 'app-2', name: 'Second App', archived: true },+];++// Place the trigger near the right edge of a phone-width viewport — the case+// that used to push the left-anchored panel off-screen.+function stubViewport({ width = 390, height = 780, rect } = {}) {+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: width });+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: height });+ vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({+ top: 600, bottom: 640, left: 300, right: 360, width: 60, height: 200, x: 300, y: 600,+ ...rect,+ });+}++afterEach(() => {+ vi.restoreAllMocks();+});++describe('RunTaskButton', () => {+ it('fires a plain global run when no active apps exist', async () => {+ const user = userEvent.setup();+ const onTrigger = vi.fn();+ render(<RunTaskButton taskType="review" apps={[]} onTrigger={onTrigger} />);+ await user.click(screen.getByRole('button', { name: /Run Now/i }));+ expect(onTrigger).toHaveBeenCalledWith('review');+ });++ it('lists only active apps and runs the task on the picked one', async () => {+ const user = userEvent.setup();+ const onTrigger = vi.fn();+ render(<RunTaskButton taskType="review" apps={APPS} onTrigger={onTrigger} />);+ await user.click(screen.getByRole('button', { name: /Run on App/i }));+ expect(screen.queryByText('Second App')).toBeNull();+ await user.click(screen.getByText('Example App'));+ expect(onTrigger).toHaveBeenCalledWith('review', 'app-1');+ // Picking an app dismisses the panel.+ expect(screen.queryByText('Example App')).toBeNull();+ });++ it('keeps the app panel inside the viewport on a phone-width screen', async () => {+ stubViewport();+ const user = userEvent.setup();+ render(<RunTaskButton taskType="review" apps={APPS} onTrigger={vi.fn()} />);+ await user.click(screen.getByRole('button', { name: /Run on App/i }));++ const panel = screen.getByText('Example App').closest('div.fixed');+ expect(panel).toBeTruthy();+ const left = Number.parseFloat(panel.style.left);+ const width = Number.parseFloat(panel.style.width);+ expect(left).toBeGreaterThanOrEqual(8);+ // The pre-migration panel was pinned to the trigger's left edge and only+ // narrowed by max-w, so it ran past the right edge instead of moving.+ expect(left + width).toBeLessThanOrEqual(window.innerWidth - 8);+ });+});diff --git a/client/src/components/sharing/ShareToButton.jsx b/client/src/components/sharing/ShareToButton.jsxindex 1cd2c81d5d..7ad4217670 100644--- a/client/src/components/sharing/ShareToButton.jsx+++ b/client/src/components/sharing/ShareToButton.jsx@@ -22,10 +22,12 @@* compact?: boolean*/-import { useEffect, useLayoutEffect, useRef, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';import { Share2, Check, Circle, CheckCircle2, Loader2 } from 'lucide-react';import toast from '../ui/Toast';+import useClickOutside from '../../hooks/useClickOutside.js';+import usePopoverPosition, { VIEWPORT_PADDING } from '../../hooks/usePopoverPosition.js';import {listShareBuckets,exportToShareBucket,@@ -35,6 +37,7 @@ import {} from '../../services/api';const SUBSCRIBABLE_KINDS = new Set(['series', 'universe']);+const MENU_WIDTH = 288; // w-72function renderRowIcon({ busy, subscribable, subscribed }) {if (busy) return <Loader2 size={14} className="animate-spin text-port-accent" />;@@ -51,20 +54,21 @@ export default function ShareToButton({ kind, ids, items, label = 'Share', compaconst [loading, setLoading] = useState(false);const [busyBucketId, setBusyBucketId] = useState(null);const wrapperRef = useRef(null);- const triggerRef = useRef(null);- const menuRef = useRef(null);// Portal the dropdown to <body> so it escapes each card's stacking context// (an in-card `absolute z-30` popover is otherwise painted under the next- // card). Position it `fixed`, anchored to the trigger's viewport rect.- const MENU_WIDTH = 288; // w-72- const [coords, setCoords] = useState(null);- const updateCoords = () => {- const el = triggerRef.current;- if (!el) return;- const r = el.getBoundingClientRect();- const left = Math.max(8, Math.min(r.right - MENU_WIDTH, window.innerWidth - MENU_WIDTH - 8));- setCoords({ top: r.bottom + 4, left });- };+ // card). `usePopoverPosition` owns the fixed placement: it anchors to the+ // trigger's viewport rect, clamps into the viewport, flips above the trigger+ // when there is no room below, and re-flows on capture-phase scroll. The+ // bucket list changes the menu's height as it loads, so it re-measures via+ // contentDeps.+ const { triggerRef, popoverRef, style: menuStyle } = usePopoverPosition({+ open,+ width: MENU_WIDTH,+ minWidth: 220,+ gap: 4,+ position: 'below',+ contentDeps: [loading, buckets.length, subscriptions.length]+ });const isSubscribable = SUBSCRIBABLE_KINDS.has(kind);const recordId = isSubscribable && Array.isArray(ids) && ids.length > 0 ? ids[0] : null;@@ -96,28 +100,9 @@ export default function ShareToButton({ kind, ids, items, label = 'Share', compaif (open) refresh();}, [open]);- useLayoutEffect(() => {- if (!open) { setCoords(null); return; }- updateCoords();- const onMove = () => updateCoords();- window.addEventListener('scroll', onMove, true);- window.addEventListener('resize', onMove);- return () => {- window.removeEventListener('scroll', onMove, true);- window.removeEventListener('resize', onMove);- };- }, [open]);-- useEffect(() => {- if (!open) return;- const handler = (e) => {- const inTrigger = wrapperRef.current && wrapperRef.current.contains(e.target);- const inMenu = menuRef.current && menuRef.current.contains(e.target);- if (!inTrigger && !inMenu) setOpen(false);- };- window.addEventListener('mousedown', handler);- return () => window.removeEventListener('mousedown', handler);- }, [open]);+ // Both refs: the menu lives outside the trigger's subtree once portaled, so a+ // trigger-only containment check would read clicks on the menu as outside.+ useClickOutside([wrapperRef, popoverRef], open, () => setOpen(false));const subscriptionForBucket = (bucketId) =>subscriptions.find((s) => s.bucketId === bucketId) || null;@@ -188,10 +173,16 @@ export default function ShareToButton({ kind, ids, items, label = 'Share', compa{!compact && <span>{label}</span>}</button>- {open && coords && createPortal(+ {open && createPortal(<div- ref={menuRef}- style={{ position: 'fixed', top: coords.top, left: coords.left, width: MENU_WIDTH }}+ ref={popoverRef}+ style={{+ position: 'fixed',+ left: menuStyle?.left ?? `${VIEWPORT_PADDING}px`,+ top: menuStyle?.top ?? `${VIEWPORT_PADDING}px`,+ width: menuStyle?.width ?? `${MENU_WIDTH}px`,+ visibility: menuStyle ? 'visible' : 'hidden'+ }}className="z-50 bg-port-card border border-port-border rounded-lg shadow-lg overflow-hidden"><div className="px-3 py-2 text-[10px] uppercase tracking-wider text-gray-500 border-b border-port-border">diff --git a/client/src/components/sharing/SyncToPeerButton.jsx b/client/src/components/sharing/SyncToPeerButton.jsxindex 85a542c2b4..ecaf9c8711 100644--- a/client/src/components/sharing/SyncToPeerButton.jsx+++ b/client/src/components/sharing/SyncToPeerButton.jsx@@ -22,10 +22,12 @@* compact?: boolean*/-import { useEffect, useLayoutEffect, useRef, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';import { Cloud, Circle, CheckCircle2, Loader2 } from 'lucide-react';import toast from '../ui/Toast';+import useClickOutside from '../../hooks/useClickOutside.js';+import usePopoverPosition, { VIEWPORT_PADDING } from '../../hooks/usePopoverPosition.js';import {getInstances,listPeerSubscriptions,@@ -33,6 +35,8 @@ import {unsubscribeFromPeer,} from '../../services/api';+const MENU_WIDTH = 288; // w-72+export default function SyncToPeerButton({recordKind,recordId,@@ -46,22 +50,21 @@ export default function SyncToPeerButton({const [loading, setLoading] = useState(false);const [busyPeerId, setBusyPeerId] = useState(null);const wrapperRef = useRef(null);- const triggerRef = useRef(null);- const menuRef = useRef(null);// The dropdown is portaled to <body> so it escapes each series/universe// card's stacking context (the cards have their own compositing layer, so an- // in-card `absolute z-30` popover is painted UNDER the next card). Position- // it `fixed`, anchored to the trigger button's viewport rect.- const MENU_WIDTH = 288; // w-72- const [coords, setCoords] = useState(null);- const updateCoords = () => {- const el = triggerRef.current;- if (!el) return;- const r = el.getBoundingClientRect();- // Right-align the menu to the button, clamped to the viewport.- const left = Math.max(8, Math.min(r.right - MENU_WIDTH, window.innerWidth - MENU_WIDTH - 8));- setCoords({ top: r.bottom + 4, left });- };+ // in-card `absolute z-30` popover is painted UNDER the next card).+ // `usePopoverPosition` owns the fixed placement: right-aligned to the trigger,+ // clamped into the viewport, flipped above when there is no room below, and+ // re-flowed on capture-phase scroll. The peer list changes the menu's height+ // as it loads, so it re-measures via contentDeps.+ const { triggerRef, popoverRef, style: menuStyle } = usePopoverPosition({+ open,+ width: MENU_WIDTH,+ minWidth: 220,+ gap: 4,+ position: 'below',+ contentDeps: [loading, peers.length, subscriptions.length]+ });const refresh = async () => {setLoading(true);@@ -104,31 +107,9 @@ export default function SyncToPeerButton({if (open) refresh();}, [open]);- // Anchor the portaled menu to the trigger while open, and keep it pinned as- // the page scrolls/resizes (capture-phase scroll catches inner scrollers too).- useLayoutEffect(() => {- if (!open) { setCoords(null); return; }- updateCoords();- const onMove = () => updateCoords();- window.addEventListener('scroll', onMove, true);- window.addEventListener('resize', onMove);- return () => {- window.removeEventListener('scroll', onMove, true);- window.removeEventListener('resize', onMove);- };- }, [open]);-- useEffect(() => {- if (!open) return;- const handler = (e) => {- // The menu lives in a portal outside wrapperRef, so check both.- const inTrigger = wrapperRef.current && wrapperRef.current.contains(e.target);- const inMenu = menuRef.current && menuRef.current.contains(e.target);- if (!inTrigger && !inMenu) setOpen(false);- };- window.addEventListener('mousedown', handler);- return () => window.removeEventListener('mousedown', handler);- }, [open]);+ // Both refs: the menu lives in a portal outside wrapperRef, so a trigger-only+ // containment check would read clicks on the menu as outside.+ useClickOutside([wrapperRef, popoverRef], open, () => setOpen(false));const subscriptionForPeer = (peerInstanceId) =>subscriptions.find((s) => s.peerId === peerInstanceId) || null;@@ -182,10 +163,16 @@ export default function SyncToPeerButton({{!compact && <span>{label}</span>}</button>- {open && coords && createPortal(+ {open && createPortal(<div- ref={menuRef}- style={{ position: 'fixed', top: coords.top, left: coords.left, width: MENU_WIDTH }}+ ref={popoverRef}+ style={{+ position: 'fixed',+ left: menuStyle?.left ?? `${VIEWPORT_PADDING}px`,+ top: menuStyle?.top ?? `${VIEWPORT_PADDING}px`,+ width: menuStyle?.width ?? `${MENU_WIDTH}px`,+ visibility: menuStyle ? 'visible' : 'hidden'+ }}className="z-50 bg-port-card border border-port-border rounded-lg shadow-lg overflow-hidden"><div className="px-3 py-2 text-[10px] uppercase tracking-wider text-gray-500 border-b border-port-border">diff --git a/client/src/components/sharing/SyncToPeerButton.test.jsx b/client/src/components/sharing/SyncToPeerButton.test.jsxindex 437f1d746b..466c5a27f1 100644--- a/client/src/components/sharing/SyncToPeerButton.test.jsx+++ b/client/src/components/sharing/SyncToPeerButton.test.jsx@@ -129,4 +129,24 @@ describe('SyncToPeerButton', () => {await user.click(screen.getByText('Peer A'));expect(api.unsubscribeFromPeer).toHaveBeenCalledWith('peer-universe-u1-peer-a', { silent: true });});++ it('flips the peer menu above the trigger when there is no room below', async () => {+ // Trigger low on a short viewport: the menu no longer fits underneath, so+ // the shared placement hook must open it upward instead of letting it hang+ // off the bottom (the hand-rolled coords this replaced always went below).+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 780 });+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1024 });+ vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({+ top: 600, bottom: 640, left: 400, right: 460, width: 60, height: 240, x: 400, y: 600,+ });+ const user = userEvent.setup();+ render(<SyncToPeerButton recordKind="universe" recordId="u1" />);+ await user.click(screen.getByRole('button', { name: /Sync/i }));+ const menu = (await screen.findByText('Peer A')).closest('div[style*="position: fixed"]');+ expect(menu).toBeTruthy();+ const top = Number.parseFloat(menu.style.top);+ expect(top).toBeLessThan(600);+ expect(top).toBeGreaterThanOrEqual(8);+ vi.restoreAllMocks();+ });});