diff --git a/.github/issue-evidence/10722-uiux-deep-qa-sweep/README.md b/.github/issue-evidence/10722-uiux-deep-qa-sweep/README.md new file mode 100644 index 0000000000000..9a60c276c81ce --- /dev/null +++ b/.github/issue-evidence/10722-uiux-deep-qa-sweep/README.md @@ -0,0 +1,46 @@ +# Deep UI/UX QA sweep — chat, launcher, home, notifications, state (2026-07-01) + +Adversarially-verified QA of the develop chat/launcher/home surfaces: 6 parallel +deep reviewers + per-finding refutation agents (20 findings confirmed, several +refuted), the full `packages/ui` vitest battery, and all boot-free real-Chromium +e2e runners. This bundle carries the post-fix captures for the batch landed with +it (see the commit message for the full finding list). + +## What was run (all real, local, headless Chromium + jsdom) + +- `packages/ui` vitest battery: shell + pages + state + widgets + conversations + + chat — **1908 tests, all green** (12 initial timeouts reproduced as pure + machine-load flakes: 127/127 green when re-run isolated). +- Boot-free e2e runners (real Chromium, real input, screenshots + webm): + chatux-gesture, chat-sheet (51 screenshots), conversation-swipe, bottombar, + chat-ambient, chat-sheet-frame-glitch, launcher, background, tutorial, + view-lifecycle, ftu-home, home-screen — **all passing after this batch**. +- Two runner failures root-caused to STALE HARNESSES (not product bugs), fixed: + chat-sheet keyboard velocity race; launcher fixture eaten by the #10800 + seeded dock (23 undocked tiles ≤ 1 page). + +## Artifacts + +| file | proves | +|------|--------| +| `home-desktop-postfix.png` | home dashboard, desktop viewport, post-fix | +| `home-mobile-postfix.png` | home dashboard, mobile viewport, post-fix | +| `launcher-mobile-dock-postfix.png` | seeded chat+settings dock + paged grid | +| `launcher-walkthrough-postfix.webm` | real-input launcher walkthrough: launch, edit-mode, page swipe (telemetry 0→2) | +| `home-launcher-flow-postfix.webm` | home→launcher rail flow incl. developer page | +| `chat-sheet-keyboard-postfix.png` | chat sheet at FULL with keyboard open (the fixed assertion) | + +Companion per-view captures regenerate deterministically via +`bun run packages/ui/src/components/**/__e2e__/run-*.mjs`. + +## Full-app audit (post-fix, this branch) + +`bun run --cwd packages/app audit:app` — **349/349 view×viewport combos passed; +broken=0, needs-work=0, needs-eyeball=212, good=136, minimalism-budget-failures=0** +(the audit walks every builtin + plugin view at mobile-portrait, mobile-landscape, +desktop-landscape, and ipad-portrait). Curated captures: + +| file | view | +|------|------| +| `audit-chat-desktop.png` / `audit-chat-mobile.png` | chat view, desktop + mobile | +| `audit-settings-desktop.png` / `audit-settings-mobile.png` | settings view (incl. new Background section entry) | diff --git a/.github/issue-evidence/10722-uiux-deep-qa-sweep/audit-chat-desktop.png b/.github/issue-evidence/10722-uiux-deep-qa-sweep/audit-chat-desktop.png new file mode 100644 index 0000000000000..d3308abf57675 Binary files /dev/null and b/.github/issue-evidence/10722-uiux-deep-qa-sweep/audit-chat-desktop.png differ diff --git a/.github/issue-evidence/10722-uiux-deep-qa-sweep/audit-chat-mobile.png b/.github/issue-evidence/10722-uiux-deep-qa-sweep/audit-chat-mobile.png new file mode 100644 index 0000000000000..536309cd59caa Binary files /dev/null and b/.github/issue-evidence/10722-uiux-deep-qa-sweep/audit-chat-mobile.png differ diff --git a/.github/issue-evidence/10722-uiux-deep-qa-sweep/audit-settings-desktop.png b/.github/issue-evidence/10722-uiux-deep-qa-sweep/audit-settings-desktop.png new file mode 100644 index 0000000000000..ff9e055508c34 Binary files /dev/null and b/.github/issue-evidence/10722-uiux-deep-qa-sweep/audit-settings-desktop.png differ diff --git a/.github/issue-evidence/10722-uiux-deep-qa-sweep/audit-settings-mobile.png b/.github/issue-evidence/10722-uiux-deep-qa-sweep/audit-settings-mobile.png new file mode 100644 index 0000000000000..6662b30fe9655 Binary files /dev/null and b/.github/issue-evidence/10722-uiux-deep-qa-sweep/audit-settings-mobile.png differ diff --git a/.github/issue-evidence/10722-uiux-deep-qa-sweep/chat-sheet-keyboard-postfix.png b/.github/issue-evidence/10722-uiux-deep-qa-sweep/chat-sheet-keyboard-postfix.png new file mode 100644 index 0000000000000..786fc39104683 Binary files /dev/null and b/.github/issue-evidence/10722-uiux-deep-qa-sweep/chat-sheet-keyboard-postfix.png differ diff --git a/.github/issue-evidence/10722-uiux-deep-qa-sweep/home-desktop-postfix.png b/.github/issue-evidence/10722-uiux-deep-qa-sweep/home-desktop-postfix.png new file mode 100644 index 0000000000000..fddef8c75a663 Binary files /dev/null and b/.github/issue-evidence/10722-uiux-deep-qa-sweep/home-desktop-postfix.png differ diff --git a/.github/issue-evidence/10722-uiux-deep-qa-sweep/home-launcher-flow-postfix.webm b/.github/issue-evidence/10722-uiux-deep-qa-sweep/home-launcher-flow-postfix.webm new file mode 100644 index 0000000000000..b4de6ce65e812 Binary files /dev/null and b/.github/issue-evidence/10722-uiux-deep-qa-sweep/home-launcher-flow-postfix.webm differ diff --git a/.github/issue-evidence/10722-uiux-deep-qa-sweep/home-mobile-postfix.png b/.github/issue-evidence/10722-uiux-deep-qa-sweep/home-mobile-postfix.png new file mode 100644 index 0000000000000..2b7e69f26b5a6 Binary files /dev/null and b/.github/issue-evidence/10722-uiux-deep-qa-sweep/home-mobile-postfix.png differ diff --git a/.github/issue-evidence/10722-uiux-deep-qa-sweep/launcher-mobile-dock-postfix.png b/.github/issue-evidence/10722-uiux-deep-qa-sweep/launcher-mobile-dock-postfix.png new file mode 100644 index 0000000000000..6e861c1193704 Binary files /dev/null and b/.github/issue-evidence/10722-uiux-deep-qa-sweep/launcher-mobile-dock-postfix.png differ diff --git a/.github/issue-evidence/10722-uiux-deep-qa-sweep/launcher-walkthrough-postfix.webm b/.github/issue-evidence/10722-uiux-deep-qa-sweep/launcher-walkthrough-postfix.webm new file mode 100644 index 0000000000000..6924e7cbff3a3 Binary files /dev/null and b/.github/issue-evidence/10722-uiux-deep-qa-sweep/launcher-walkthrough-postfix.webm differ diff --git a/packages/ui/src/components/chat/widgets/notifications.tsx b/packages/ui/src/components/chat/widgets/notifications.tsx index 3b244898ce630..a38d3b43c0c42 100644 --- a/packages/ui/src/components/chat/widgets/notifications.tsx +++ b/packages/ui/src/components/chat/widgets/notifications.tsx @@ -1,7 +1,14 @@ import type { AgentNotification } from "@elizaos/core"; import { Bell } from "lucide-react"; import { categoryIcon } from "../../../state/notifications/category-icon"; -import { useNotifications } from "../../../state/notifications/notification-store"; +import { + isSafeDeepLink, + navigateDeepLink, +} from "../../../state/notifications/navigate-deep-link"; +import { + markNotificationRead, + useNotifications, +} from "../../../state/notifications/notification-store"; import { rankHomeNotifications } from "../../../widgets/home-priority"; import type { WidgetProps } from "../../../widgets/types"; import { HomeWidgetCard, useWidgetNavigation } from "./home-widget-card"; @@ -78,11 +85,18 @@ export function NotificationsWidget(props: WidgetProps) { tone={urgent ? "danger" : top.priority === "high" ? "warn" : "default"} testId="widget-notifications" ariaLabel={`Notifications: ${unreadCount} unread, latest ${top.title}. Open inbox.`} - onActivate={() => - top.deepLink - ? nav.openView(top.deepLink, "inbox") - : nav.openView("/inbox", "inbox") - } + onActivate={() => { + // Mirror NotificationCenter's row behavior exactly: mark read, then + // navigate through the scheme-checked deep-link helper (deepLink is + // producer/LLM-influenceable — raw pushState both broke https links + // and skipped the safety allowlist). Unsafe/missing → inbox. + if (!top.readAt) void markNotificationRead(top.id); + if (top.deepLink && isSafeDeepLink(top.deepLink)) { + navigateDeepLink(top.deepLink); + } else { + nav.openView("/inbox", "inbox"); + } + }} /> ); } diff --git a/packages/ui/src/components/composites/chat/chat-message.tap-reveal.test.tsx b/packages/ui/src/components/composites/chat/chat-message.tap-reveal.test.tsx new file mode 100644 index 0000000000000..cb148406b9739 --- /dev/null +++ b/packages/ui/src/components/composites/chat/chat-message.tap-reveal.test.tsx @@ -0,0 +1,139 @@ +// @vitest-environment jsdom + +// Touch tap-vs-scroll discrimination for the composite ChatMessage's +// tap-to-reveal action rail (copy/edit/play/delete). On non-hover devices the +// whole
toggles the rail on touchend; without move-slop tracking a +// flick-scroll over the transcript toggled the rail on whichever message the +// finger started on. The fix mirrors the shell ThreadLine: finger travel past +// the slop (TAP_REVEAL_MOVE_CANCEL_PX) cancels the toggle, and an active +// (non-collapsed) text selection suppresses it so ending a highlight drag +// never also flips the rail. + +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; + +import { ChatMessage } from "./chat-message"; +import type { ChatMessageData } from "./chat-types"; + +beforeAll(() => { + // Simulate a touch-only device: the hover media query must NOT match so the + // tap-to-reveal path (not mouse hover) drives the action rail. Installed + // before the first render because ChatMessage caches the MediaQueryList. + window.matchMedia = vi.fn().mockImplementation((query: string) => ({ + matches: false, + media: query, + onchange: null, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + addListener: vi.fn(), + removeListener: vi.fn(), + dispatchEvent: vi.fn(), + })); +}); + +afterEach(() => { + window.getSelection()?.removeAllRanges(); + cleanup(); +}); + +function makeMessage( + overrides: Partial = {}, +): ChatMessageData { + return { + id: "msg-1", + role: "assistant", + text: "Here are your latest balances.", + ...overrides, + }; +} + +function getArticle(): HTMLElement { + return screen.getByTestId("chat-message"); +} + +/** + * The rail's visibility is carried by an opacity class on the wrapper around + * ChatMessageActions (opacity-100 shown, opacity-0 hidden) — walk up from the + * always-rendered Copy button to read it. + */ +function railVisible(): boolean { + let el: HTMLElement | null = screen.getByLabelText("Copy message"); + while (el) { + if (el.classList.contains("opacity-100")) return true; + if (el.classList.contains("opacity-0")) return false; + el = el.parentElement; + } + throw new Error("action-rail visibility wrapper not found"); +} + +function touchPoint(clientX: number, clientY: number) { + return { clientX, clientY }; +} + +describe("ChatMessage tap-to-reveal vs transcript scroll", () => { + it("a clean tap toggles the action rail on and off", () => { + render(); + const article = getArticle(); + expect(railVisible()).toBe(false); + + // Tap with negligible travel (within the slop) reveals the rail. + fireEvent.touchStart(article, { touches: [touchPoint(50, 100)] }); + fireEvent.touchEnd(article, { changedTouches: [touchPoint(52, 103)] }); + expect(railVisible()).toBe(true); + + // A second clean tap hides it again. + fireEvent.touchStart(article, { touches: [touchPoint(50, 100)] }); + fireEvent.touchEnd(article, { changedTouches: [touchPoint(50, 100)] }); + expect(railVisible()).toBe(false); + }); + + it("a scroll-like touch (travel past the slop) does NOT toggle the rail", () => { + render(); + const article = getArticle(); + + // Vertical flick — the transcript scroll gesture. + fireEvent.touchStart(article, { touches: [touchPoint(50, 100)] }); + fireEvent.touchEnd(article, { changedTouches: [touchPoint(50, 180)] }); + expect(railVisible()).toBe(false); + + // Horizontal drag past the slop is not a tap either. + fireEvent.touchStart(article, { touches: [touchPoint(50, 100)] }); + fireEvent.touchEnd(article, { changedTouches: [touchPoint(90, 100)] }); + expect(railVisible()).toBe(false); + + // Once revealed by a clean tap, a scroll must not hide it either. + fireEvent.touchStart(article, { touches: [touchPoint(50, 100)] }); + fireEvent.touchEnd(article, { changedTouches: [touchPoint(50, 100)] }); + expect(railVisible()).toBe(true); + fireEvent.touchStart(article, { touches: [touchPoint(50, 100)] }); + fireEvent.touchEnd(article, { changedTouches: [touchPoint(50, 20)] }); + expect(railVisible()).toBe(true); + }); + + it("an active text selection suppresses the toggle; clearing it restores taps", () => { + render(); + const article = getArticle(); + + // Highlight the bubble text (a non-collapsed selection), as a finished + // press-drag-select leaves behind. + const bubbleText = screen.getByText("Here are your latest balances."); + const range = document.createRange(); + range.selectNodeContents(bubbleText); + const selection = window.getSelection(); + if (!selection) throw new Error("jsdom selection unavailable"); + selection.removeAllRanges(); + selection.addRange(range); + expect(selection.isCollapsed).toBe(false); + + // The tap that ends the highlight must not also flip the rail. + fireEvent.touchStart(article, { touches: [touchPoint(50, 100)] }); + fireEvent.touchEnd(article, { changedTouches: [touchPoint(50, 100)] }); + expect(railVisible()).toBe(false); + + // With the selection cleared, tapping works again. + selection.removeAllRanges(); + fireEvent.touchStart(article, { touches: [touchPoint(50, 100)] }); + fireEvent.touchEnd(article, { changedTouches: [touchPoint(50, 100)] }); + expect(railVisible()).toBe(true); + }); +}); diff --git a/packages/ui/src/components/composites/chat/chat-message.tsx b/packages/ui/src/components/composites/chat/chat-message.tsx index 6e7d6254c663f..0ec599575b5e2 100644 --- a/packages/ui/src/components/composites/chat/chat-message.tsx +++ b/packages/ui/src/components/composites/chat/chat-message.tsx @@ -59,6 +59,11 @@ export interface ChatMessageProps { } const HOVER_MEDIA_QUERY = "(hover: hover) and (pointer: fine)"; +// Tap-to-reveal move slop: finger travel past this between touchstart and +// touchend means the gesture was a transcript scroll, not a tap, so it must +// not toggle the action rail (mirrors the shell ThreadLine's +// COPY_MOVE_CANCEL_PX). +const TAP_REVEAL_MOVE_CANCEL_PX = 10; const hoverSupportListeners = new Set<() => void>(); let hoverMediaQuery: MediaQueryList | null = null; let hoverMediaQueryUnsubscribe: (() => void) | null = null; @@ -323,6 +328,7 @@ export const ChatMessage = memo(function ChatMessage({ const [savingEdit, setSavingEdit] = useState(false); const articleRef = useRef(null); const editTextareaRef = useRef(null); + const tapStartRef = useRef<{ x: number; y: number } | null>(null); const isUser = message.role === "user"; const isRightAligned = isUser ? userMessagesOnRight : !userMessagesOnRight; const canEdit = @@ -421,13 +427,39 @@ export const ChatMessage = memo(function ChatMessage({ } }, [draftText, message.id, message.text, onEdit]); + const handleTapStart = useCallback((event: TouchEvent) => { + const touch = event.touches[0]; + tapStartRef.current = touch ? { x: touch.clientX, y: touch.clientY } : null; + }, []); + const handleTapReveal = useCallback( (event: TouchEvent) => { + const tapStart = tapStartRef.current; + tapStartRef.current = null; if (supportsHover || isEditing) return; const target = event.target as HTMLElement | null; if (target?.closest("button, a, textarea, input")) { return; } + // Scroll, not tap: finger travel past the slop means the touch was a + // transcript flick, so it must not toggle the rail on whichever message + // it happened to start on (mirrors the shell ThreadLine). + const touch = event.changedTouches[0]; + if ( + tapStart && + touch && + (Math.abs(touch.clientX - tapStart.x) > TAP_REVEAL_MOVE_CANCEL_PX || + Math.abs(touch.clientY - tapStart.y) > TAP_REVEAL_MOVE_CANCEL_PX) + ) { + return; + } + // Never hijack a text selection: a tap that ends a highlight drag must + // not also toggle the rail (the bubble text stays selectable to copy). + const selection = + typeof window !== "undefined" ? window.getSelection() : null; + if (selection && !selection.isCollapsed) { + return; + } setShowActions((prev) => !prev); }, [isEditing, supportsHover], @@ -510,6 +542,7 @@ export const ChatMessage = memo(function ChatMessage({ data-role={message.role} onMouseEnter={supportsHover ? () => setShowActions(true) : undefined} onMouseLeave={supportsHover ? () => setShowActions(false) : undefined} + onTouchStart={handleTapStart} onTouchEnd={handleTapReveal} aria-label={`${ isUser && showSenderHeader diff --git a/packages/ui/src/components/conversations/ConversationsSidebar.tsx b/packages/ui/src/components/conversations/ConversationsSidebar.tsx index 1d32bb46e23cc..b16e74d4a82ad 100644 --- a/packages/ui/src/components/conversations/ConversationsSidebar.tsx +++ b/packages/ui/src/components/conversations/ConversationsSidebar.tsx @@ -547,6 +547,10 @@ export function ConversationsSidebar({ const handleNewChat = () => { setState("activeInboxChat", null); + // Mirror handleRowSelect's conversation branch: an active terminal session + // otherwise keeps rendering over the fresh conversation (ChatView prefers + // the terminal branch), making "New chat" look dead. + setState("activeTerminalSessionId", null); setTab("chat"); void handleNewConversation(); onClose?.(); @@ -804,16 +808,10 @@ export function ConversationsSidebar({ collapseButtonAriaLabel={t("aria.closePanel")} expandButtonAriaLabel={t("aria.expandChatsPanel")} collapsedRailAction={ - showNewTerminalAction ? ( - void spawnShell()} - > - - - ) : showNewChatAction ? ( + // Chat-first: the single collapsed-rail "+" always starts a new + // CHAT. New terminal stays reachable from the expanded terminal + // section header — a shell session is never the primary affordance. + showNewChatAction ? ( { + cleanup(); +}); + +function makeSession( + sessionId: string, + status: CodingAgentSession["status"], +): CodingAgentSession { + return { + sessionId, + agentType: "claude-code", + label: `Session ${sessionId}`, + originalTask: "fix the tests", + workdir: "/tmp/work", + status, + decisionCount: 0, + autoResolvedCount: 0, + }; +} + +/** + * Minimal stand-in for ChatView's terminal-focus wiring: same ref + effect + + * "focus sets activeTerminalSessionId" shape, with a Close button playing the + * TerminalChannelPanel onClose (setState('activeTerminalSessionId', null)). + */ +function TerminalFocusHarness({ + sessions, + onFocus, +}: { + sessions: CodingAgentSession[]; + onFocus: (sessionId: string) => void; +}) { + const [activeTerminalSessionId, setActiveTerminalSessionId] = useState< + string | null + >(null); + const handledProblemSessionsRef = useRef>(new Set()); + useEffect(() => { + const sessionId = pickProblemSessionToAutoFocus( + sessions, + activeTerminalSessionId, + handledProblemSessionsRef.current, + ); + if (sessionId) { + onFocus(sessionId); + setActiveTerminalSessionId(sessionId); + } + }, [sessions, activeTerminalSessionId, onFocus]); + return ( +
+ + {activeTerminalSessionId ?? "none"} + + +
+ ); +} + +describe("ChatView terminal auto-focus (once per problem transition)", () => { + it("blocked session focuses once; closing the panel does NOT re-focus (the hijack loop)", () => { + const onFocus = vi.fn(); + const { rerender } = render( + , + ); + + // The blocked session pulls focus exactly once. + expect(onFocus).toHaveBeenCalledTimes(1); + expect(onFocus).toHaveBeenCalledWith("s1"); + expect(screen.getByTestId("active-terminal").textContent).toBe("s1"); + + // User closes the terminal panel while the session is STILL blocked. + act(() => { + fireEvent.click(screen.getByTestId("close-terminal")); + }); + expect(screen.getByTestId("active-terminal").textContent).toBe("none"); + // The effect re-runs (activeTerminalSessionId is null again) but must NOT + // bounce the user back to the terminal. + expect(onFocus).toHaveBeenCalledTimes(1); + + // Further updates while the session stays blocked (e.g. a poll refresh + // delivering a new sessions array) must not re-focus either. + rerender( + , + ); + expect(onFocus).toHaveBeenCalledTimes(1); + expect(screen.getByTestId("active-terminal").textContent).toBe("none"); + }); + + it("a NEW problem transition (recovered then errored) focuses once again", () => { + const onFocus = vi.fn(); + const { rerender } = render( + , + ); + expect(onFocus).toHaveBeenCalledTimes(1); + act(() => { + fireEvent.click(screen.getByTestId("close-terminal")); + }); + + // The session recovers (user's input unblocked it)… + rerender( + , + ); + expect(onFocus).toHaveBeenCalledTimes(1); + + // …then hits a NEW problem: that transition may focus again, once. + rerender( + , + ); + expect(onFocus).toHaveBeenCalledTimes(2); + expect(onFocus).toHaveBeenLastCalledWith("s1"); + expect(screen.getByTestId("active-terminal").textContent).toBe("s1"); + + // And dismissing it sticks again. + act(() => { + fireEvent.click(screen.getByTestId("close-terminal")); + }); + expect(onFocus).toHaveBeenCalledTimes(2); + expect(screen.getByTestId("active-terminal").textContent).toBe("none"); + }); + + it("a second session's problem transition still pulls focus after the first was dismissed", () => { + const onFocus = vi.fn(); + const { rerender } = render( + , + ); + act(() => { + fireEvent.click(screen.getByTestId("close-terminal")); + }); + expect(onFocus).toHaveBeenCalledTimes(1); + + rerender( + , + ); + expect(onFocus).toHaveBeenCalledTimes(2); + expect(onFocus).toHaveBeenLastCalledWith("s2"); + }); +}); + +describe("pickProblemSessionToAutoFocus (helper semantics)", () => { + it("marks a problem session the user is already viewing as handled", () => { + const handled = new Set(); + // The terminal panel is open on s1 when it transitions to blocked: no + // focus needed, but closing the panel afterwards must stick. + expect( + pickProblemSessionToAutoFocus( + [makeSession("s1", "blocked")], + "s1", + handled, + ), + ).toBeNull(); + expect( + pickProblemSessionToAutoFocus( + [makeSession("s1", "blocked")], + null, + handled, + ), + ).toBeNull(); + }); + + it("evicts handled entries when the session leaves the list (completed/stopped)", () => { + const handled = new Set(["s1"]); + expect(pickProblemSessionToAutoFocus([], null, handled)).toBeNull(); + expect(handled.has("s1")).toBe(false); + }); + + it("never auto-focuses while another terminal session is active", () => { + const handled = new Set(); + expect( + pickProblemSessionToAutoFocus( + [makeSession("s1", "active"), makeSession("s2", "blocked")], + "s1", + handled, + ), + ).toBeNull(); + // Once the non-problem session is dismissed, the blocked one may focus. + expect( + pickProblemSessionToAutoFocus( + [makeSession("s1", "active"), makeSession("s2", "blocked")], + null, + handled, + ), + ).toBe("s2"); + }); + + it("treats only error and blocked as problem statuses", () => { + expect(isProblemSessionStatus("error")).toBe(true); + expect(isProblemSessionStatus("blocked")).toBe(true); + expect(isProblemSessionStatus("active")).toBe(false); + expect(isProblemSessionStatus("tool_running")).toBe(false); + expect(isProblemSessionStatus("completed")).toBe(false); + expect(isProblemSessionStatus("stopped")).toBe(false); + }); +}); diff --git a/packages/ui/src/components/pages/ChatView.terminal-focus.ts b/packages/ui/src/components/pages/ChatView.terminal-focus.ts new file mode 100644 index 0000000000000..acc374ecd27ca --- /dev/null +++ b/packages/ui/src/components/pages/ChatView.terminal-focus.ts @@ -0,0 +1,71 @@ +import type { CodingAgentSession } from "../../api/client"; + +/** + * Session states that should pull the user's attention into the Terminal + * channel. "blocked" is routine ("Waiting for input" — set on every + * blocked/escalation event) and a session can sit in it for a long time, so + * attention-routing must fire once per transition, never continuously. + */ +export function isProblemSessionStatus( + status: CodingAgentSession["status"], +): boolean { + return status === "error" || status === "blocked"; +} + +/** + * Decide which problem (error/blocked) session, if any, should be auto-focused + * into the Terminal channel — at most ONCE per transition into a problem state. + * + * `handledSessionIds` is caller-owned bookkeeping (a ref in ChatView) that this + * function mutates: + * - A session picked for focus is marked handled, so a user-initiated dismissal + * (closing the panel or selecting a conversation, both of which clear + * `activeTerminalSessionId`) sticks instead of bouncing the user straight + * back to the terminal while the session still waits for input. + * - A problem session the user is already viewing is marked handled for the + * same reason. + * - Sessions that left the problem state (or left the list) are evicted, so a + * NEW error/blocked transition can auto-focus again. + * + * Returns the sessionId to focus, or null when nothing new needs attention. + */ +export function pickProblemSessionToAutoFocus( + sessions: readonly CodingAgentSession[], + activeTerminalSessionId: string | null, + handledSessionIds: Set, +): string | null { + const problemIds = new Set(); + for (const session of sessions) { + if (isProblemSessionStatus(session.status)) { + problemIds.add(session.sessionId); + } + } + + // Evict sessions that recovered/finished: their next problem transition is a + // new event and may auto-focus again. + for (const id of handledSessionIds) { + if (!problemIds.has(id)) { + handledSessionIds.delete(id); + } + } + + if (activeTerminalSessionId) { + // The terminal panel is already open. If it shows a problem session, count + // it as seen so closing the panel does not immediately re-open it. + if (problemIds.has(activeTerminalSessionId)) { + handledSessionIds.add(activeTerminalSessionId); + } + return null; + } + + for (const session of sessions) { + if ( + isProblemSessionStatus(session.status) && + !handledSessionIds.has(session.sessionId) + ) { + handledSessionIds.add(session.sessionId); + return session.sessionId; + } + } + return null; +} diff --git a/packages/ui/src/components/pages/ChatView.tsx b/packages/ui/src/components/pages/ChatView.tsx index dc1ee659bfd2b..8eb2020c0d758 100644 --- a/packages/ui/src/components/pages/ChatView.tsx +++ b/packages/ui/src/components/pages/ChatView.tsx @@ -69,6 +69,7 @@ import { ChatTranscript } from "../composites/chat/chat-transcript"; import type { ChatMessageData } from "../composites/chat/chat-types"; import { TypingIndicator } from "../composites/chat/chat-typing-indicator"; import { useConversationReset } from "../shell/use-conversation-reset"; +import { pickProblemSessionToAutoFocus } from "./ChatView.terminal-focus"; import { useChatVoiceController, useGameModalMessages, @@ -303,14 +304,20 @@ export function ChatView({ [setState], ); - // Route a problem session into the Terminal channel so the user sees it. + // Route a problem session into the Terminal channel so the user sees it — + // but only ONCE per transition into error/blocked. "blocked" is a routine, + // long-lived "waiting for input" state: without the once-per-transition + // guard, closing the panel or selecting a conversation would immediately + // bounce the user back to the terminal for as long as the session waits. + const handledProblemSessionsRef = useRef>(new Set()); useEffect(() => { - if (activeTerminalSessionId) return; - const problemSession = ptySessions.find( - (s) => s.status === "error" || s.status === "blocked", + const sessionId = pickProblemSessionToAutoFocus( + ptySessions, + activeTerminalSessionId, + handledProblemSessionsRef.current, ); - if (problemSession) { - focusTerminalSession(problemSession.sessionId); + if (sessionId) { + focusTerminalSession(sessionId); } }, [ptySessions, activeTerminalSessionId, focusTerminalSession]); diff --git a/packages/ui/src/components/pages/Launcher.gestures.test.tsx b/packages/ui/src/components/pages/Launcher.gestures.test.tsx index 52776bb4be953..66067ea24eef0 100644 --- a/packages/ui/src/components/pages/Launcher.gestures.test.tsx +++ b/packages/ui/src/components/pages/Launcher.gestures.test.tsx @@ -101,18 +101,14 @@ function clearTelemetry() { function mockDesktopPagingMedia({ finePointer, - desktopWidth = true, }: { finePointer: boolean; - desktopWidth?: boolean; }): void { window.matchMedia = vi.fn().mockImplementation((query: string) => ({ matches: finePointer && - desktopWidth && query.includes("(hover: hover)") && - query.includes("(pointer: fine)") && - query.includes("(min-width: 1024px)"), + query.includes("(pointer: fine)"), media: query, onchange: null, addEventListener: vi.fn(), @@ -251,12 +247,17 @@ describe("Launcher swipe paging (onDragEnd)", () => { expect(screen.queryByTestId("launcher-pager-edge-next")).toBeNull(); }); - it("hides pager edge buttons at phone width even when the browser reports a fine pointer", () => { - mockDesktopPagingMedia({ finePointer: true, desktopWidth: false }); + it("shows pager edge buttons on any fine-pointer window — the gate has no min-width clause", () => { + mockDesktopPagingMedia({ finePointer: true }); render( {}} />); - expect(screen.queryByTestId("launcher-pager-edge-prev")).toBeNull(); - expect(screen.queryByTestId("launcher-pager-edge-next")).toBeNull(); + // Fine pointer + hover is sufficient: a sub-1024px window still gets the + // `>` control (production renders no page dots, so without it a narrow + // fine-pointer window would have no paging affordance at all). + expect(screen.queryByTestId("launcher-pager-edge-next")).not.toBeNull(); + expect(window.matchMedia).toHaveBeenCalledWith( + expect.not.stringContaining("min-width"), + ); }); it("shows desktop edge buttons and pages exactly one step per click", () => { diff --git a/packages/ui/src/components/pages/Launcher.test.tsx b/packages/ui/src/components/pages/Launcher.test.tsx index 5090a0af3dcba..dbbe40ab06d87 100644 --- a/packages/ui/src/components/pages/Launcher.test.tsx +++ b/packages/ui/src/components/pages/Launcher.test.tsx @@ -99,7 +99,11 @@ describe("Launcher", () => { expect(page.getByTestId("launcher-tile-wallet")).toBeTruthy(); }); - it("preserves the manual order from a migrated Springboard layout", () => { + it("re-seeds the dock when migrating a dock-less Springboard layout (upgrade path)", () => { + // A springboard-era layout has favorites [] with no dockCleared marker — + // that predates the dock feature, so migration re-seeds chat+settings into + // the dock instead of suppressing it forever (#10800 QA). The seeded ids + // leave the page grid (an icon lives in exactly one surface). window.localStorage.setItem( LEGACY_SPRINGBOARD_STORAGE_KEY, JSON.stringify({ @@ -111,6 +115,38 @@ describe("Launcher", () => { render( {}} />); + const dockIds = Array.from( + screen + .getByTestId("launcher-dock") + .querySelectorAll('[data-testid^="launcher-tile-"]'), + ).map((node) => + node.getAttribute("data-testid")?.replace("launcher-tile-", ""), + ); + expect(dockIds).toEqual(["chat", "settings"]); + expect( + screen + .queryByTestId("launcher-page-0") + ?.querySelectorAll('[data-testid^="launcher-tile-"]').length ?? 0, + ).toBe(0); + }); + + it("preserves the manual page order of non-dock ids from a migrated Springboard layout", () => { + window.localStorage.setItem( + LEGACY_SPRINGBOARD_STORAGE_KEY, + JSON.stringify({ + favorites: [], + pages: [["beta", "alpha"]], + manual: true, + }), + ); + + render( + {}} + />, + ); + const tileIds = Array.from( screen .getByTestId("launcher-page-0") @@ -118,7 +154,7 @@ describe("Launcher", () => { ).map((node) => node.getAttribute("data-testid")?.replace("launcher-tile-", ""), ); - expect(tileIds).toEqual(["settings", "chat"]); + expect(tileIds).toEqual(["beta", "alpha"]); }); it("marks preview and developer tiles without changing release tiles", () => { diff --git a/packages/ui/src/components/pages/PluginsView.tsx b/packages/ui/src/components/pages/PluginsView.tsx index 1d0090addf4dc..d36131b2c77b6 100644 --- a/packages/ui/src/components/pages/PluginsView.tsx +++ b/packages/ui/src/components/pages/PluginsView.tsx @@ -405,7 +405,10 @@ function PluginListView({ const handleConfigSave = async (pluginId: string) => { if (pluginId === "__ui-showcase__") return; const config = pluginConfigs[pluginId] ?? {}; - await handlePluginConfigSave(pluginId, config); + // Only clear the draft when the save persisted — sensitive params never + // echo back from the server, so wiping on failure loses the pasted token. + const saved = await handlePluginConfigSave(pluginId, config); + if (!saved) return; setPluginConfigs((prev) => { const next = { ...prev }; delete next[pluginId]; diff --git a/packages/ui/src/components/pages/__e2e__/launcher-fixture.tsx b/packages/ui/src/components/pages/__e2e__/launcher-fixture.tsx index bb61e9f4890fe..1f1aff89a0d02 100644 --- a/packages/ui/src/components/pages/__e2e__/launcher-fixture.tsx +++ b/packages/ui/src/components/pages/__e2e__/launcher-fixture.tsx @@ -1,15 +1,21 @@ // Self-contained fixture for the Launcher e2e: mounts the real Launcher -// (the iOS-like view-launcher) with ~25 deterministic mock ViewEntry items -// spread across multiple pages. A couple carry an `imageUrl` data-URI so an -// image tile renders; the rest fall back to the Lucide glyph. Launch / edit / -// delete are wired to stubs and surfaced on `window.__launcherCalls` so the -// runner can assert the real interaction handlers fired. No app server, no -// network — fully self-contained (mirrors background-fixture's self-containment). -// Paired with run-launcher-e2e.mjs. +// (the iOS-like view-launcher) with 27 deterministic mock ViewEntry items. +// Two of them (chat + settings) land in the seeded default dock (#10800), so +// 25 undocked tiles overflow the 24-per-page grid onto 2 pages — exercising +// the production first-run UX (seeded dock AND overflow pagination) together. +// A couple carry an `imageUrl` data-URI so an image tile renders; the rest +// fall back to the Lucide glyph. Launch / edit / delete are wired to stubs and +// surfaced on `window.__launcherCalls` so the runner can assert the real +// interaction handlers fired. No app server, no network — fully self-contained +// (mirrors background-fixture's self-containment). Paired with run-launcher-e2e.mjs. import * as React from "react"; import { createRoot } from "react-dom/client"; import type { ViewEntry } from "../../../hooks/view-catalog"; +import { + DEFAULT_LAUNCHER_FAVORITES, + LAUNCHER_PAGE_SIZE, +} from "../../../state/launcher-layout"; import { Launcher } from "../Launcher"; type Win = typeof window & { @@ -63,8 +69,19 @@ const SPECS: Array<{ id: string; label: string; icon?: string; image?: boolean } { id: "screenshare", label: "Screen Share", icon: "Monitor" }, { id: "keys", label: "Keys", icon: "KeyRound" }, { id: "network", label: "Network", icon: "Network" }, + { id: "notes", label: "Notes", icon: "NotebookPen" }, + { id: "camera", label: "Camera", icon: "Camera" }, ]; +// The paging assertions need the undocked tiles to overflow one page. Fail at +// bundle time — not as a misleading "no Page 2 dot" e2e failure — if a future +// page-size or default-dock change silently collapses the fixture to one page. +if (SPECS.length - DEFAULT_LAUNCHER_FAVORITES.length <= LAUNCHER_PAGE_SIZE) { + throw new Error( + `launcher-fixture: ${SPECS.length} specs minus ${DEFAULT_LAUNCHER_FAVORITES.length} seeded dock ids must exceed LAUNCHER_PAGE_SIZE=${LAUNCHER_PAGE_SIZE} for the multi-page assertions`, + ); +} + function makeEntry(spec: (typeof SPECS)[number]): ViewEntry { return { key: `view:${spec.id}`, diff --git a/packages/ui/src/components/pages/tutorial/TutorialSpotlight.tsx b/packages/ui/src/components/pages/tutorial/TutorialSpotlight.tsx index e6e7746fb1644..1f9ddd132b190 100644 --- a/packages/ui/src/components/pages/tutorial/TutorialSpotlight.tsx +++ b/packages/ui/src/components/pages/tutorial/TutorialSpotlight.tsx @@ -152,6 +152,10 @@ export function TutorialSpotlight({ style={{ pointerEvents: "none", zIndex: Z_TUTORIAL }} aria-live="polite" data-testid="tutorial-spotlight" + // Marks this layer as painted above the chat glass so the chat's + // outside-tap swallower cedes taps on the card's interactive children + // (the root itself is pointer-transparent). + data-above-shell-overlay data-tutorial-target-missing={targetMissing ? targetSelector : undefined} > diff --git a/packages/ui/src/components/settings/BackgroundSettingsControls.tsx b/packages/ui/src/components/settings/BackgroundSettingsControls.tsx index 960084af81df8..019323f38d292 100644 --- a/packages/ui/src/components/settings/BackgroundSettingsControls.tsx +++ b/packages/ui/src/components/settings/BackgroundSettingsControls.tsx @@ -4,6 +4,7 @@ import { ImagePlus, Loader2, Pipette, + Redo2, Sparkles, Undo2, } from "lucide-react"; @@ -76,6 +77,8 @@ export function BackgroundSettingsControls({ setBackgroundConfig, undoBackgroundConfig, canUndoBackground, + redoBackgroundConfig, + canRedoBackground, } = useBackgroundConfig(); const { cloudConnected, cloudAuthRejected } = useAppSelectorShallow((s) => ({ cloudConnected: s.elizaCloudConnected, @@ -173,6 +176,14 @@ export function BackgroundSettingsControls({ description: "Revert to the previous background", onActivate: () => undoBackgroundConfig(), }); + const redoButton = useAgentElement({ + id: "background-redo", + role: "button", + label: "Redo background change", + group: "background-controls", + description: "Restore the background change that was undone", + onActivate: () => redoBackgroundConfig(), + }); return (
) : null} + {canRedoBackground ? ( + + ) : null}
{cloudAvailable && promptOpen ? ( diff --git a/packages/ui/src/components/settings/ConnectorsSection.routing.test.ts b/packages/ui/src/components/settings/ConnectorsSection.routing.test.ts index 2c4fa745998f9..39f2a7ac7202a 100644 --- a/packages/ui/src/components/settings/ConnectorsSection.routing.test.ts +++ b/packages/ui/src/components/settings/ConnectorsSection.routing.test.ts @@ -79,4 +79,28 @@ describe("ConnectorsSection mode routing", () => { }), ).toBe(true); }); + + it("shows the credential form for connectors with NO declared mode list (farcaster, bluesky, …)", () => { + // Connectors outside the hardcoded mode map fall through with an undefined + // selected mode; when they declare parameters, the env form IS their setup + // surface — not the dead-end "uses its own setup surface" text. + for (const connectorId of ["farcaster", "bluesky", "matrix", "nostr"]) { + expect(getConnectorModes(connectorId, {}).length).toBe(0); + } + expect( + shouldRenderConnectorConfigForm({ + managementMode: undefined, + hasParameters: true, + setupTargetsPlugin: true, + }), + ).toBe(true); + // …but a no-mode connector with no parameters still has nothing to render. + expect( + shouldRenderConnectorConfigForm({ + managementMode: undefined, + hasParameters: false, + setupTargetsPlugin: true, + }), + ).toBe(false); + }); }); diff --git a/packages/ui/src/components/settings/ConnectorsSection.tsx b/packages/ui/src/components/settings/ConnectorsSection.tsx index d2af3730ba1a8..d4ce9403d76f6 100644 --- a/packages/ui/src/components/settings/ConnectorsSection.tsx +++ b/packages/ui/src/components/settings/ConnectorsSection.tsx @@ -49,8 +49,11 @@ type ConnectorStatusTone = "ok" | "warn" | "off"; * Whether Settings → Connectors should render the generic plugin-config (env * credential) form for the selected connector mode. * - * The form is shown ONLY for a `local-config` mode whose setup target is the - * plugin itself and that actually declares parameters. Every other mode kind — + * The form is shown for a `local-config` mode whose setup target is the + * plugin itself and that actually declares parameters — and for connectors + * with NO declared mode list at all (farcaster, bluesky, matrix, nostr, …): + * those have no dedicated panel to protect, so a declared-parameters plugin + * gets the credential form instead of a dead-end. Every other mode kind — * `local-setup` (iMessage Full-Disk-Access status, Signal/WhatsApp QR pairing, * Discord/Telegram desktop panels), `plugin-managed` account lists, and * `cloud-managed` gateways — keeps its dedicated {@link ConnectorSetupPanel} @@ -59,12 +62,13 @@ type ConnectorStatusTone = "ok" | "warn" | "off"; * reachable instead of being overwritten by a raw env form. */ export function shouldRenderConnectorConfigForm(args: { - managementMode: ConnectorMode["managementMode"]; + managementMode: ConnectorMode["managementMode"] | undefined; hasParameters: boolean; setupTargetsPlugin: boolean; }): boolean { return ( - args.managementMode === "local-config" && + (args.managementMode === "local-config" || + args.managementMode === undefined) && args.hasParameters && args.setupTargetsPlugin ); @@ -140,7 +144,10 @@ function ConnectorBody({ plugin }: { plugin: PluginInfo }) { const showPluginConfig = shouldRenderConnectorConfigForm({ managementMode: selectedMode?.managementMode, hasParameters: plugin.parameters.length > 0, - setupTargetsPlugin: setupPluginId === plugin.id, + // Mirror the canonical /connectors fallback: a connector with no declared + // mode list has no companion setup plugin, so its own credential form is + // the setup surface (previously a dead-end "uses its own setup surface"). + setupTargetsPlugin: (setupPluginId ?? plugin.id) === plugin.id, }); const pendingConfig = pluginConfigs[plugin.id] ?? {}; const hasPendingConfig = Object.keys(pendingConfig).length > 0; @@ -158,7 +165,10 @@ function ConnectorBody({ plugin }: { plugin: PluginInfo }) { ); const handleSave = useCallback(async () => { - await handlePluginConfigSave(plugin.id, pendingConfig); + // Only clear the draft when the save persisted — sensitive params never + // echo back from the server, so wiping on failure loses the pasted token. + const saved = await handlePluginConfigSave(plugin.id, pendingConfig); + if (!saved) return; setPluginConfigs((prev) => { const next = { ...prev }; delete next[plugin.id]; diff --git a/packages/ui/src/components/settings/settings-section-meta.ts b/packages/ui/src/components/settings/settings-section-meta.ts index 89bb8ca75b84f..c528a3db48fae 100644 --- a/packages/ui/src/components/settings/settings-section-meta.ts +++ b/packages/ui/src/components/settings/settings-section-meta.ts @@ -44,6 +44,7 @@ export const SETTINGS_SECTION_META: SettingsSectionMeta[] = [ { id: "connectors", defaultLabel: "Connectors", group: "agent" }, { id: "runtime", defaultLabel: "Runtime", group: "system" }, { id: "appearance", defaultLabel: "Appearance", group: "system" }, + { id: "background", defaultLabel: "Background", group: "system" }, { id: "remote-plugins", defaultLabel: "Remote Plugins", group: "system" }, { id: "wallet-rpc", defaultLabel: "Wallet & RPC", group: "system" }, { id: "updates", defaultLabel: "Updates", group: "system" }, diff --git a/packages/ui/src/components/settings/settings-sections.ts b/packages/ui/src/components/settings/settings-sections.ts index 4ed88475a5b00..1cae0ac8afc22 100644 --- a/packages/ui/src/components/settings/settings-sections.ts +++ b/packages/ui/src/components/settings/settings-sections.ts @@ -17,6 +17,7 @@ import { SlidersHorizontal, User, Wallet, + Wallpaper, Webhook, } from "lucide-react"; import type { ComponentType } from "react"; @@ -31,6 +32,7 @@ import { AdvancedSection } from "./AdvancedSection"; import { AppearanceSettingsSection } from "./AppearanceSettingsSection"; import { AppPermissionsSection } from "./AppPermissionsSection"; import { AppsManagementSection } from "./AppsManagementSection"; +import { BackgroundSettingsSection } from "./BackgroundSettingsSection"; import { CapabilitiesSection } from "./CapabilitiesSection"; import { CloudAgentsSection } from "./CloudAgentsSection"; import { CloudOverviewSection } from "./CloudOverviewSection"; @@ -165,6 +167,14 @@ const SECTION_VISUALS: Record = { labelKey: "settings.sections.appearance.label", Component: AppearanceSettingsSection, }, + background: { + icon: Wallpaper, + tone: "neutral", + hue: "rose", + labelKey: "settings.sections.background.label", + // Chrome-light so the live wallpaper shows through while choices apply. + Component: BackgroundSettingsSection, + }, "remote-plugins": { icon: Puzzle, tone: "accent", diff --git a/packages/ui/src/components/shell/ContinuousChatOverlay.test.tsx b/packages/ui/src/components/shell/ContinuousChatOverlay.test.tsx index 0213c8bd22a0f..ecd719676f525 100644 --- a/packages/ui/src/components/shell/ContinuousChatOverlay.test.tsx +++ b/packages/ui/src/components/shell/ContinuousChatOverlay.test.tsx @@ -708,6 +708,60 @@ describe("ContinuousChatOverlay", () => { expect(sheet.getAttribute("data-variant")).toBe("closed"); }); + it("cedes taps to a layer painted ABOVE the chat (dialog / notification sheet) instead of collapsing", () => { + render(); + const sheet = screen.getByTestId("chat-sheet"); + fireEvent.focus(screen.getByLabelText("message")); + expect(sheet.getAttribute("data-variant")).toBe("open"); + + // Simulate the notification pull-down sheet / a Radix dialog stacked above + // the chat glass (role="dialog" or data-above-shell-overlay): its taps must + // NOT be swallowed into a chat collapse — the overlay's own handlers win. + const overlay = document.createElement("div"); + overlay.setAttribute("role", "dialog"); + const rowButton = document.createElement("button"); + overlay.appendChild(rowButton); + document.body.appendChild(overlay); + try { + fireEvent.pointerDown(rowButton, { + clientX: 30, + clientY: 30, + pointerId: 5, + }); + fireEvent.pointerUp(rowButton, { + clientX: 30, + clientY: 30, + pointerId: 5, + }); + expect(sheet.getAttribute("data-variant")).toBe("open"); + } finally { + overlay.remove(); + } + }); + + it("lets an open dialog own Escape — the chat only collapses once the dialog is gone", () => { + render(); + const sheet = screen.getByTestId("chat-sheet"); + fireEvent.focus(screen.getByLabelText("message")); + expect(sheet.getAttribute("data-variant")).toBe("open"); + + // An open Radix dialog (e.g. the command palette) above the chat: Escape + // must close IT, not also collapse the chat underneath. + const dialog = document.createElement("div"); + dialog.setAttribute("role", "dialog"); + dialog.setAttribute("data-state", "open"); + document.body.appendChild(dialog); + try { + fireEvent.keyDown(document.body, { key: "Escape" }); + expect(sheet.getAttribute("data-variant")).toBe("open"); + } finally { + dialog.remove(); + } + // Dialog gone: Escape collapses the chat as before. + fireEvent.keyDown(document.body, { key: "Escape" }); + expect(sheet.getAttribute("data-variant")).toBe("closed"); + }); + it("renders the full thread as one scroll log when the sheet is open", () => { const controller = makeController({ messages: [ diff --git a/packages/ui/src/components/shell/ContinuousChatOverlay.tsx b/packages/ui/src/components/shell/ContinuousChatOverlay.tsx index 4db9e8e248e6b..b85a3af11d682 100644 --- a/packages/ui/src/components/shell/ContinuousChatOverlay.tsx +++ b/packages/ui/src/components/shell/ContinuousChatOverlay.tsx @@ -2891,6 +2891,19 @@ export function ContinuousChatOverlay({ submitText(exec.text); return; } + // The CommandPalette is a Radix dialog (Z_DIALOG=170) that paints UNDER + // the open chat glass (Z_SHELL_OVERLAY=9000): opening it from the + // composer left an invisible, focus-trapped dialog behind the sheet. + // Collapse first so the palette opens over the pill, fully visible and + // dismissible; skip the composer refocus so focus stays in the palette. + const opensPalette = + exec.kind === "client" && + (exec.clientAction === "open-command-palette" || + exec.clientAction === "show-commands"); + const openPaletteCollapsed = () => { + collapse(); + slash.openCommandPalette(); + }; runSlashExecution(exec, { navigateTab: slash.navigateTab, navigateSettings: slash.navigateSettings, @@ -2900,16 +2913,25 @@ export function ContinuousChatOverlay({ // The overlay owns full-screen via the `maximized` detent flag, not a // controller method, so toggle it directly here. toggleFullscreen: toggleMaximize, - openCommandPalette: slash.openCommandPalette, - showCommands: slash.openCommandPalette, + openCommandPalette: openPaletteCollapsed, + showCommands: openPaletteCollapsed, toggleTranscription: toggleTranscriptionMode, send: (text) => submitText(text), }); setDraft(""); setSlashDismissed(true); - inputRef.current?.focus(); + if (!opensPalette) { + inputRef.current?.focus(); + } }, - [slash, controller, submitText, toggleMaximize, toggleTranscriptionMode], + [ + slash, + controller, + submitText, + toggleMaximize, + toggleTranscriptionMode, + collapse, + ], ); const submit = React.useCallback(() => { @@ -3005,10 +3027,21 @@ export function ContinuousChatOverlay({ const isGrabber = (target: EventTarget | null): boolean => target instanceof Element && !!target.closest('[data-testid="chat-sheet-grabber"]'); + // Surfaces painted ABOVE the chat glass (notification sheet at z-9501, + // tutorial at Z_TUTORIAL, any open Radix dialog) must win the tap — the + // swallower otherwise eats their first tap AND collapses the chat under + // them. "Tap outside collapses" is only for the background view. + const isAboveShellOverlay = (target: EventTarget | null): boolean => + target instanceof Element && + !!target.closest('[data-above-shell-overlay], [role="dialog"]'); const onPointerDown = (event: PointerEvent) => { if (event.button !== 0 && event.pointerType === "mouse") return; - if (isInsidePanel(event.target) || isGrabber(event.target)) { + if ( + isInsidePanel(event.target) || + isGrabber(event.target) || + isAboveShellOverlay(event.target) + ) { outsideSheetPointerRef.current = null; return; } @@ -3077,6 +3110,20 @@ export function ContinuousChatOverlay({ if (typeof document === "undefined" || !sheetOpen) return undefined; const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") { + // An open Radix dialog (data-state="open" — e.g. the command palette) + // or the notification pull-down sheet (mounts only while open) sits + // above the chat: let ITS Escape handling win — collapsing here too + // closed both at once (e.g. an invisible palette + the chat). Scoped + // to exactly these; broad role="dialog" would match always-mounted + // shell surfaces (AssistantOverlay, tutorial card) and permanently + // disable Escape-collapse. + if ( + document.querySelector( + '[role="dialog"][data-state="open"], [data-testid="notification-sheet"]', + ) + ) { + return; + } e.preventDefault(); collapse(); } diff --git a/packages/ui/src/components/shell/HomeLauncherSurface.composed.test.tsx b/packages/ui/src/components/shell/HomeLauncherSurface.composed.test.tsx index 05df208ab2780..caaef682c6afc 100644 --- a/packages/ui/src/components/shell/HomeLauncherSurface.composed.test.tsx +++ b/packages/ui/src/components/shell/HomeLauncherSurface.composed.test.tsx @@ -17,7 +17,10 @@ import { import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { ViewRegistryEntry } from "../../hooks/useAvailableViews"; import { useRoutableViews } from "../../hooks/useAvailableViews"; -import { resetShellSurfaceForTests } from "../../state/shell-surface-store"; +import { + getShellSurface, + resetShellSurfaceForTests, +} from "../../state/shell-surface-store"; import { useEnabledViewKinds } from "../../state/useViewKinds"; import { runAnimationFramesImmediately } from "../../testing/run-animation-frames-immediately"; import { LauncherSurface } from "../pages/LauncherSurface"; @@ -230,6 +233,114 @@ describe("Home ↔ Launcher composed surface", () => { expect(surface.getAttribute("data-page")).toBe("home"); }); + // ── Nested gesture arbitration — the bubbling path a real finger takes ──── + // Every gesture below starts on a TILE INSIDE the inner page window, so the + // pointer events bubble through the inner Launcher pager's handlers first + // and then the outer rail's half-div handlers — the composition where the + // rail used to steal mouse capture from the grid pager and double-paint + // touch drags. + + /** Mock a fixed layout width (jsdom reports 0) on a pager viewport. */ + function mockClientWidth(el: HTMLElement, value: number): void { + Object.defineProperty(el, "clientWidth", { configurable: true, value }); + } + + /** A tile INSIDE the inner page window (page 0) — NOT the dock. */ + function tileInsidePage0(): HTMLElement { + const tile = screen + .getByTestId("launcher-page-0") + .querySelector('[data-testid^="launcher-tile-"]'); + if (!tile) throw new Error("no tile inside launcher page 0"); + return tile; + } + + function renderComposedOnLauncher(): { + surface: HTMLElement; + outerRail: HTMLElement; + innerRail: HTMLElement; + tile: HTMLElement; + } { + runAnimationFramesImmediately(); + const surface = renderComposed(); + mockClientWidth(surface, 390); + mockClientWidth(screen.getByTestId("launcher-page-window"), 390); + openLauncher(); + expect(surface.getAttribute("data-page")).toBe("launcher"); + return { + surface, + outerRail: screen.getByTestId("home-launcher-rail"), + innerRail: screen.getByTestId("launcher-page-rail"), + tile: tileInsidePage0(), + }; + } + + it("a MOUSE drag left on a tile advances the INNER grid pager — the rail no longer steals the gesture", () => { + const { surface, outerRail, tile } = renderComposedOnLauncher(); + const outerResting = outerRail.style.transform; + const opts = { + isPrimary: true, + pointerId: 11, + pointerType: "mouse", + clientY: 300, + } as const; + + fireEvent.pointerDown(tile, { ...opts, clientX: 300 }); + fireEvent.pointerMove(tile, { ...opts, clientX: 280 }); + fireEvent.pointerMove(tile, { ...opts, clientX: 100 }); + fireEvent.pointerUp(tile, { ...opts, clientX: 100 }); + + // The inner pager advanced to the second grid page (e.g. Developer) … + expect(getShellSurface().launcherPage).toBe(1); + // … and the outer rail neither paged home nor moved at all. + expect(surface.getAttribute("data-page")).toBe("launcher"); + expect(outerRail.style.transform).toBe(outerResting); + }); + + it("a touch drag left claimed by the inner grid never moves the OUTER rail (no double-paint)", () => { + const { outerRail, innerRail, tile } = renderComposedOnLauncher(); + const outerResting = outerRail.style.transform; + const opts = { + isPrimary: true, + pointerId: 12, + pointerType: "touch", + clientY: 300, + } as const; + + fireEvent.pointerDown(tile, { ...opts, clientX: 300 }); + fireEvent.pointerMove(tile, { ...opts, clientX: 280 }); + fireEvent.pointerMove(tile, { ...opts, clientX: 180 }); + + // Mid-drag: the inner rail follows the finger 1:1 … + expect(innerRail.style.transform).toContain("-120px"); + // … while the outer rail stays parked (it used to add its own dx·0.35 + // rubber-band on top — ~1.35× finger motion and a gap at the edge). + expect(outerRail.style.transform).toBe(outerResting); + + fireEvent.pointerUp(tile, { ...opts, clientX: 180 }); + expect(getShellSurface().launcherPage).toBe(1); + expect(outerRail.style.transform).toBe(outerResting); + }); + + it("a swipe right on a tile at inner page 0 still returns HOME (the rail owns the back gesture)", () => { + const { surface, tile } = renderComposedOnLauncher(); + const opts = { + isPrimary: true, + pointerId: 13, + pointerType: "touch", + clientY: 300, + } as const; + + fireEvent.pointerDown(tile, { ...opts, clientX: 100 }); + fireEvent.pointerMove(tile, { ...opts, clientX: 120 }); + fireEvent.pointerMove(tile, { ...opts, clientX: 300 }); + fireEvent.pointerUp(tile, { ...opts, clientX: 300 }); + + // The inner pager cannot move right at page 0, so the outer rail claims + // the gesture and pages back home. + expect(surface.getAttribute("data-page")).toBe("home"); + expect(getShellSurface().page).toBe("home"); + }); + it("launcher tiles render DISTINCT generated app-icon imagery (#5)", () => { renderComposed(); openLauncher(); diff --git a/packages/ui/src/components/shell/HomeLauncherSurface.test.tsx b/packages/ui/src/components/shell/HomeLauncherSurface.test.tsx index 7513e564b16fb..a9b93a3b53a1c 100644 --- a/packages/ui/src/components/shell/HomeLauncherSurface.test.tsx +++ b/packages/ui/src/components/shell/HomeLauncherSurface.test.tsx @@ -26,18 +26,14 @@ const originalMatchMedia = window.matchMedia; function mockDesktopPagingMedia({ finePointer, - desktopWidth = true, }: { finePointer: boolean; - desktopWidth?: boolean; }): void { window.matchMedia = vi.fn().mockImplementation((query: string) => ({ matches: finePointer && - desktopWidth && query.includes("(hover: hover)") && - query.includes("(pointer: fine)") && - query.includes("(min-width: 1024px)"), + query.includes("(pointer: fine)"), media: query, onchange: null, addEventListener: vi.fn(), @@ -137,8 +133,8 @@ describe("HomeLauncherSurface", () => { expect(screen.queryByTestId("rail-pager-edge-next")).toBeNull(); }); - it("hides rail edge buttons at phone width even when the browser reports a fine pointer", () => { - mockDesktopPagingMedia({ finePointer: true, desktopWidth: false }); + it("shows rail edge buttons on any fine-pointer window — the gate has no min-width clause", () => { + mockDesktopPagingMedia({ finePointer: true }); render( home} @@ -146,8 +142,13 @@ describe("HomeLauncherSurface", () => { />, ); - expect(screen.queryByTestId("rail-pager-edge-prev")).toBeNull(); - expect(screen.queryByTestId("rail-pager-edge-next")).toBeNull(); + // Fine pointer + hover is sufficient: a sub-1024px window still gets the + // `>` control (there are no page dots in production, so without it a + // narrow fine-pointer window would have no paging affordance at all). + expect(screen.queryByTestId("rail-pager-edge-next")).not.toBeNull(); + expect(window.matchMedia).toHaveBeenCalledWith( + expect.not.stringContaining("min-width"), + ); }); it("shows desktop rail edge buttons and moves one rail page per click", () => { diff --git a/packages/ui/src/components/shell/HomeScreen.tsx b/packages/ui/src/components/shell/HomeScreen.tsx index b8def76a899ea..74f2d1f9975b8 100644 --- a/packages/ui/src/components/shell/HomeScreen.tsx +++ b/packages/ui/src/components/shell/HomeScreen.tsx @@ -178,6 +178,9 @@ export function HomeScreen({ // Pull-DOWN from the top edge opens the notification center (#10706), iOS-style. // The gesture lives on a thin non-scrolling top strip — deliberately NOT the // scrollable widget list — so it can never fight the list's vertical scroll. + // The strip is a real button: click/tap and Enter/Space open the center too, + // so desktop fine-pointer and keyboard/AT users aren't locked out of the + // only notification entry point. const [notificationsOpen, setNotificationsOpen] = useState(false); const notificationPull = usePullGesture({ onPullDown: () => setNotificationsOpen(true), @@ -186,13 +189,22 @@ export function HomeScreen({ return ( <> {/* Thin top-edge pull affordance. Sits above the home surface (z-[2]) but - only over the status-bar strip, so widget taps/scroll below are - untouched. A faint grabber hints the gesture. */} - {/* biome-ignore lint/a11y/noStaticElementInteractions: pointer-only pull target, not a click affordance (the notification center has its own reachable trigger). */} -
setNotificationsOpen(true)} {...notificationPull} >
-
+ @@ -402,6 +405,7 @@ export function NotificationCenter({ type="button" aria-label="Dismiss notifications" data-testid="notification-sheet-backdrop" + data-above-shell-overlay onClick={() => onOpenChange?.(false)} className="fixed inset-0 z-[9500] bg-black/40" /> @@ -409,6 +413,7 @@ export function NotificationCenter({ role="dialog" aria-label="Notifications" data-testid="notification-sheet" + data-above-shell-overlay className={cn( "fixed inset-x-0 top-0 z-[9501] mx-auto flex max-h-[85vh] w-[min(440px,calc(100vw-1rem))] flex-col overflow-hidden rounded-b-2xl border-x border-b border-border bg-popover shadow-xl", "pt-[var(--safe-area-top,0px)]", diff --git a/packages/ui/src/components/shell/PagerEdgeButtons.test.tsx b/packages/ui/src/components/shell/PagerEdgeButtons.test.tsx index 851cbca0be2e4..4a0f3e65c43a2 100644 --- a/packages/ui/src/components/shell/PagerEdgeButtons.test.tsx +++ b/packages/ui/src/components/shell/PagerEdgeButtons.test.tsx @@ -1,27 +1,19 @@ // @vitest-environment jsdom // -// #10717: the web/desktop `< >` pager edge buttons — desktop fine-pointer -// gated (never on touch/phone-width), self-hiding at the first/last page, -// click → goPrev/goNext. +// #10717: the web/desktop `< >` pager edge buttons — fine-pointer gated +// (never on touch/coarse pointers, but at ANY viewport width), self-hiding at +// the first/last page, click → goPrev/goNext. import { cleanup, fireEvent, render } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; import { PagerEdgeButtons } from "./PagerEdgeButtons"; -function mockDesktopPointer({ - finePointer, - desktopWidth = true, -}: { - finePointer: boolean; - desktopWidth?: boolean; -}) { +function mockPointerCapability({ finePointer }: { finePointer: boolean }) { window.matchMedia = vi.fn().mockImplementation((query: string) => ({ matches: finePointer && - desktopWidth && query.includes("(hover: hover)") && - query.includes("(pointer: fine)") && - query.includes("(min-width: 1024px)"), + query.includes("(pointer: fine)"), media: query, onchange: null, addEventListener: vi.fn(), @@ -39,7 +31,7 @@ afterEach(() => { describe("PagerEdgeButtons (#10717)", () => { it("renders nothing on touch / coarse pointers", () => { - mockDesktopPointer({ finePointer: false }); + mockPointerCapability({ finePointer: false }); const { queryByTestId } = render( , ); @@ -47,17 +39,23 @@ describe("PagerEdgeButtons (#10717)", () => { expect(queryByTestId("pager-edge-next")).toBeNull(); }); - it("renders nothing at phone width even if the browser reports a fine pointer", () => { - mockDesktopPointer({ finePointer: true, desktopWidth: false }); + it("gates on pointer capability only — no min-width clause, so a narrow fine-pointer window still gets a paging control", () => { + mockPointerCapability({ finePointer: true }); const { queryByTestId } = render( , ); - expect(queryByTestId("pager-edge-prev")).toBeNull(); - expect(queryByTestId("pager-edge-next")).toBeNull(); + // The buttons render from the pointer-capability match alone; the media + // gate never consults the viewport width (below 1024px there are no page + // dots in production, so these arrows are the only paging control). + expect(queryByTestId("pager-edge-prev")).not.toBeNull(); + expect(queryByTestId("pager-edge-next")).not.toBeNull(); + expect(window.matchMedia).toHaveBeenCalledWith( + expect.not.stringContaining("min-width"), + ); }); it("renders both arrows on fine pointers and routes clicks", () => { - mockDesktopPointer({ finePointer: true }); + mockPointerCapability({ finePointer: true }); const goPrev = vi.fn(); const goNext = vi.fn(); const { getByTestId } = render( @@ -70,7 +68,7 @@ describe("PagerEdgeButtons (#10717)", () => { }); it("hides the arrow with no page to move to (first / last page)", () => { - mockDesktopPointer({ finePointer: true }); + mockPointerCapability({ finePointer: true }); const first = render( { }); it("uses neutral icon color with no card chrome or blue", () => { - mockDesktopPointer({ finePointer: true }); + mockPointerCapability({ finePointer: true }); const { getByTestId } = render( , ); diff --git a/packages/ui/src/components/shell/PagerEdgeButtons.tsx b/packages/ui/src/components/shell/PagerEdgeButtons.tsx index 1f92715d68e56..14696395bf5b4 100644 --- a/packages/ui/src/components/shell/PagerEdgeButtons.tsx +++ b/packages/ui/src/components/shell/PagerEdgeButtons.tsx @@ -5,17 +5,18 @@ import { cn } from "../../lib/utils"; /** * Web/desktop `<` `>` edge buttons for a horizontal pager (#10717). Rendered - * ONLY on desktop-width fine-pointer / hover-capable devices, so they never - * appear on touch/coarse phones/tablets where the swipe gesture is the sole - * navigation. The width guard also keeps mobile audit captures clean when a - * headless browser reports a fine pointer at phone dimensions. + * ONLY on fine-pointer / hover-capable devices, so they never appear on + * touch/coarse phones/tablets where the swipe gesture is the sole navigation. + * There is deliberately NO width gate: page dots are off in production, so a + * fine-pointer window below desktop width (a narrow browser window, a small + * desktop shell) still needs a visible paging control alongside the drag + * gesture. * * Icon-only (no card chrome), neutral resting → neutral hover (no orange→black, * no blue), positioned on the vertical center of the left/right edges. Each * arrow is hidden when there is no page to move to in that direction. */ -const DESKTOP_EDGE_BUTTON_QUERY = - "(hover: hover) and (pointer: fine) and (min-width: 1024px)"; +const FINE_POINTER_EDGE_BUTTON_QUERY = "(hover: hover) and (pointer: fine)"; export function PagerEdgeButtons({ canPrev, @@ -39,8 +40,8 @@ export function PagerEdgeButtons({ */ idPrefix?: string; }): React.JSX.Element | null { - const desktopFinePointer = useMediaQuery(DESKTOP_EDGE_BUTTON_QUERY); - if (!desktopFinePointer) return null; + const finePointer = useMediaQuery(FINE_POINTER_EDGE_BUTTON_QUERY); + if (!finePointer) return null; const prefix = idPrefix ? `${idPrefix}-` : ""; const edgeClass = diff --git a/packages/ui/src/components/shell/__e2e__/run-home-screen-e2e.mjs b/packages/ui/src/components/shell/__e2e__/run-home-screen-e2e.mjs index abc2131776baf..d8173c5414c6b 100644 --- a/packages/ui/src/components/shell/__e2e__/run-home-screen-e2e.mjs +++ b/packages/ui/src/components/shell/__e2e__/run-home-screen-e2e.mjs @@ -554,6 +554,39 @@ try { `developer tool "${id}" renders on the launcher developer page`, ); } + + // ── MOUSE drag-paging across the nested pagers. The outer rail used to steal + // pointer capture from the inner grid pager mid-drag (both pagers commit the + // axis on the same bubbled move; the outer's later setPointerCapture won), so + // a mouse drag left on launcher page 0 could NEVER reach the developer page. + // The claim registry now hands the gesture to the movable inner pager. Drive + // real mouse drags over the inner page window: back to the apps page, then + // forward again through the historically dead path. + const innerRailX = async () => + mobile.getByTestId("launcher-page-rail").evaluate((el) => { + const m = new DOMMatrixReadOnly(getComputedStyle(el).transform); + return { x: m.m41, width: el.getBoundingClientRect().width / 2 }; + }); + await swipeRight(mobile.getByTestId("launcher-page-window")); + await mobile.waitForTimeout(750); + const backToApps = await innerRailX(); + assert( + backToApps.x > -backToApps.width * 0.5, + `mouse swipe right pages the inner grid back to apps (rail x=${Math.round(backToApps.x)})`, + ); + assert( + (await mobile + .getByTestId("home-launcher-surface") + .getAttribute("data-page")) === "launcher", + "inner mouse paging stays on the launcher (the rail did not hijack the drag)", + ); + await swipeLeft(mobile.getByTestId("launcher-page-window")); + await mobile.waitForTimeout(750); + const forwardAgain = await innerRailX(); + assert( + forwardAgain.x < -forwardAgain.width * 0.5, + `mouse swipe left from page 0 reaches the developer page (rail x=${Math.round(forwardAgain.x)})`, + ); await snap(mobile, "mobile-launcher-page2"); // The home is a clean, action-driven dashboard: no Edit chrome, no "Pinned" diff --git a/packages/ui/src/components/shell/shell-state.test.ts b/packages/ui/src/components/shell/shell-state.test.ts index 7dc4b6c02d832..6e298d844b17c 100644 --- a/packages/ui/src/components/shell/shell-state.test.ts +++ b/packages/ui/src/components/shell/shell-state.test.ts @@ -106,4 +106,70 @@ describe("selectVisibleShellMessages (#9141 gap 4 windowing)", () => { expect(ids).toEqual(phase === "responding" ? ["u1", "a1"] : ["u1"]); } }); + + it("keeps an image-only USER turn (no caption) in every phase", () => { + const imageOnly: ShellMessage = { + ...msg("u1", "user", ""), + attachments: [ + { id: "att1", url: "/api/media/abc.png", contentType: "image" }, + ], + }; + const phases: ShellPhase[] = [ + "booting", + "idle", + "summoned", + "listening", + "responding", + ]; + for (const phase of phases) { + const ids = selectVisibleShellMessages( + [imageOnly, msg("a1", "assistant", "nice photo")], + phase, + ).map((m) => m.id); + expect(ids).toEqual(["u1", "a1"]); + } + }); + + it("keeps an attachment-only ASSISTANT turn after the phase leaves responding", () => { + const generated: ShellMessage = { + ...msg("a1", "assistant", ""), + attachments: [ + { id: "att1", url: "/api/media/gen.png", contentType: "image" }, + ], + }; + const thread = [msg("u1", "user", "draw me a cat"), generated]; + // Visible while streaming AND once settled — it must not vanish. + expect( + selectVisibleShellMessages(thread, "responding").map((m) => m.id), + ).toEqual(["u1", "a1"]); + expect(selectVisibleShellMessages(thread, "idle").map((m) => m.id)).toEqual( + ["u1", "a1"], + ); + }); + + it("keeps a secret-request-only turn (actionable block, no text)", () => { + const secret: ShellMessage = { + ...msg("a1", "assistant", ""), + secretRequest: { key: "DISCORD_TOKEN", status: "pending" }, + }; + expect( + selectVisibleShellMessages( + [msg("u1", "user", "connect discord"), secret], + "idle", + ).map((m) => m.id), + ).toEqual(["u1", "a1"]); + }); + + it("still drops turns with an EMPTY attachments array", () => { + const emptyAtt: ShellMessage = { + ...msg("a1", "assistant", ""), + attachments: [], + }; + expect( + selectVisibleShellMessages( + [msg("u1", "user", "hi"), emptyAtt], + "idle", + ).map((m) => m.id), + ).toEqual(["u1"]); + }); }); diff --git a/packages/ui/src/components/shell/shell-state.ts b/packages/ui/src/components/shell/shell-state.ts index 36232da0bc686..63eb1ee602564 100644 --- a/packages/ui/src/components/shell/shell-state.ts +++ b/packages/ui/src/components/shell/shell-state.ts @@ -51,11 +51,14 @@ export const MAX_RENDERED_SHELL_MESSAGES = 80; /** * Pure transcript-windowing decision (#9141 gap 4 seam). Drops empty turns — - * EXCEPT the in-flight assistant turn while a reply is streaming (phase === - * "responding"), so its bubble can show the breathing dots anchored where the - * text will fill in — then keeps only the most recent `max` turns to bound DOM - * nodes. Pure + DOM-free so the cap + streaming-turn exception are unit-testable - * and any future virtualizer can reuse the same predicate. + * EXCEPT turns that carry non-text content (attachments or a pending secret + * request: an image-only send is a valid user turn and an assistant reply can + * be a bare generated image) and EXCEPT the in-flight assistant turn while a + * reply is streaming (phase === "responding"), so its bubble can show the + * breathing dots anchored where the text will fill in — then keeps only the + * most recent `max` turns to bound DOM nodes. Pure + DOM-free so the cap + + * exceptions are unit-testable and any future virtualizer can reuse the same + * predicate. */ export function selectVisibleShellMessages( messages: readonly ShellMessage[], @@ -64,7 +67,10 @@ export function selectVisibleShellMessages( ): ShellMessage[] { const kept = messages.filter( (m) => - m.content.trim() || (m.role === "assistant" && phase === "responding"), + m.content.trim() || + (m.attachments?.length ?? 0) > 0 || + m.secretRequest !== undefined || + (m.role === "assistant" && phase === "responding"), ); return max > 0 && kept.length > max ? kept.slice(-max) : [...kept]; } diff --git a/packages/ui/src/hooks/useHorizontalPager.test.tsx b/packages/ui/src/hooks/useHorizontalPager.test.tsx index 5fcf185c0e369..b196e149526a6 100644 --- a/packages/ui/src/hooks/useHorizontalPager.test.tsx +++ b/packages/ui/src/hooks/useHorizontalPager.test.tsx @@ -1,15 +1,17 @@ // @vitest-environment jsdom // // Unit coverage for useHorizontalPager (#10717): velocity-aware momentum settle -// (a fast flick settles quicker than a slow drag over the same distance) and the -// pointer edge-button surface (canPrev/canNext + goPrev/goNext one-page nav). -// Drives REAL React pointer events through the hook and reads the transition the -// hook writes to the rail; performance.now is mocked to make release velocity -// deterministic. +// (a fast flick settles quicker than a slow drag over the same distance), the +// pointer edge-button surface (canPrev/canNext + goPrev/goNext one-page nav), +// and the nested-pager claim registry (one horizontal drag is owned by exactly +// one pager along the bubble path). Drives REAL React pointer events through +// the hook and reads the transition the hook writes to the rail; +// performance.now is mocked to make release velocity deterministic. import { act, cleanup, fireEvent, render } from "@testing-library/react"; import * as React from "react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { runAnimationFramesImmediately } from "../testing/run-animation-frames-immediately"; import { useHorizontalPager } from "./useHorizontalPager"; let clock = 1000; @@ -141,6 +143,218 @@ describe("useHorizontalPager — velocity-aware momentum settle (#10717)", () => }); }); +/** + * Two REAL pagers nested along one bubble path, mirroring the home↔launcher + * rail (outer, 2 pages, resting on its last page) wrapping the launcher grid + * pager (inner, 3 pages): pointer events fired on the tile bubble through the + * inner pager's handlers first, then the outer's — the exact composition the + * shared claim registry arbitrates. + */ +function NestedHarness({ + innerInitialPage = 0, + onOuterPageChange, + onInnerPageChange, +}: { + innerInitialPage?: number; + onOuterPageChange?: (page: number) => void; + onInnerPageChange?: (page: number) => void; +}): React.JSX.Element { + const [outerPage, setOuterPage] = React.useState(1); + const [innerPage, setInnerPage] = React.useState(innerInitialPage); + const outer = useHorizontalPager({ + page: outerPage, + pageCount: 2, + onPageChange: (next) => { + onOuterPageChange?.(next); + setOuterPage(next); + }, + }); + const inner = useHorizontalPager({ + page: innerPage, + pageCount: 3, + onPageChange: (next) => { + onInnerPageChange?.(next); + setInnerPage(next); + }, + }); + return ( +
+
+
+
+
+
+
+
+
+
+
+ ); +} + +describe("useHorizontalPager — nested-pager gesture arbitration", () => { + it("a leftward touch drag the inner pager can move on is claimed by it — the outer never tracks or paints", () => { + runAnimationFramesImmediately(); + const outerChange = vi.fn(); + const innerChange = vi.fn(); + const { getByTestId } = render( + , + ); + const tile = getByTestId("inner-tile"); + const outerRail = getByTestId("outer-rail"); + const outerResting = outerRail.style.transform; + const opts = { + pointerId: 21, + pointerType: "touch", + isPrimary: true, + clientY: 300, + } as const; + + act(() => { + fireEvent.pointerDown(tile, { ...opts, clientX: 500 }); + fireEvent.pointerMove(tile, { ...opts, clientX: 480 }); + fireEvent.pointerMove(tile, { ...opts, clientX: 200 }); + }); + // The inner rail follows the finger 1:1 … + expect(getByTestId("inner-rail").style.transform).toContain("-300px"); + // … while the outer rail must not move at all (it used to paint its own + // rubber-band on top, translating both rails for one finger). + expect(outerRail.style.transform).toBe(outerResting); + + act(() => { + clock = 1050; + fireEvent.pointerUp(tile, { ...opts, clientX: 200 }); + }); + expect(innerChange).toHaveBeenCalledWith(1); + expect(outerChange).not.toHaveBeenCalled(); + }); + + it("a leftward MOUSE drag advances the inner pager — the outer no longer steals the gesture via pointer capture", () => { + runAnimationFramesImmediately(); + const outerChange = vi.fn(); + const innerChange = vi.fn(); + const { getByTestId } = render( + , + ); + const tile = getByTestId("inner-tile"); + const opts = { + pointerId: 22, + pointerType: "mouse", + isPrimary: true, + clientY: 300, + } as const; + + act(() => { + fireEvent.pointerDown(tile, { ...opts, clientX: 500 }); + fireEvent.pointerMove(tile, { ...opts, clientX: 480 }); + fireEvent.pointerMove(tile, { ...opts, clientX: 200 }); + clock = 1050; + fireEvent.pointerUp(tile, { ...opts, clientX: 200 }); + }); + expect(innerChange).toHaveBeenCalledWith(1); + expect(outerChange).not.toHaveBeenCalled(); + }); + + it("a rightward drag the inner pager CANNOT move on falls through to the outer rail", () => { + runAnimationFramesImmediately(); + const outerChange = vi.fn(); + const innerChange = vi.fn(); + const { getByTestId } = render( + , + ); + const tile = getByTestId("inner-tile"); + const opts = { + pointerId: 23, + pointerType: "touch", + isPrimary: true, + clientY: 300, + } as const; + + act(() => { + fireEvent.pointerDown(tile, { ...opts, clientX: 200 }); + fireEvent.pointerMove(tile, { ...opts, clientX: 220 }); + fireEvent.pointerMove(tile, { ...opts, clientX: 520 }); + }); + // The outer claimed the gesture on the commit move, evicting the inner — + // the inner rail must sit back at its resting page, not rubber-band along. + expect(getByTestId("inner-rail").style.transform).toContain( + "translate3d(0px,0,0)", + ); + + act(() => { + clock = 1050; + fireEvent.pointerUp(tile, { ...opts, clientX: 520 }); + }); + expect(outerChange).toHaveBeenCalledWith(0); + expect(innerChange).not.toHaveBeenCalled(); + }); + + it("an unowned dead-end drag rubber-bands the INNERMOST pager only", () => { + runAnimationFramesImmediately(); + const outerChange = vi.fn(); + const innerChange = vi.fn(); + const { getByTestId } = render( + , + ); + const tile = getByTestId("inner-tile"); + const outerRail = getByTestId("outer-rail"); + const outerResting = outerRail.style.transform; + const opts = { + pointerId: 24, + pointerType: "touch", + isPrimary: true, + clientY: 300, + } as const; + + // Both pagers sit on their last page: neither can move left, so nobody + // claims — the drag stays unowned. + act(() => { + fireEvent.pointerDown(tile, { ...opts, clientX: 500 }); + fireEvent.pointerMove(tile, { ...opts, clientX: 480 }); + fireEvent.pointerMove(tile, { ...opts, clientX: 300 }); + }); + // Inner (innermost): base -2 pages × 1024px, plus dx·0.35 resistance. + expect(getByTestId("inner-rail").style.transform).toContain("-2118px"); + // Outer: no edge resistance for a gesture it does not own. + expect(outerRail.style.transform).toBe(outerResting); + + act(() => { + clock = 1050; + fireEvent.pointerUp(tile, { ...opts, clientX: 300 }); + }); + expect(outerChange).not.toHaveBeenCalled(); + expect(innerChange).not.toHaveBeenCalled(); + }); +}); + describe("useHorizontalPager — edge-button navigation (#10717)", () => { it("exposes canPrev/canNext for the current page position", () => { const first = render(); diff --git a/packages/ui/src/hooks/useHorizontalPager.ts b/packages/ui/src/hooks/useHorizontalPager.ts index c294f05b1b4c5..582b559e1c186 100644 --- a/packages/ui/src/hooks/useHorizontalPager.ts +++ b/packages/ui/src/hooks/useHorizontalPager.ts @@ -28,9 +28,120 @@ interface DragState { page: number; width: number; captured: boolean; + /** Element holding pointer capture for this drag (mouse/pen only). */ + captureTarget: HTMLDivElement | null; axis: "pending" | "horizontal" | "vertical"; } +/** + * Cross-pager gesture arbitration (nested pagers). + * + * The home↔launcher rail nests the launcher's grid pager and both attach + * pointer handlers along the same bubble path, so without arbitration one + * horizontal drag is tracked — and painted — by BOTH pagers at once, and for + * mouse/pen the outer handler's later `setPointerCapture` steals the pointer + * from the inner pager mid-drag. This registry makes a swipe claimed by two + * pagers structurally impossible (the shell-surface store invariant): every + * pager that sees a pointerdown registers as a tracker in bubble order + * (innermost first), and the first pager that commits a horizontal axis AND + * can move in the drag direction claims the pointer exclusively, evicting + * every other tracker on the spot. + */ +interface PagerPointerTracker { + /** + * Called when another pager claims the pointer. Eviction is pushed (not + * polled) because once the winner holds mouse capture the losers may never + * receive another pointer event to learn from. + */ + onEvicted: () => void; +} + +interface PagerPointerGesture { + /** The pointerdown that opened this gesture — tells a fresh gesture apart + * from a stale entry when the browser reuses a pointer id. */ + downEvent: Event; + /** Trackers in bubble order: index 0 is the innermost pager. */ + trackers: PagerPointerTracker[]; + /** Exclusive owner of the horizontal gesture, once claimed. */ + owner: PagerPointerTracker | null; +} + +const pagerPointerGestures = new Map(); + +function registerPagerPointerTracker( + pointerId: number, + downEvent: Event, + tracker: PagerPointerTracker, +): void { + const gesture = pagerPointerGestures.get(pointerId); + // A different pointerdown under a reused pointer id is a NEW gesture — the + // old entry is stale (its pointerup never reached us), so replace it. + if (!gesture || gesture.downEvent !== downEvent) { + pagerPointerGestures.set(pointerId, { + downEvent, + trackers: [tracker], + owner: null, + }); + return; + } + if (!gesture.trackers.includes(tracker)) gesture.trackers.push(tracker); +} + +function unregisterPagerPointerTracker( + pointerId: number, + tracker: PagerPointerTracker, +): void { + const gesture = pagerPointerGestures.get(pointerId); + if (!gesture) return; + gesture.trackers = gesture.trackers.filter((t) => t !== tracker); + if (gesture.owner === tracker) gesture.owner = null; + if (gesture.trackers.length === 0) pagerPointerGestures.delete(pointerId); +} + +/** True when a DIFFERENT pager holds the exclusive claim on this pointer. */ +function isPagerPointerOwnedElsewhere( + pointerId: number, + tracker: PagerPointerTracker, +): boolean { + const owner = pagerPointerGestures.get(pointerId)?.owner ?? null; + return owner !== null && owner !== tracker; +} + +/** + * Claim the pointer for `tracker` (first claim wins) and evict every other + * tracker. Returns whether `tracker` owns the pointer after the call. + */ +function claimPagerPointer( + pointerId: number, + tracker: PagerPointerTracker, +): boolean { + const gesture = pagerPointerGestures.get(pointerId); + // An untracked pointer means this pager is the only one listening. + if (!gesture) return true; + if (gesture.owner === tracker) return true; + if (gesture.owner !== null) return false; + gesture.owner = tracker; + // Iterate a snapshot: eviction unregisters, which replaces the array. + for (const other of [...gesture.trackers]) { + if (other !== tracker) other.onEvicted(); + } + return true; +} + +/** + * True when `tracker` sits closest to the original event target among the + * pagers still tracking this pointer. An UNOWNED horizontal drag (every pager + * at its edge) paints its rubber-band on the innermost pager only, so two + * nested rails never translate for the same finger. + */ +function isInnermostPagerPointerTracker( + pointerId: number, + tracker: PagerPointerTracker, +): boolean { + const gesture = pagerPointerGestures.get(pointerId); + return !gesture || gesture.trackers[0] === tracker; +} + export interface UseHorizontalPagerOptions { page: number; pageCount: number; @@ -162,6 +273,12 @@ export function useHorizontalPager< const edgeSwipeRightEnabledRef = React.useRef(edgeSwipeRightEnabled); const onPageChangeRef = React.useRef(onPageChange); const onEdgeSwipeRightRef = React.useRef(onEdgeSwipeRight); + // This pager's identity in the shared pointer-claim registry. `onEvicted` + // dispatches through a ref so the registry never holds a stale closure. + const abandonDragRef = React.useRef<() => void>(() => {}); + const pointerTrackerRef = React.useRef({ + onEvicted: () => abandonDragRef.current(), + }); pageRef.current = page; pageCountRef.current = pageCount; @@ -203,7 +320,14 @@ export function useHorizontalPager< pendingOffsetRef.current = offset; if (rafRef.current !== 0) return; if (typeof requestAnimationFrame === "function") { - rafRef.current = requestAnimationFrame(flushOffset); + // Mark the frame pending BEFORE scheduling: a synchronous rAF (test + // environments run the callback inline) clears rafRef inside + // flushOffset, and assigning the returned handle afterwards would + // re-mark the frame as pending forever — swallowing every later + // offset of the gesture. + rafRef.current = -1; + const handle = requestAnimationFrame(flushOffset); + if (rafRef.current === -1) rafRef.current = handle; return; } flushOffset(); @@ -235,17 +359,33 @@ export function useHorizontalPager< return dx; }, []); - const releaseCapture = React.useCallback( - (event: React.PointerEvent, state: DragState) => { - if (!state.captured) return; - try { - event.currentTarget.releasePointerCapture?.(state.pointerId); - } catch { - // The browser may already have revoked capture. - } - }, - [], - ); + const releaseCapture = React.useCallback((state: DragState) => { + if (!state.captured || state.captureTarget === null) return; + try { + state.captureTarget.releasePointerCapture?.(state.pointerId); + } catch { + // The browser may already have revoked capture. + } + }, []); + + /** + * Stand down mid-gesture: another pager claimed this pointer (or this pager + * is unmounting). Dropping the drag immediately — rather than waiting for a + * pointerup that may never arrive once the winner holds capture — re-arms + * the ResizeObserver resync and the controlled-page layout effect, and + * settles the rail back to its resting page so a half-painted rubber-band + * never sticks. + */ + const abandonDrag = React.useCallback(() => { + const state = dragRef.current; + if (!state) return; + cancelScheduledOffset(); + dragRef.current = null; + releaseCapture(state); + unregisterPagerPointerTracker(state.pointerId, pointerTrackerRef.current); + writeOffset(pageOffset(state.page, state.width), SETTLE_MS); + }, [cancelScheduledOffset, releaseCapture, writeOffset]); + abandonDragRef.current = abandonDrag; React.useLayoutEffect(() => { const width = measureWidth(); @@ -285,13 +425,18 @@ export function useHorizontalPager< React.useEffect(() => cancelScheduledOffset, [cancelScheduledOffset]); + // Unmounting mid-gesture must not leave a dead tracker (or a stale claim) + // in the shared registry. + React.useEffect(() => () => abandonDragRef.current(), []); + const finish = React.useCallback( (event: React.PointerEvent, cancelled = false) => { const state = dragRef.current; if (!state || state.pointerId !== event.pointerId) return; cancelScheduledOffset(); dragRef.current = null; - releaseCapture(event, state); + releaseCapture(state); + unregisterPagerPointerTracker(event.pointerId, pointerTrackerRef.current); const base = pageOffset(state.page, state.width); const dx = event.clientX - state.startX; @@ -310,7 +455,16 @@ export function useHorizontalPager< momentumSettleMs(Math.abs(offset - lastVisual), velocity), ); - if (cancelled || state.axis !== "horizontal" || !canMove(state, dx)) { + // A page only advances for the gesture's exclusive owner. Claiming here + // covers a release whose direction flipped after the last move: the + // first pager to claim wins and evicts the rest, so two nested pagers + // can never both advance off one pointerup. + if ( + cancelled || + state.axis !== "horizontal" || + !canMove(state, dx) || + !claimPagerPointer(event.pointerId, pointerTrackerRef.current) + ) { settleTo(base); return; } @@ -389,6 +543,14 @@ export function useHorizontalPager< return; } cancelScheduledOffset(); + // Enter the shared claim registry. Handlers run innermost-first in the + // bubble phase, so registration order records which pager sits closest + // to the finger. + registerPagerPointerTracker( + event.pointerId, + event.nativeEvent, + pointerTrackerRef.current, + ); const currentPage = clampPage(pageRef.current, pageCountRef.current); const width = measureWidth(); dragRef.current = { @@ -399,6 +561,7 @@ export function useHorizontalPager< page: currentPage, width, captured: false, + captureTarget: null, axis: "pending", }; writeOffset(pageOffset(currentPage, width), null); @@ -411,6 +574,16 @@ export function useHorizontalPager< const state = dragRef.current; if (!state || state.pointerId !== event.pointerId) return; + // Another pager already owns this pointer's horizontal gesture — stand + // down instead of double-tracking it. (Eviction usually beat us to it; + // this guards any event that still slips through.) + if ( + isPagerPointerOwnedElsewhere(event.pointerId, pointerTrackerRef.current) + ) { + abandonDrag(); + return; + } + const dx = event.clientX - state.startX; const dy = event.clientY - state.startY; if (state.axis === "pending") { @@ -421,6 +594,26 @@ export function useHorizontalPager< } if (state.axis !== "horizontal") return; + // A pager that can actually move in the drag direction claims the + // pointer exclusively. Handlers run innermost-first in the bubble phase, + // so a movable inner grid pager wins the gesture before the outer rail + // ever sees the move. + const owned = canMove(state, dx) + ? claimPagerPointer(event.pointerId, pointerTrackerRef.current) + : false; + // An unowned drag (every pager at its edge) rubber-bands on the + // innermost pager only — the outer rail must not paint edge resistance + // for a gesture it does not own. + if ( + !owned && + !isInnermostPagerPointerTracker( + event.pointerId, + pointerTrackerRef.current, + ) + ) { + return; + } + // Touch pointers are IMPLICITLY captured to the target on pointerdown, so // an explicit setPointerCapture is redundant — and on Android WebView it // makes the browser fire `pointercancel` + `lostpointercapture` the instant @@ -432,6 +625,7 @@ export function useHorizontalPager< try { event.currentTarget.setPointerCapture(event.pointerId); state.captured = true; + state.captureTarget = event.currentTarget; } catch { // Capture is best-effort; the transform can still follow pointermove. } @@ -440,7 +634,7 @@ export function useHorizontalPager< pageOffset(state.page, state.width) + visualDragOffset(state, dx), ); }, - [scheduleOffset, visualDragOffset], + [abandonDrag, canMove, scheduleOffset, visualDragOffset], ); const onPointerUp = React.useCallback( diff --git a/packages/ui/src/i18n/locales/en.json b/packages/ui/src/i18n/locales/en.json index d3d9bedb78f23..7daa03d1c7aaa 100644 --- a/packages/ui/src/i18n/locales/en.json +++ b/packages/ui/src/i18n/locales/en.json @@ -4103,6 +4103,7 @@ "settings.sections.aimodel.desc": "Cloud, local, subscriptions, and direct providers.", "settings.sections.appearance.desc": "Content packs, VRM avatars, backgrounds, and themes", "settings.sections.appearance.label": "Appearance", + "settings.sections.background.label": "Background", "settings.sections.apps.basedOnLabel": "Based on existing app (optional)", "settings.sections.apps.basedOnNone": "Start from scratch", "settings.sections.apps.col.actions": "Actions", diff --git a/packages/ui/src/state/chat-conversation-guards.ts b/packages/ui/src/state/chat-conversation-guards.ts index 1ea57b1e6e065..b3635c7a54076 100644 --- a/packages/ui/src/state/chat-conversation-guards.ts +++ b/packages/ui/src/state/chat-conversation-guards.ts @@ -17,6 +17,19 @@ const LEGACY_PAGE_CHAT_TITLES = new Set([ "wallet", ]); +/** + * True when a title collides with the legacy page-chat title heuristic in + * {@link isMainChatConversation}. A scope-less conversation with one of these + * exact titles is treated as a legacy page chat and hidden from every list — + * so user renames must reject them (QA: renaming a chat to "wallet" made it + * vanish with no recovery path). New conversations are stamped + * `scope: "general"` at creation, but the pre-stamp backlog stays vulnerable + * to this collision. + */ +export function isReservedLegacyChatTitle(title: string): boolean { + return LEGACY_PAGE_CHAT_TITLES.has(title.trim().toLowerCase()); +} + export function isConversationRecord(value: unknown): value is Conversation { if (!value || typeof value !== "object") { return false; diff --git a/packages/ui/src/state/launcher-layout.test.ts b/packages/ui/src/state/launcher-layout.test.ts index 7371c317d0b17..ff8e198a8be72 100644 --- a/packages/ui/src/state/launcher-layout.test.ts +++ b/packages/ui/src/state/launcher-layout.test.ts @@ -162,9 +162,9 @@ describe("launcher-layout persistence", () => { expect(readLauncherLayout()).toEqual(layout); }); - it("returns an empty layout on malformed storage", () => { + it("falls back to the first-run default (seeded dock) on malformed storage", () => { window.localStorage.setItem(LAUNCHER_STORAGE_KEY, "{not json"); - expect(readLauncherLayout()).toEqual(emptyLayout()); + expect(readLauncherLayout()).toEqual(defaultLayout()); }); it("migrates a pre-rename 'springboard' layout forward (#9951)", () => { @@ -229,4 +229,36 @@ describe("launcher-layout default dock (#9144)", () => { expect(out.favorites).toEqual([]); expect(out.pages.flat()).toEqual(["chat", "settings", "activity"]); }); + + it("stamps dockCleared when an empty dock is explicitly committed", () => { + writeLauncherLayout({ favorites: [], pages: [["a"]] }); + const stored = JSON.parse( + window.localStorage.getItem(LAUNCHER_STORAGE_KEY) ?? "{}", + ) as LauncherLayout; + expect(stored.dockCleared).toBe(true); + }); + + it("re-seeds the dock for a pre-dock-era payload (favorites [] without the marker)", () => { + // The no-dock era (#10789–#10800) persisted `favorites: []` on every + // commit; the product had no clear-dock affordance, so an unmarked empty + // dock is residue, not intent — it must not suppress the dock forever. + window.localStorage.setItem( + LAUNCHER_STORAGE_KEY, + JSON.stringify({ favorites: [], pages: [["b", "a"]], manual: true }), + ); + const layout = readLauncherLayout(); + expect(layout.favorites).toEqual(DEFAULT_LAUNCHER_FAVORITES); + expect(layout.pages).toEqual([["b", "a"]]); + expect(layout.manual).toBe(true); + }); + + it("re-seeds the dock when migrating a dock-less springboard-era payload", () => { + window.localStorage.setItem( + "elizaos.views.springboard", + JSON.stringify({ favorites: [], pages: [["d"]] }), + ); + const layout = readLauncherLayout(); + expect(layout.favorites).toEqual(DEFAULT_LAUNCHER_FAVORITES); + expect(layout.pages).toEqual([["d"]]); + }); }); diff --git a/packages/ui/src/state/launcher-layout.ts b/packages/ui/src/state/launcher-layout.ts index 3a26fca6bdaad..099d847ac7251 100644 --- a/packages/ui/src/state/launcher-layout.ts +++ b/packages/ui/src/state/launcher-layout.ts @@ -8,8 +8,13 @@ * here so it is unit testable without a DOM. * * The `favorites` field is the launcher dock. Fresh installs seed a tiny, - * stable dock with Chat + Settings; explicit stored layouts (including an empty - * user-cleared dock) are respected. + * stable dock with Chat + Settings. An explicitly cleared dock is respected + * only when the payload carries the `dockCleared` marker (stamped by + * {@link writeLauncherLayout} whenever a layout is committed with no + * favorites). A stored `favorites: []` WITHOUT the marker is legacy residue + * from the no-dock era (#10789–#10800) — the product had no way to clear a + * dock then, so it re-seeds the default instead of suppressing the dock + * forever. * * Mirrors the persistence style of `view-recents.ts`. */ @@ -56,6 +61,12 @@ export interface LauncherLayout { * arrangement is preserved. */ manual?: boolean; + /** + * True when an empty dock was explicitly committed (user intent) rather + * than inherited from the pre-dock era. Distinguishes "cleared" from + * "never had a dock" so the default dock can be re-seeded for the latter. + */ + dockCleared?: boolean; } export function emptyLayout(): LauncherLayout { @@ -86,32 +97,52 @@ function parseLayout(raw: string): LauncherLayout { ? (record.pages as string[][]) : []; const manual = record.manual === true ? true : undefined; - return { favorites, pages, manual }; + const dockCleared = record.dockCleared === true ? true : undefined; + return { favorites, pages, manual, dockCleared }; +} + +/** + * Upgrade path (#10800 QA): a stored empty dock WITHOUT the explicit + * `dockCleared` marker predates the dock feature (or is corrupt residue) — + * the product had no clear-dock affordance then, so it cannot be user intent. + * Re-seed the default dock for those payloads; marked payloads stay empty. + */ +function withSeededDock(layout: LauncherLayout): LauncherLayout { + if (layout.favorites.length > 0 || layout.dockCleared === true) { + return layout; + } + return { ...layout, favorites: [...DEFAULT_LAUNCHER_FAVORITES] }; } export function readLauncherLayout(): LauncherLayout { if (typeof window === "undefined") return emptyLayout(); try { const raw = window.localStorage.getItem(LAUNCHER_STORAGE_KEY); - if (raw) return parseLayout(raw); + if (raw) return withSeededDock(parseLayout(raw)); // One-time migration from the pre-rename "springboard" key (#9951): read the // legacy layout, persist it under the new key, and drop the old entry so the // user keeps their page order / favorites / manual flag across the rename. const legacyRaw = window.localStorage.getItem(LEGACY_LAUNCHER_STORAGE_KEY); if (!legacyRaw) return defaultLayout(); - const migrated = parseLayout(legacyRaw); + const migrated = withSeededDock(parseLayout(legacyRaw)); writeLauncherLayout(migrated); window.localStorage.removeItem(LEGACY_LAUNCHER_STORAGE_KEY); return migrated; } catch { - return emptyLayout(); + // Corrupt/unreadable payload: fall back to the first-run default (with the + // seeded dock) rather than a dock-less empty layout. + return defaultLayout(); } } export function writeLauncherLayout(layout: LauncherLayout): void { if (typeof window === "undefined") return; try { - window.localStorage.setItem(LAUNCHER_STORAGE_KEY, JSON.stringify(layout)); + // Stamp an explicitly-committed empty dock so a future read distinguishes + // user intent from pre-dock-era residue (see withSeededDock). + const toStore = + layout.favorites.length === 0 ? { ...layout, dockCleared: true } : layout; + window.localStorage.setItem(LAUNCHER_STORAGE_KEY, JSON.stringify(toStore)); } catch { /* localStorage unavailable */ } diff --git a/packages/ui/src/state/types.ts b/packages/ui/src/state/types.ts index 4b9867d8d5829..f66b691a4e892 100644 --- a/packages/ui/src/state/types.ts +++ b/packages/ui/src/state/types.ts @@ -862,10 +862,11 @@ export interface AppActions { loadPlugins: (options?: { silent?: boolean }) => Promise; ensurePluginsLoaded: () => Promise; handlePluginToggle: (pluginId: string, enabled: boolean) => Promise; + /** Resolves true only when the config actually persisted (false = save failed; the caller must keep the user's typed draft). */ handlePluginConfigSave: ( pluginId: string, config: Record, - ) => Promise; + ) => Promise; // Skills loadSkills: () => Promise; diff --git a/packages/ui/src/state/useChatCallbacks.ts b/packages/ui/src/state/useChatCallbacks.ts index 38910306c3696..dedd98a36e471 100644 --- a/packages/ui/src/state/useChatCallbacks.ts +++ b/packages/ui/src/state/useChatCallbacks.ts @@ -22,6 +22,7 @@ import type { Tab } from "../navigation"; import { isTtsDebugEnabled } from "../utils/tts-debug"; import { isConversationRecord, + isReservedLegacyChatTitle, normalizeConversationList, } from "./chat-conversation-guards"; import type { AppState, LifecycleAction } from "./internal"; @@ -887,6 +888,11 @@ export function useChatCallbacks(deps: UseChatCallbacksDeps) { const { conversation: rawConversation, greeting: inlineGreeting } = await client.createConversation(title, { lang: uiLanguage, + // Stamp an explicit scope so the legacy page-chat TITLE heuristic + // (isMainChatConversation) can never hide this conversation — a + // scope-less chat renamed/auto-titled to "wallet"/"settings"/… + // used to vanish from every list. + metadata: { scope: "general" }, }); if (!isConversationRecord(rawConversation)) { throw new Error("Conversation creation returned an invalid payload."); @@ -1249,6 +1255,16 @@ export function useChatCallbacks(deps: UseChatCallbacksDeps) { setActionNotice("Conversation title cannot be empty.", "error", 2800); return; } + if (isReservedLegacyChatTitle(trimmed)) { + // A scope-less conversation with this exact title is classified as a + // legacy page chat and hidden from every list — apparent data loss. + setActionNotice( + `"${trimmed}" is a reserved name. Pick a different title.`, + "error", + 3600, + ); + return; + } try { const { conversation } = await client.renameConversation(id, trimmed); setConversations((prev) => diff --git a/packages/ui/src/state/usePluginsSkillsState.ts b/packages/ui/src/state/usePluginsSkillsState.ts index 7d0ccbdc6308c..c9cef95eb4733 100644 --- a/packages/ui/src/state/usePluginsSkillsState.ts +++ b/packages/ui/src/state/usePluginsSkillsState.ts @@ -310,8 +310,14 @@ export function usePluginsSkillsState({ ); const handlePluginConfigSave = useCallback( - async (pluginId: string, config: Record) => { - if (Object.keys(config).length === 0) return; + // Returns true only when the save actually persisted — callers keep the + // user's typed draft (pasted tokens/keys never echo back from the server) + // when the save failed, instead of silently wiping the form. + async ( + pluginId: string, + config: Record, + ): Promise => { + if (Object.keys(config).length === 0) return true; setPluginSaving((prev) => new Set([...prev, pluginId])); try { const result = await client.updatePlugin(pluginId, { config }); @@ -385,12 +391,14 @@ export function usePluginsSkillsState({ return next; }); }, 2000); + return true; } catch (err) { setActionNotice( `Save failed: ${err instanceof Error ? err.message : "unknown error"}`, "error", 3800, ); + return false; } finally { setPluginSaving((prev) => { const next = new Set(prev); diff --git a/packages/ui/src/state/view-lifecycle-matrix.test.ts b/packages/ui/src/state/view-lifecycle-matrix.test.ts index 30754e79dabea..50b1b2fc69a0c 100644 --- a/packages/ui/src/state/view-lifecycle-matrix.test.ts +++ b/packages/ui/src/state/view-lifecycle-matrix.test.ts @@ -36,7 +36,6 @@ const VIEW_CLASSIFICATION: Record = { tasks: "system", automations: "system", browser: "system", - companion: "system", stream: "system", apps: "system", views: "system", @@ -47,7 +46,6 @@ const VIEW_CLASSIFICATION: Record = { files: "system", triggers: "system", rolodex: "system", - voice: "system", desktop: "system", settings: "system", tutorial: "system",