Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(web): add canonical user bar extension (#754)
Generc596df0102f7
diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsxindex a2954b24b..d72116f64 100644--- a/src/web/src/app/c/community-shell.tsx+++ b/src/web/src/app/c/community-shell.tsx@@ -13,7 +13,6 @@ import { useNotificationSettings } from "@/hooks/community/use-notification-settimport { PerfTraceBootstrap } from "@/components/perf/perf-trace-bootstrap"import { CommunityOnboardingForm } from "@/components/community/onboarding/community-onboarding-form"import { CommunityWsReconnectBoundary } from "@/components/community/shell/community-ws-reconnect-overlay"-import { CommunityDaemonUpdateNotice } from "@/components/daemon-update-notice"import { useCommunityWsStore } from "@/stores/community/ws"/**@@ -113,7 +112,6 @@ function CommunityBootstrap({ children }: { children: ReactNode }) {return (<><PerfTraceBootstrap />- <CommunityDaemonUpdateNotice userId={currentUser.id} /><CommunityWsReconnectBoundary><CommunityOnboardingForm />{children}diff --git a/src/web/src/app/c/layout.dom.test.ts b/src/web/src/app/c/layout.dom.test.tsindex 292f35a04..21deb4753 100644--- a/src/web/src/app/c/layout.dom.test.ts+++ b/src/web/src/app/c/layout.dom.test.ts@@ -124,13 +124,19 @@ describe("CommunityLayout session boundary", () => {expect(source).toContain("useDmRouteVerification(params.dmId, rawDms, canonicalDmsUnsettled)")})- it("mounts the daemon check inside the authenticated Community query cache", () => {+ it("keeps the daemon update controller inside the authenticated Community query cache", () => {const shell = readFileSync(resolve(process.cwd(),process.cwd().endsWith("/src/web") ? "" : "src/web","src/app/c/community-shell.tsx",), "utf8")- expect(shell.indexOf("<QueryProvider")).toBeLessThan(shell.indexOf("<CommunityDaemonUpdateNotice"))- expect(shell).toContain("<CommunityDaemonUpdateNotice userId={currentUser.id} />")+ const frame = readFileSync(resolve(+ process.cwd(),+ process.cwd().endsWith("/src/web") ? "" : "src/web",+ "src/components/community/shell/shell-frame.tsx",+ ), "utf8")+ expect(shell).toMatch(/<QueryProvider[\s\S]*<CurrentUserProvider[\s\S]*<CommunityBootstrap>/)+ expect(shell).not.toContain("CommunityDaemonUpdateNotice")+ expect(frame).toContain("useShellDaemonUpdateController")})})diff --git a/src/web/src/components/community/messages/composer-view.dom.test.ts b/src/web/src/components/community/messages/composer-view.dom.test.tsindex c6dab0c86..4d45a42c3 100644--- a/src/web/src/components/community/messages/composer-view.dom.test.ts+++ b/src/web/src/components/community/messages/composer-view.dom.test.ts@@ -386,7 +386,9 @@ describe("ComposerView", () => {"absolute right-2 bottom-2 size-8 rounded-full sm:hidden",])expect(renderer.container.firstElementChild?.tagName).toBe("DIV")- expect(renderer.container.firstElementChild?.className).toBe("relative px-3 pb-3 pt-0")+ expect(renderer.container.firstElementChild?.className).toBe(+ "relative pl-[max(0.75rem,var(--app-safe-area-left))] pr-[max(0.75rem,var(--app-safe-area-right))] pb-[calc(0.75rem+var(--app-safe-area-bottom))] pt-0 sm:px-3 sm:pb-3",+ )expect(renderer.container.innerHTML).toContain("relative rounded-xl bg-muted py-3 pl-12 pr-24 shadow-(--e1) ring-1 ring-border/40 sm:px-12",)diff --git a/src/web/src/components/community/messages/composer-view.tsx b/src/web/src/components/community/messages/composer-view.tsxindex 94b43cf3e..e088445f1 100644--- a/src/web/src/components/community/messages/composer-view.tsx+++ b/src/web/src/components/community/messages/composer-view.tsx@@ -31,6 +31,9 @@ import {import type { ComposerReplyTarget } from "./composer-types"import { FluentSendFilledIcon } from "./fluent-send-filled-icon"+const COMPOSER_OUTER_CLASS =+ "relative pl-[max(0.75rem,var(--app-safe-area-left))] pr-[max(0.75rem,var(--app-safe-area-right))] pb-[calc(0.75rem+var(--app-safe-area-bottom))] pt-0 sm:px-3 sm:pb-3"+export type ComposerViewProps = {isForumThreadBody: booleandragging: boolean@@ -91,7 +94,9 @@ export function ComposerView({return (<divclassName={- isForumThreadBody ? "relative" : "relative px-3 pb-3 pt-0"+ isForumThreadBody+ ? "relative"+ : COMPOSER_OUTER_CLASS}onDragEnter={onDragEnter}onDragLeave={onDragLeave}@@ -163,6 +168,7 @@ export function ComposerView({)}<div+ data-slot="community-composer-base"className={`relative ${isForumThreadBody? "bg-transparent ring-0"@@ -241,7 +247,7 @@ export function ComposerView({export function ComposerSkeleton() {return (- <div className="relative px-3 pb-3 pt-0">+ <div className={COMPOSER_OUTER_CLASS}><div className="relative rounded-xl bg-muted py-3 pl-12 pr-24 shadow-(--e1) ring-1 ring-border/40 sm:px-12"><Skeleton className="h-6 w-2/5 rounded" /><Skeleton className="absolute left-2 bottom-2 size-8 rounded-full" />diff --git a/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts b/src/web/src/components/community/shell/community-inbox-popover.dom.test.tsindex 80683695f..ef9a955bf 100644--- a/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts+++ b/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts@@ -286,7 +286,26 @@ describe("InboxPopover responsive continuity", () => {fireEvent.scroll(mentionsScroll)expect(onScrollOffsetChange).toHaveBeenCalledWith("mentions", 42)expect(renderer.getByTestId(tid.inboxTabList)).toBeInTheDocument()- expect(renderer.container.querySelector("h2")?.parentElement?.className)- .toBe("flex items-center gap-2 px-3 pt-4")+ const header = renderer.container.querySelector("h2")?.parentElement+ expect(header).toHaveClass("flex", "items-center", "gap-2", "px-3", "pt-4")+ expect(header).not.toHaveClass("pr-15", "sm:pr-12")+ })++ it("does not reserve extension header space for a shell close button", () => {+ const renderer = render(React.createElement(InboxPopover, {+ unreads: [],+ unreadDms: [],+ mentions: [],+ marked: [],+ hasProjectedUnreads: false,+ hasProjectedMentions: false,+ onMarkAllRead: vi.fn(),+ surface: "extension",+ }))++ const header = renderer.container.querySelector("h2")?.parentElement+ expect(header).toHaveClass("flex", "items-center", "gap-2", "px-3", "pt-4")+ expect(header).not.toHaveClass("pr-15", "sm:pr-12")+ expect(renderer.getByRole("button", { name: "Mark all read" })).toBeInTheDocument()})})diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsxindex ebde3cd5d..1e41f47f3 100644--- a/src/web/src/components/community/shell/community-inbox-popover.tsx+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx@@ -382,7 +382,7 @@ export function InboxPopover({onActiveTabChange?: (tab: InboxTab) => voidgetScrollOffset?: (tab: InboxTab) => numberonScrollOffsetChange?: (tab: InboxTab, scrollTop: number) => void- surface?: "desktop" | "mobile"+ surface?: "desktop" | "mobile" | "extension"}) {const profilesByUserId = useProfilesByUserId()const hasUnreads = hasProjectedUnreads@@ -403,7 +403,7 @@ export function InboxPopover({onActiveTabChange?.(tab)if (tab === "marked") onMarkedTabSelected?.()}}- className={surface === "mobile" ? "flex h-full min-h-0 flex-col" : "flex h-112 flex-col"}+ className={surface === "desktop" ? "flex h-112 flex-col" : "flex h-full min-h-0 flex-col"}><div className="flex items-center gap-2 px-3 pt-4"><Inbox className="size-5" />diff --git a/src/web/src/components/community/shell/shell-frame-geometry.test.ts b/src/web/src/components/community/shell/shell-frame-geometry.test.tsindex 5636d3c91..57060e5ac 100644--- a/src/web/src/components/community/shell/shell-frame-geometry.test.ts+++ b/src/web/src/components/community/shell/shell-frame-geometry.test.ts@@ -43,7 +43,7 @@ describe("desktop community shell geometry", () => {})describe("mobile Inbox shell geometry", () => {- it("uses one safe-area-aware user-bar expression across body portals", () => {+ it("uses the same 60px visual-plus-margin footprint as the mobile Composer", () => {expect(COMMUNITY_USER_BAR_BASE_HEIGHT).toBe(60)expect(COMMUNITY_USER_BAR_HEIGHT_CSS).toBe("calc(60px + var(--app-safe-area-bottom))",@@ -58,10 +58,10 @@ describe("mobile Inbox shell geometry", () => {[568, 0, 0, 508],[844, 0, 0, 784],[844, 20, 34, 730],- [320, 30, 40, 190],- [80, 30, 40, 0],+ [320, 30, 12, 218],+ [80, 30, 34, 0],])(- "caps a %ipx viewport with %ipx top and %ipx bottom safe areas",+ "caps a %ipx viewport below its %ipx top and %ipx bottom safe areas",(height, top, bottom, expected) => {expect(mobileInboxAvailableHeight(height, top, bottom)).toBe(expected)},diff --git a/src/web/src/components/community/shell/shell-frame-overlays.dom.test.ts b/src/web/src/components/community/shell/shell-frame-overlays.dom.test.tsindex 01495b3f7..1926b5990 100644--- a/src/web/src/components/community/shell/shell-frame-overlays.dom.test.ts+++ b/src/web/src/components/community/shell/shell-frame-overlays.dom.test.ts@@ -144,6 +144,19 @@ describe("ShellFrameOverlays", () => {expect(hostProps.get("dialog-root")?.open).toBe(false)})+ it("suppresses only the profile shell when its content is in the User Bar extension", () => {+ const renderer = render(createElement(ShellFrameOverlays, {+ controller,+ breakpoint: "desktop",+ suppressProfileCard: true,+ }))++ expect(renderer.container.querySelectorAll("profile-card")).toHaveLength(0)+ expect(renderer.container.querySelectorAll("image-lightbox")).toHaveLength(1)+ expect(renderer.container.querySelectorAll("attachment-sheet")).toHaveLength(1)+ expect(renderer.container.querySelectorAll("user-settings")).toHaveLength(1)+ })+it("stays a render-only boundary", () => {const source = readFileSync(resolve(process.cwd(),diff --git a/src/web/src/components/community/shell/shell-frame-overlays.tsx b/src/web/src/components/community/shell/shell-frame-overlays.tsxindex 1abf081cc..75848cfef 100644--- a/src/web/src/components/community/shell/shell-frame-overlays.tsx+++ b/src/web/src/components/community/shell/shell-frame-overlays.tsx@@ -16,16 +16,18 @@ export function ShellFrameOverlays({controller,breakpoint,extraDialogs,+ suppressProfileCard = false,}: {controller: ProfileControllerbreakpoint: BreakpointextraDialogs?: ReactNode+ suppressProfileCard?: boolean}) {const { profile, currentUser } = controllerconst pendingAvatarCrop = controller.pendingAvatarCropreturn (<>- {profile && (+ {profile && !suppressProfileCard && (<ProfileCardkey={`${profile.data.userId ?? profile.data.name}:${profile.x}:${profile.y}`}data={profile.data}diff --git a/src/web/src/components/community/shell/shell-frame-view.dom.test.ts b/src/web/src/components/community/shell/shell-frame-view.dom.test.tsindex ef5329e2b..32646b168 100644--- a/src/web/src/components/community/shell/shell-frame-view.dom.test.ts+++ b/src/web/src/components/community/shell/shell-frame-view.dom.test.ts@@ -133,6 +133,14 @@ const inbox = {open: false,onOpenChange: vi.fn(),} as never+const extensionProps = {+ userBarExtension: { active: "none", update: null },+ daemonUpdate: { update: null, eligibleMachines: [], request: vi.fn() },+ onUserBarInboxOpenChange: vi.fn(),+ onUserBarOpenProfile: vi.fn(),+ onUserBarOpenUpdate: vi.fn(),+ dismissUserBarExtension: vi.fn(),+} as neverlet animateDescriptor: PropertyDescriptor | undefined@@ -159,6 +167,7 @@ describe("ShellFrameView", () => {it("keeps responsive detail shell zones while the breakpoint is unknown", async () => {const renderer = render(createElement(ShellFrameView, {+ ...extensionProps,breakpoint: "unknown",checkpoint: committedCheckpoint("/c/me/dm_1", "detail"),sidebar: () => createElement("sidebar-content"),@@ -193,6 +202,7 @@ describe("ShellFrameView", () => {it("keeps rail, sidebar, and UserBar in the unknown list shell", async () => {const renderer = render(createElement(ShellFrameView, {+ ...extensionProps,breakpoint: "unknown",checkpoint: committedCheckpoint("/c/me", "list"),sidebar: () => createElement("sidebar-content"),@@ -213,6 +223,7 @@ describe("ShellFrameView", () => {it("keeps the desktop panel geometry, order, and seeded overlay call", async () => {const sidebar = vi.fn(() => createElement("sidebar-content"))const renderer = render(createElement(ShellFrameView, {+ ...extensionProps,breakpoint: "desktop",checkpoint: committedCheckpoint("/c/channels/s1/c1", "detail"),sidebar,@@ -284,6 +295,7 @@ describe("ShellFrameView", () => {it("seeds the User bar from the persisted panel percentage before pixel sizing", () => {mocks.defaultLayout.current = { sidebar: 18.75, main: 81.25 }const renderer = render(createElement(ShellFrameView, {+ ...extensionProps,breakpoint: "desktop",checkpoint: committedCheckpoint("/c/me", "list"),sidebar: () => createElement("sidebar-content"),@@ -305,6 +317,7 @@ describe("ShellFrameView", () => {it("composes the server-root list surface with desktop rail, sidebar, and landing content", async () => {const sidebar = vi.fn(() => createElement("sidebar-content"))const renderer = render(createElement(ShellFrameView, {+ ...extensionProps,breakpoint: "desktop",checkpoint: committedCheckpoint("/c/channels/s1", "list"),sidebar,@@ -326,6 +339,7 @@ describe("ShellFrameView", () => {it("keeps one responsive skeleton while mobile nav and detail geometry stay distinct", async () => {const sidebar = vi.fn(() => createElement("sidebar-content"))const renderer = render(createElement(ShellFrameView, {+ ...extensionProps,breakpoint: "mobile",checkpoint: committedCheckpoint("/c/me", "list"),sidebar,@@ -367,6 +381,7 @@ describe("ShellFrameView", () => {expect(sidebar).toHaveBeenCalledWith({ noHeader: false })renderer.rerender(createElement(ShellFrameView, {+ ...extensionProps,breakpoint: "mobile",checkpoint: committedCheckpoint("/c/me/dm_1", "detail"),sidebar,@@ -418,6 +433,7 @@ describe("ShellFrameView", () => {}const sidebar = () => createElement(StatefulSidebar)const common = {+ ...extensionProps,breakpoint: "mobile" as const,sidebar,cancelPendingNavigation: vi.fn(),@@ -520,6 +536,7 @@ describe("ShellFrameView", () => {value: animate,})const common = {+ ...extensionProps,breakpoint: "mobile" as const,sidebar: () => createElement("sidebar-content"),cancelPendingNavigation: vi.fn(),@@ -644,6 +661,7 @@ describe("ShellFrameView", () => {value: animate,})const common = {+ ...extensionProps,breakpoint: "mobile" as const,sidebar: () => createElement("sidebar-content"),cancelPendingNavigation: vi.fn(),@@ -679,6 +697,7 @@ describe("ShellFrameView", () => {return createElement("div", { "data-stateful-main": "", "data-identity": identity })}const common = {+ ...extensionProps,checkpoint: committedCheckpoint("/c/me/dm_1", "detail"),sidebar: () => createElement("sidebar-content"),cancelPendingNavigation: vi.fn(),@@ -707,6 +726,7 @@ describe("ShellFrameView", () => {it("keeps one panel-owned resize callback across breakpoint changes", async () => {const sidebar = vi.fn(() => createElement("sidebar-content"))const common = {+ ...extensionProps,checkpoint: committedCheckpoint("/c/me", "list"),sidebar,cancelPendingNavigation: vi.fn(),@@ -740,6 +760,7 @@ describe("ShellFrameView", () => {it("keeps committed content mounted while same-scope navigation is pending", async () => {const sidebar = vi.fn(() => createElement("sidebar-content"))const common = {+ ...extensionProps,sidebar,cancelPendingNavigation: vi.fn(),rail,@@ -779,6 +800,7 @@ describe("ShellFrameView", () => {it("replaces the committed sidebar with one target-scoped cold server checkpoint", async () => {const sidebar = vi.fn(() => createElement("old-sidebar"))const common = {+ ...extensionProps,cancelPendingNavigation: vi.fn(),checkpoint: {mode: "cold-scope",@@ -829,6 +851,7 @@ describe("ShellFrameView", () => {const renderer = render(createElement(ShellFrameView,{+ ...extensionProps,breakpoint: "desktop",checkpoint,sidebar,diff --git a/src/web/src/components/community/shell/shell-frame-view.tsx b/src/web/src/components/community/shell/shell-frame-view.tsxindex 9bfa4847d..56695f5ad 100644--- a/src/web/src/components/community/shell/shell-frame-view.tsx+++ b/src/web/src/components/community/shell/shell-frame-view.tsx@@ -8,12 +8,17 @@ import { UserBar } from "./user-bar"import { InboxPopover } from "./community-inbox-popover"import { ShellFrameOverlays } from "./shell-frame-overlays"import { CommunityShellLayout } from "./community-shell-layout"+import { ProfileCard } from "../social/profile-card"import type { Breakpoint } from "@/hooks/use-mobile"import type { CommunityCheckpointPlan } from "@/lib/community/community-route"import type { ShellFrameProps } from "./shell-frame-types"import type { useShellRailController } from "./use-shell-rail-controller"import type { useShellProfileController } from "./use-shell-profile-controller"import type { useShellInboxController } from "./use-shell-inbox-controller"+import type { useShellDaemonUpdateController } from "./use-shell-daemon-update-controller"+import type { UserBarExtensionState } from "./user-bar-extension-state"+import { userBarUpdateBadgePhase } from "./user-bar-extension-state"+import type { OpenProfile } from "../social/profile-types"type Props = Pick<ShellFrameProps, "sidebar" | "children" | "extraDialogs"> & {breakpoint: Breakpoint@@ -22,6 +27,12 @@ type Props = Pick<ShellFrameProps, "sidebar" | "children" | "extraDialogs"> & {rail: ReturnType<typeof useShellRailController>profile: ReturnType<typeof useShellProfileController>inbox: ReturnType<typeof useShellInboxController>+ userBarExtension: UserBarExtensionState+ daemonUpdate: ReturnType<typeof useShellDaemonUpdateController>+ onUserBarInboxOpenChange: (open: boolean) => void+ onUserBarOpenProfile: OpenProfile+ onUserBarOpenUpdate: () => void+ dismissUserBarExtension: () => void}export function ShellFrameView({@@ -34,12 +45,18 @@ export function ShellFrameView({rail,profile,inbox,+ userBarExtension,+ daemonUpdate,+ onUserBarInboxOpenChange,+ onUserBarOpenProfile,+ onUserBarOpenUpdate,+ dismissUserBarExtension,}: Props) {const { surface } = checkpointconst inboxElement = (<InboxPopover{...inbox.popoverProps}- surface={breakpoint === "mobile" ? "mobile" : "desktop"}+ surface="extension"/>)const user = {@@ -48,6 +65,23 @@ export function ShellFrameView({avatar: profile.currentUser.avatar,}const isInitial = breakpoint === "unknown"+ const profileInExtension = userBarExtension.active === "profile"+ && profile.profile?.data.userId === profile.currentUser.id+ const profileElement = profileInExtension && profile.profile ? (+ <ProfileCard+ data={profile.profile.data}+ x={profile.profile.x}+ y={profile.profile.y}+ bp={breakpoint}+ onClose={profile.closeProfile}+ onMessage={profile.profileMessage}+ isSelf+ onUpdateStatus={profile.updateOwnStatus}+ onOpenOwnerProfile={profile.openOwnerProfile}+ onOpenBotAudit={profile.openBotAudit}+ extension+ />+ ) : nullreturn (<CommunityShellLayout@@ -71,12 +105,23 @@ export function ShellFrameView({<UserBarbreakpoint={breakpoint}user={user}- onOpenProfile={profile.openProfile}+ onOpenProfile={onUserBarOpenProfile}onEditProfile={profile.openUserSettings}inbox={inboxElement}hasUnread={inbox.hasUnread}- inboxOpen={inbox.open}- onInboxOpenChange={inbox.onOpenChange}+ inboxOpen={userBarExtension.active === "inbox"}+ onInboxOpenChange={onUserBarInboxOpenChange}+ extension={{+ active: userBarExtension.active,+ inbox: inboxElement,+ profile: profileElement,+ update: daemonUpdate.update,+ updateBadgePhase: userBarUpdateBadgePhase(userBarExtension),+ eligibleMachines: daemonUpdate.eligibleMachines,+ onOpenUpdate: onUserBarOpenUpdate,+ onRequestUpdate: daemonUpdate.request,+ onDismiss: dismissUserBarExtension,+ }}/>)}overlays={!isInitial && (@@ -84,6 +129,7 @@ export function ShellFrameView({controller={profile}breakpoint={breakpoint}extraDialogs={extraDialogs}+ suppressProfileCard={profileInExtension}/>)}/>diff --git a/src/web/src/components/community/shell/shell-frame.dom.test.ts b/src/web/src/components/community/shell/shell-frame.dom.test.tsindex 81920b8cd..f69e02bce 100644--- a/src/web/src/components/community/shell/shell-frame.dom.test.ts+++ b/src/web/src/components/community/shell/shell-frame.dom.test.ts@@ -36,6 +36,13 @@ const mocks = vi.hoisted(() => {openProfile: handlers.openProfile,},inbox: {},+ daemonUpdate: {+ update: null,+ eligibleMachines: [],+ collapse: vi.fn(),+ open: vi.fn(),+ request: vi.fn(),+ },viewProps: { current: {} as Record<string, unknown> },}})@@ -92,6 +99,9 @@ vi.mock("./use-shell-inbox-controller", () => ({return mocks.inbox},}))+vi.mock("./use-shell-daemon-update-controller", () => ({+ useShellDaemonUpdateController: () => mocks.daemonUpdate,+}))vi.mock("./shell-frame-view", () => ({ShellFrameView: (props: Record<string, unknown>) => {mocks.viewProps.current = propsdiff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsxindex 8f3fcbd6a..b35964b79 100644--- a/src/web/src/components/community/shell/shell-frame.tsx+++ b/src/web/src/components/community/shell/shell-frame.tsx@@ -1,6 +1,6 @@"use client"-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"+import { useCallback, useEffect, useLayoutEffect, useReducer, useRef, useState } from "react"import { useQueryClient } from "@tanstack/react-query"import { useBreakpoint } from "@/hooks/use-mobile"import { useCommunityOnboarding } from "@/lib/community-onboarding"@@ -22,6 +22,11 @@ import { useShellInboxController } from "./use-shell-inbox-controller"import { useCommunityNavigationController } from "./use-community-navigation-controller"import type { ShellFrameProps } from "./shell-frame-types"import { useStructuralSnapshot } from "@/hooks/community/use-structural-snapshot"+import {+ initialUserBarExtensionState,+ userBarExtensionReducer,+} from "./user-bar-extension-state"+import { useShellDaemonUpdateController } from "./use-shell-daemon-update-controller"/** Shared community shell orchestration for the server and DM layouts. */export function ShellFrame(props: ShellFrameProps) {@@ -117,10 +122,72 @@ export function ShellFrame(props: ShellFrameProps) {viewerId: currentUser.id,accessEpoch,})+ const [userBarExtension, dispatchUserBarExtension] = useReducer(+ userBarExtensionReducer,+ initialUserBarExtensionState,+ )+ const daemonUpdate = useShellDaemonUpdateController({+ userId: currentUser.id,+ extensionState: userBarExtension,+ dispatch: dispatchUserBarExtension,+ })+ const onUserBarInboxOpenChange = useCallback((open: boolean) => {+ if (!open) {+ inbox.onOpenChange(false)+ dispatchUserBarExtension({ type: "extension.close", extension: "inbox" })+ return+ }+ if (userBarExtension.active === "profile") profile.closeProfile()+ if (userBarExtension.active === "update") daemonUpdate.collapse()+ inbox.onOpenChange(true)+ dispatchUserBarExtension({ type: "extension.open", extension: "inbox" })+ }, [daemonUpdate, inbox, profile, userBarExtension.active])+ const onUserBarOpenProfile = useCallback<ReturnType<typeof useShellProfileController>["openProfile"]>((+ name,+ event,+ discriminator,+ targetUserId,+ ) => {+ if (userBarExtension.active === "profile") {+ profile.closeProfile()+ dispatchUserBarExtension({ type: "extension.close", extension: "profile" })+ return+ }+ if (userBarExtension.active === "inbox") inbox.onOpenChange(false)+ if (userBarExtension.active === "update") daemonUpdate.collapse()+ profile.openProfile(name, event, discriminator, targetUserId)+ dispatchUserBarExtension({ type: "extension.open", extension: "profile" })+ }, [daemonUpdate, inbox, profile, userBarExtension.active])+ const onUserBarOpenUpdate = useCallback(() => {+ if (userBarExtension.active === "inbox") inbox.onOpenChange(false)+ if (userBarExtension.active === "profile") profile.closeProfile()+ daemonUpdate.open()+ }, [daemonUpdate, inbox, profile, userBarExtension.active])+ const dismissUserBarExtension = useCallback(() => {+ if (userBarExtension.active === "inbox") inbox.onOpenChange(false)+ if (userBarExtension.active === "profile") profile.closeProfile()+ if (userBarExtension.active === "update") daemonUpdate.collapse()+ dispatchUserBarExtension({+ type: "extension.close",+ extension: userBarExtension.active,+ })+ }, [daemonUpdate, inbox, profile, userBarExtension.active])const goBackMobile = useCallback(() => {if (route.parentPath) navigation.replace(route.parentPath)}, [navigation, route.parentPath])+ useEffect(() => {+ if (userBarExtension.active === "inbox" && !inbox.open) {+ dispatchUserBarExtension({ type: "extension.close", extension: "inbox" })+ }+ }, [inbox.open, userBarExtension.active])++ useEffect(() => {+ if (userBarExtension.active !== "profile") return+ if (profile.profile?.data.userId === currentUser.id) return+ dispatchUserBarExtension({ type: "extension.close", extension: "profile" })+ }, [currentUser.id, profile.profile, userBarExtension.active])+useEffect(() => {if (breakpoint !== "mobile" ||@@ -164,6 +231,12 @@ export function ShellFrame(props: ShellFrameProps) {rail={rail}profile={profile}inbox={inbox}+ userBarExtension={userBarExtension}+ daemonUpdate={daemonUpdate}+ onUserBarInboxOpenChange={onUserBarInboxOpenChange}+ onUserBarOpenProfile={onUserBarOpenProfile}+ onUserBarOpenUpdate={onUserBarOpenUpdate}+ dismissUserBarExtension={dismissUserBarExtension}>{children}</ShellFrameView>diff --git a/src/web/src/components/community/shell/use-shell-daemon-update-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-daemon-update-controller.dom.test.tsnew file mode 100644index 000000000..e7ea80ec3--- /dev/null+++ b/src/web/src/components/community/shell/use-shell-daemon-update-controller.dom.test.ts@@ -0,0 +1,283 @@+import { createElement, useReducer } from "react"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { act, render as rtlRender } from "@/test/react-dom-harness"+import type { MachineSummary } from "@/hooks/community/use-machines"+import {+ daemonUpdateCollapseStorageKey,+ useShellDaemonUpdateController,+} from "./use-shell-daemon-update-controller"+import {+ initialUserBarExtensionState,+ userBarExtensionReducer,+ type UserBarExtensionState,+} from "./user-bar-extension-state"++const mocks = vi.hoisted(() => ({+ machines: {+ machines: [] as MachineSummary[],+ isSuccess: true,+ },+ warn: vi.fn(),+}))++vi.mock("@/hooks/community/use-machines", () => ({+ useMachines: () => mocks.machines,+}))+vi.mock("@/lib/logger", () => ({+ log: { warn: mocks.warn },+}))++const latestVersion = "0.1.35"++function machine(+ id: string,+ daemonVersion = "0.1.34",+): MachineSummary {+ return {+ id,+ hostname: `${id}.local`,+ displayName: id,+ platform: "darwin",+ arch: "arm64",+ osRelease: "26.0",+ daemonVersion,+ lastSeenAt: null,+ status: "online",+ availableRuntimes: [],+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ }+}++type Controller = ReturnType<typeof useShellDaemonUpdateController>+type Snapshot = { state: UserBarExtensionState; controller: Controller }++function Capture({+ initialState,+ version,+ requestUpdate,+ onResult,+}: {+ initialState: UserBarExtensionState+ version?: string+ requestUpdate?: (machineId: string) => Promise<unknown>+ onResult: (snapshot: Snapshot) => void+}) {+ const [state, dispatch] = useReducer(userBarExtensionReducer, initialState)+ const controller = useShellDaemonUpdateController({+ userId: "user-1",+ extensionState: state,+ dispatch,+ latestDaemonVersion: version,+ requestUpdate,+ })+ onResult({ state, controller })+ return null+}++async function renderController({+ initialState = initialUserBarExtensionState,+ version = latestVersion,+ requestUpdate = vi.fn(async () => {}),+}: {+ initialState?: UserBarExtensionState+ version?: string+ requestUpdate?: (machineId: string) => Promise<unknown>+} = {}) {+ let current!: Snapshot+ let renderer!: ReturnType<typeof rtlRender>+ const element = () => createElement(Capture, {+ initialState,+ version,+ requestUpdate,+ onResult: (snapshot) => { current = snapshot },+ })+ await act(async () => {+ renderer = rtlRender(element())+ })+ return {+ get current() { return current },+ rerender: async () => act(async () => renderer.rerender(element())),+ unmount: () => renderer.unmount(),+ }+}++function activeUpdate(values: Partial<NonNullable<UserBarExtensionState["update"]>> = {}): UserBarExtensionState {+ return {+ active: "update",+ update: {+ phase: "expanded",+ targetMachineIds: ["machine-1"],+ acceptedMachineIds: [],+ failedMachineIds: [],+ pendingMachineIds: [],+ ...values,+ },+ }+}++describe("useShellDaemonUpdateController", () => {+ beforeEach(() => {+ window.localStorage.clear()+ mocks.warn.mockReset()+ mocks.machines = { machines: [], isSuccess: true }+ })++ afterEach(() => {+ vi.restoreAllMocks()+ vi.unstubAllEnvs()+ window.localStorage.clear()+ })++ it("uses the configured production dependencies when optional overrides are omitted", async () => {+ vi.stubEnv("NEXT_PUBLIC_LATEST_DAEMON_VERSION", latestVersion)+ mocks.machines = { machines: [machine("machine-1")], isSuccess: true }+ let current!: Snapshot+ let renderer!: ReturnType<typeof rtlRender>++ await act(async () => {+ renderer = rtlRender(createElement(Capture, {+ initialState: initialUserBarExtensionState,+ onResult: (snapshot) => { current = snapshot },+ }))+ })++ expect(current.state).toMatchObject({+ active: "update",+ update: { phase: "expanded", targetMachineIds: ["machine-1"] },+ })+ renderer.unmount()+ })++ it("restores, opens, collapses, and clears the version-scoped preference from live Machines", async () => {+ const key = daemonUpdateCollapseStorageKey("user-1", latestVersion)+ window.localStorage.setItem(key, "1")+ mocks.machines = { machines: [machine("machine-1")], isSuccess: true }+ const hook = await renderController()++ expect(hook.current.state).toMatchObject({+ active: "none",+ update: { phase: "collapsedBadge", targetMachineIds: ["machine-1"] },+ })+ await act(async () => hook.current.controller.open())+ expect(hook.current.state).toMatchObject({ active: "update", update: { phase: "expanded" } })+ expect(window.localStorage.getItem(key)).toBeNull()++ await act(async () => hook.current.controller.collapse())+ expect(hook.current.state).toMatchObject({ active: "none", update: { phase: "collapsedBadge" } })+ expect(window.localStorage.getItem(key)).toBe("1")++ mocks.machines = { machines: [machine("machine-1", latestVersion)], isSuccess: true }+ await hook.rerender()+ expect(hook.current.state).toEqual(initialUserBarExtensionState)+ expect(window.localStorage.getItem(key)).toBeNull()+ })++ it("waits for a successful Machine snapshot and a valid target version", async () => {+ mocks.machines = { machines: [machine("machine-1")], isSuccess: false }+ const loading = await renderController()+ expect(loading.current.state).toEqual(initialUserBarExtensionState)+ loading.unmount()++ mocks.machines = { machines: [machine("machine-1")], isSuccess: true }+ const missing = await renderController({ version: "" })+ expect(missing.current.controller.eligibleMachines).toEqual([])+ expect(missing.current.state).toEqual(initialUserBarExtensionState)+ missing.unmount()++ const malformed = await renderController({ version: "next" })+ expect(malformed.current.state).toEqual(initialUserBarExtensionState)+ })++ it("keeps accepted requests updating and retries only failed eligible Machines", async () => {+ mocks.machines = {+ machines: [machine("machine-1"), machine("machine-2")],+ isSuccess: true,+ }+ let failSecond = true+ const requestUpdate = vi.fn(async (machineId: string) => {+ if (machineId === "machine-2" && failSecond) {+ failSecond = false+ throw new Error("offline race")+ }+ })+ const hook = await renderController({+ initialState: activeUpdate({ targetMachineIds: ["machine-1", "machine-2"] }),+ requestUpdate,+ })++ await act(async () => hook.current.controller.request())+ expect(hook.current.state.update).toMatchObject({+ phase: "retry",+ acceptedMachineIds: ["machine-1"],+ failedMachineIds: ["machine-2"],+ pendingMachineIds: [],+ })+ expect(mocks.warn).toHaveBeenCalledWith("daemon update request failed", {+ machineId: "machine-2",+ })++ await act(async () => hook.current.controller.request())+ expect(requestUpdate.mock.calls).toEqual([+ ["machine-1"],+ ["machine-2"],+ ["machine-2"],+ ])+ expect(hook.current.state.update).toMatchObject({+ phase: "updating",+ acceptedMachineIds: ["machine-1", "machine-2"],+ failedMachineIds: [],+ pendingMachineIds: [],+ })+ })++ it("does not dispatch without update state, with pending requests, or with no requestable target", async () => {+ const requestUpdate = vi.fn(async () => {})+ mocks.machines = { machines: [], isSuccess: false }+ const absent = await renderController({ requestUpdate })+ await act(async () => {+ absent.current.controller.collapse()+ absent.current.controller.open()+ await absent.current.controller.request()+ })+ expect(requestUpdate).not.toHaveBeenCalled()+ absent.unmount()++ mocks.machines = { machines: [machine("machine-1")], isSuccess: true }+ const pending = await renderController({+ initialState: activeUpdate({ pendingMachineIds: ["machine-1"] }),+ requestUpdate,+ })+ await act(async () => pending.current.controller.request())+ expect(requestUpdate).not.toHaveBeenCalled()+ pending.unmount()++ const accepted = await renderController({+ initialState: activeUpdate({ acceptedMachineIds: ["machine-1"] }),+ requestUpdate,+ })+ await act(async () => accepted.current.controller.request())+ expect(requestUpdate).not.toHaveBeenCalled()+ })++ it("keeps state transitions functional when local storage is unavailable", async () => {+ mocks.machines = { machines: [machine("machine-1")], isSuccess: true }+ vi.spyOn(Storage.prototype, "getItem").mockImplementationOnce(() => {+ throw new Error("storage disabled")+ })+ const hook = await renderController()+ expect(hook.current.state).toMatchObject({ active: "update", update: { phase: "expanded" } })++ vi.spyOn(Storage.prototype, "setItem").mockImplementationOnce(() => {+ throw new Error("storage disabled")+ })+ await act(async () => hook.current.controller.collapse())+ expect(hook.current.state.active).toBe("none")++ vi.spyOn(Storage.prototype, "removeItem").mockImplementationOnce(() => {+ throw new Error("storage disabled")+ })+ await act(async () => hook.current.controller.open())+ expect(hook.current.state.active).toBe("update")+ })+})diff --git a/src/web/src/components/community/shell/use-shell-daemon-update-controller.test.ts b/src/web/src/components/community/shell/use-shell-daemon-update-controller.test.tsnew file mode 100644index 000000000..af1944f9d--- /dev/null+++ b/src/web/src/components/community/shell/use-shell-daemon-update-controller.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it, vi } from "vitest"+import {+ daemonUpdateCollapseStorageKey,+ daemonUpdateRequestMachineIds,+ dispatchMachineUpdateRequests,+} from "./use-shell-daemon-update-controller"+import type { UserBarUpdateState } from "./user-bar-extension-state"++function update(+ values: Partial<UserBarUpdateState> = {},+): UserBarUpdateState {+ return {+ phase: "expanded",+ targetMachineIds: ["accepted", "failed", "pending"],+ acceptedMachineIds: [],+ failedMachineIds: [],+ pendingMachineIds: [],+ ...values,+ }+}++describe("Community daemon update controller helpers", () => {+ it("scopes the collapsed preference by viewer and target daemon version", () => {+ expect(daemonUpdateCollapseStorageKey("user-1", "0.1.35")).toBe(+ "alook:daemon-update-collapsed:user-1:0.1.35",+ )+ })++ it("dispatches every initial target except accepted or pending Machines", () => {+ expect(daemonUpdateRequestMachineIds(update({+ acceptedMachineIds: ["accepted"],+ pendingMachineIds: ["pending"],+ }), ["accepted", "failed", "pending"])).toEqual(["failed"])+ })++ it("retries only failed Machines that remain eligible", () => {+ expect(daemonUpdateRequestMachineIds(update({+ phase: "retry",+ acceptedMachineIds: ["accepted"],+ failedMachineIds: ["failed", "completed"],+ }), ["accepted", "failed"])).toEqual(["failed"])+ })++ it("preserves accepted and failed request outcomes without short-circuiting", async () => {+ const requestUpdate = vi.fn(async (machineId: string) => {+ if (machineId === "failed") throw new Error("offline race")+ })+ await expect(dispatchMachineUpdateRequests(+ ["accepted", "failed", "accepted-2"],+ requestUpdate,+ )).resolves.toEqual({+ acceptedMachineIds: ["accepted", "accepted-2"],+ failedMachineIds: ["failed"],+ })+ expect(requestUpdate.mock.calls).toEqual([+ ["accepted"],+ ["failed"],+ ["accepted-2"],+ ])+ })+})diff --git a/src/web/src/components/community/shell/use-shell-daemon-update-controller.ts b/src/web/src/components/community/shell/use-shell-daemon-update-controller.tsnew file mode 100644index 000000000..203773b0b--- /dev/null+++ b/src/web/src/components/community/shell/use-shell-daemon-update-controller.ts@@ -0,0 +1,158 @@+"use client"++import { useCallback, useEffect, useMemo, type Dispatch } from "react"+import { parseReleaseVersion } from "@alook/shared"+import {+ eligibleDaemonUpdateMachines,+ requestMachineUpdate,+} from "@/components/daemon-update-notice"+import { useMachines } from "@/hooks/community/use-machines"+import { log } from "@/lib/logger"+import type {+ UserBarExtensionAction,+ UserBarExtensionState,+ UserBarUpdateState,+} from "./user-bar-extension-state"++const STORAGE_KEY_PREFIX = "alook:daemon-update-collapsed"++export function daemonUpdateCollapseStorageKey(+ userId: string,+ latestDaemonVersion: string,+): string {+ return `${STORAGE_KEY_PREFIX}:${userId}:${latestDaemonVersion}`+}++function readCollapsed(userId: string, latestDaemonVersion: string): boolean {+ try {+ return window.localStorage.getItem(+ daemonUpdateCollapseStorageKey(userId, latestDaemonVersion),+ ) === "1"+ } catch {+ return false+ }+}++function writeCollapsed(+ userId: string,+ latestDaemonVersion: string,+ collapsed: boolean,+): void {+ try {+ const key = daemonUpdateCollapseStorageKey(userId, latestDaemonVersion)+ if (collapsed) window.localStorage.setItem(key, "1")+ else window.localStorage.removeItem(key)+ } catch {}+}++export function daemonUpdateRequestMachineIds(+ update: UserBarUpdateState,+ eligibleMachineIds: readonly string[],+): string[] {+ const eligible = new Set(eligibleMachineIds)+ if (update.phase === "retry") {+ return update.failedMachineIds.filter((machineId) => eligible.has(machineId))+ }+ const accepted = new Set(update.acceptedMachineIds)+ const pending = new Set(update.pendingMachineIds)+ return update.targetMachineIds.filter((machineId) => (+ eligible.has(machineId) && !accepted.has(machineId) && !pending.has(machineId)+ ))+}++export async function dispatchMachineUpdateRequests(+ machineIds: readonly string[],+ requestUpdate: (machineId: string) => Promise<unknown>,+): Promise<{ acceptedMachineIds: string[]; failedMachineIds: string[] }> {+ const results = await Promise.allSettled(machineIds.map(async (machineId) => {+ await requestUpdate(machineId)+ return machineId+ }))+ const acceptedMachineIds: string[] = []+ const failedMachineIds: string[] = []+ results.forEach((result, index) => {+ const machineId = machineIds[index]!+ if (result.status === "fulfilled") acceptedMachineIds.push(machineId)+ else failedMachineIds.push(machineId)+ })+ return { acceptedMachineIds, failedMachineIds }+}++export function useShellDaemonUpdateController({+ userId,+ extensionState,+ dispatch,+ latestDaemonVersion = process.env.NEXT_PUBLIC_LATEST_DAEMON_VERSION,+ requestUpdate = requestMachineUpdate,+}: {+ userId: string+ extensionState: UserBarExtensionState+ dispatch: Dispatch<UserBarExtensionAction>+ latestDaemonVersion?: string+ requestUpdate?: (machineId: string) => Promise<unknown>+}) {+ const machines = useMachines()+ const eligibleMachines = useMemo(() => (+ latestDaemonVersion+ ? eligibleDaemonUpdateMachines(machines.machines, latestDaemonVersion)+ : []+ ), [latestDaemonVersion, machines.machines])+ const eligibleMachineIds = useMemo(+ () => eligibleMachines.map((machine) => machine.id),+ [eligibleMachines],+ )+ const update = extensionState.update++ useEffect(() => {+ if (!latestDaemonVersion || !parseReleaseVersion(latestDaemonVersion)) return+ if (!machines.isSuccess) return+ if (eligibleMachineIds.length === 0) {+ writeCollapsed(userId, latestDaemonVersion, false)+ dispatch({ type: "update.clear" })+ return+ }+ if (!update) {+ dispatch({+ type: "update.sync",+ collapsed: readCollapsed(userId, latestDaemonVersion),+ eligibleMachineIds,+ })+ return+ }+ dispatch({ type: "update.eligibility", eligibleMachineIds })+ }, [dispatch, eligibleMachineIds, latestDaemonVersion, machines.isSuccess, update, userId])++ const collapse = useCallback(() => {+ if (!latestDaemonVersion || !extensionState.update) return+ writeCollapsed(userId, latestDaemonVersion, true)+ dispatch({ type: "update.collapse" })+ }, [dispatch, extensionState.update, latestDaemonVersion, userId])++ const open = useCallback(() => {+ if (!latestDaemonVersion || !extensionState.update) return+ writeCollapsed(userId, latestDaemonVersion, false)+ dispatch({ type: "update.open" })+ }, [dispatch, extensionState.update, latestDaemonVersion, userId])++ const request = useCallback(async () => {+ const current = extensionState.update+ if (!current || current.pendingMachineIds.length > 0) return+ const machineIds = daemonUpdateRequestMachineIds(current, eligibleMachineIds)+ if (machineIds.length === 0) return+ dispatch({ type: "update.dispatch", machineIds })+ const result = await dispatchMachineUpdateRequests(machineIds, requestUpdate)+ for (const machineId of result.failedMachineIds) {+ log.warn("daemon update request failed", { machineId })+ }+ dispatch({ type: "update.settle", ...result })+ }, [dispatch, eligibleMachineIds, extensionState.update, requestUpdate])++ return {+ eligibleMachines,+ eligibleMachineIds,+ update,+ collapse,+ open,+ request,+ }+}diff --git a/src/web/src/components/community/shell/user-bar-extension-slot.dom.test.tsx b/src/web/src/components/community/shell/user-bar-extension-slot.dom.test.tsxnew file mode 100644index 000000000..bb6a86bc1--- /dev/null+++ b/src/web/src/components/community/shell/user-bar-extension-slot.dom.test.tsx@@ -0,0 +1,186 @@+import { createElement } from "react"+import { describe, expect, it, vi } from "vitest"+import { act, render } from "@/test/react-dom-harness"+import { tid } from "@/lib/community/testids"+import { UserBarExtensionSlot } from "./user-bar-extension-slot"+import type { UserBarUpdateState } from "./user-bar-extension-state"++function update(+ values: Partial<UserBarUpdateState> = {},+): UserBarUpdateState {+ return {+ phase: "expanded",+ targetMachineIds: ["machine-1"],+ acceptedMachineIds: [],+ failedMachineIds: [],+ pendingMachineIds: [],+ ...values,+ }+}++const machines = [{+ id: "machine-1",+ hostname: "studio-mac",+ displayName: "Studio Mac",+ platform: "darwin",+ arch: "arm64",+ osRelease: "26.0",+ daemonVersion: "0.1.34",+ lastSeenAt: null,+ status: "online" as const,+ availableRuntimes: [],+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+}]++describe("UserBarExtensionSlot", () => {+ it("renders only the active Inbox occupant in the bounded joined surface", () => {+ const renderer = render(createElement(UserBarExtensionSlot, {+ active: "inbox",+ inbox: createElement("div", { "data-testid": "inbox-content" }, "Inbox content"),+ profile: createElement("div", { "data-testid": "profile-content" }),+ update: update(),+ eligibleMachines: machines,+ onDismiss: vi.fn(),+ onRequestUpdate: vi.fn(),+ }))++ const slot = renderer.getByTestId(tid.userBarExtension)+ expect(slot).toHaveAttribute("role", "dialog")+ expect(slot).toHaveAttribute("aria-modal", "false")+ expect(slot).toHaveAttribute("data-extension", "inbox")+ expect(slot.className).toContain("rounded-t-xl")+ expect(slot.className).toContain("shadow-(--e2)")+ expect(slot.className).toContain("[clip-path:inset(-2rem_-2rem_0)]")+ expect(slot.className).not.toContain("shadow-none")+ expect(slot.style.height).toContain("100dvh")+ expect(renderer.getByTestId("inbox-content")).toBeInTheDocument()+ expect(renderer.queryByTestId("profile-content")).not.toBeInTheDocument()+ expect(renderer.queryByTestId(tid.daemonUpdateNotice)).not.toBeInTheDocument()+ expect(renderer.queryByRole("button", { name: "Dismiss Inbox" })).not.toBeInTheDocument()+ })++ it.each([+ [["machine-1"], "You can update your machine to get more features."],+ [["machine-1", "machine-2"], "You can update your machines to get more features."],+ ])("restores the exact initial Update copy for %d eligible Machines", (targetMachineIds, description) => {+ const renderer = render(createElement(UserBarExtensionSlot, {+ active: "update",+ update: update({ targetMachineIds }),+ eligibleMachines: machines,+ onDismiss: vi.fn(),+ onRequestUpdate: vi.fn(),+ }))++ expect(renderer.getByText("Machine update available")).toBeInTheDocument()+ expect(renderer.getByText(description)).toBeInTheDocument()+ expect(renderer.queryByRole("button", { name: "Dismiss Machine update" })).not.toBeInTheDocument()+ })++ it("keeps accepted machines in Updating until live eligibility clears", () => {+ const renderer = render(createElement(UserBarExtensionSlot, {+ active: "update",+ update: update({ phase: "updating", acceptedMachineIds: ["machine-1"] }),+ eligibleMachines: machines,+ onDismiss: vi.fn(),+ onRequestUpdate: vi.fn(),+ }))++ expect(renderer.getByText("Updating machines")).toBeInTheDocument()+ expect(renderer.getByText(/disappear when they report the new version/)).toBeInTheDocument()+ expect(renderer.queryByTestId(tid.daemonUpdateAction)).not.toBeInTheDocument()+ })++ it("shows Updating and a failure-only Retry together after a partial dispatch", async () => {+ const onRequestUpdate = vi.fn()+ const renderer = render(createElement(UserBarExtensionSlot, {+ active: "update",+ update: update({+ phase: "retry",+ targetMachineIds: ["machine-1", "machine-2"],+ acceptedMachineIds: ["machine-1"],+ failedMachineIds: ["machine-2"],+ }),+ eligibleMachines: machines,+ onDismiss: vi.fn(),+ onRequestUpdate,+ }))++ expect(renderer.getByText("1 machine is updating. 1 update request failed.")).toBeInTheDocument()+ const action = renderer.getByTestId(tid.daemonUpdateAction)+ expect(action).toHaveTextContent("Retry")+ await act(async () => action.click())+ expect(onRequestUpdate).toHaveBeenCalledOnce()+ })++ it("dismisses on Escape and a blank outside click but leaves User Bar switching atomic", async () => {+ const onDismiss = vi.fn()+ const onDismissOutside = vi.fn()+ const userBar = document.createElement("div")+ userBar.dataset.testid = tid.userBar+ const switchButton = document.createElement("button")+ userBar.appendChild(switchButton)+ document.body.appendChild(userBar)+ const renderer = render(createElement(UserBarExtensionSlot, {+ active: "profile",+ profile: createElement("div", null, "Profile"),+ update: update(),+ eligibleMachines: machines,+ onDismiss,+ onDismissOutside,+ onRequestUpdate: vi.fn(),+ }))++ await act(async () => switchButton.click())+ expect(onDismiss).not.toHaveBeenCalled()+ expect(onDismissOutside).not.toHaveBeenCalled()+ await act(async () => document.body.click())+ expect(onDismiss).toHaveBeenCalledOnce()+ expect(onDismissOutside).not.toHaveBeenCalled()+ await act(async () => document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })))+ expect(onDismiss).toHaveBeenCalledTimes(2)++ renderer.unmount()+ userBar.remove()+ })++ it("lets an outside control complete its click before dismissing", async () => {+ const order: string[] = []+ const outsideButton = document.createElement("button")+ outsideButton.addEventListener("click", () => order.push("outside action"))+ document.body.appendChild(outsideButton)+ const renderer = render(createElement(UserBarExtensionSlot, {+ active: "update",+ update: update(),+ eligibleMachines: machines,+ onDismiss: () => order.push("focus-return dismiss"),+ onDismissOutside: () => order.push("outside dismiss"),+ onRequestUpdate: vi.fn(),+ }))++ await act(async () => outsideButton.click())+ expect(order).toEqual(["outside action", "outside dismiss"])++ renderer.unmount()+ outsideButton.remove()+ })++ it("moves focus into the dialog only for an explicit open request", () => {+ const onInitialFocus = vi.fn()+ const renderer = render(createElement(UserBarExtensionSlot, {+ active: "inbox",+ inbox: createElement("button", null, "Inbox action"),+ update: update(),+ eligibleMachines: machines,+ onDismiss: vi.fn(),+ onRequestUpdate: vi.fn(),+ focusOnOpen: true,+ onInitialFocus,+ }))++ const slot = renderer.getByTestId(tid.userBarExtension)+ expect(slot).toHaveAttribute("tabindex", "-1")+ expect(slot).toHaveFocus()+ expect(onInitialFocus).toHaveBeenCalledOnce()+ })+})diff --git a/src/web/src/components/community/shell/user-bar-extension-slot.tsx b/src/web/src/components/community/shell/user-bar-extension-slot.tsxnew file mode 100644index 000000000..fa2c0a015--- /dev/null+++ b/src/web/src/components/community/shell/user-bar-extension-slot.tsx@@ -0,0 +1,197 @@+"use client"++import { useEffect, useRef, type ReactNode } from "react"+import { CircleAlert, Download, LoaderCircle } from "lucide-react"+import { Button } from "@/components/ui/button"+import type { MachineSummary } from "@/hooks/community/use-machines"+import { tid } from "@/lib/community/testids"+import { cn } from "@/lib/utils"+import { COMMUNITY_USER_BAR_HEIGHT_CSS } from "./shell-frame-geometry"+import type {+ UserBarExtensionKind,+ UserBarUpdateState,+} from "./user-bar-extension-state"++const EXTERNAL_INTERACTIVE_SELECTOR = [+ "button:not(:disabled)",+ "a[href]",+ "input:not(:disabled)",+ "select:not(:disabled)",+ "textarea:not(:disabled)",+ "[contenteditable='true']",+ "[role='button']",+ "[role='link']",+ "[tabindex]:not([tabindex='-1'])",+].join(",")++type Props = {+ active: Exclude<UserBarExtensionKind, "none">+ inbox?: ReactNode+ profile?: ReactNode+ update: UserBarUpdateState | null+ eligibleMachines: readonly MachineSummary[]+ onDismiss: () => void+ onDismissOutside?: () => void+ onRequestUpdate: () => void+ focusOnOpen?: boolean+ onInitialFocus?: () => void+}++export function UserBarExtensionSlot({+ active,+ inbox,+ profile,+ update,+ eligibleMachines,+ onDismiss,+ onDismissOutside = onDismiss,+ onRequestUpdate,+ focusOnOpen = false,+ onInitialFocus,+}: Props) {+ const ref = useRef<HTMLDivElement>(null)++ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key !== "Escape") return+ event.preventDefault()+ onDismiss()+ }+ const onClick = (event: MouseEvent) => {+ if (!(event.target instanceof Element)) return+ if (ref.current?.contains(event.target)) return+ if (event.target.closest(`[data-testid='${tid.userBar}']`)) return+ if (event.target.closest(EXTERNAL_INTERACTIVE_SELECTOR)) onDismissOutside()+ else onDismiss()+ }+ document.addEventListener("keydown", onKeyDown)+ document.addEventListener("click", onClick)+ return () => {+ document.removeEventListener("keydown", onKeyDown)+ document.removeEventListener("click", onClick)+ }+ }, [onDismiss, onDismissOutside])++ useEffect(() => {+ if (!focusOnOpen) return+ ref.current?.focus()+ onInitialFocus?.()+ }, [active, focusOnOpen, onInitialFocus])++ const title = active === "inbox"+ ? "Inbox"+ : active === "profile"+ ? "Your profile"+ : "Machine update"++ return (+ <div+ ref={ref}+ id="community-user-bar-extension"+ role="dialog"+ aria-modal="false"+ aria-label={title}+ data-testid={tid.userBarExtension}+ data-extension={active}+ tabIndex={-1}+ className={cn(+ "relative min-h-0 origin-bottom overflow-hidden rounded-t-xl border border-b-0 border-border bg-popover text-popover-foreground shadow-(--e2) [clip-path:inset(-2rem_-2rem_0)]",+ "motion-safe:animate-in motion-safe:fade-in motion-safe:slide-in-from-bottom-1 motion-safe:duration-150",+ active === "inbox" && "flex flex-col",+ )}+ style={{+ maxHeight: `min(28rem, max(0px, calc(100dvh - ${COMMUNITY_USER_BAR_HEIGHT_CSS} - var(--app-safe-area-top))))`,+ height: active === "inbox"+ ? `min(28rem, max(0px, calc(100dvh - ${COMMUNITY_USER_BAR_HEIGHT_CSS} - var(--app-safe-area-top))))`+ : undefined,+ }}+ >+ {active === "inbox" && inbox}+ {active === "profile" && (+ <div className="overflow-y-auto thin-scrollbar p-2">{profile}</div>+ )}+ {active === "update" && update && (+ <DaemonUpdateExtension+ update={update}+ eligibleMachines={eligibleMachines}+ onRequestUpdate={onRequestUpdate}+ />+ )}+ </div>+ )+}++function DaemonUpdateExtension({+ update,+ eligibleMachines,+ onRequestUpdate,+}: {+ update: UserBarUpdateState+ eligibleMachines: readonly MachineSummary[]+ onRequestUpdate: () => void+}) {+ const accepted = new Set(update.acceptedMachineIds)+ const pending = new Set(update.pendingMachineIds)+ const updatingCount = update.targetMachineIds.filter((machineId) => (+ accepted.has(machineId) || pending.has(machineId)+ )).length+ const retryCount = update.failedMachineIds.length+ const initialCount = update.targetMachineIds.length+ const activeCount = updatingCount || initialCount+ const unavailable = new Set([+ ...update.acceptedMachineIds,+ ...update.failedMachineIds,+ ...update.pendingMachineIds,+ ])+ const availableCount = update.targetMachineIds.filter((machineId) => (+ !unavailable.has(machineId)+ )).length+ const updating = update.phase === "updating" || update.pendingMachineIds.length > 0+ const retry = update.phase === "retry"+ const description = retry+ ? updatingCount > 0+ ? `${updatingCount} ${updatingCount === 1 ? "machine is" : "machines are"} updating. ${retryCount} update ${retryCount === 1 ? "request" : "requests"} failed.`+ : `${retryCount} update ${retryCount === 1 ? "request" : "requests"} failed.`+ : updating+ ? availableCount > 0+ ? `${updatingCount} ${updatingCount === 1 ? "machine is" : "machines are"} updating. ${availableCount} ${availableCount === 1 ? "machine is" : "machines are"} ready to update.`+ : `${activeCount} ${activeCount === 1 ? "machine is" : "machines are"} updating. This will disappear when they report the new version.`+ : initialCount === 1+ ? "You can update your machine to get more features."+ : "You can update your machines to get more features."+ const Icon = retry ? CircleAlert : updating ? LoaderCircle : Download++ return (+ <div data-testid={tid.daemonUpdateNotice} className="flex min-h-36 flex-col justify-between gap-5 p-5">+ <div className="flex items-start gap-3">+ <div className="grid size-9 shrink-0 place-items-center rounded-lg bg-secondary text-secondary-foreground">+ <Icon+ className={cn("size-4", updating && "animate-spin motion-reduce:animate-none")}+ aria-hidden+ />+ </div>+ <div className="min-w-0">+ <h2 className="font-semibold">+ {retry ? "Machine update needs attention" : updating ? "Updating machines" : "Machine update available"}+ </h2>+ <p className="mt-1 text-sm text-muted-foreground">{description}</p>+ {eligibleMachines.length > 0 && (+ <p className="mt-2 truncate text-xs text-muted-foreground">+ {eligibleMachines.map((machine) => machine.displayName || machine.hostname).join(", ")}+ </p>+ )}+ </div>+ </div>+ {(!updating || retry || availableCount > 0) && (+ <Button+ type="button"+ data-testid={tid.daemonUpdateAction}+ className="min-h-11 self-end sm:min-h-9"+ onClick={onRequestUpdate}+ >+ {retry ? "Retry" : "Update"}+ </Button>+ )}+ </div>+ )+}diff --git a/src/web/src/components/community/shell/user-bar-extension-state.test.ts b/src/web/src/components/community/shell/user-bar-extension-state.test.tsnew file mode 100644index 000000000..bfad838f2--- /dev/null+++ b/src/web/src/components/community/shell/user-bar-extension-state.test.ts@@ -0,0 +1,285 @@+import { describe, expect, it } from "vitest"+import {+ initialUserBarExtensionState,+ userBarExtensionReducer,+ userBarUpdateBadgePhase,+ type UserBarExtensionAction,+ type UserBarExtensionState,+} from "./user-bar-extension-state"++function reduce(+ actions: UserBarExtensionAction[],+ initial: UserBarExtensionState = initialUserBarExtensionState,+) {+ return actions.reduce(userBarExtensionReducer, initial)+}++describe("userBarExtensionReducer", () => {+ it("opens the first eligible update or restores its persisted badge", () => {+ const expanded = reduce([{+ type: "update.sync",+ collapsed: false,+ eligibleMachineIds: ["m1", "m2"],+ }])+ expect(expanded).toEqual({+ active: "update",+ update: {+ phase: "expanded",+ targetMachineIds: ["m1", "m2"],+ acceptedMachineIds: [],+ failedMachineIds: [],+ pendingMachineIds: [],+ },+ })+ expect(userBarUpdateBadgePhase(expanded)).toBeNull()+ expect(reduce([{+ type: "update.sync",+ collapsed: true,+ eligibleMachineIds: ["m1"],+ }])).toEqual({+ active: "none",+ update: {+ phase: "collapsedBadge",+ targetMachineIds: ["m1"],+ acceptedMachineIds: [],+ failedMachineIds: [],+ pendingMachineIds: [],+ },+ })+ })++ it.each(["inbox", "profile"] as const)(+ "lets %s take the slot and collapses an expanded update",+ (extension) => {+ const state = reduce([+ { type: "update.sync", collapsed: false, eligibleMachineIds: ["m1"] },+ { type: "extension.open", extension },+ ])+ expect(state.active).toBe(extension)+ expect(state.update?.phase).toBe("collapsedBadge")+ expect(userBarUpdateBadgePhase(state)).toBe("collapsedBadge")+ },+ )++ it("does not let a late availability sync steal the active Inbox slot", () => {+ const inbox = reduce([{ type: "extension.open", extension: "inbox" }])+ expect(userBarExtensionReducer(inbox, {+ type: "update.sync",+ collapsed: false,+ eligibleMachineIds: ["m1"],+ })).toMatchObject({+ active: "inbox",+ update: { phase: "collapsedBadge", targetMachineIds: ["m1"] },+ })+ })++ it("restores the update from its badge without losing truthful progress", () => {+ const updating = reduce([+ { type: "update.sync", collapsed: false, eligibleMachineIds: ["m1"] },+ { type: "update.dispatch", machineIds: ["m1"] },+ {+ type: "update.settle",+ acceptedMachineIds: ["m1"],+ failedMachineIds: [],+ },+ { type: "update.collapse" },+ ])+ expect(updating.active).toBe("none")+ expect(updating.update).toMatchObject({+ phase: "updating",+ acceptedMachineIds: ["m1"],+ failedMachineIds: [],+ })+ expect(userBarUpdateBadgePhase(updating)).toBe("updating")+ expect(userBarExtensionReducer(updating, { type: "update.open" })).toMatchObject({+ active: "update",+ update: { phase: "updating", acceptedMachineIds: ["m1"] },+ })+ })++ it("keeps accepted and failed outcomes separate for a failure-only retry", () => {+ const retry = reduce([+ {+ type: "update.sync",+ collapsed: false,+ eligibleMachineIds: ["accepted", "failed"],+ },+ { type: "update.dispatch", machineIds: ["accepted", "failed"] },+ {+ type: "update.settle",+ acceptedMachineIds: ["accepted"],+ failedMachineIds: ["failed"],+ },+ ])+ expect(retry).toMatchObject({+ active: "update",+ update: {+ phase: "retry",+ acceptedMachineIds: ["accepted"],+ failedMachineIds: ["failed"],+ pendingMachineIds: [],+ },+ })+ const retrying = userBarExtensionReducer(retry, {+ type: "update.dispatch",+ machineIds: ["failed"],+ })+ expect(retrying.update).toMatchObject({+ phase: "updating",+ acceptedMachineIds: ["accepted"],+ failedMachineIds: [],+ pendingMachineIds: ["failed"],+ })+ })++ it("does not reclaim the slot when a request settles after an Inbox takeover", () => {+ const inbox = reduce([+ { type: "update.sync", collapsed: false, eligibleMachineIds: ["m1"] },+ { type: "update.dispatch", machineIds: ["m1"] },+ { type: "extension.open", extension: "inbox" },+ ])++ expect(userBarExtensionReducer(inbox, {+ type: "update.settle",+ acceptedMachineIds: ["m1"],+ failedMachineIds: [],+ })).toMatchObject({+ active: "inbox",+ update: { phase: "updating", acceptedMachineIds: ["m1"] },+ })+ })++ it("prunes completed Machines and clears only when no target remains eligible", () => {+ const retry = reduce([+ {+ type: "update.sync",+ collapsed: false,+ eligibleMachineIds: ["accepted", "failed"],+ },+ { type: "update.dispatch", machineIds: ["accepted", "failed"] },+ {+ type: "update.settle",+ acceptedMachineIds: ["accepted"],+ failedMachineIds: ["failed"],+ },+ ])+ const failedOnly = userBarExtensionReducer(retry, {+ type: "update.eligibility",+ eligibleMachineIds: ["failed"],+ })+ expect(failedOnly.update).toMatchObject({+ phase: "retry",+ targetMachineIds: ["failed"],+ acceptedMachineIds: [],+ failedMachineIds: ["failed"],+ })+ expect(userBarExtensionReducer(failedOnly, {+ type: "update.eligibility",+ eligibleMachineIds: [],+ })).toEqual(initialUserBarExtensionState)+ })++ it("adds newly eligible Machines without losing accepted outcomes", () => {+ const state = reduce([+ { type: "update.sync", collapsed: false, eligibleMachineIds: ["a"] },+ { type: "update.dispatch", machineIds: ["a"] },+ { type: "update.settle", acceptedMachineIds: ["a"], failedMachineIds: [] },+ { type: "update.eligibility", eligibleMachineIds: ["a", "b"] },+ ])++ expect(state.update).toMatchObject({+ phase: "updating",+ targetMachineIds: ["a", "b"],+ acceptedMachineIds: ["a"],+ })+ })++ it("clears the active update when eligibility ends", () => {+ const active = reduce([{+ type: "update.sync",+ collapsed: false,+ eligibleMachineIds: ["m1"],+ }])+ expect(userBarExtensionReducer(active, { type: "update.clear" })).toEqual(+ initialUserBarExtensionState,+ )+ })++ it("ignores stale close events and duplicate eligibility syncs", () => {+ const profile = reduce([+ { type: "update.sync", collapsed: false, eligibleMachineIds: ["m1"] },+ { type: "extension.open", extension: "profile" },+ ])+ expect(userBarExtensionReducer(profile, {+ type: "extension.close",+ extension: "inbox",+ })).toBe(profile)+ expect(userBarExtensionReducer(profile, {+ type: "update.sync",+ collapsed: false,+ eligibleMachineIds: ["m1"],+ })).toBe(profile)+ })++ it("ignores update-only actions before update state exists", () => {+ expect(userBarExtensionReducer(initialUserBarExtensionState, {+ type: "update.eligibility",+ eligibleMachineIds: ["stale"],+ })).toBe(initialUserBarExtensionState)+ expect(userBarExtensionReducer(initialUserBarExtensionState, {+ type: "update.sync",+ collapsed: false,+ eligibleMachineIds: [],+ })).toBe(initialUserBarExtensionState)+ expect(userBarExtensionReducer(initialUserBarExtensionState, {+ type: "update.open",+ })).toBe(initialUserBarExtensionState)+ expect(userBarExtensionReducer(initialUserBarExtensionState, {+ type: "update.dispatch",+ machineIds: ["stale"],+ })).toBe(initialUserBarExtensionState)+ expect(userBarExtensionReducer(initialUserBarExtensionState, {+ type: "update.settle",+ acceptedMachineIds: ["stale"],+ failedMachineIds: [],+ })).toBe(initialUserBarExtensionState)+ expect(userBarExtensionReducer(initialUserBarExtensionState, {+ type: "update.collapse",+ })).toBe(initialUserBarExtensionState)+ })++ it("closes the requested non-update extension without update state", () => {+ expect(userBarExtensionReducer({ active: "inbox", update: null }, {+ type: "extension.close",+ extension: "inbox",+ })).toEqual(initialUserBarExtensionState)+ })++ it.each(["inbox", "profile"] as const)(+ "closes active %s and collapses an expanded update",+ (extension) => {+ const update: NonNullable<UserBarExtensionState["update"]> = {+ phase: "expanded",+ targetMachineIds: ["m1"],+ acceptedMachineIds: [],+ failedMachineIds: [],+ pendingMachineIds: [],+ }+ const state: UserBarExtensionState = {+ active: extension,+ update,+ }++ expect(userBarExtensionReducer(state, {+ type: "extension.close",+ extension,+ })).toEqual({+ active: "none",+ update: {+ ...update,+ phase: "collapsedBadge",+ },+ })+ },+ )+})diff --git a/src/web/src/components/community/shell/user-bar-extension-state.ts b/src/web/src/components/community/shell/user-bar-extension-state.tsnew file mode 100644index 000000000..ce3cfff35--- /dev/null+++ b/src/web/src/components/community/shell/user-bar-extension-state.ts@@ -0,0 +1,225 @@+export type UserBarExtensionKind = "none" | "inbox" | "update" | "profile"++export type UserBarUpdatePhase =+ | "expanded"+ | "collapsedBadge"+ | "updating"+ | "retry"++export type UserBarUpdateState = {+ phase: UserBarUpdatePhase+ targetMachineIds: readonly string[]+ acceptedMachineIds: readonly string[]+ failedMachineIds: readonly string[]+ pendingMachineIds: readonly string[]+}++export type UserBarExtensionState = {+ active: UserBarExtensionKind+ update: UserBarUpdateState | null+}++export type UserBarExtensionAction =+ | {+ type: "update.sync"+ collapsed: boolean+ eligibleMachineIds: readonly string[]+ }+ | { type: "update.eligibility"; eligibleMachineIds: readonly string[] }+ | { type: "update.clear" }+ | { type: "update.open" }+ | { type: "update.collapse" }+ | { type: "update.dispatch"; machineIds: readonly string[] }+ | {+ type: "update.settle"+ acceptedMachineIds: readonly string[]+ failedMachineIds: readonly string[]+ }+ | { type: "extension.open"; extension: "inbox" | "profile" }+ | { type: "extension.close"; extension?: UserBarExtensionKind }++export const initialUserBarExtensionState: UserBarExtensionState = {+ active: "none",+ update: null,+}++function unique(values: readonly string[]): string[] {+ return [...new Set(values)]+}++function without(values: readonly string[], removed: ReadonlySet<string>): string[] {+ return values.filter((value) => !removed.has(value))+}++function intersect(values: readonly string[], allowed: ReadonlySet<string>): string[] {+ return values.filter((value) => allowed.has(value))+}++function sameValues(left: readonly string[], right: readonly string[]): boolean {+ return left.length === right.length && left.every((value, index) => value === right[index])+}++function withEligibleMachines(+ state: UserBarExtensionState,+ eligibleMachineIds: readonly string[],+): UserBarExtensionState {+ if (!state.update) return state+ const eligible = new Set(eligibleMachineIds)+ const targetMachineIds = unique(eligibleMachineIds)+ if (targetMachineIds.length === 0) {+ return {+ active: state.active === "update" ? "none" : state.active,+ update: null,+ }+ }+ const acceptedMachineIds = intersect(state.update.acceptedMachineIds, eligible)+ const failedMachineIds = intersect(state.update.failedMachineIds, eligible)+ const pendingMachineIds = intersect(state.update.pendingMachineIds, eligible)+ const phase: UserBarUpdatePhase = failedMachineIds.length > 0+ ? "retry"+ : acceptedMachineIds.length > 0 || pendingMachineIds.length > 0+ ? "updating"+ : state.active === "update"+ ? "expanded"+ : "collapsedBadge"+ if (+ phase === state.update.phase+ && sameValues(targetMachineIds, state.update.targetMachineIds)+ && sameValues(acceptedMachineIds, state.update.acceptedMachineIds)+ && sameValues(failedMachineIds, state.update.failedMachineIds)+ && sameValues(pendingMachineIds, state.update.pendingMachineIds)+ ) return state+ return {+ ...state,+ update: {+ phase,+ targetMachineIds,+ acceptedMachineIds,+ failedMachineIds,+ pendingMachineIds,+ },+ }+}++export function userBarExtensionReducer(+ state: UserBarExtensionState,+ action: UserBarExtensionAction,+): UserBarExtensionState {+ switch (action.type) {+ case "update.sync": {+ if (state.update) return withEligibleMachines(state, action.eligibleMachineIds)+ if (action.eligibleMachineIds.length === 0) return state+ const preserveActiveExtension = action.collapsed || state.active !== "none"+ return {+ active: preserveActiveExtension ? state.active : "update",+ update: {+ phase: preserveActiveExtension ? "collapsedBadge" : "expanded",+ targetMachineIds: unique(action.eligibleMachineIds),+ acceptedMachineIds: [],+ failedMachineIds: [],+ pendingMachineIds: [],+ },+ }+ }+ case "update.eligibility":+ return withEligibleMachines(state, action.eligibleMachineIds)+ case "update.clear":+ return {+ active: state.active === "update" ? "none" : state.active,+ update: null,+ }+ case "update.open":+ if (!state.update) return state+ return {+ active: "update",+ update: {+ ...state.update,+ phase: state.update.phase === "collapsedBadge"+ ? "expanded"+ : state.update.phase,+ },+ }+ case "update.collapse":+ if (!state.update) {+ return state.active === "update" ? { ...state, active: "none" } : state+ }+ return {+ active: state.active === "update" ? "none" : state.active,+ update: {+ ...state.update,+ phase: state.update.phase === "expanded"+ ? "collapsedBadge"+ : state.update.phase,+ },+ }+ case "update.dispatch": {+ if (!state.update) return state+ const requested = new Set(action.machineIds)+ return {+ active: "update",+ update: {+ ...state.update,+ phase: "updating",+ failedMachineIds: without(state.update.failedMachineIds, requested),+ pendingMachineIds: unique([+ ...state.update.pendingMachineIds,+ ...action.machineIds,+ ]),+ },+ }+ }+ case "update.settle": {+ if (!state.update) return state+ const target = new Set(state.update.targetMachineIds)+ const acceptedActionMachineIds = action.acceptedMachineIds.filter((machineId) => (+ target.has(machineId)+ ))+ const failedActionMachineIds = action.failedMachineIds.filter((machineId) => (+ target.has(machineId)+ ))+ const accepted = new Set(acceptedActionMachineIds)+ const failed = new Set(failedActionMachineIds)+ const settled = new Set([...accepted, ...failed])+ const acceptedMachineIds = unique([+ ...without(state.update.acceptedMachineIds, failed),+ ...acceptedActionMachineIds,+ ])+ const failedMachineIds = unique([+ ...without(state.update.failedMachineIds, accepted),+ ...failedActionMachineIds,+ ])+ return {+ active: state.active,+ update: {+ ...state.update,+ phase: failedMachineIds.length > 0 ? "retry" : "updating",+ acceptedMachineIds,+ failedMachineIds,+ pendingMachineIds: without(state.update.pendingMachineIds, settled),+ },+ }+ }+ case "extension.open":+ return {+ active: action.extension,+ update: state.update?.phase === "expanded"+ ? { ...state.update, phase: "collapsedBadge" }+ : state.update,+ }+ case "extension.close":+ if (action.extension && state.active !== action.extension) return state+ return {+ active: "none",+ update: state.update?.phase === "expanded"+ ? { ...state.update, phase: "collapsedBadge" }+ : state.update,+ }+ }+}++export function userBarUpdateBadgePhase(+ state: UserBarExtensionState,+): Exclude<UserBarUpdatePhase, "expanded"> | null {+ if (!state.update || state.active === "update") return null+ return state.update.phase === "expanded" ? "collapsedBadge" : state.update.phase+}diff --git a/src/web/src/components/community/shell/user-bar.test.ts b/src/web/src/components/community/shell/user-bar.test.tsindex 6165044f6..219b18f86 100644--- a/src/web/src/components/community/shell/user-bar.test.ts+++ b/src/web/src/components/community/shell/user-bar.test.ts@@ -16,9 +16,9 @@ describe("UserBar", () => {}))expect(html).toContain(`data-testid="${tid.userBar}"`)- expect(html).toContain("var(--app-safe-area-left)")- expect(html).toContain("var(--app-safe-area-right)")- expect(html).toContain("var(--app-safe-area-bottom)")+ expect(html).toContain("pl-[max(0.75rem,var(--app-safe-area-left))]")+ expect(html).toContain("pr-[max(0.75rem,var(--app-safe-area-right))]")+ expect(html).toContain("pb-[calc(0.75rem+var(--app-safe-area-bottom))]")expect(html).toContain("sm:px-3 sm:pb-3")expect(html).toContain('class="flex min-w-0 flex-1 items-center gap-2"')expect(html).toContain('data-testid="community-user-bar-name"')@@ -46,13 +46,14 @@ describe("UserBar", () => {expect(settingsClass).toContain("focus-visible:ring-2")})- it("provides an inert account-neutral placeholder with the same outer geometry", () => {+ it("provides an inert account-neutral placeholder with the same Composer-aligned geometry", () => {const html = renderToStaticMarkup(createElement(UserBarSkeleton))expect(html).toContain(`data-testid="${tid.initialUserBarPending}"`)expect(html).toContain("aria-hidden=\"true\"")- expect(html).toContain("var(--app-safe-area-left)")- expect(html).toContain("var(--app-safe-area-right)")- expect(html).toContain("var(--app-safe-area-bottom)")+ expect(html).toContain("pl-[max(0.75rem,var(--app-safe-area-left))]")+ expect(html).toContain("pr-[max(0.75rem,var(--app-safe-area-right))]")+ expect(html).toContain("pb-[calc(0.75rem+var(--app-safe-area-bottom))]")+ expect(html).toContain("sm:px-3 sm:pb-3")expect(html).not.toContain("<button")expect(html).not.toContain("<a")})@@ -76,4 +77,103 @@ describe("UserBar", () => {'class="flex h-12 items-center gap-3 bg-muted px-4 ring-1 ring-border/40 rounded-xl"',)})++ it("preserves the desktop Inbox name while mobile exposes open state", () => {+ const extension = {+ active: "none" as const,+ inbox: createElement("div", null, "Inbox content"),+ profile: null,+ update: null,+ updateBadgePhase: null,+ eligibleMachines: [],+ onOpenUpdate: () => {},+ onRequestUpdate: () => {},+ onDismiss: () => {},+ }+ const props = {+ user: { id: "u1", name: "User", avatar: "U" },+ inbox: createElement("div", null, "Inbox content"),+ hasUnread: false,+ inboxOpen: false,+ extension,+ }++ const desktop = renderToStaticMarkup(createElement(UserBar, {+ ...props,+ breakpoint: "desktop",+ }))+ expect(desktop).toContain('aria-label="Inbox"')+ expect(desktop).not.toContain('aria-label="Open Inbox"')++ const mobile = renderToStaticMarkup(createElement(UserBar, {+ ...props,+ breakpoint: "mobile",+ }))+ expect(mobile).toContain('aria-label="Open Inbox"')+ })++ it.each(["desktop", "mobile"] as const)(+ "renders the %s Update badge as one accessible icon without status text",+ (breakpoint) => {+ const html = renderToStaticMarkup(createElement(UserBar, {+ breakpoint,+ user: { id: "u1", name: "User", avatar: "U" },+ hasUnread: false,+ extension: {+ active: "none",+ inbox: null,+ profile: null,+ update: null,+ updateBadgePhase: "collapsedBadge",+ eligibleMachines: [],+ onOpenUpdate: () => {},+ onRequestUpdate: () => {},+ onDismiss: () => {},+ },+ }))+ const badge = html.match(new RegExp(+ `<button[^>]*data-testid="${tid.daemonUpdateBadge}"[^>]*>(.*?)</button>`,+ ))?.[1]++ expect(html).toContain('aria-label="Open machine update"')+ expect(badge).toContain("<svg")+ expect(badge).not.toContain("<span")+ expect(badge).not.toContain("Update")+ expect(badge).not.toContain("Updating")+ expect(badge).not.toContain("Retry")+ },+ )++ it("keeps the Inbox glyph outlined and expresses open state on its trigger", () => {+ const renderInbox = (open: boolean) => renderToStaticMarkup(createElement(UserBar, {+ breakpoint: "desktop",+ user: { id: "u1", name: "User", avatar: "U" },+ inbox: createElement("div", null, "Inbox content"),+ hasUnread: false,+ inboxOpen: open,+ extension: {+ active: open ? "inbox" : "none",+ inbox: createElement("div", null, "Inbox content"),+ profile: null,+ update: null,+ updateBadgePhase: null,+ eligibleMachines: [],+ onOpenUpdate: () => {},+ onRequestUpdate: () => {},+ onDismiss: () => {},+ },+ }))++ const closed = renderInbox(false)+ const open = renderInbox(true)++ expect(closed).toContain('aria-expanded="false"')+ expect(open).toContain('aria-expanded="true"')+ expect(closed).toContain("aria-expanded:bg-accent")+ expect(closed).toContain("aria-expanded:text-foreground")+ expect(open).toContain("aria-expanded:bg-accent")+ expect(open).toContain("aria-expanded:text-foreground")+ expect(closed).not.toContain("fill-current")+ expect(open).not.toContain("fill-current")+ })})diff --git a/src/web/src/components/community/shell/user-bar.tsx b/src/web/src/components/community/shell/user-bar.tsxindex 8c3713892..956753917 100644--- a/src/web/src/components/community/shell/user-bar.tsx+++ b/src/web/src/components/community/shell/user-bar.tsx@@ -2,21 +2,41 @@import {useRef,+ useState,type MutableRefObject,type ReactNode,type RefObject,} from "react"-import { Settings } from "lucide-react"+import { CircleAlert, Download, Inbox, LoaderCircle, Settings } from "lucide-react"import { Avatar } from "../avatar"import { Skeleton } from "@/components/ui/skeleton"+import type { MachineSummary } from "@/hooks/community/use-machines"import type { OpenProfile } from "@/components/community/social/profile-types"import type { Presence } from "@/lib/community/models/people"import type { Breakpoint } from "@/hooks/use-mobile"import { tid } from "@/lib/community/testids"import { cn } from "@/lib/utils"import { CommunityInboxSurface } from "./community-inbox-surface"+import { UserBarExtensionSlot } from "./user-bar-extension-slot"+import type {+ UserBarExtensionKind,+ UserBarUpdatePhase,+ UserBarUpdateState,+} from "./user-bar-extension-state"-export function UserBar({ breakpoint, user, onOpenProfile, onEditProfile, inbox, hasUnread, inboxOpen, onInboxOpenChange }: {+type UserBarExtension = {+ active: UserBarExtensionKind+ inbox: ReactNode+ profile: ReactNode+ update: UserBarUpdateState | null+ updateBadgePhase: Exclude<UserBarUpdatePhase, "expanded"> | null+ eligibleMachines: readonly MachineSummary[]+ onOpenUpdate: () => void+ onRequestUpdate: () => void+ onDismiss: () => void+}++export function UserBar({ breakpoint, user, onOpenProfile, onEditProfile, inbox, hasUnread, inboxOpen, onInboxOpenChange, extension }: {breakpoint: Breakpointuser: { id: string; name: string; avatar: string; presence?: Presence }onOpenProfile?: OpenProfile@@ -25,23 +45,63 @@ export function UserBar({ breakpoint, user, onOpenProfile, onEditProfile, inbox,hasUnread: booleaninboxOpen?: booleanonInboxOpenChange?: (open: boolean) => void+ extension?: UserBarExtension}) {const inboxAnchorRef = useRef<HTMLDivElement>(null)+ const profileTriggerRef = useRef<HTMLButtonElement>(null)+ const profileNameTriggerRef = useRef<HTMLButtonElement>(null)+ const lastProfileTriggerRef = useRef<HTMLButtonElement | null>(null)+ const inboxTriggerRef = useRef<HTMLButtonElement>(null)+ const updateBadgeRef = useRef<HTMLButtonElement>(null)+ const [pendingExtensionFocus, setPendingExtensionFocus] = useState<UserBarExtensionKind>("none")const suppressInboxFocusReturnRef = useRef(false)const closeInboxForAction = () => {suppressInboxFocusReturnRef.current = trueif (inboxOpen) onInboxOpenChange?.(false)}+ const dismissExtensionWithFocus = () => {+ if (!extension || extension.active === "none") return+ const active = extension.active+ extension.onDismiss()+ globalThis.requestAnimationFrame(() => {+ if (active === "inbox") inboxTriggerRef.current?.focus()+ else if (active === "profile") {+ (lastProfileTriggerRef.current ?? profileTriggerRef.current)?.focus()+ }+ else updateBadgeRef.current?.focus()+ })+ }return (<divdata-testid={tid.userBar}className="w-full min-w-0 max-w-full shrink-0 overflow-hidden pl-[max(0.75rem,var(--app-safe-area-left))] pr-[max(0.75rem,var(--app-safe-area-right))] pb-[calc(0.75rem+var(--app-safe-area-bottom))] pt-0 sm:px-3 sm:pb-3">+ {extension && extension.active !== "none" && (+ <UserBarExtensionSlot+ active={extension.active}+ inbox={extension.inbox}+ profile={extension.profile}+ update={extension.update}+ eligibleMachines={extension.eligibleMachines}+ onDismiss={dismissExtensionWithFocus}+ onDismissOutside={extension.onDismiss}+ onRequestUpdate={extension.onRequestUpdate}+ focusOnOpen={pendingExtensionFocus === extension.active}+ onInitialFocus={() => {+ if (pendingExtensionFocus === extension.active) {+ setPendingExtensionFocus("none")+ }+ }}+ />+ )}<divref={inboxAnchorRef}+ data-slot="community-user-bar-base"className={cn("flex h-12 items-center gap-3 bg-muted px-4 ring-1 ring-border/40",- breakpoint === "mobile" && inboxOpen ? "rounded-b-xl" : "rounded-xl",+ (extension && extension.active !== "none") || (breakpoint === "mobile" && inboxOpen)+ ? "rounded-b-xl"+ : "rounded-xl",)}><Inner@@ -56,6 +116,13 @@ export function UserBar({ breakpoint, user, onOpenProfile, onEditProfile, inbox,inboxAnchorRef={inboxAnchorRef}suppressInboxFocusReturnRef={suppressInboxFocusReturnRef}closeInboxForAction={closeInboxForAction}+ profileTriggerRef={profileTriggerRef}+ profileNameTriggerRef={profileNameTriggerRef}+ lastProfileTriggerRef={lastProfileTriggerRef}+ inboxTriggerRef={inboxTriggerRef}+ updateBadgeRef={updateBadgeRef}+ onRequestExtensionFocus={setPendingExtensionFocus}+ extension={extension}/></div></div>@@ -79,7 +146,7 @@ export function UserBarSkeleton() {)}-function Inner({ breakpoint, user, onOpenProfile, onEditProfile, inbox, hasUnread, inboxOpen, onInboxOpenChange, inboxAnchorRef, suppressInboxFocusReturnRef, closeInboxForAction }: {+function Inner({ breakpoint, user, onOpenProfile, onEditProfile, inbox, hasUnread, inboxOpen, onInboxOpenChange, inboxAnchorRef, suppressInboxFocusReturnRef, closeInboxForAction, profileTriggerRef, profileNameTriggerRef, lastProfileTriggerRef, inboxTriggerRef, updateBadgeRef, onRequestExtensionFocus, extension }: {breakpoint: Breakpointuser: { id: string; name: string; avatar: string; presence?: Presence }onOpenProfile?: OpenProfile@@ -91,23 +158,92 @@ function Inner({ breakpoint, user, onOpenProfile, onEditProfile, inbox, hasUnreainboxAnchorRef: RefObject<HTMLDivElement | null>suppressInboxFocusReturnRef: MutableRefObject<boolean>closeInboxForAction: () => void+ profileTriggerRef: RefObject<HTMLButtonElement | null>+ profileNameTriggerRef: RefObject<HTMLButtonElement | null>+ lastProfileTriggerRef: MutableRefObject<HTMLButtonElement | null>+ inboxTriggerRef: RefObject<HTMLButtonElement | null>+ updateBadgeRef: RefObject<HTMLButtonElement | null>+ onRequestExtensionFocus: (extension: UserBarExtensionKind) => void+ extension?: UserBarExtension}) {+ const mobile = breakpoint === "mobile"+ const updateBadgeLabel = extension?.updateBadgePhase === "retry"+ ? "Retry machine update"+ : extension?.updateBadgePhase === "updating"+ ? "Machine update in progress"+ : "Open machine update"+ const UpdateBadgeIcon = extension?.updateBadgePhase === "retry"+ ? CircleAlert+ : extension?.updateBadgePhase === "updating"+ ? LoaderCircle+ : Downloadreturn (<div className="flex min-w-0 flex-1 items-center gap-2">- <button onClick={(e) => {- closeInboxForAction()+ <button ref={profileTriggerRef} onClick={(e) => {+ lastProfileTriggerRef.current = e.currentTarget+ if (extension && extension.active !== "profile") {+ onRequestExtensionFocus("profile")+ }+ if (!extension) closeInboxForAction()onOpenProfile?.(user.name, e, undefined, user.id)- }} className="shrink-0 rounded-full focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">+ }} className="shrink-0 rounded-full focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none" aria-expanded={extension ? extension.active === "profile" : undefined} aria-controls={extension?.active === "profile" ? "community-user-bar-extension" : undefined}><Avatar label={user.avatar} seed={user.id} size={28} presence={user.presence} ringColor="var(--muted)" /></button>- <button onClick={(e) => {- closeInboxForAction()+ <button ref={profileNameTriggerRef} onClick={(e) => {+ lastProfileTriggerRef.current = e.currentTarget+ if (extension && extension.active !== "profile") {+ onRequestExtensionFocus("profile")+ }+ if (!extension) closeInboxForAction()onOpenProfile?.(user.name, e, undefined, user.id)- }} className="min-w-0 flex-1 text-left rounded focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">- <div data-testid="community-user-bar-name" className="truncate text-sm font-medium leading-tight">{user.name}</div>+ }} className="min-w-0 flex-1 text-left rounded focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none" aria-expanded={extension ? extension.active === "profile" : undefined} aria-controls={extension?.active === "profile" ? "community-user-bar-extension" : undefined}>+ <div data-testid={tid.userBarName} className="truncate text-sm font-medium leading-tight">{user.name}</div></button><div className="flex shrink-0 items-center gap-1">- {inbox && (+ {extension?.updateBadgePhase && (+ <button+ ref={updateBadgeRef}+ type="button"+ data-testid={tid.daemonUpdateBadge}+ className="grid size-11 place-items-center rounded-lg bg-secondary text-secondary-foreground hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:size-7"+ aria-label={updateBadgeLabel}+ onClick={() => {+ onRequestExtensionFocus("update")+ extension.onOpenUpdate()+ }}+ >+ <UpdateBadgeIcon className={cn(+ "size-4",+ extension.updateBadgePhase === "updating" && "animate-spin motion-reduce:animate-none",+ )} />+ </button>+ )}+ {inbox && extension ? (+ <button+ ref={inboxTriggerRef}+ type="button"+ data-testid={tid.inboxTrigger}+ className={cn(+ "relative grid size-11 place-items-center rounded-lg text-muted-foreground aria-expanded:bg-accent aria-expanded:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:size-7",+ mobile+ ? "hover:text-foreground active:text-foreground"+ : "hover:bg-accent hover:text-foreground",+ )}+ aria-label={mobile ? (inboxOpen ? "Close Inbox" : "Open Inbox") : "Inbox"}+ aria-expanded={inboxOpen}+ aria-pressed={mobile ? inboxOpen : undefined}+ aria-controls={inboxOpen ? "community-user-bar-extension" : undefined}+ onClick={() => {+ if (!inboxOpen) onRequestExtensionFocus("inbox")+ onInboxOpenChange?.(!inboxOpen)+ }}+ >+ <span className="relative grid size-4 place-items-center">+ <Inbox className="size-4" />+ {hasUnread && <span className="absolute -right-1 -top-1 size-2 rounded-full bg-primary" />}+ </span>+ </button>+ ) : inbox ? (<CommunityInboxSurfacebreakpoint={breakpoint}open={inboxOpen}@@ -118,10 +254,11 @@ function Inner({ breakpoint, user, onOpenProfile, onEditProfile, inbox, hasUnrea>{inbox}</CommunityInboxSurface>- )}+ ) : null}<buttononClick={() => {- closeInboxForAction()+ if (extension) extension.onDismiss()+ else closeInboxForAction()onEditProfile?.()}}className={cn(diff --git a/src/web/src/components/community/social/profile-card-surface.dom.test.ts b/src/web/src/components/community/social/profile-card-surface.dom.test.tsindex 684579004..6cdf6617d 100644--- a/src/web/src/components/community/social/profile-card-surface.dom.test.ts+++ b/src/web/src/components/community/social/profile-card-surface.dom.test.ts@@ -71,6 +71,27 @@ function renderSurface(bp: "mobile" | "desktop") {}describe("ProfileCard surface contracts", () => {+ it("reuses profile content without an overlay shell inside the User Bar extension", () => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ const renderer = render(React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(ProfileCard, {+ data: { name: "Ren", userId: "user_1", mutual: 0 },+ x: 0,+ y: 0,+ bp: "mobile",+ onClose: vi.fn(),+ extension: true,+ }),+ ))++ const profile = renderer.getByTestId("community-profile-card")+ expect(profile.className).toBe("w-full")+ expect(renderer.container.querySelectorAll("sheet-root")).toHaveLength(0)+ expect(renderer.container.querySelectorAll("popover-root")).toHaveLength(0)+ })+it("uses the shared modal bottom Sheet without a copied or foreground-derived overlay", () => {const { renderer } = renderSurface("mobile")const root = mockProps.get("sheet-root")!diff --git a/src/web/src/components/community/social/profile-card.tsx b/src/web/src/components/community/social/profile-card.tsxindex 38742ac52..7f0b09956 100644--- a/src/web/src/components/community/social/profile-card.tsx+++ b/src/web/src/components/community/social/profile-card.tsx@@ -195,7 +195,7 @@ function useAuditPreviewPosition(enabled: boolean, x: number, y: number) {// Profile card — popover anchored at the click point on desktop, bottom sheet on mobile.// Identity, about, status, and presence are read from the global profile map// whenever a userId is present. Static cards use their supplied display data.-export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdateStatus, onOpenOwnerProfile, onOpenBotAudit, initialStatusEmoji, initialStatusText, activityStatusEmoji, activityStatusText, embedded }: {+export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdateStatus, onOpenOwnerProfile, onOpenBotAudit, initialStatusEmoji, initialStatusText, activityStatusEmoji, activityStatusText, embedded, extension }: {data: Profilex: numbery: number@@ -215,6 +215,7 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda// Static card surface for contexts such as product previews. The regular// profile interaction still uses the anchored popover / mobile sheet.embedded?: boolean+ extension?: boolean}) {const [msg, setMsg] = useState("")const [open, setOpen] = useState(true)@@ -251,7 +252,7 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdaconst botIdentity = data.identity?.kind === "bot" ? data.identity : nullconst showOwnedBotCard = Boolean(botIdentity?.ownedByViewer && data.userId)const { popoverRef, cardRef, previewRef, position: previewPosition } = useAuditPreviewPosition(- showOwnedBotCard && !mobile && !embedded,+ showOwnedBotCard && !mobile && !embedded && !extension,x,y,)@@ -444,6 +445,9 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda/>) : null+ if (extension)+ return <div data-testid={tid.profileCard} className="w-full">{card}</div>+if (embedded)return (<div className="flex w-full flex-col gap-2">diff --git a/src/web/src/components/daemon-update-notice.dom.test.ts b/src/web/src/components/daemon-update-notice.dom.test.tsindex e419be921..f7dc1937d 100644--- a/src/web/src/components/daemon-update-notice.dom.test.ts+++ b/src/web/src/components/daemon-update-notice.dom.test.ts@@ -236,10 +236,15 @@ describe("DaemonUpdateNotice", () => {expect(mocks.notificationAdd).not.toHaveBeenCalled()})- it("mounts the thin controller only in authenticated route groups", () => {+ it("keeps the legacy notice outside Community while Community owns its shell surface", () => {const appLayout = readFileSync(resolve(webRoot, "src/app/(app)/layout.tsx"), "utf8")const communityShell = readFileSync(resolve(webRoot, "src/app/c/community-shell.tsx"), "utf8")+ const shellFrame = readFileSync(resolve(+ webRoot,+ "src/components/community/shell/shell-frame.tsx",+ ), "utf8")expect(appLayout).toContain("<DaemonUpdateNotice userId={session.user.id} />")- expect(communityShell).toContain("<CommunityDaemonUpdateNotice userId={currentUser.id} />")+ expect(communityShell).not.toContain("DaemonUpdateNotice")+ expect(shellFrame).toContain("useShellDaemonUpdateController")})})diff --git a/src/web/src/components/daemon-update-notice.tsx b/src/web/src/components/daemon-update-notice.tsxindex df6248f19..34f4dc5e0 100644--- a/src/web/src/components/daemon-update-notice.tsx+++ b/src/web/src/components/daemon-update-notice.tsx@@ -1,8 +1,7 @@"use client"-import { useCallback, useEffect, useRef, type ComponentPropsWithoutRef } from "react"+import { useEffect, useRef, type ComponentPropsWithoutRef } from "react"import Image from "next/image"-import { useQueryClient } from "@tanstack/react-query"import {SELF_UPDATE_MIN_DAEMON_VERSION,isPresenceOnline,@@ -12,7 +11,6 @@ import {import { machinesQueryFn, type MachineSummary } from "@/hooks/community/use-machines"import { messageNotification } from "@/components/ui/toast"import { apiFetch } from "@/lib/api/client"-import { communityKeys } from "@/lib/query-keys"import { tid } from "@/lib/community/testids"import { log } from "@/lib/logger"@@ -40,7 +38,7 @@ export function eligibleDaemonUpdateMachines<T extends Pick<MachineSummary, "id"type MachineUpdateRequester = (machineId: string) => Promise<unknown>-async function requestMachineUpdate(machineId: string): Promise<void> {+export async function requestMachineUpdate(machineId: string): Promise<void> {await apiFetch<{ dispatched: true }>(`/api/community/machines/${machineId}/update`, {method: "POST",})@@ -163,16 +161,3 @@ export function DaemonUpdateNotice({return null}--export function CommunityDaemonUpdateNotice({ userId }: { userId: string }) {- const queryClient = useQueryClient()- const loadMachines = useCallback(- () => queryClient.fetchQuery({- queryKey: communityKeys.machines(),- queryFn: machinesQueryFn,- }),- [queryClient],- )-- return <DaemonUpdateNotice userId={userId} loadMachines={loadMachines} />-}diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex c9402e4ed..01396a62b 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -96,6 +96,7 @@ export const tid = {machineUpdateConfirm: "machine-update-confirm",daemonUpdateNotice: "daemon-update-notice",daemonUpdateAction: "daemon-update-action",+ daemonUpdateBadge: "daemon-update-badge",landingMobileMotionStage: "landing-mobile-motion-stage",homeButton: "community-home-button",alookLogo: "community-alook-logo",@@ -221,6 +222,8 @@ export const tid = {inboxUnreadChild: (id: string) => `community-inbox-unread-child-${id}`,inboxUnreadDm: (id: string) => `community-inbox-unread-dm-${id}`,userBar: "community-user-bar",+ userBarName: "community-user-bar-name",+ userBarExtension: "community-user-bar-extension",inboxTrigger: "community-inbox-trigger",inboxMobileBackdrop: "community-inbox-mobile-backdrop",inboxMobileSurface: "community-inbox-mobile-surface",diff --git a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.tsindex aed1a262c..60855b606 100644--- a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts+++ b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts@@ -314,7 +314,9 @@ test("My Bots restores the 30-day token heatmap across PC and mobile", async ({`[data-testid^="${tid.botUsageDay("bot_claude", "")}"]`,)).toHaveCount(30)const quota = page.getByTestId(tid.machineQuota(machine.id))+ const updateExtension = page.getByTestId(tid.userBarExtension)await expect(quota).toHaveCount(1)+ await expect(updateExtension).toHaveAttribute("data-extension", "update")await expect(quota).toHaveAttribute("aria-label","Quota details: Claude 64% left; Codex 18% left; Grok 72% left. 4 limits",@@ -351,6 +353,7 @@ test("My Bots restores the 30-day token heatmap across PC and mobile", async ({await expect(quota).toHaveAttribute("aria-expanded", "false")await quota.click()+ await expect(updateExtension).toHaveCount(0)await expect(quota).toHaveAttribute("aria-expanded", "true")const quotaDetail = page.getByTestId(tid.machineQuotaDetail(machine.id))await expect(quotaDetail).toContainText("Codex")diff --git a/src/web/src/test/e2e-ui/50-daemon-update-notice.spec.ts b/src/web/src/test/e2e-ui/50-daemon-update-notice.spec.tsindex a6dbec9ed..cf33dcc73 100644--- a/src/web/src/test/e2e-ui/50-daemon-update-notice.spec.ts+++ b/src/web/src/test/e2e-ui/50-daemon-update-notice.spec.ts@@ -1,7 +1,8 @@import { readFileSync } from "node:fs"-import type { BrowserContext, Locator, Page } from "@playwright/test"+import type { Page, Request } from "@playwright/test"import { test, expect } from "./_fixtures/community-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"import { tid } from "./_fixtures/testids"import { REPO_ROOT } from "./_setup/paths"@@ -9,10 +10,6 @@ const latestDaemonVersion = (JSON.parse(readFileSync(`${REPO_ROOT}/src/daemon/package.json`,"utf8",)) as { version: string }).version-const currentWebVersion = (JSON.parse(readFileSync(- `${REPO_ROOT}/src/web/package.json`,- "utf8",-)) as { version: string }).versionconst outdatedMachine = {id: "machine_daemon_notice",@@ -30,9 +27,16 @@ const outdatedMachine = {quota: [],}-async function serveMachines(page: Page, machines = [outdatedMachine]) {+async function serveMachines(page: Page, {+ machines = [outdatedMachine],+ failOnce = [],+}: {+ machines?: Array<typeof outdatedMachine>+ failOnce?: string[]+} = {}) {let requestCount = 0const updateRequests: string[] = []+ const remainingFailures = new Set(failOnce)await page.route("**/api/community/machines", async (route) => {requestCount += 1await route.fulfill({@@ -43,7 +47,16 @@ async function serveMachines(page: Page, machines = [outdatedMachine]) {})await page.route("**/api/community/machines/*/update", async (route) => {const match = new URL(route.request().url()).pathname.match(/\/machines\/([^/]+)\/update$/)- if (match) updateRequests.push(match[1]!)+ const machineId = match?.[1]+ if (machineId) updateRequests.push(machineId)+ if (machineId && remainingFailures.delete(machineId)) {+ await route.fulfill({+ status: 503,+ contentType: "application/json",+ body: JSON.stringify({ error: "temporary unavailable" }),+ })+ return+ }await route.fulfill({status: 200,contentType: "application/json",@@ -56,135 +69,199 @@ async function serveMachines(page: Page, machines = [outdatedMachine]) {}}-async function clearSavedDaemonCheckOnce(context: BrowserContext) {- await context.addInitScript(() => {- const marker = "alook:qa:daemon-update-check-cleared"- if (sessionStorage.getItem(marker)) return- for (let index = localStorage.length - 1; index >= 0; index -= 1) {- const key = localStorage.key(index)- if (key?.startsWith("alook:daemon-update-check:")) localStorage.removeItem(key)+function observeWrites(page: Page) {+ const writes: string[] = []+ const listener = (request: Request) => {+ if (!["GET", "HEAD", "OPTIONS"].includes(request.method())) {+ writes.push(`${request.method()} ${new URL(request.url()).pathname}`)}- sessionStorage.setItem(marker, "1")- })-}--async function waitForNoticeLogo(notice: Locator) {- const logo = notice.locator('[data-slot="message-notification-icon"] img')- await expect(logo).toBeVisible()- await expect.poll(() => logo.evaluate((image: HTMLImageElement) => (- image.complete && image.naturalWidth > 0- ))).toBe(true)-}--async function hideDevelopmentToolsForScreenshot(page: Page) {- await page.addStyleTag({- content: "nextjs-portal, .tsqd-parent-container { display: none !important; }",- })+ }+ page.on("request", listener)+ return { writes, stop: () => page.off("request", listener) }}-test("daemon reminder checks once, respects reduced motion, and stays dismissed", async ({ asUser }, testInfo) => {- const { context, page } = await asUser("alice")- await clearSavedDaemonCheckOnce(context)+test("Update, Inbox, and viewer Profile share one persistent User Bar extension", async ({ asUser }) => {+ const { page } = await asUser("alice")const requests = await serveMachines(page)await page.emulateMedia({ reducedMotion: "reduce" })await page.setViewportSize({ width: 1280, height: 900 })await gotoAfterUserWsAuth(page, "/c/me/friends")- const notice = page.getByTestId(tid.daemonUpdateNotice)- await expect(notice).toBeVisible()- await expect(notice).toContainText("Machine update available")- await expect(notice).toContainText("You can update your machine to get more features.")+ const slot = page.getByTestId(tid.userBarExtension)+ const userBar = page.getByTestId(tid.userBar)+ const userBarBase = userBar.locator("[data-slot='community-user-bar-base']")+ await expect(slot).toBeVisible()+ await expect(slot).toHaveAttribute("data-extension", "update")+ await expect(slot).toContainText("Machine update available")+ await expect(slot).toContainText("You can update your machine to get more features.")await expect(page.getByTestId(tid.daemonUpdateAction)).toHaveText("Update")- await waitForNoticeLogo(notice)+ await expect(page.getByTestId(tid.daemonUpdateBadge)).toHaveCount(0)+ await expect(slot.getByRole("button", { name: /^Dismiss / })).toHaveCount(0)+ await expect(slot).toHaveCSS("animation-name", "none")expect(requests.machineRequestCount()).toBe(1)- const box = await notice.boundingBox()- expect(box).not.toBeNull()- expect(Math.abs(box!.x + box!.width / 2 - 640)).toBeLessThanOrEqual(1)- expect(box!.y).toBe(16)- await expect(notice).toHaveCSS("transition-property", "none")- await expect(notice.locator('[data-slot="message-notification-content"]'))- .toHaveCSS("transition-property", "none")- await hideDevelopmentToolsForScreenshot(page)- const desktopScreenshot = testInfo.outputPath("daemon-update-desktop.png")- await page.screenshot({ path: desktopScreenshot })- await testInfo.attach("daemon-update-desktop", {- path: desktopScreenshot,- contentType: "image/png",- })+ const [slotBox, baseBox] = await Promise.all([slot.boundingBox(), userBarBase.boundingBox()])+ expect(slotBox).not.toBeNull()+ expect(baseBox).not.toBeNull()+ expect(Math.abs(slotBox!.y + slotBox!.height - baseBox!.y)).toBeLessThanOrEqual(1)+ expect(Math.abs(slotBox!.x - baseBox!.x)).toBeLessThanOrEqual(1)+ expect(Math.abs(slotBox!.width - baseBox!.width)).toBeLessThanOrEqual(1)- await notice.locator('[data-slot="message-notification-close"]').click()- await expect(notice).toBeHidden()- await expect.poll(() => page.evaluate(() => {- const savedVersions: Array<string | null> = []+ await page.keyboard.press("Escape")+ const badge = page.getByTestId(tid.daemonUpdateBadge)+ await expect(slot).toHaveCount(0)+ await expect(badge).toBeVisible()+ await expect(badge).toHaveText("")+ await expect(badge.locator("svg")).toHaveCount(1)+ await expect.poll(() => page.evaluate((version) => {for (let index = 0; index < localStorage.length; index += 1) {const key = localStorage.key(index)- if (key?.startsWith("alook:daemon-update-check:")) {- savedVersions.push(localStorage.getItem(key))+ if (key?.startsWith("alook:daemon-update-collapsed:") && key.endsWith(`:${version}`)) {+ return localStorage.getItem(key)}}- return savedVersions- })).toEqual([currentWebVersion])+ return null+ }, latestDaemonVersion)).toBe("1")+await page.reload()- await expect(notice).toHaveCount(0)- expect(requests.updateRequests()).toEqual([])-})+ await expect(badge).toBeVisible()+ await expect(slot).toHaveCount(0)+ await badge.focus()+ await page.keyboard.press("Enter")+ await expect(slot).toHaveAttribute("data-extension", "update")+ await expect(slot).toBeFocused()+ await expect(badge).toHaveCount(0)+ await page.keyboard.press("Tab")+ await expect(page.getByTestId(tid.daemonUpdateAction)).toBeFocused()-test("mobile daemon reminder fits, swipes away, and dispatches eligible updates", async ({ asUser }, testInfo) => {- const swipeSession = await asUser("bob", { hasTouch: true })- await clearSavedDaemonCheckOnce(swipeSession.context)- await serveMachines(swipeSession.page)- await swipeSession.page.setViewportSize({ width: 390, height: 844 })- await gotoAfterUserWsAuth(swipeSession.page, "/c/me/friends")-- const swipeNotice = swipeSession.page.getByTestId(tid.daemonUpdateNotice)- await expect(swipeNotice).toBeVisible()- await waitForNoticeLogo(swipeNotice)- const [noticeBox, actionBox, closeBox] = await Promise.all([- swipeNotice.boundingBox(),- swipeSession.page.getByTestId(tid.daemonUpdateAction).boundingBox(),- swipeNotice.locator('[data-slot="message-notification-close"]').boundingBox(),+ const writes = observeWrites(page)+ const inboxTrigger = page.getByTestId(tid.inboxTrigger)+ const inboxIcon = inboxTrigger.locator("svg")+ const readInboxTriggerStyle = () => inboxTrigger.evaluate((element) => {+ const style = getComputedStyle(element)+ return {+ backgroundColor: style.backgroundColor,+ color: style.color,+ }+ })+ await expect(inboxTrigger).toHaveAttribute("aria-label", "Inbox")+ await expect(inboxIcon).toHaveAttribute("fill", "none")+ await expect(inboxIcon).not.toHaveClass(/fill-current/)+ const closedInboxTriggerStyle = await readInboxTriggerStyle()+ await inboxTrigger.focus()+ await page.keyboard.press("Enter")+ await expect(slot).toHaveAttribute("data-extension", "inbox")+ await expect(slot).toBeFocused()+ await expect(page.getByTestId(tid.daemonUpdateBadge)).toBeVisible()+ await expect(inboxIcon).toHaveAttribute("fill", "none")+ await expect(inboxIcon).not.toHaveClass(/fill-current/)+ await expect.poll(async () => {+ const openStyle = await readInboxTriggerStyle()+ return {+ backgroundChanged: openStyle.backgroundColor !== closedInboxTriggerStyle.backgroundColor,+ foregroundChanged: openStyle.color !== closedInboxTriggerStyle.color,+ }+ }).toEqual({ backgroundChanged: true, foregroundChanged: true })+ const [badgeBox, inboxBox] = await Promise.all([+ page.getByTestId(tid.daemonUpdateBadge).boundingBox(),+ inboxTrigger.boundingBox(),])- expect(noticeBox).not.toBeNull()- expect(actionBox).not.toBeNull()- expect(closeBox).not.toBeNull()- expect(noticeBox!.x).toBeGreaterThanOrEqual(0)- expect(noticeBox!.x + noticeBox!.width).toBeLessThanOrEqual(390)- expect(actionBox!.height).toBeGreaterThanOrEqual(43.9)- expect(closeBox!.height).toBeGreaterThanOrEqual(43.9)- expect(await swipeSession.page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)- await hideDevelopmentToolsForScreenshot(swipeSession.page)- const mobileScreenshot = testInfo.outputPath("daemon-update-mobile.png")- await swipeSession.page.screenshot({ path: mobileScreenshot })- await testInfo.attach("daemon-update-mobile", {- path: mobileScreenshot,- contentType: "image/png",+ expect(badgeBox).not.toBeNull()+ expect(inboxBox).not.toBeNull()+ expect(badgeBox!.x + badgeBox!.width).toBeLessThanOrEqual(inboxBox!.x)++ await inboxTrigger.click()+ await page.mouse.move(0, 0)+ await expect(slot).toHaveCount(0)+ await expect(inboxTrigger).toHaveAttribute("aria-expanded", "false")+ await expect(inboxIcon).toHaveAttribute("fill", "none")+ await expect(inboxIcon).not.toHaveClass(/fill-current/)+ await expect.poll(readInboxTriggerStyle).toEqual(closedInboxTriggerStyle)+ await inboxTrigger.click()+ await page.mouse.move(0, 0)+ await expect(slot).toHaveAttribute("data-extension", "inbox")+ await expect(inboxIcon).toHaveAttribute("fill", "none")+ await expect(inboxIcon).not.toHaveClass(/fill-current/)+ await expect.poll(async () => {+ const openStyle = await readInboxTriggerStyle()+ return {+ backgroundChanged: openStyle.backgroundColor !== closedInboxTriggerStyle.backgroundColor,+ foregroundChanged: openStyle.color !== closedInboxTriggerStyle.color,+ }+ }).toEqual({ backgroundChanged: true, foregroundChanged: true })++ const profileNameTrigger = userBarBase.getByTestId(tid.userBarName).locator("..")+ await profileNameTrigger.focus()+ await page.keyboard.press("Enter")+ await expect(slot).toHaveAttribute("data-extension", "profile")+ await expect(slot).toBeFocused()+ await expect(page.getByTestId(tid.profileCard)).toBeVisible()+ await expect(page.getByTestId(tid.inboxTabList)).toHaveCount(0)+ await profileNameTrigger.click()+ await expect(slot).toHaveCount(0)+ await expect(profileNameTrigger).toBeFocused()+ await expect(page.getByTestId(tid.daemonUpdateBadge)).toBeVisible()+ expect(writes.writes).toEqual([])+ writes.stop()+})++test("partial dispatch retries only failed eligible Machines and clears from live Machine data", async ({ asUser }) => {+ const { context, page } = await asUser("bob")+ const ws = await proxyCommunityWebSockets(context)+ const secondMachine = {+ ...outdatedMachine,+ id: "machine_daemon_notice_2",+ hostname: "travel-mac",+ displayName: "Travel Mac",+ daemonVersion: "0.1.20",+ }+ const requests = await serveMachines(page, {+ machines: [outdatedMachine, secondMachine],+ failOnce: [secondMachine.id],})+ await page.setViewportSize({ width: 390, height: 844 })+ await gotoAfterUserWsAuth(page, "/c/me")- await swipeSession.page.mouse.move(noticeBox!.x + noticeBox!.width / 2, noticeBox!.y + noticeBox!.height / 2)- await swipeSession.page.mouse.down()- await swipeSession.page.mouse.move(noticeBox!.x + 24, noticeBox!.y + noticeBox!.height / 2, { steps: 8 })- await swipeSession.page.mouse.up()- await expect(swipeNotice).toBeHidden()-- const actionSession = await asUser("carol", { hasTouch: true })- await clearSavedDaemonCheckOnce(actionSession.context)- const actionRequests = await serveMachines(actionSession.page, [- outdatedMachine,- { ...outdatedMachine, id: "machine_daemon_notice_2", daemonVersion: "0.1.20" },- { ...outdatedMachine, id: "offline_machine", status: "offline" },- { ...outdatedMachine, id: "manual_update_machine", daemonVersion: "0.1.6" },- { ...outdatedMachine, id: "current_machine", daemonVersion: latestDaemonVersion },+ const slot = page.getByTestId(tid.userBarExtension)+ await expect(slot).toContainText("You can update your machines to get more features.")+ await expect(page.getByTestId(tid.daemonUpdateBadge)).toHaveCount(0)+ await page.getByTestId(tid.daemonUpdateAction).click()+ await expect(slot).toContainText("1 machine is updating. 1 update request failed.")+ await expect(page.getByTestId(tid.daemonUpdateAction)).toHaveText("Retry")+ await expect.poll(() => requests.updateRequests()).toEqual([+ outdatedMachine.id,+ secondMachine.id,])- await actionSession.page.setViewportSize({ width: 390, height: 844 })- await gotoAfterUserWsAuth(actionSession.page, "/c/me/friends")- await expect(actionSession.page.getByTestId(tid.daemonUpdateNotice))- .toContainText("You can update your machines to get more features.")- await actionSession.page.getByTestId(tid.daemonUpdateAction).click()- await expect(actionSession.page.getByTestId(tid.daemonUpdateNotice)).toHaveCount(0)- await expect(actionSession.page).toHaveURL(/\/c\/me\/friends$/)- await expect.poll(() => actionRequests.updateRequests().sort()).toEqual([- "machine_daemon_notice",- "machine_daemon_notice_2",++ await page.getByTestId(tid.daemonUpdateAction).click()+ await expect(slot).toContainText("2 machines are updating")+ await expect(page.getByTestId(tid.daemonUpdateAction)).toHaveCount(0)+ await expect.poll(() => requests.updateRequests()).toEqual([+ outdatedMachine.id,+ secondMachine.id,+ secondMachine.id,])++ await page.keyboard.press("Escape")+ const progressBadge = page.getByTestId(tid.daemonUpdateBadge)+ await expect(progressBadge).toHaveAttribute("aria-label", "Machine update in progress")+ await expect(progressBadge).toHaveText("")++ const { quota: _firstQuota, ...firstUpdated } = outdatedMachine+ const { quota: _secondQuota, ...secondUpdated } = secondMachine+ ws.send({+ type: "community:machine.updated",+ machine: { ...firstUpdated, daemonVersion: latestDaemonVersion },+ })+ await expect(progressBadge).toBeVisible()+ ws.send({+ type: "community:machine.updated",+ machine: { ...secondUpdated, daemonVersion: latestDaemonVersion },+ })+ await expect(progressBadge).toHaveCount(0)+ await expect(slot).toHaveCount(0)+ await expect.poll(() => page.evaluate(() => (+ Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index))+ .filter((key) => key?.startsWith("alook:daemon-update-collapsed:"))+ ))).toEqual([])})diff --git a/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts b/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.tsindex f7d1318fb..fef6945be 100644--- a/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts+++ b/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts@@ -1,6 +1,6 @@import type { Page, Request } from "@playwright/test"import { expect, sessionCookie, test } from "./_fixtures/community-fixture"-import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import { gotoAfterUserWsAuth, ignoreNextDevToolsPointerCapture } from "./_fixtures/actions"import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"import { WEB_URL } from "./_setup/paths"import {@@ -14,7 +14,7 @@ import { tid } from "./_fixtures/testids"type SurfaceGeometry = {viewport: { width: number; height: number }- userBar: { top: number; bottom: number; left: number; right: number }+ userBar: { top: number; surfaceBottom: number; bottom: number; left: number; right: number }card: { top: number; bottom: number; left: number; right: number; height: number }seam: {cardTopLeft: string@@ -45,15 +45,18 @@ async function removeServerChannels(serverId: string) {}async function surfaceGeometry(page: Page): Promise<SurfaceGeometry> {- return page.getByTestId(tid.inboxMobileCard).evaluate((card, ids) => {+ return page.getByTestId(tid.userBarExtension).evaluate((card, ids) => {const userBar = document.querySelector<HTMLElement>(`[data-testid='${ids.userBar}']`,)- const userBarSurface = userBar?.firstElementChild as HTMLElement | null+ const userBarSurface = userBar?.querySelector<HTMLElement>(+ "[data-slot='community-user-bar-base']",+ ) ?? nullif (!userBar || !userBarSurface) {throw new Error("missing mobile Inbox geometry")}- const userRect = userBar.getBoundingClientRect()+ const wrapperRect = userBar.getBoundingClientRect()+ const userRect = userBarSurface.getBoundingClientRect()const cardRect = card.getBoundingClientRect()const cardStyle = getComputedStyle(card)const userBarStyle = getComputedStyle(userBarSurface)@@ -65,7 +68,8 @@ async function surfaceGeometry(page: Page): Promise<SurfaceGeometry> {viewport: { width: innerWidth, height: innerHeight },userBar: {top: userRect.top,- bottom: userRect.bottom,+ surfaceBottom: userRect.bottom,+ bottom: wrapperRect.bottom,left: userRect.left,right: userRect.right,},@@ -119,6 +123,7 @@ test.describe.serial("mobile Inbox interactive user-bar base", () => {const ws = await proxyCommunityWebSockets(bob.context)await bob.page.setViewportSize({ width: 390, height: 844 })await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}`)+ await ignoreNextDevToolsPointerCapture(bob.page)await expect(bob.page.getByTestId(tid.inboxTrigger)).toBeVisible()await bob.page.evaluate(() => {@@ -137,18 +142,22 @@ test.describe.serial("mobile Inbox interactive user-bar base", () => {await expect(inboxTrigger).toHaveAttribute("aria-pressed", "false")await expect(inboxIcon).toHaveAttribute("fill", "none")await expect(inboxIcon).not.toHaveClass(/fill-current/)- const closedTriggerStyle = await inboxTrigger.evaluate((element) => {+ const readTriggerSurfaceStyle = () => inboxTrigger.evaluate((element) => {const style = getComputedStyle(element)return {backgroundColor: style.backgroundColor,+ color: style.color,borderWidth: style.borderWidth,- boxShadow: style.boxShadow,}})- const closedInboxIconColor = await inboxIcon.evaluate((element) => getComputedStyle(element).color)+ const readTriggerFocusRing = () => inboxTrigger.evaluate((element) => (+ getComputedStyle(element).boxShadow+ ))+ const closedTriggerSurfaceStyle = await readTriggerSurfaceStyle()+ const closedTriggerFocusRing = await readTriggerFocusRing()await inboxTrigger.click()await bob.page.mouse.move(0, 0)- const mobileSurface = bob.page.getByTestId(tid.inboxMobileSurface)+ const mobileSurface = bob.page.getByTestId(tid.userBarExtension)await expect(mobileSurface).toBeVisible()await expect(mobileSurface).toHaveAttribute("role", "dialog")await expect(mobileSurface).not.toHaveAttribute("aria-modal", "true")@@ -158,25 +167,39 @@ test.describe.serial("mobile Inbox interactive user-bar base", () => {await expect(inboxTrigger).toHaveAttribute("aria-pressed", "true")await expect(inboxIcon).toHaveAttribute("fill", "none")await expect(inboxIcon).not.toHaveClass(/fill-current/)- await expect.poll(() => inboxIcon.evaluate((element) => (- getComputedStyle(element).color- ))).not.toBe(closedInboxIconColor)- await expect.poll(() => inboxTrigger.evaluate((element) => {- const style = getComputedStyle(element)+ await expect.poll(async () => {+ const openStyle = await readTriggerSurfaceStyle()return {- backgroundColor: style.backgroundColor,- borderWidth: style.borderWidth,- boxShadow: style.boxShadow,+ backgroundChanged: openStyle.backgroundColor !== closedTriggerSurfaceStyle.backgroundColor,+ foregroundChanged: openStyle.color !== closedTriggerSurfaceStyle.color,+ borderWidth: openStyle.borderWidth,+ boxShadow: await readTriggerFocusRing(),}- })).toEqual(closedTriggerStyle)- expect(closedTriggerStyle.borderWidth).toBe("0px")- expect(closedTriggerStyle.boxShadow).toBe("none")+ }).toEqual({+ backgroundChanged: true,+ foregroundChanged: true,+ borderWidth: closedTriggerSurfaceStyle.borderWidth,+ boxShadow: closedTriggerFocusRing,+ })+ expect(closedTriggerSurfaceStyle.borderWidth).toBe("0px")+ expect(closedTriggerFocusRing).toBe("none")await expect(bob.page.getByRole("button", { name: "Close Inbox" })).toHaveCount(1)- await expect(inboxTrigger).toBeFocused()+ await expect(mobileSurface.getByRole("button", { name: /^Dismiss / })).toHaveCount(0)+ await expect(mobileSurface).toBeFocused()+ await bob.page.keyboard.press("Tab")+ expect(await mobileSurface.evaluate((element) => (+ element.contains(document.activeElement)+ && document.activeElement !== element+ ))).toBe(true)await expect(bob.page.getByTestId(tid.inboxMobileBackdrop)).toHaveCount(0)+ await expect.poll(async () => {+ const current = await surfaceGeometry(bob.page)+ return Math.abs(current.card.bottom - current.userBar.top)+ }).toBeLessThanOrEqual(1)const geometry = await surfaceGeometry(bob.page)expect(Math.abs(geometry.card.bottom - geometry.userBar.top)).toBeLessThanOrEqual(1)expect(geometry.userBar.bottom).toBe(844)+ expect(geometry.userBar.surfaceBottom).toBe(844 - 34 - 12)expect(geometry.userBarOwnsCenter).toBe(true)expect(geometry.card.height).toBeLessThanOrEqual(448)expect(geometry.card.top).toBeGreaterThanOrEqual(20)@@ -220,60 +243,67 @@ test.describe.serial("mobile Inbox interactive user-bar base", () => {].join(","))return {exists: !!hit,- insideInbox: !!hit?.closest(`[data-testid='${ids.inboxMobileSurface}']`),+ insideInbox: !!hit?.closest(`[data-testid='${ids.userBarExtension}']`),interactive: !!interactive,}- }, { point: outsidePoint, ids: { inboxMobileSurface: tid.inboxMobileSurface } })+ }, { point: outsidePoint, ids: { userBarExtension: tid.userBarExtension } })expect(outsideHit).toEqual({exists: true,insideInbox: false,interactive: false,})await bob.page.mouse.click(outsidePoint.x, outsidePoint.y)- await expect(bob.page.getByTestId(tid.inboxMobileSurface)).toHaveCount(0)+ await expect(bob.page.getByTestId(tid.userBarExtension)).toHaveCount(0)await expect(inboxTrigger).toBeFocused()await expect(inboxTrigger).toHaveAttribute("aria-label", "Open Inbox")await expect(inboxTrigger).toHaveAttribute("aria-pressed", "false")await expect(inboxIcon).toHaveAttribute("fill", "none")await expect(inboxIcon).not.toHaveClass(/fill-current/)- await expect.poll(() => inboxIcon.evaluate((element) => (- getComputedStyle(element).color- ))).toBe(closedInboxIconColor)+ await expect.poll(readTriggerSurfaceStyle).toEqual(closedTriggerSurfaceStyle)+ await expect.poll(readTriggerFocusRing).toContain("2px")await expect(bob.page).toHaveURL(new RegExp(`/c/channels/${serverId}$`))expect(writes.writes).toEqual([])expect(ws.frames).toHaveLength(wsBefore)await inboxTrigger.click()await inboxTrigger.click()- await expect(bob.page.getByTestId(tid.inboxMobileSurface)).toHaveCount(0)+ await bob.page.mouse.move(0, 0)+ await expect(bob.page.getByTestId(tid.userBarExtension)).toHaveCount(0)await expect(inboxTrigger).toBeFocused()+ await expect(inboxIcon).toHaveAttribute("fill", "none")+ await expect(inboxIcon).not.toHaveClass(/fill-current/)+ await expect.poll(readTriggerSurfaceStyle).toEqual(closedTriggerSurfaceStyle)+ await expect.poll(readTriggerFocusRing).toBe("none")await inboxTrigger.click()await bob.page.keyboard.press("Escape")- await expect(bob.page.getByTestId(tid.inboxMobileSurface)).toHaveCount(0)+ await expect(bob.page.getByTestId(tid.userBarExtension)).toHaveCount(0)await expect(inboxTrigger).toBeFocused()await inboxTrigger.click()await bob.page.getByTestId(tid.userSettingsOpen).click()- await expect(bob.page.getByTestId(tid.inboxMobileSurface)).toHaveCount(0)+ await expect(bob.page.getByTestId(tid.userBarExtension)).toHaveCount(0)await expect(bob.page.getByTestId(tid.settingsShell)).toHaveCount(1)await expect(inboxTrigger).not.toBeFocused()await bob.page.getByTestId(tid.settingsClose).click()await inboxTrigger.click()- await bob.page.getByTestId(tid.userBar).locator("button").first().click()- await expect(bob.page.getByTestId(tid.inboxMobileSurface)).toHaveCount(0)+ await bob.page.locator("[data-slot='community-user-bar-base'] button").first().click()+ await expect(bob.page.getByTestId(tid.userBarExtension)).toHaveAttribute("data-extension", "profile")await expect(bob.page.getByTestId(tid.profileCard)).toHaveCount(1)await expect(inboxTrigger).not.toBeFocused()await bob.page.keyboard.press("Escape")await bob.page.setViewportSize({ width: 320, height: 568 })await inboxTrigger.click()+ await expect.poll(async () => {+ const current = await surfaceGeometry(bob.page)+ return Math.abs(current.card.bottom - current.userBar.top)+ }).toBeLessThanOrEqual(1)const compact = await surfaceGeometry(bob.page)- expect(Math.abs(compact.card.bottom - compact.userBar.top)).toBeLessThanOrEqual(1)expect(compact.card.top).toBeGreaterThanOrEqual(20)- expect(compact.card.left).toBeGreaterThanOrEqual(18)- expect(compact.card.right).toBeLessThanOrEqual(320 - 16)+ expect(compact.card.left).toBe(18)+ expect(compact.card.right).toBe(320 - 16)await inboxTrigger.click()expect(writes.writes).toEqual([])@@ -281,6 +311,58 @@ test.describe.serial("mobile Inbox interactive user-bar base", () => {writes.stop()})+ test("matches the mobile Composer width, height, and bottom margin", async ({ asUser }) => {+ const stamp = Date.now()+ const serverId = await seedServer("alice", `User Bar alignment ${stamp}`)+ const channelId = await seedChannel("alice", serverId, `alignment-${stamp}`)+ await seedJoinServer("alice", "bob", serverId)+ const bob = await asUser("bob")++ for (const width of [320, 390]) {+ await bob.page.setViewportSize({ width, height: 844 })+ await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}`)+ await expect(bob.page.locator('meta[name="viewport"]')).toHaveAttribute(+ "content",+ /viewport-fit=cover/,+ )+ await bob.page.evaluate(() => {+ const style = document.documentElement.style+ style.setProperty("--app-safe-area-top", "20px")+ style.setProperty("--app-safe-area-right", "16px")+ style.setProperty("--app-safe-area-bottom", "34px")+ style.setProperty("--app-safe-area-left", "18px")+ })+ const userBarBox = await bob.page+ .locator("[data-slot='community-user-bar-base']")+ .boundingBox()+ expect(userBarBox).not.toBeNull()++ await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${channelId}`)+ await bob.page.evaluate(() => {+ const style = document.documentElement.style+ style.setProperty("--app-safe-area-top", "20px")+ style.setProperty("--app-safe-area-right", "16px")+ style.setProperty("--app-safe-area-bottom", "34px")+ style.setProperty("--app-safe-area-left", "18px")+ })+ const composer = bob.page+ .getByTestId(tid.channelComposerShell)+ .locator("[data-slot='community-composer-base']")+ await expect(composer).toBeVisible()+ const composerBox = await composer.boundingBox()+ expect(composerBox).not.toBeNull()++ expect(Math.abs(userBarBox!.x - composerBox!.x)).toBeLessThanOrEqual(1)+ expect(Math.abs(userBarBox!.width - composerBox!.width)).toBeLessThanOrEqual(1)+ expect(Math.abs(userBarBox!.height - composerBox!.height)).toBeLessThanOrEqual(1)+ expect(Math.abs(userBarBox!.y - composerBox!.y)).toBeLessThanOrEqual(1)+ expect(userBarBox!.x).toBe(18)+ expect(userBarBox!.x + userBarBox!.width).toBe(width - 16)+ expect(userBarBox!.height).toBe(48)+ expect(Math.abs(844 - userBarBox!.y - userBarBox!.height)).toBe(34 + 12)+ }+ })+test("preserves Marked tab, scroll, and request ownership across 639↔640", async ({ asUser }) => {const stamp = Date.now()const serverId = await seedServer("alice", `Inbox continuity ${stamp}`)@@ -352,15 +434,16 @@ test.describe.serial("mobile Inbox interactive user-bar base", () => {const getsBeforeResize = inboxGets.lengthawait bob.page.setViewportSize({ width: 640, height: 844 })- await expect(bob.page.getByTestId(tid.inboxMobileSurface)).toHaveCount(0)- await expect(bob.page.locator("[data-slot='popover-content']")).toBeVisible()+ await expect(bob.page.getByTestId(tid.userBarExtension)).toBeVisible()+ await expect(bob.page.getByTestId(tid.userBarExtension)).toHaveAttribute("data-extension", "inbox")+ await expect(bob.page.locator("[data-slot='popover-content']")).toHaveCount(0)await expect(bob.page.getByRole("tab", { name: "Marked" })).toHaveAttribute("aria-selected", "true")const desktopScroll = bob.page.getByTestId(tid.inboxTabScroll("marked"))await expect.poll(() => desktopScroll.evaluate((element) => element.scrollTop)).toBeGreaterThanOrEqual(priorScroll - 1)await bob.page.setViewportSize({ width: 639, height: 844 })- await expect(bob.page.getByTestId(tid.inboxMobileSurface)).toBeVisible()+ await expect(bob.page.getByTestId(tid.userBarExtension)).toBeVisible()await expect(bob.page.getByRole("tab", { name: "Marked" })).toHaveAttribute("aria-selected", "true")const mobileScroll = bob.page.getByTestId(tid.inboxTabScroll("marked"))const restoredMobileScroll = await mobileScroll.evaluate((element) => ({@@ -373,12 +456,14 @@ test.describe.serial("mobile Inbox interactive user-bar base", () => {)).toBeLessThanOrEqual(1)await bob.page.setViewportSize({ width: 1280, height: 900 })- const desktopContent = bob.page.locator("[data-slot='popover-content']")+ const desktopContent = bob.page.getByTestId(tid.userBarExtension)await expect(desktopContent).toBeVisible()await expect.poll(async () => (await desktopContent.boundingBox())?.width ?? 0)- .toBeGreaterThanOrEqual(359)+ .toBeGreaterThanOrEqual(200)const desktopBox = await desktopContent.boundingBox()- expect(desktopBox?.width).toBeLessThanOrEqual(361)+ const desktopBaseBox = await bob.page.locator("[data-slot='community-user-bar-base']").boundingBox()+ expect(desktopBaseBox).not.toBeNull()+ expect(Math.abs((desktopBox?.width ?? 0) - desktopBaseBox!.width)).toBeLessThanOrEqual(1)await expect(bob.page.getByTestId(tid.inboxMobileBackdrop)).toHaveCount(0)await expect(bob.page.getByRole("tab", { name: "Marked" })).toHaveAttribute("aria-selected", "true")diff --git a/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts b/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.tsindex c121b92a0..f3c57425d 100644--- a/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts+++ b/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts@@ -49,6 +49,7 @@ export type CommunityWsProxy = {releaseHeld: (predicate?: (frame: CapturedCommunityFrame) => boolean) => numberreleaseHeldConnections: (predicate?: (frame: CapturedConnectionFrame) => boolean) => numberreplay: (frame: CapturedCommunityFrame) => void+ send: (frame: CapturedCommunityFrame) => voidsendConnectionFrame: (frame: { type: "connection.pong" | "auth.ok"; nonce?: string }) => voiddisconnect: () => Promise<void>}@@ -198,6 +199,10 @@ export async function proxyCommunityWebSockets(if (!message || !activeClient) throw new Error("community frame is not replayable")activeClient.send(message)},+ send: (frame) => {+ if (!activeClient) throw new Error("community frame target missing")+ activeClient.send(JSON.stringify(frame))+ },sendConnectionFrame: (frame) => {if (!activeClient || activeConnectionId === undefined) {throw new Error("connection frame target missing")