Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(deck): make the dock magnification smooth, anchored, and audible

Haralde3a0bf29f78e
diff --git a/jarvis/ui/web/frontend/src/components/deck/DeckDock.test.tsx b/jarvis/ui/web/frontend/src/components/deck/DeckDock.test.tsx
new file mode 100644
index 0000000000..4d9fb72a26
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/deck/DeckDock.test.tsx
@@ -0,0 +1,135 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import { DECK_DOCK_GEOMETRY, DeckDock } from "@/components/deck/DeckDock";
+import { NAV_GROUPS } from "@/components/layout/navGroups";
+import { useEventStore } from "@/store/events";
+
+// usePluginAttention polls /api/marketplace/plugins; the dock's attention pip
+// is not under test here, so keep it quiet.
+vi.mock("@/hooks/usePluginAttention", () => ({
+ usePluginAttention: () => ({ count: 0, names: [] }),
+}));
+
+// The tick is WebAudio; here only WHEN it fires matters.
+const soundMock = vi.hoisted(() => ({ playDockTick: vi.fn() }));
+vi.mock("@/lib/sound", () => ({ playDockTick: soundMock.playDockTick }));
+
+const ITEMS = NAV_GROUPS.flat();
+const { BASE, GAP, PAD_TOP } = DECK_DOCK_GEOMETRY;
+
+/** clientY that lands on the centre of icon `i` (jsdom rects sit at 0,0). */
+function centreOf(i: number): number {
+ return PAD_TOP + GAP + i * (BASE + GAP) + BASE / 2;
+}
+
+/** jsdom has no PointerEvent; a MouseEvent under the pointer name carries the
+ * clientY the dock reads. */
+function moveTo(rail: HTMLElement, clientY: number) {
+ act(() => {
+ rail.dispatchEvent(new MouseEvent("pointermove", { bubbles: true, clientY }));
+ });
+}
+function leave(rail: HTMLElement) {
+ act(() => {
+ // React derives onPointerLeave from pointerout + relatedTarget.
+ rail.dispatchEvent(
+ new MouseEvent("pointerout", { bubbles: true, relatedTarget: document.body }),
+ );
+ });
+}
+
+function renderDock() {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ return render(
+ <QueryClientProvider client={client}>
+ <DeckDock />
+ </QueryClientProvider>,
+ );
+}
+
+describe("DeckDock", () => {
+ beforeEach(() => {
+ soundMock.playDockTick.mockClear();
+ useEventStore.setState({ activeSection: "chats", conversations: [] });
+ });
+ afterEach(() => cleanup());
+
+ test("shows every section of the sidebar's NAV_GROUPS as one named button", () => {
+ renderDock();
+ for (const item of ITEMS) {
+ expect(screen.getByTestId(`deck-dock-${item.id}`)).toBeTruthy();
+ }
+ expect(screen.getAllByRole("button")).toHaveLength(ITEMS.length);
+ expect(screen.getByTestId("deck-dock-chats").getAttribute("aria-current")).toBe("page");
+ // No native title: the dock draws its own label, and a browser tooltip on
+ // top of it would be a second, late label.
+ expect(screen.getByTestId("deck-dock-chats").getAttribute("title")).toBeNull();
+ });
+
+ test("hovering names exactly one icon, and crossing to the next one ticks once", () => {
+ renderDock();
+ const rail = screen.getByTestId("deck-dock-rail");
+
+ expect(screen.queryByTestId("deck-dock-label")).toBeNull();
+
+ moveTo(rail, centreOf(2));
+ let labels = screen.getAllByTestId("deck-dock-label");
+ expect(labels).toHaveLength(1);
+ expect(labels[0].textContent).toContain(
+ screen.getByTestId(`deck-dock-${ITEMS[2].id}`).getAttribute("aria-label"),
+ );
+ expect(soundMock.playDockTick).toHaveBeenCalledTimes(1);
+ expect(soundMock.playDockTick).toHaveBeenLastCalledWith("hover");
+
+ // Moving WITHIN the same icon is not a notch.
+ moveTo(rail, centreOf(2) + 6);
+ expect(soundMock.playDockTick).toHaveBeenCalledTimes(1);
+
+ moveTo(rail, centreOf(3));
+ labels = screen.getAllByTestId("deck-dock-label");
+ expect(labels).toHaveLength(1);
+ expect(labels[0].textContent).toContain(
+ screen.getByTestId(`deck-dock-${ITEMS[3].id}`).getAttribute("aria-label"),
+ );
+ expect(soundMock.playDockTick).toHaveBeenCalledTimes(2);
+ });
+
+ test("leaving the rail takes the label away without a tick", async () => {
+ renderDock();
+ const rail = screen.getByTestId("deck-dock-rail");
+ moveTo(rail, centreOf(1));
+ expect(screen.getAllByTestId("deck-dock-label")).toHaveLength(1);
+ leave(rail);
+ await waitFor(() => expect(screen.queryByTestId("deck-dock-label")).toBeNull(), {
+ timeout: 2000,
+ });
+ expect(soundMock.playDockTick).toHaveBeenCalledTimes(1);
+ });
+
+ test("picking an icon jumps to its section with the firmer tick", () => {
+ renderDock();
+ act(() => {
+ fireEvent.click(screen.getByTestId("deck-dock-tasks"));
+ });
+ expect(useEventStore.getState().activeSection).toBe("tasks");
+ expect(soundMock.playDockTick).toHaveBeenLastCalledWith("select");
+ });
+
+ test("keyboard focus names the icon too, so the rail is not a row of blank glyphs", () => {
+ renderDock();
+ act(() => {
+ fireEvent.focus(screen.getByTestId("deck-dock-docs"));
+ });
+ const labels = screen.getAllByTestId("deck-dock-label");
+ expect(labels).toHaveLength(1);
+ expect(labels[0].textContent).toContain(
+ screen.getByTestId("deck-dock-docs").getAttribute("aria-label"),
+ );
+ // Focus is not a notch.
+ expect(soundMock.playDockTick).not.toHaveBeenCalled();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/deck/DeckDock.tsx b/jarvis/ui/web/frontend/src/components/deck/DeckDock.tsx
index 10906b27f6..27beaf6c63 100644
--- a/jarvis/ui/web/frontend/src/components/deck/DeckDock.tsx
+++ b/jarvis/ui/web/frontend/src/components/deck/DeckDock.tsx
@@ -1,9 +1,26 @@
-import { useCallback, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ AnimatePresence,
+ motion,
+ useMotionValue,
+ useReducedMotion,
+ useSpring,
+ useTransform,
+ type MotionValue,
+} from "framer-motion";
import { useEventStore, type SectionId } from "@/store/events";
-import { NAV_GROUPS, resolveNavLabel } from "@/components/layout/navGroups";
+import { NAV_GROUPS, resolveNavLabel, type NavItem } from "@/components/layout/navGroups";
import { useSectionHealth } from "@/hooks/useProviders";
import { usePluginAttention } from "@/hooks/usePluginAttention";
-import { layoutDock } from "@/lib/dockMagnify";
+import {
+ DOCK_MAX_SCALE,
+ DOCK_RADIUS_UNITS,
+ dockSlotAt,
+ layoutDock,
+ maxAnchorLift,
+ type DockLayout,
+} from "@/lib/dockMagnify";
+import { playDockTick } from "@/lib/sound";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
@@ -22,14 +39,55 @@ import { useT } from "@/i18n";
* attention signals are the sidebar's too: a provider error lights API Keys,
* a plugin that needs a reconnect lights Plugins.
*
- * Magnification is pure geometry from `lib/dockMagnify.ts`; this component
- * only measures the pointer and applies the resulting transforms. Motion is
- * suppressed for users who asked for less of it — the dock then simply
- * highlights the hovered icon.
+ * How the motion is built — the same recipe as the well-known Framer Motion
+ * docks, tuned to how the desktop docks actually behave:
+ *
+ * - Nothing about the pointer goes through React state. The pointer writes a
+ * motion value; the whole layout is ONE derived motion value; every icon
+ * binds its box to that. Re-rendering twenty-odd buttons on every mouse
+ * event, and then letting a CSS transition chase the result, is what made
+ * the first version stutter and trail the mouse.
+ * - The hill follows the pointer instantly, like the real thing; only its
+ * HEIGHT is sprung. Enter the rail and the hill rises in place under the
+ * pointer; leave it and it settles back where it was — no pop on entry,
+ * no jump on exit, and no lag while inside.
+ * - Geometry (the hill, the push-apart, the anchoring that keeps the icon
+ * under the pointer under the pointer) is pure math in `lib/dockMagnify.ts`.
+ * - Exactly one label: the hovered icon's, sliding along the rail with it and
+ * fading in and out. Three labels at once, popping in and out on a size
+ * threshold, read as noise.
+ * - A soft detent tick each time the pointer crosses onto another icon, and a
+ * firmer one on the pick — the ratchet of a picker wheel, quiet.
+ *
+ * Users who asked for less motion get the label and the tick but no hill.
*/
const BASE = 30; // px — icon box at rest
const GAP = 8; // px — between icon boxes at rest
-const PAD = 12; // px — dock padding top/bottom
+const ICON = 16; // px — glyph at rest; scales with the box
+const RAIL_WIDTH = 64; // px — Tailwind w-16, the column the icons centre in
+/**
+ * Space above the first icon at rest. Also the headroom the anchoring lifts
+ * the row into while magnified — computed from the geometry so a change to
+ * the hill can never quietly leave the anchoring clipped.
+ */
+const PAD_TOP = Math.max(12, maxAnchorLift(BASE, GAP));
+const PAD_BOTTOM = 12;
+/** The rest geometry, for tests that need to aim a pointer at an icon. */
+export const DECK_DOCK_GEOMETRY = { BASE, GAP, PAD_TOP } as const;
+/** Enter/leave: quick, a hair under critical damping so it never wobbles. */
+const HILL_SPRING = { stiffness: 600, damping: 45, mass: 1 };
+/** How far the label sits from the icon's edge. */
+const LABEL_GAP = 12;
+/**
+ * The label glides from icon to icon instead of hopping — critically damped,
+ * so it settles in ~40 ms and never overshoots the icon it names.
+ */
+const LABEL_SPRING = { stiffness: 900, damping: 60, mass: 1 };
+
+interface DockFrame {
+ layout: DockLayout;
+ hovered: number;
+}
export function DeckDock({ className }: { className?: string }) {
const t = useT();
@@ -38,6 +96,7 @@ export function DeckDock({ className }: { className?: string }) {
const conversations = useEventStore((s) => s.conversations);
const { health } = useSectionHealth();
const pluginAttention = usePluginAttention();
+ const reduced = useReducedMotion() ?? false;
const items = useMemo(() => NAV_GROUPS.flat(), []);
const groupBreaks = useMemo(() => {
@@ -57,121 +116,285 @@ export function DeckDock({ className }: { className?: string }) {
[health],
);
- const reduced = useMemo(
- () => window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false,
- [],
+ // --- pointer → motion values (no React state on the hot path) -----------
+ const scrollerRef = useRef<HTMLDivElement | null>(null);
+ const lastClientY = useRef<number | null>(null);
+ const hoveredRef = useRef(-1);
+ const [hovered, setHovered] = useState(-1);
+
+ /** Pointer position along the rail, in the REST layout's coordinates. */
+ const hillY = useMotionValue(0);
+ /** 0 = rail at rest, 1 = hill fully up. Sprung; the position is not. */
+ const hillTarget = useMotionValue(0);
+ const hill = useSpring(hillTarget, HILL_SPRING);
+ const hoveredMV = useMotionValue(-1);
+
+ const frame = useTransform([hillY, hill, hoveredMV], (latest: number[]): DockFrame => {
+ const [y, a, h] = latest;
+ const amount = Math.min(1, Math.max(0, a));
+ return {
+ layout: layoutDock(
+ items.length,
+ BASE,
+ GAP,
+ amount > 0.002 ? y : null,
+ 1 + (DOCK_MAX_SCALE - 1) * amount,
+ DOCK_RADIUS_UNITS,
+ PAD_TOP,
+ ),
+ hovered: h,
+ };
+ });
+ const blockHeight = useTransform(frame, (f) => PAD_TOP + f.layout.extent + PAD_BOTTOM);
+
+ // --- the one label ------------------------------------------------------
+ // The last position is kept so the label fades out where it was rather than
+ // jumping to a default the instant the pointer leaves.
+ const lastLabelPos = useRef({
+ top: PAD_TOP + GAP + BASE / 2,
+ left: RAIL_WIDTH / 2 + BASE / 2 + LABEL_GAP,
+ });
+ const labelTopRaw = useTransform(frame, (f) => {
+ if (f.hovered < 0) return lastLabelPos.current.top;
+ const it = f.layout.items[f.hovered];
+ const top = PAD_TOP + it.center - (scrollerRef.current?.scrollTop ?? 0);
+ lastLabelPos.current.top = top;
+ return top;
+ });
+ const labelTopSmooth = useSpring(labelTopRaw, LABEL_SPRING);
+ const labelTop = reduced ? labelTopRaw : labelTopSmooth;
+ const labelLeft = useTransform(frame, (f) => {
+ if (f.hovered < 0) return lastLabelPos.current.left;
+ const left = RAIL_WIDTH / 2 + f.layout.items[f.hovered].size / 2 + LABEL_GAP;
+ lastLabelPos.current.left = left;
+ return left;
+ });
+
+ const setHoveredSlot = useCallback(
+ (slot: number, tick: boolean) => {
+ const prev = hoveredRef.current;
+ if (slot === prev) return;
+ hoveredRef.current = slot;
+ hoveredMV.set(slot);
+ setHovered(slot);
+ if (prev < 0 && slot >= 0) {
+ // A fresh label appears AT its icon; only a label that is already on
+ // screen glides. Without this it would fly in from wherever the last
+ // one faded out. Derived values update on the next frame, so the rest
+ // centre is used — the glide closes the last few px itself.
+ labelTopSmooth.jump(
+ PAD_TOP + GAP + slot * (BASE + GAP) + BASE / 2 - (scrollerRef.current?.scrollTop ?? 0),
+ );
+ }
+ if (tick && slot >= 0) playDockTick("hover");
+ },
+ [hoveredMV, labelTopSmooth],
);
- const railRef = useRef<HTMLDivElement | null>(null);
- const [pointerY, setPointerY] = useState<number | null>(null);
+ const track = useCallback(
+ (clientY: number) => {
+ const el = scrollerRef.current;
+ if (!el) return;
+ const y = clientY - el.getBoundingClientRect().top + el.scrollTop - PAD_TOP;
+ hillY.set(y);
+ hillTarget.set(reduced ? 0 : 1);
+ setHoveredSlot(dockSlotAt(y, items.length, BASE, GAP), true);
+ },
+ [hillY, hillTarget, items.length, reduced, setHoveredSlot],
+ );
- const onMove = useCallback((e: React.PointerEvent<HTMLDivElement>) => {
- const rect = railRef.current?.getBoundingClientRect();
- if (!rect) return;
- setPointerY(e.clientY - rect.top - PAD);
- }, []);
- const onLeave = useCallback(() => setPointerY(null), []);
+ const onPointerMove = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ lastClientY.current = e.clientY;
+ track(e.clientY);
+ },
+ [track],
+ );
+ const onPointerLeave = useCallback(() => {
+ lastClientY.current = null;
+ hillTarget.set(0);
+ setHoveredSlot(-1, false);
+ }, [hillTarget, setHoveredSlot]);
+ // Wheel-scrolling under a still pointer moves the icons under it — re-aim.
+ const onScroll = useCallback(() => {
+ if (lastClientY.current !== null) track(lastClientY.current);
+ }, [track]);
- const layout = useMemo(
- () => layoutDock(items.length, BASE, GAP, reduced ? null : pointerY),
- [items.length, pointerY, reduced],
+ // Unmounting mid-hover (the pick navigates away) must not leave a stale
+ // hover behind for the next mount.
+ useEffect(
+ () => () => {
+ hoveredRef.current = -1;
+ },
+ [],
);
+ const hoveredItem = hovered >= 0 ? items[hovered] : null;
+ const hoveredCount = hoveredItem?.id === "chats" ? conversations.length : 0;
+
return (
<nav
aria-label={t("deck.sections")}
- className={cn("relative flex h-full w-16 shrink-0 flex-col items-center", className)}
+ className={cn("relative z-10 flex h-full w-16 shrink-0 flex-col", className)}
>
<div
- ref={railRef}
- onPointerMove={onMove}
- onPointerLeave={onLeave}
- className="relative w-full flex-1 overflow-visible"
- style={{ paddingTop: PAD, paddingBottom: PAD }}
+ ref={scrollerRef}
+ data-testid="deck-dock-rail"
+ onPointerMove={onPointerMove}
+ onPointerLeave={onPointerLeave}
+ onScroll={onScroll}
+ className="deck-dock-scroller relative h-full w-full overflow-y-auto overflow-x-hidden"
>
- {/* Height follows the magnified extent so the dock never clips. */}
- <div className="relative w-full" style={{ height: layout.extent }}>
- {items.map((item, i) => {
- const li = layout.items[i];
- const isActive =
- activeSection === item.id || item.matchIds?.includes(activeSection);
- const count = item.id === "chats" ? conversations.length : 0;
- const attention =
- (item.id === "apikeys" && apikeysError) ||
- (item.id === "skills" && pluginAttention.count > 0);
- const label = resolveNavLabel(t, item);
- const hot = li.scale > 1.35;
-
- return (
- <div key={item.id} className="contents">
- {groupBreaks.has(i) && (
- <span
- aria-hidden
- className="absolute left-4 right-4 h-px bg-border"
- style={{ top: li.center - li.size / 2 - GAP / 2 - 0.5 }}
- />
- )}
- <button
- type="button"
- onClick={() => setActiveSection(item.id)}
- aria-label={label}
- aria-current={isActive ? "page" : undefined}
- title={label}
- className={cn(
- "absolute left-1/2 flex items-center justify-center rounded-xl border transition-colors",
- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",
- isActive
- ? "border-primary/50 bg-primary/15 text-primary"
- : "border-transparent text-muted-foreground hover:text-foreground",
- hot && !isActive && "border-border/60 bg-card/30 text-foreground",
- )}
- style={{
- top: li.center - li.size / 2,
- width: li.size,
- height: li.size,
- transform: "translateX(-50%)",
- // The icon scales with its box; the box is what pushes
- // neighbours, so nothing overlaps.
- transition: reduced ? undefined : "top 90ms linear, width 90ms linear, height 90ms linear",
- }}
- >
- <item.icon
- className="shrink-0"
- style={{ width: Math.round(16 * li.scale), height: Math.round(16 * li.scale) }}
- />
-
- {/* Live pip: something is going on in this section. */}
- {(count > 0 || attention) && (
- <span
- aria-hidden
- className={cn(
- "absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full ring-2 ring-background",
- attention ? "bg-destructive" : "bg-primary",
- )}
- />
- )}
-
- {/* Label flies out while magnified — the dock has no room
- for text otherwise, and a hovered icon should name
- itself without a tooltip delay. */}
- {hot && (
- <span
- className="pointer-events-none absolute left-full ml-3 whitespace-nowrap rounded-md border border-border bg-background/90 px-2 py-0.5 text-xs text-foreground shadow-sm"
- >
- {label}
- {count > 0 && (
- <span className="ml-1.5 font-mono text-[10px] text-primary">{count}</span>
- )}
- </span>
- )}
- </button>
- </div>
- );
- })}
- </div>
+ {/* Height follows the magnified extent so the row never clips. */}
+ <motion.div className="relative w-full" style={{ height: blockHeight }}>
+ {items.map((item, i) => (
+ <DockIcon
+ key={item.id}
+ item={item}
+ index={i}
+ frame={frame}
+ label={resolveNavLabel(t, item)}
+ active={activeSection === item.id || !!item.matchIds?.includes(activeSection)}
+ hovered={hovered === i}
+ live={item.id === "chats" && conversations.length > 0}
+ attention={
+ (item.id === "apikeys" && apikeysError) ||
+ (item.id === "skills" && pluginAttention.count > 0)
+ }
+ groupBreak={groupBreaks.has(i)}
+ onSelect={() => {
+ playDockTick("select");
+ setActiveSection(item.id);
+ }}
+ onFocus={() => setHoveredSlot(i, false)}
+ onBlur={() => {
+ if (hoveredRef.current === i && lastClientY.current === null) {
+ setHoveredSlot(-1, false);
+ }
+ }}
+ />
+ ))}
+ </motion.div>
</div>
+
+ {/* The label rides beside the hovered icon, outside the scroller so the
+ scroller's clipping cannot cut it off. Decorative: every button
+ already carries its name as aria-label. */}
+ <AnimatePresence>
+ {hoveredItem && (
+ <motion.div
+ key="label"
+ aria-hidden
+ data-testid="deck-dock-label"
+ initial={{ opacity: 0, x: -6 }}
+ animate={{ opacity: 1, x: 0 }}
+ exit={{ opacity: 0, x: -4 }}
+ transition={reduced ? { duration: 0 } : { duration: 0.12, ease: "easeOut" }}
+ style={{ top: labelTop, left: labelLeft, y: "-50%" }}
+ className="pointer-events-none absolute whitespace-nowrap rounded-md border border-border bg-background/95 px-2 py-1 text-xs text-foreground shadow-md backdrop-blur"
+ >
+ {resolveNavLabel(t, hoveredItem)}
+ {hoveredCount > 0 && (
+ <span className="ml-1.5 font-mono text-[10px] text-primary">{hoveredCount}</span>
+ )}
+ </motion.div>
+ )}
+ </AnimatePresence>
</nav>
);
}
+function DockIcon({
+ item,
+ index,
+ frame,
+ label,
+ active,
+ hovered,
+ live,
+ attention,
+ groupBreak,
+ onSelect,
+ onFocus,
+ onBlur,
+}: {
+ item: NavItem;
+ index: number;
+ frame: MotionValue<DockFrame>;
+ label: string;
+ active: boolean;
+ hovered: boolean;
+ /** Something is going on in this section (a pip in the accent colour). */
+ live: boolean;
+ /** Something needs the user in this section (a pip in the alert colour). */
+ attention: boolean;
+ groupBreak: boolean;
+ onSelect: () => void;
+ onFocus: () => void;
+ onBlur: () => void;
+}) {
+ // Each icon binds its box to the shared layout — written straight to the
+ // element by the motion runtime, never through a React render.
+ const top = useTransform(frame, (f) => {
+ const it = f.layout.items[index];
+ return PAD_TOP + it.center - it.size / 2;
+ });
+ const size = useTransform(frame, (f) => f.layout.items[index].size);
+ const glyph = useTransform(frame, (f) => ICON * f.layout.items[index].scale);
+ const ruleTop = useTransform(frame, (f) => {
+ const it = f.layout.items[index];
+ return PAD_TOP + it.center - it.size / 2 - GAP / 2 - 0.5;
+ });
+ const Icon = item.icon;
+
+ return (
+ <>
+ {groupBreak && (
+ <motion.span
+ aria-hidden
+ className="absolute left-4 right-4 h-px bg-border"
+ style={{ top: ruleTop }}
+ />
+ )}
+ <motion.button
+ type="button"
+ data-testid={`deck-dock-${item.id}`}
+ onClick={onSelect}
+ onFocus={onFocus}
+ onBlur={onBlur}
+ aria-label={label}
+ aria-current={active ? "page" : undefined}
+ className={cn(
+ "absolute left-1/2 flex items-center justify-center rounded-xl border transition-colors duration-150",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",
+ active
+ ? "border-primary/50 bg-primary/15 text-primary"
+ : hovered
+ ? "border-border/60 bg-card/40 text-foreground"
+ : "border-transparent text-muted-foreground",
+ )}
+ style={{ top, width: size, height: size, x: "-50%" }}
+ >
+ <motion.span
+ aria-hidden
+ className="flex shrink-0 items-center justify-center"
+ style={{ width: glyph, height: glyph }}
+ >
+ <Icon className="h-full w-full" />
+ </motion.span>
+
+ {(live || attention) && (
+ <span
+ aria-hidden
+ className={cn(
+ "absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full ring-2 ring-background",
+ attention ? "bg-destructive" : "bg-primary",
+ )}
+ />
+ )}
+ </motion.button>
+ </>
+ );
+}
+
export type { SectionId };
diff --git a/jarvis/ui/web/frontend/src/index.css b/jarvis/ui/web/frontend/src/index.css
index 03abe0013c..2f08faf5fa 100644
--- a/jarvis/ui/web/frontend/src/index.css
+++ b/jarvis/ui/web/frontend/src/index.css
@@ -359,6 +359,19 @@
height: 0;
}
+/* The mission deck's dock scrolls when the window is shorter than its column
+ of icons, but shows no bar: a 10 px thumb inside a 64 px rail would sit on
+ the icons themselves. Top-level for the same reason as the rules above. */
+.deck-dock-scroller {
+ overscroll-behavior: contain;
+ scrollbar-width: none;
+}
+
+.deck-dock-scroller::-webkit-scrollbar {
+ width: 0;
+ height: 0;
+}
+
/* While a boundary is being dragged, the terminal inside a pane keeps the size
it had — a terminal is a grid of whole character cells, and re-cutting that
grid means telling the agent to redraw its entire screen, which is far too
diff --git a/jarvis/ui/web/frontend/src/lib/dockMagnify.test.ts b/jarvis/ui/web/frontend/src/lib/dockMagnify.test.ts
index 141bcc3d24..b764c1036f 100644
--- a/jarvis/ui/web/frontend/src/lib/dockMagnify.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/dockMagnify.test.ts
@@ -1,5 +1,12 @@
import { describe, expect, it } from "vitest";
-import { DOCK_MAX_SCALE, DOCK_RADIUS_UNITS, layoutDock, magnifyScale } from "@/lib/dockMagnify";
+import {
+ DOCK_MAX_SCALE,
+ DOCK_RADIUS_UNITS,
+ dockSlotAt,
+ layoutDock,
+ magnifyScale,
+ maxAnchorLift,
+} from "@/lib/dockMagnify";
describe("magnifyScale", () => {
it("is full size under the pointer and rest size beyond the radius", () => {
@@ -53,3 +60,77 @@ describe("layoutDock", () => {
expect(items[11].size).toBe(32);
});
});
+
+describe("layoutDock — pointer anchoring", () => {
+ it("does not lift the row without headroom (top-anchored, as before)", () => {
+ const rest = layoutDock(9, 30, 8, null);
+ const { items, shift } = layoutDock(9, 30, 8, rest.items[4].center);
+ expect(shift).toBe(0);
+ // Everything after the hill has been pushed DOWN — the icon under the
+ // pointer is no longer centred on it.
+ expect(items[4].center).toBeGreaterThan(rest.items[4].center + 10);
+ });
+
+ it("keeps the icon under the pointer under the pointer when it may lift", () => {
+ const rest = layoutDock(9, 30, 8, null);
+ const p = rest.items[4].center;
+ const { items, shift } = layoutDock(9, 30, 8, p, undefined, undefined, 40);
+ expect(shift).toBeLessThan(0);
+ expect(items[4].center).toBeCloseTo(p, 6);
+ // Still no overlap: neighbours moved by exactly the room they need.
+ for (let i = 1; i < items.length; i++) {
+ const prevEnd = items[i - 1].center + items[i - 1].size / 2;
+ const thisStart = items[i].center - items[i].size / 2;
+ expect(thisStart).toBeGreaterThanOrEqual(prevEnd + 8 - 1e-9);
+ }
+ });
+
+ it("pins the material point, not just the centre — the icon's edges stay put too", () => {
+ const rest = layoutDock(9, 30, 8, null);
+ const top = rest.items[4].center - 15;
+ const { items } = layoutDock(9, 30, 8, top, undefined, undefined, 40);
+ expect(items[4].center - items[4].size / 2).toBeCloseTo(top, 6);
+ });
+
+ it("never lifts more than the headroom allows", () => {
+ const rest = layoutDock(9, 30, 8, null);
+ const { shift, items } = layoutDock(9, 30, 8, rest.items[6].center, undefined, undefined, 5);
+ expect(shift).toBeGreaterThanOrEqual(-5);
+ expect(items[0].center - items[0].size / 2).toBeGreaterThanOrEqual(8 - 5 - 1e-9);
+ });
+
+ it("a pointer past the end pins that end, so the last icon grows towards it", () => {
+ const rest = layoutDock(5, 30, 8, null);
+ const bottom = rest.items[4].center + 15;
+ const { items } = layoutDock(5, 30, 8, bottom + 30, undefined, undefined, 40);
+ expect(items[4].center + items[4].size / 2).toBeCloseTo(bottom, 6);
+ });
+});
+
+describe("dockSlotAt", () => {
+ it("maps a rest position to its icon, gaps split between neighbours", () => {
+ expect(dockSlotAt(8 + 15, 5, 30, 8)).toBe(0);
+ expect(dockSlotAt(8 + 30 + 3, 5, 30, 8)).toBe(0); // first half of the gap
+ expect(dockSlotAt(8 + 30 + 5, 5, 30, 8)).toBe(1); // second half
+ expect(dockSlotAt(8 + 4 * 38 + 15, 5, 30, 8)).toBe(4);
+ });
+
+ it("is -1 outside the row", () => {
+ expect(dockSlotAt(-20, 5, 30, 8)).toBe(-1);
+ expect(dockSlotAt(8 + 5 * 38 + 4, 5, 30, 8)).toBe(-1);
+ expect(dockSlotAt(Number.NaN, 5, 30, 8)).toBe(-1);
+ expect(dockSlotAt(10, 0, 30, 8)).toBe(-1);
+ });
+});
+
+describe("maxAnchorLift", () => {
+ it("is the headroom the anchoring actually needs — no sample lifts further", () => {
+ const need = maxAnchorLift(30, 8);
+ expect(need).toBeGreaterThan(0);
+ const rest = layoutDock(15, 30, 8, null);
+ for (let p = rest.items[6].center - 19; p <= rest.items[8].center + 19; p += 1) {
+ const { shift } = layoutDock(15, 30, 8, p, undefined, undefined, 1000);
+ expect(-shift).toBeLessThanOrEqual(need + 1e-9);
+ }
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/dockMagnify.ts b/jarvis/ui/web/frontend/src/lib/dockMagnify.ts
index d5889ffa87..9683fc51e0 100644
--- a/jarvis/ui/web/frontend/src/lib/dockMagnify.ts
+++ b/jarvis/ui/web/frontend/src/lib/dockMagnify.ts
@@ -1,23 +1,31 @@
/**
* The dock's magnification curve — the pure math behind DeckDock.tsx.
*
- * The effect the maintainer asked for is the one desktop docks made familiar:
- * the icon under the pointer grows, its neighbours grow a little less, and
- * everything else stays put — a smooth hill, not a step. Two things make it
- * feel right rather than jumpy, and both live here so they can be tested
- * without a DOM:
+ * The effect is the one desktop docks made familiar: the icon under the
+ * pointer grows, its neighbours grow a little less, and everything else stays
+ * put — a smooth hill, not a step. Three things make it feel right rather than
+ * jumpy, and all three live here so they can be tested without a DOM:
*
* 1. A cosine falloff over a fixed radius. Linear falloff has a visible kink
* where it hits zero; cosine eases into rest.
* 2. Positions derived from the SCALES, not from the pointer. Each icon's
* centre is the running sum of the sizes before it, so growing one pushes
* the rest outward by exactly the space it takes — no overlap, no gap.
+ * 3. The row is ANCHORED AT THE POINTER. Summing sizes from the top pushes
+ * every magnified icon downward, away from the pointer that is magnifying
+ * it — by almost a full icon in the middle of a long dock, which is what
+ * made the old dock feel as if the hill lagged behind the mouse. The real
+ * desktop docks lift the row so the point under the pointer stays exactly
+ * where it is: what grows above the pointer moves up, what grows below
+ * moves down. `headroom` is how far the row may be lifted (the space the
+ * dock reserves above its first icon at rest); `maxAnchorLift` says how
+ * much a given geometry needs.
*/
/** Largest scale for the icon directly under the pointer. */
-export const DOCK_MAX_SCALE = 1.75;
+export const DOCK_MAX_SCALE = 1.5;
/** How far (in base-icon units) the hill reaches to either side. */
-export const DOCK_RADIUS_UNITS = 2.6;
+export const DOCK_RADIUS_UNITS = 2.4;
/**
* Scale for one icon given the pointer's distance from its rest centre, in
@@ -43,13 +51,26 @@ export interface DockLayoutItem {
size: number;
}
+export interface DockLayout {
+ items: DockLayoutItem[];
+ /** Where the row ends, in px from the dock's start (trailing gap included). */
+ extent: number;
+ /**
+ * How far the whole row was lifted to keep the point under the pointer in
+ * place: 0 at rest, negative while magnified, never below `-headroom`.
+ */
+ shift: number;
+}
+
/**
* Lay out `count` icons of `baseSize` px with `gap` px between them, given the
* pointer position along the axis (`pointer`, px from the start; null = at
* rest). Returns one entry per icon and the total extent.
*
* Positions come from the scales — every icon starts where the previous one
- * ended — so the row grows to make room instead of overlapping.
+ * ended — so the row grows to make room instead of overlapping. With a
+ * `headroom` > 0 the row is then lifted (by at most that much) so the point of
+ * the rest layout under the pointer stays under the pointer.
*/
export function layoutDock(
count: number,
@@ -58,7 +79,8 @@ export function layoutDock(
pointer: number | null,
maxScale = DOCK_MAX_SCALE,
radiusUnits = DOCK_RADIUS_UNITS,
-): { items: DockLayoutItem[]; extent: number } {
+ headroom = 0,
+): DockLayout {
const items: DockLayoutItem[] = [];
const stride = baseSize + gap;
// Rest centres are what the pointer is measured against: measuring against
@@ -75,5 +97,69 @@ export function layoutDock(
items.push({ scale, center: cursor + size / 2, size });
cursor += size + gap;
}
- return { items, extent: cursor };
+
+ let shift = 0;
+ if (pointer !== null && headroom > 0 && count > 0) {
+ // The "material point": which slot of the REST layout is under the pointer,
+ // and how far into it. A pointer past either end pins that end's edge, so
+ // an icon approached from beyond the row grows towards the pointer.
+ const rowStart = gap;
+ const rowEnd = gap + (count - 1) * stride + baseSize;
+ const p = Math.min(rowEnd, Math.max(rowStart, pointer));
+ const i = Math.min(count - 1, Math.max(0, Math.floor((p - rowStart) / stride)));
+ const within = p - (rowStart + i * stride);
+ const it = items[i];
+ const magnified =
+ within <= baseSize
+ ? it.center - it.size / 2 + (within / baseSize) * it.size
+ : it.center + it.size / 2 + (within - baseSize); // in the gap below: gaps do not grow
+ // Growth only ever pushes material down, so the lift is never positive.
+ shift = Math.max(-headroom, Math.min(0, p - magnified));
+ if (shift !== 0) {
+ for (const item of items) item.center += shift;
+ }
+ }
+ return { items, extent: cursor + shift, shift };
+}
+
+/**
+ * Which icon's slot a rest-space position falls into: the icon's box plus half
+ * a gap on either side, so there is no dead zone between neighbours. -1 when
+ * the position is outside the row.
+ *
+ * Because the layout is anchored at the pointer, the slot under the pointer in
+ * REST space is also the icon visibly under it — one hit test serves both.
+ */
+export function dockSlotAt(pointer: number, count: number, baseSize: number, gap: number): number {
+ if (!Number.isFinite(pointer) || count <= 0) return -1;
+ const i = Math.floor((pointer - gap / 2) / (baseSize + gap));
+ return i >= 0 && i < count ? i : -1;
+}
+
+/**
+ * The largest lift `layoutDock` will ever ask for with this geometry — the
+ * headroom a dock has to reserve above its first icon so the anchoring is
+ * never clipped. Found by sampling pointer positions across one stride in
+ * the middle of a long row (that is where the hill has the most material
+ * above the pointer). Rounded up to whole px.
+ */
+export function maxAnchorLift(
+ baseSize: number,
+ gap: number,
+ maxScale = DOCK_MAX_SCALE,
+ radiusUnits = DOCK_RADIUS_UNITS,
+): number {
+ const stride = baseSize + gap;
+ const count = Math.ceil(radiusUnits) * 2 + 3;
+ const mid = Math.floor(count / 2);
+ const start = gap + mid * stride;
+ let worst = 0;
+ const steps = 48;
+ for (let s = 0; s <= steps; s++) {
+ const p = start + (stride * s) / steps;
+ // A generous headroom so the sample measures the unclamped lift.
+ const { shift } = layoutDock(count, baseSize, gap, p, maxScale, radiusUnits, baseSize * count);
+ worst = Math.max(worst, -shift);
+ }
+ return Math.ceil(worst);
}
diff --git a/jarvis/ui/web/frontend/src/lib/sound.test.ts b/jarvis/ui/web/frontend/src/lib/sound.test.ts
index f92bdff717..83b3a0bd53 100644
--- a/jarvis/ui/web/frontend/src/lib/sound.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/sound.test.ts
@@ -83,3 +83,72 @@ describe("playDropConfirm", () => {
expect(fake.ctorSpy).not.toHaveBeenCalled();
});
});
+
+describe("playDockTick", () => {
+ beforeEach(() => {
+ vi.resetModules();
+ delete (window as unknown as { AudioContext?: unknown }).AudioContext;
+ delete (window as unknown as { webkitAudioContext?: unknown })
+ .webkitAudioContext;
+ delete (navigator as unknown as { userActivation?: unknown }).userActivation;
+ try {
+ localStorage.removeItem("jarvis.ui.sound");
+ } catch {
+ /* ignore */
+ }
+ });
+
+ it("is a no-op and never throws when WebAudio is unavailable", async () => {
+ const { playDockTick } = await import("./sound");
+ expect(() => playDockTick()).not.toThrow();
+ expect(() => playDockTick("select")).not.toThrow();
+ });
+
+ it("plays one short body voice per tick, even on an engine without buffers", async () => {
+ const fake = installFakeAudio();
+ const { playDockTick } = await import("./sound");
+ playDockTick("hover");
+ expect(fake.ctorSpy).toHaveBeenCalledTimes(1);
+ expect(fake.oscillators.length).toBe(1);
+ expect(fake.started.length).toBe(1);
+ // Sub-40 ms: a detent, not a note.
+ expect(fake.stopped[0]).toBeLessThan(0.05);
+ });
+
+ it("rate-limits: two ticks on the same audio clock play once", async () => {
+ const fake = installFakeAudio();
+ const { playDockTick } = await import("./sound");
+ playDockTick("hover");
+ playDockTick("hover");
+ expect(fake.oscillators.length).toBe(1);
+ });
+
+ it("gives the pick a lower voice than the pass", async () => {
+ const fake = installFakeAudio();
+ const { playDockTick } = await import("./sound");
+ playDockTick("select");
+ const osc = fake.oscillators[0] as { frequency: { setValueAtTime: ReturnType<typeof vi.fn> } };
+ const start = osc.frequency.setValueAtTime.mock.calls[0][0] as number;
+ // 1300 Hz ± 4 % jitter — well under the 2100 Hz hover voice.
+ expect(start).toBeGreaterThan(1200);
+ expect(start).toBeLessThan(1400);
+ });
+
+ it("does not even create a context before the page has seen a gesture", async () => {
+ const fake = installFakeAudio();
+ (navigator as unknown as { userActivation: unknown }).userActivation = {
+ hasBeenActive: false,
+ };
+ const { playDockTick } = await import("./sound");
+ playDockTick();
+ expect(fake.ctorSpy).not.toHaveBeenCalled();
+ });
+
+ it("stays silent when the user muted UI sound", async () => {
+ const fake = installFakeAudio();
+ localStorage.setItem("jarvis.ui.sound", "off");
+ const { playDockTick } = await import("./sound");
+ playDockTick();
+ expect(fake.ctorSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/sound.ts b/jarvis/ui/web/frontend/src/lib/sound.ts
index 3af38f3f77..b0b7fc41a4 100644
--- a/jarvis/ui/web/frontend/src/lib/sound.ts
+++ b/jarvis/ui/web/frontend/src/lib/sound.ts
@@ -1,11 +1,12 @@
/**
- * A tiny, dependency-free confirmation chime for UI affordances (currently the
- * JarvisDock "mission captured" feedback). WebAudio is a browser built-in, so
- * this works on any cloud-first client and adds nothing to the bundle.
+ * Tiny, dependency-free UI sounds: the JarvisDock "mission captured" chime and
+ * the deck dock's detent tick. WebAudio is a browser built-in, so this works on
+ * any cloud-first client and adds nothing to the bundle.
*
- * Brief from the product: quiet and smooth. Two soft sine voices a gentle
- * interval apart, a low peak gain, a short attack and a smooth exponential
- * release — a "tding", never a beep.
+ * Brief from the product: quiet and smooth. The chime is two soft sine voices
+ * a gentle interval apart, a low peak gain, a short attack and a smooth
+ * exponential release — a "tding", never a beep. The tick is a sub-40 ms
+ * detent, the sound a picker wheel makes as it passes a notch.
*
* Every call is safe from any event handler: it is a no-op (never throws) when
* WebAudio is unavailable (headless / jsdom) or the user muted UI sounds via
@@ -48,6 +49,19 @@ function getCtx(): AudioContext | null {
return sharedCtx;
}
+/**
+ * Has the page seen a user gesture yet? Browsers refuse to start audio before
+ * one, and a context created too early logs a warning and stays suspended.
+ * Unknown (older engines, jsdom) counts as yes — the play paths still guard
+ * against a suspended context.
+ */
+function hadUserGesture(): boolean {
+ if (typeof navigator === "undefined") return true;
+ const ua = (navigator as unknown as { userActivation?: { hasBeenActive?: boolean } })
+ .userActivation;
+ return ua?.hasBeenActive !== false;
+}
+
/**
* Play the soft "mission captured" confirmation chime. No-op when WebAudio is
* unavailable or UI sound is muted; any audio quirk is swallowed so it can
@@ -93,3 +107,113 @@ export function playDropConfirm(): void {
// Never let an audio hiccup surface to the interaction.
}
}
+
+/** Two flavours of the dock tick: passing a notch, and picking one. */
+export type DockTick = "hover" | "select";
+
+/** Fastest the tick may repeat; a sweep across the dock still reads as a
+ * ratchet, but two pointer events on one frame never double-fire. */
+const TICK_MIN_INTERVAL_S = 0.024;
+let lastTickAt = -Infinity;
+let noiseBuffer: AudioBuffer | null = null;
+
+interface TickVoice {
+ /** Sine sweep: start and end frequency (Hz) and how long the glide takes. */
+ from: number;
+ to: number;
+ sweep: number;
+ /** Peak gain and how long the body rings. */
+ peak: number;
+ decay: number;
+ /** Band-passed noise transient: centre frequency and peak gain. */
+ click: number;
+ clickPeak: number;
+}
+
+// The hover tick is short and bright, the pick a shade lower, longer and
+// firmer — same family, so the two read as one mechanism.
+const TICK_VOICES: Record<DockTick, TickVoice> = {
+ hover: { from: 2100, to: 700, sweep: 0.018, peak: 0.035, decay: 0.03, click: 3200, clickPeak: 0.02 },
+ select: { from: 1300, to: 420, sweep: 0.03, peak: 0.06, decay: 0.05, click: 2200, clickPeak: 0.03 },
+};
+
+function noiseFor(ctx: AudioContext): AudioBuffer | null {
+ if (typeof ctx.createBuffer !== "function") return null;
+ if (!noiseBuffer || noiseBuffer.sampleRate !== ctx.sampleRate) {
+ const length = Math.max(1, Math.round(ctx.sampleRate * 0.03));
+ noiseBuffer = ctx.createBuffer(1, length, ctx.sampleRate);
+ const data = noiseBuffer.getChannelData(0);
+ for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
+ }
+ return noiseBuffer;
+}
+
+/**
+ * Play one detent tick of the deck dock — the pointer moved onto another icon
+ * (`hover`) or picked one (`select`). No-op when WebAudio is unavailable, the
+ * page has not been interacted with yet, UI sound is muted, or the last tick
+ * was under `TICK_MIN_INTERVAL_S` ago; any audio quirk is swallowed so it can
+ * never break the hover it accompanies.
+ */
+export function playDockTick(kind: DockTick = "hover"): void {
+ if (!soundEnabled() || !hadUserGesture()) return;
+ const ctx = getCtx();
+ if (!ctx) return;
+ try {
+ if (ctx.state === "suspended") {
+ // A hover is not a gesture; the page has had one, so this may succeed.
+ // The tick itself is skipped: scheduling into a suspended context would
+ // fire every queued tick at once when it finally starts.
+ if (typeof ctx.resume === "function") void ctx.resume();
+ return;
+ }
+ const now = ctx.currentTime;
+ if (now - lastTickAt < TICK_MIN_INTERVAL_S) return;
+ lastTickAt = now;
+ const v = TICK_VOICES[kind];
+
+ // Body: a short downward sine glide with a near-instant attack — the
+ // "tock" of a notch. A few percent of pitch jitter keeps a fast sweep
+ // from sounding like a machine.
+ const jitter = 1 + (Math.random() - 0.5) * 0.08;
+ const osc = ctx.createOscillator();
+ osc.type = "sine";
+ osc.frequency.setValueAtTime(v.from * jitter, now);
+ osc.frequency.exponentialRampToValueAtTime(v.to * jitter, now + v.sweep);
+ const body = ctx.createGain();
+ body.gain.setValueAtTime(0.0001, now);
+ body.gain.exponentialRampToValueAtTime(v.peak, now + 0.0015);
+ body.gain.exponentialRampToValueAtTime(0.0001, now + v.decay);
+ osc.connect(body);
+ body.connect(ctx.destination);
+ osc.start(now);
+ osc.stop(now + v.decay + 0.01);
+
+ // Transient: a few milliseconds of band-passed noise on top gives the
+ // click its "tick" — without it the sine alone is a blip. Optional: an
+ // engine without buffers or filters still gets the body.
+ const noise = noiseFor(ctx);
+ if (noise && typeof ctx.createBufferSource === "function") {
+ const src = ctx.createBufferSource();
+ src.buffer = noise;
+ let tail: AudioNode = src;
+ if (typeof ctx.createBiquadFilter === "function") {
+ const band = ctx.createBiquadFilter();
+ band.type = "bandpass";
+ band.frequency.value = v.click;
+ band.Q.value = 1.2;
+ src.connect(band);
+ tail = band;
+ }
+ const clickGain = ctx.createGain();
+ clickGain.gain.setValueAtTime(v.clickPeak, now);
+ clickGain.gain.exponentialRampToValueAtTime(0.0001, now + 0.012);
+ tail.connect(clickGain);
+ clickGain.connect(ctx.destination);
+ src.start(now);
+ src.stop(now + 0.02);
+ }
+ } catch {
+ // Never let an audio hiccup surface to the interaction.
+ }
+}