Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): notify users about daemon updates (#645)

Gustavo Yeaecae800b890
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index aa359e96a..b7148d88a 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -58,6 +58,7 @@ export const SPEC_SECONDS = {
"41-community-initial-load-module-skeletons.spec.ts": 30,
"42-versioned-avatar-identity.spec.ts": 50,
"44-mobile-reaction-details.spec.ts": 70,
+ "50-daemon-update-notice.spec.ts": 35,
"51-share-image-assets.spec.ts": 20,
}
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index 8e5c4ef8f..e30ec223e 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -70,7 +70,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([432, 433, 436, 437, 437])
+ expect(totals.sort((left, right) => left - right)).toEqual([439, 440, 443, 444, 444])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/web/next.config.ts b/src/web/next.config.ts
index 9714584b3..fdd4eb566 100644
--- a/src/web/next.config.ts
+++ b/src/web/next.config.ts
@@ -5,10 +5,12 @@ import createMDX from "@next/mdx";
import { blogRedirects } from "./src/lib/blog/redirects";
const pkg = JSON.parse(readFileSync(path.resolve(__dirname, "package.json"), "utf-8"));
+const daemonPkg = JSON.parse(readFileSync(path.resolve(__dirname, "../daemon/package.json"), "utf-8"));
const nextConfig: NextConfig = {
env: {
NEXT_PUBLIC_APP_VERSION: pkg.version,
+ NEXT_PUBLIC_LATEST_DAEMON_VERSION: daemonPkg.version,
},
// Prevent the bundler from creating duplicate copies of @better-auth/core,
// which breaks AsyncLocalStorage-based request state (dual module hazard).
diff --git a/src/web/src/app/(app)/layout.tsx b/src/web/src/app/(app)/layout.tsx
index 810263483..668024b8b 100644
--- a/src/web/src/app/(app)/layout.tsx
+++ b/src/web/src/app/(app)/layout.tsx
@@ -3,6 +3,7 @@ import { redirect } from "next/navigation";
import { getSession } from "@/lib/session";
import { SignupTracker } from "@/components/signup-tracker";
import { SigninTracker } from "@/components/signin-tracker";
+import { DaemonUpdateNotice } from "@/components/daemon-update-notice";
export const metadata: Metadata = {
robots: { index: false, follow: false },
@@ -20,6 +21,7 @@ export default async function AppLayout({
<>
<SignupTracker />
<SigninTracker />
+ <DaemonUpdateNotice userId={session.user.id} />
{children}
</>
);
diff --git a/src/web/src/app/c/community-shell.identity.test.ts b/src/web/src/app/c/community-shell.identity.test.ts
index 6ae0bdb84..55cb7b783 100644
--- a/src/web/src/app/c/community-shell.identity.test.ts
+++ b/src/web/src/app/c/community-shell.identity.test.ts
@@ -31,6 +31,9 @@ vi.mock("@/lib/community/profile-seed", () => ({
apiFetchProfiles: (...args: unknown[]) => apiFetchProfiles(...args),
}))
vi.mock("@/components/perf/perf-trace-bootstrap", () => ({ PerfTraceBootstrap: () => null }))
+vi.mock("@/components/daemon-update-notice", () => ({
+ CommunityDaemonUpdateNotice: () => null,
+}))
vi.mock("@/components/community/onboarding/community-onboarding-guide", () => ({
CommunityOnboardingGuide: () => null,
}))
diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsx
index 8ba3ab4ec..ae5780a74 100644
--- a/src/web/src/app/c/community-shell.tsx
+++ b/src/web/src/app/c/community-shell.tsx
@@ -12,6 +12,7 @@ import { useCommunityWs } from "@/hooks/community/use-community-ws"
import { PerfTraceBootstrap } from "@/components/perf/perf-trace-bootstrap"
import { CommunityOnboardingGuide } from "@/components/community/onboarding/community-onboarding-guide"
import { CommunityWsReconnectBoundary } from "@/components/community/shell/community-ws-reconnect-overlay"
+import { CommunityDaemonUpdateNotice } from "@/components/daemon-update-notice"
import { useCommunityWsStore } from "@/stores/community/ws"
/**
@@ -109,6 +110,7 @@ function CommunityBootstrap({ children }: { children: ReactNode }) {
return (
<>
<PerfTraceBootstrap />
+ <CommunityDaemonUpdateNotice userId={currentUser.id} />
<CommunityWsReconnectBoundary>
<CommunityOnboardingGuide />
{children}
diff --git a/src/web/src/app/c/layout.test.ts b/src/web/src/app/c/layout.test.ts
index 02cea2b24..1167175d6 100644
--- a/src/web/src/app/c/layout.test.ts
+++ b/src/web/src/app/c/layout.test.ts
@@ -24,7 +24,6 @@ vi.mock("@/components/community/shell/community-session-pending-frame", () => ({
vi.mock("@/components/signup-tracker", () => ({
SignupTracker: (props: Record<string, unknown>) => createElement("signup-tracker", props),
}))
-
import CommunityLayout from "./layout"
function render() {
@@ -64,6 +63,7 @@ describe("CommunityLayout session boundary", () => {
const shell = renderer.root.findByType("community-shell")
expect(shell.props.currentUser).toMatchObject({ id: "u1", name: "Ada", email: "[email protected]" })
expect(renderer.root.findAllByType("session-pending")).toHaveLength(0)
+ expect(shell.props.currentUser.id).toBe("u1")
})
it("preserves the public invite bypass", () => {
@@ -90,4 +90,10 @@ describe("CommunityLayout session boundary", () => {
expect(source).toContain("const canonicalDmsUnsettled = dmsPending || dmsFetching")
expect(source).toContain("useDmRouteVerification(params.dmId, rawDms, canonicalDmsUnsettled)")
})
+
+ it("mounts the daemon check inside the authenticated Community query cache", () => {
+ const shell = readFileSync(new URL("./community-shell.tsx", import.meta.url), "utf8")
+ expect(shell.indexOf("<QueryProvider")).toBeLessThan(shell.indexOf("<CommunityDaemonUpdateNotice"))
+ expect(shell).toContain("<CommunityDaemonUpdateNotice userId={currentUser.id} />")
+ })
})
diff --git a/src/web/src/app/layout.tsx b/src/web/src/app/layout.tsx
index ddbf9cd01..cfdb29609 100644
--- a/src/web/src/app/layout.tsx
+++ b/src/web/src/app/layout.tsx
@@ -2,6 +2,7 @@ import type { Metadata, Viewport } from "next";
import { GoogleTagManager } from "@next/third-parties/google";
import { ThemeProvider } from "@/components/theme-provider";
import { ToasterProvider } from "@/components/toaster-provider";
+import { MessageNotificationToaster } from "@/components/ui/toast";
import { TooltipProvider } from "@/components/ui/tooltip";
import { MockNetworkBanner } from "@/components/mock-network-banner";
import { TauriThemeSync } from "@/components/tauri-theme-sync";
@@ -121,6 +122,7 @@ export default function RootLayout({
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
<ThemeColorSync />
<TauriThemeSync />
+ <MessageNotificationToaster />
<TooltipProvider>
{children}
</TooltipProvider>
diff --git a/src/web/src/components/daemon-update-notice.test.ts b/src/web/src/components/daemon-update-notice.test.ts
new file mode 100644
index 000000000..5a79af29e
--- /dev/null
+++ b/src/web/src/components/daemon-update-notice.test.ts
@@ -0,0 +1,243 @@
+import React from "react"
+import { readFileSync } from "node:fs"
+import TestRenderer, { act } from "react-test-renderer"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ machinesQueryFn: vi.fn(),
+ notificationAdd: vi.fn(),
+ notificationClose: vi.fn(),
+ requestUpdate: vi.fn(),
+}))
+
+vi.mock("@/hooks/community/use-machines", () => ({
+ machinesQueryFn: mocks.machinesQueryFn,
+}))
+
+vi.mock("@/components/ui/toast", () => ({
+ messageNotification: {
+ add: mocks.notificationAdd,
+ close: mocks.notificationClose,
+ },
+}))
+
+import {
+ DaemonUpdateNotice,
+ daemonUpdateStorageKey,
+ dispatchDaemonUpdates,
+ eligibleDaemonUpdateMachines,
+} from "./daemon-update-notice"
+
+const values = new Map<string, string>()
+const localStorage = {
+ getItem: vi.fn((key: string) => values.get(key) ?? null),
+ setItem: vi.fn((key: string, value: string) => values.set(key, value)),
+}
+
+function machine(
+ daemonVersion: string,
+ overrides: { id?: string; status?: "online" | "offline" } = {},
+) {
+ return {
+ id: overrides.id ?? `machine-${daemonVersion}`,
+ status: overrides.status ?? "online",
+ daemonVersion,
+ }
+}
+
+async function renderNotice() {
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(DaemonUpdateNotice, {
+ userId: "user-1",
+ webVersion: "0.1.27",
+ latestDaemonVersion: "0.1.27",
+ requestUpdate: mocks.requestUpdate,
+ }),
+ )
+ })
+ return renderer
+}
+
+describe("DaemonUpdateNotice", () => {
+ beforeEach(() => {
+ values.clear()
+ localStorage.getItem.mockReset()
+ localStorage.getItem.mockImplementation((key: string) => values.get(key) ?? null)
+ localStorage.setItem.mockReset()
+ localStorage.setItem.mockImplementation((key: string, value: string) => values.set(key, value))
+ mocks.machinesQueryFn.mockReset()
+ mocks.notificationAdd.mockReset()
+ mocks.notificationAdd.mockReturnValue("toast-1")
+ mocks.notificationClose.mockReset()
+ mocks.requestUpdate.mockReset()
+ mocks.requestUpdate.mockResolvedValue({ dispatched: true })
+ vi.stubGlobal("window", { localStorage })
+ })
+
+ it("uses the release daemon package as the Web build target", () => {
+ const config = readFileSync(new URL("../../next.config.ts", import.meta.url), "utf8")
+ expect(config).toContain('path.resolve(__dirname, "../daemon/package.json")')
+ expect(config).toContain("NEXT_PUBLIC_LATEST_DAEMON_VERSION: daemonPkg.version")
+ })
+
+ it("selects only online, remotely updateable daemon releases below the target", () => {
+ expect(eligibleDaemonUpdateMachines([
+ machine("0.1.26"),
+ machine("0.1.27"),
+ machine("0.1.28"),
+ machine("0.1.26", { id: "offline", status: "offline" }),
+ machine("0.1.6", { id: "manual-update-only" }),
+ machine(""),
+ machine("dev"),
+ ], "0.1.27")).toEqual([machine("0.1.26")])
+ expect(eligibleDaemonUpdateMachines([machine("0.1.26")], "latest")).toEqual([])
+ })
+
+ it("records the current Web version after one successful all-current query", async () => {
+ mocks.machinesQueryFn.mockResolvedValue({ machines: [machine("0.1.27"), machine("")] })
+ await renderNotice()
+
+ expect(mocks.machinesQueryFn).toHaveBeenCalledOnce()
+ expect(localStorage.setItem).toHaveBeenCalledWith(
+ daemonUpdateStorageKey("user-1"),
+ "0.1.27",
+ )
+ expect(mocks.notificationAdd).not.toHaveBeenCalled()
+ })
+
+ it("skips the query when this user already checked the current Web version", async () => {
+ values.set(daemonUpdateStorageKey("user-1"), "0.1.27")
+ await renderNotice()
+
+ expect(mocks.machinesQueryFn).not.toHaveBeenCalled()
+ expect(mocks.notificationAdd).not.toHaveBeenCalled()
+ })
+
+ it("checks again when the stored flag belongs to an older Web version", async () => {
+ values.set(daemonUpdateStorageKey("user-1"), "0.1.26")
+ mocks.machinesQueryFn.mockResolvedValue({ machines: [machine("0.1.26")] })
+ await renderNotice()
+
+ expect(mocks.machinesQueryFn).toHaveBeenCalledOnce()
+ expect(mocks.notificationAdd).toHaveBeenCalledOnce()
+ })
+
+ it("shows the exact one-click update notification without recording early", async () => {
+ mocks.machinesQueryFn.mockResolvedValue({
+ machines: [machine("0.1.26")],
+ })
+ await renderNotice()
+ const notice = mocks.notificationAdd.mock.calls[0]![0]
+
+ expect(notice.title).toBe("Machine update available")
+ expect(notice.description).toBe("You can update your machine to get more features.")
+ expect(notice.actionProps.children).toBe("Update")
+ expect(notice.data.closeLabel).toBe("Hide until the next Web update")
+ expect(notice.data.bareIcon).toBe(true)
+ expect(notice.data.icon.props).toMatchObject({
+ src: "/alook.svg",
+ alt: "",
+ width: 32,
+ height: 32,
+ })
+ expect(notice.timeout).toBe(0)
+ expect(localStorage.setItem).not.toHaveBeenCalled()
+ })
+
+ it("uses plural copy when multiple machines can update", async () => {
+ mocks.machinesQueryFn.mockResolvedValue({
+ machines: [machine("0.1.26"), machine("0.1.20")],
+ })
+ await renderNotice()
+
+ expect(mocks.notificationAdd.mock.calls[0]![0].description)
+ .toBe("You can update your machines to get more features.")
+ })
+
+ it("retries the canceled development pass under React Strict Mode", async () => {
+ mocks.machinesQueryFn.mockResolvedValue({ machines: [machine("0.1.26")] })
+
+ await act(async () => {
+ TestRenderer.create(
+ React.createElement(
+ React.StrictMode,
+ null,
+ React.createElement(DaemonUpdateNotice, {
+ userId: "user-1",
+ webVersion: "0.1.27",
+ latestDaemonVersion: "0.1.27",
+ requestUpdate: mocks.requestUpdate,
+ }),
+ ),
+ )
+ })
+
+ expect(mocks.machinesQueryFn).toHaveBeenCalledOnce()
+ expect(mocks.notificationAdd).toHaveBeenCalledOnce()
+ })
+
+ it("closes immediately, records handling, and dispatches every eligible machine once", async () => {
+ mocks.machinesQueryFn.mockResolvedValue({
+ machines: [
+ machine("0.1.26", { id: "eligible-1" }),
+ machine("0.1.20", { id: "eligible-2" }),
+ machine("0.1.26", { id: "offline", status: "offline" }),
+ machine("0.1.6", { id: "manual-update-only" }),
+ ],
+ })
+ await renderNotice()
+ const notice = mocks.notificationAdd.mock.calls[0]![0]
+
+ act(() => notice.actionProps.onClick())
+ act(() => notice.actionProps.onClick())
+ expect(mocks.notificationClose).toHaveBeenCalledWith("toast-1")
+ expect(localStorage.setItem).toHaveBeenCalledWith(
+ daemonUpdateStorageKey("user-1"),
+ "0.1.27",
+ )
+ expect(mocks.requestUpdate.mock.calls).toEqual([
+ ["eligible-1"],
+ ["eligible-2"],
+ ])
+ })
+
+ it("absorbs background dispatch failures", async () => {
+ const requestUpdate = vi.fn().mockRejectedValue(new Error("offline race"))
+
+ await expect(dispatchDaemonUpdates(
+ [{ id: "machine-1" }],
+ requestUpdate,
+ )).resolves.toBeUndefined()
+ })
+
+ it("keeps request failures retryable", async () => {
+ mocks.machinesQueryFn.mockRejectedValue(new Error("offline"))
+ await renderNotice()
+
+ expect(localStorage.setItem).not.toHaveBeenCalled()
+ expect(mocks.notificationAdd).not.toHaveBeenCalled()
+ })
+
+ it("fails open when local storage is unavailable", async () => {
+ localStorage.getItem.mockImplementationOnce(() => {
+ throw new Error("storage disabled")
+ })
+ localStorage.setItem.mockImplementationOnce(() => {
+ throw new Error("storage disabled")
+ })
+ mocks.machinesQueryFn.mockResolvedValue({ machines: [machine("0.1.27")] })
+
+ await expect(renderNotice()).resolves.toBeDefined()
+ expect(mocks.machinesQueryFn).toHaveBeenCalledOnce()
+ expect(mocks.notificationAdd).not.toHaveBeenCalled()
+ })
+
+ it("mounts the thin controller only in authenticated route groups", () => {
+ const appLayout = readFileSync(new URL("../app/(app)/layout.tsx", import.meta.url), "utf8")
+ const communityShell = readFileSync(new URL("../app/c/community-shell.tsx", import.meta.url), "utf8")
+ expect(appLayout).toContain("<DaemonUpdateNotice userId={session.user.id} />")
+ expect(communityShell).toContain("<CommunityDaemonUpdateNotice userId={currentUser.id} />")
+ })
+})
diff --git a/src/web/src/components/daemon-update-notice.tsx b/src/web/src/components/daemon-update-notice.tsx
new file mode 100644
index 000000000..df6248f19
--- /dev/null
+++ b/src/web/src/components/daemon-update-notice.tsx
@@ -0,0 +1,178 @@
+"use client"
+
+import { useCallback, useEffect, useRef, type ComponentPropsWithoutRef } from "react"
+import Image from "next/image"
+import { useQueryClient } from "@tanstack/react-query"
+import {
+ SELF_UPDATE_MIN_DAEMON_VERSION,
+ isPresenceOnline,
+ parseReleaseVersion,
+ releaseVersionGte,
+} from "@alook/shared"
+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"
+
+const STORAGE_KEY_PREFIX = "alook:daemon-update-check"
+const pendingMachineChecks = new Map<string, ReturnType<typeof machinesQueryFn>>()
+
+export function daemonUpdateStorageKey(userId: string): string {
+ return `${STORAGE_KEY_PREFIX}:${userId}`
+}
+
+export function eligibleDaemonUpdateMachines<T extends Pick<MachineSummary, "id" | "status" | "daemonVersion">>(
+ machines: readonly T[],
+ latestDaemonVersion: string,
+): T[] {
+ if (!parseReleaseVersion(latestDaemonVersion)) return []
+ return machines.filter((machine) => {
+ const currentVersion = machine.daemonVersion
+ if (!isPresenceOnline(machine.status) || !currentVersion || !parseReleaseVersion(currentVersion)) {
+ return false
+ }
+ return releaseVersionGte(currentVersion, SELF_UPDATE_MIN_DAEMON_VERSION)
+ && !releaseVersionGte(currentVersion, latestDaemonVersion)
+ })
+}
+
+type MachineUpdateRequester = (machineId: string) => Promise<unknown>
+
+async function requestMachineUpdate(machineId: string): Promise<void> {
+ await apiFetch<{ dispatched: true }>(`/api/community/machines/${machineId}/update`, {
+ method: "POST",
+ })
+}
+
+export async function dispatchDaemonUpdates(
+ machines: readonly Pick<MachineSummary, "id">[],
+ requestUpdate: MachineUpdateRequester = requestMachineUpdate,
+): Promise<void> {
+ await Promise.all(machines.map(async (machine) => {
+ try {
+ await requestUpdate(machine.id)
+ } catch (error) {
+ log.warn("daemon update notification dispatch failed", {
+ machineId: machine.id,
+ error: String(error),
+ })
+ }
+ }))
+}
+
+function readCheckedWebVersion(userId: string): string | null {
+ try {
+ return window.localStorage.getItem(daemonUpdateStorageKey(userId))
+ } catch {
+ return null
+ }
+}
+
+function writeCheckedWebVersion(userId: string, webVersion: string): void {
+ try {
+ window.localStorage.setItem(daemonUpdateStorageKey(userId), webVersion)
+ } catch {}
+}
+
+type MachinesLoader = typeof machinesQueryFn
+
+function fetchMachinesOnce(
+ checkKey: string,
+ loadMachines: MachinesLoader,
+): ReturnType<typeof machinesQueryFn> {
+ const pending = pendingMachineChecks.get(checkKey)
+ if (pending) return pending
+
+ const request = loadMachines().finally(() => {
+ if (pendingMachineChecks.get(checkKey) === request) pendingMachineChecks.delete(checkKey)
+ })
+ pendingMachineChecks.set(checkKey, request)
+ return request
+}
+
+export function DaemonUpdateNotice({
+ userId,
+ webVersion = process.env.NEXT_PUBLIC_APP_VERSION,
+ latestDaemonVersion = process.env.NEXT_PUBLIC_LATEST_DAEMON_VERSION,
+ loadMachines = machinesQueryFn,
+ requestUpdate = requestMachineUpdate,
+}: {
+ userId: string
+ webVersion?: string
+ latestDaemonVersion?: string
+ loadMachines?: MachinesLoader
+ requestUpdate?: MachineUpdateRequester
+}) {
+ const startedCheck = useRef<string | null>(null)
+
+ useEffect(() => {
+ if (!webVersion || !latestDaemonVersion) return
+ if (!parseReleaseVersion(webVersion) || !parseReleaseVersion(latestDaemonVersion)) return
+ const checkKey = `${userId}:${webVersion}:${latestDaemonVersion}`
+ if (startedCheck.current === checkKey) return
+ startedCheck.current = checkKey
+ if (readCheckedWebVersion(userId) === webVersion) return
+
+ let active = true
+ void fetchMachinesOnce(checkKey, loadMachines)
+ .then(({ machines }) => {
+ if (!active) return
+ const eligible = eligibleDaemonUpdateMachines(machines, latestDaemonVersion)
+ if (eligible.length === 0) {
+ writeCheckedWebVersion(userId, webVersion)
+ return
+ }
+ let dispatched = false
+ const notificationId = messageNotification.add({
+ id: `daemon-update:${userId}:${webVersion}`,
+ title: "Machine update available",
+ description: eligible.length === 1
+ ? "You can update your machine to get more features."
+ : "You can update your machines to get more features.",
+ type: "warning",
+ timeout: 0,
+ data: {
+ closeLabel: "Hide until the next Web update",
+ bareIcon: true,
+ icon: <Image src="/alook.svg" alt="" width={32} height={32} className="size-8" />,
+ testId: tid.daemonUpdateNotice,
+ },
+ actionProps: {
+ children: "Update",
+ "data-testid": tid.daemonUpdateAction,
+ onClick: () => {
+ if (dispatched) return
+ dispatched = true
+ writeCheckedWebVersion(userId, webVersion)
+ messageNotification.close(notificationId)
+ void dispatchDaemonUpdates(eligible, requestUpdate)
+ },
+ } as ComponentPropsWithoutRef<"button">,
+ onClose: () => writeCheckedWebVersion(userId, webVersion),
+ })
+ })
+ .catch(() => {})
+
+ return () => {
+ active = false
+ if (startedCheck.current === checkKey) startedCheck.current = null
+ }
+ }, [latestDaemonVersion, loadMachines, requestUpdate, userId, webVersion])
+
+ 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/components/ui/toast.test.ts b/src/web/src/components/ui/toast.test.ts
new file mode 100644
index 000000000..fb99cf91a
--- /dev/null
+++ b/src/web/src/components/ui/toast.test.ts
@@ -0,0 +1,314 @@
+import { readFileSync } from "node:fs"
+import React, { type ReactNode } from "react"
+import { act, create, type ReactTestInstance, type ReactTestRenderer } from "react-test-renderer"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+type MockToast = {
+ actionProps?: { children?: ReactNode; onClick?: () => void }
+ data?: { closeLabel?: string; icon?: ReactNode; testId?: string }
+ description?: ReactNode
+ id: string
+ limited?: boolean
+ onClose?: () => void
+ title?: ReactNode
+ type?: string
+}
+
+type MockManager = {
+ add: (toast: Omit<MockToast, "id"> & { id?: string }) => string
+ close: (id?: string) => void
+ items: MockToast[]
+ subscribe: (listener: () => void) => () => void
+}
+
+vi.mock("@base-ui/react/toast", async () => {
+ const ReactModule = await import("react")
+ const ManagerContext = ReactModule.createContext<{
+ manager: MockManager
+ toasts: MockToast[]
+ } | null>(null)
+ const CurrentToastContext = ReactModule.createContext<{
+ manager: MockManager
+ toast: MockToast
+ } | null>(null)
+
+ function createToastManager(): MockManager {
+ const listeners = new Set<() => void>()
+ const manager: MockManager = {
+ items: [],
+ add(toast) {
+ const id = toast.id ?? `toast-${manager.items.length + 1}`
+ manager.items = [{ ...toast, id }, ...manager.items.filter((item) => item.id !== id)]
+ listeners.forEach((listener) => listener())
+ return id
+ },
+ close(id) {
+ const closing = id
+ ? manager.items.filter((item) => item.id === id)
+ : manager.items
+ closing.forEach((item) => item.onClose?.())
+ manager.items = id ? manager.items.filter((item) => item.id !== id) : []
+ listeners.forEach((listener) => listener())
+ },
+ subscribe(listener) {
+ listeners.add(listener)
+ return () => listeners.delete(listener)
+ },
+ }
+ return manager
+ }
+
+ function Provider({
+ children,
+ limit = Number.POSITIVE_INFINITY,
+ toastManager,
+ }: {
+ children: ReactNode
+ limit?: number
+ toastManager: MockManager
+ }) {
+ const [, rerender] = ReactModule.useReducer((value) => value + 1, 0)
+ ReactModule.useEffect(() => toastManager.subscribe(rerender), [toastManager])
+ const toasts = toastManager.items.map((toast, index) => ({
+ ...toast,
+ limited: index >= limit,
+ }))
+ return ReactModule.createElement(
+ ManagerContext.Provider,
+ { value: { manager: toastManager, toasts } },
+ children,
+ )
+ }
+
+ function useToastManager() {
+ const context = ReactModule.useContext(ManagerContext)
+ if (!context) throw new Error("Missing toast provider")
+ return { toasts: context.toasts }
+ }
+
+ function Root({ children, swipeDirection, toast, ...props }: Record<string, unknown> & {
+ children?: ReactNode
+ swipeDirection?: string[]
+ toast: MockToast
+ }) {
+ const context = ReactModule.useContext(ManagerContext)
+ if (!context) throw new Error("Missing toast provider")
+ return ReactModule.createElement(
+ CurrentToastContext.Provider,
+ { value: { manager: context.manager, toast } },
+ ReactModule.createElement("toast-root", {
+ ...props,
+ "data-limited": toast.limited || undefined,
+ onSwipeDismiss: () => context.manager.close(toast.id),
+ swipeDirection,
+ }, children),
+ )
+ }
+
+ function CurrentToastElement({ as, children, ...props }: Record<string, unknown> & {
+ as: string
+ children?: ReactNode
+ }) {
+ const context = ReactModule.useContext(CurrentToastContext)
+ if (!context) throw new Error("Missing current toast")
+ const value = as === "toast-title" ? context.toast.title : context.toast.description
+ return ReactModule.createElement(as, props, children ?? value)
+ }
+
+ function Action({ children, render: _render, ...props }: Record<string, unknown> & {
+ children?: ReactNode
+ }) {
+ const context = ReactModule.useContext(CurrentToastContext)
+ if (!context) throw new Error("Missing current toast")
+ return ReactModule.createElement("button", {
+ ...props,
+ ...context.toast.actionProps,
+ }, children ?? context.toast.actionProps?.children)
+ }
+
+ function Close({ children, render: _render, ...props }: Record<string, unknown> & {
+ children?: ReactNode
+ }) {
+ const context = ReactModule.useContext(CurrentToastContext)
+ if (!context) throw new Error("Missing current toast")
+ return ReactModule.createElement("button", {
+ ...props,
+ onClick: () => context.manager.close(context.toast.id),
+ }, children)
+ }
+
+ const passthrough = (as: string) => function Passthrough({ children, ...props }: Record<string, unknown> & {
+ children?: ReactNode
+ }) {
+ return ReactModule.createElement(as, props, children)
+ }
+
+ return {
+ Toast: {
+ Action,
+ Close,
+ Content: passthrough("toast-content"),
+ Description: (props: Record<string, unknown>) => ReactModule.createElement(CurrentToastElement, { ...props, as: "toast-description" }),
+ Portal: passthrough("toast-portal"),
+ Provider,
+ Root,
+ Title: (props: Record<string, unknown>) => ReactModule.createElement(CurrentToastElement, { ...props, as: "toast-title" }),
+ Viewport: passthrough("toast-viewport"),
+ createToastManager,
+ useToastManager,
+ },
+ }
+})
+
+import {
+ MessageNotificationToaster,
+ messageNotification,
+} from "./toast"
+
+let renderer: ReactTestRenderer
+
+function renderToaster() {
+ act(() => {
+ renderer = create(React.createElement(MessageNotificationToaster))
+ })
+}
+
+function bySlot(slot: string): ReactTestInstance[] {
+ return renderer.root.findAll((node) => node.props["data-slot"] === slot)
+}
+
+describe("top-center message notification", () => {
+ beforeEach(() => {
+ act(() => messageNotification.close())
+ })
+
+ it("renders notifications added through the shared manager", () => {
+ renderToaster()
+
+ act(() => {
+ messageNotification.add({
+ description: "Install the latest daemon on this machine.",
+ title: "Daemon update available",
+ type: "warning",
+ })
+ })
+
+ expect(renderer.root.findByType("toast-title").children).toEqual(["Daemon update available"])
+ expect(renderer.root.findByType("toast-description").children).toEqual([
+ "Install the latest daemon on this machine.",
+ ])
+ expect(bySlot("message-notification-icon")).toHaveLength(1)
+ })
+
+ it("can render a custom icon without a status boundary", () => {
+ renderToaster()
+
+ act(() => {
+ messageNotification.add({
+ data: { bareIcon: true, icon: React.createElement("brand-logo") },
+ title: "Machine update available",
+ type: "warning",
+ })
+ })
+
+ const iconClass = bySlot("message-notification-icon")[0]!.props.className as string
+ expect(iconClass).not.toContain("rounded-lg")
+ expect(iconClass).not.toContain("bg-warning/15")
+ })
+
+ it("mounts the external manager provider before authenticated producers", () => {
+ const layout = readFileSync(new URL("../../app/layout.tsx", import.meta.url), "utf8")
+ expect(layout.indexOf("<MessageNotificationToaster />"))
+ .toBeLessThan(layout.indexOf("<TooltipProvider>"))
+ })
+
+ it("uses semantic icon tones and removes the icon grid track when no icon exists", () => {
+ renderToaster()
+
+ act(() => {
+ messageNotification.add({ id: "success", title: "Connected", type: "success" })
+ messageNotification.add({ id: "error", title: "Failed", type: "error" })
+ messageNotification.add({ id: "info", title: "FYI", type: "info" })
+ messageNotification.add({ id: "loading", title: "Loading", type: "loading" })
+ messageNotification.add({ id: "warning", title: "Caution", type: "warning" })
+ messageNotification.add({ id: "plain", title: "Plain message" })
+ })
+
+ const icons = bySlot("message-notification-icon")
+ expect(icons.map((icon) => icon.props.className)).toEqual(expect.arrayContaining([
+ expect.stringContaining("bg-primary/10 text-primary"),
+ expect.stringContaining("bg-destructive/10 text-destructive"),
+ expect.stringContaining("bg-muted text-muted-foreground"),
+ expect.stringContaining("bg-warning/15 text-warning"),
+ ]))
+
+ const contents = bySlot("message-notification-content")
+ expect(contents.some((content) => content.props.className.includes("grid-cols-[minmax(0,1fr)_auto]"))).toBe(true)
+ expect(contents.every((content) => content.props.className.includes("motion-reduce:transition-none"))).toBe(true)
+ const textColumns = renderer.root.findAll((node) => typeof node.props.className === "string"
+ && node.props.className.includes("row-start-1 flex min-w-0"))
+ expect(textColumns.some((node) => node.props.className.includes("col-start-1"))).toBe(true)
+ const loadingRoot = renderer.root.findAllByType("toast-root")
+ .find((root) => root.findAllByType("toast-title")[0]?.children[0] === "Loading")
+ const loadingIcon = loadingRoot?.findAllByType("svg")
+ .find((icon) => String(icon.props.className).includes("animate-spin"))
+ expect(loadingIcon?.props.className).toContain("motion-reduce:animate-none")
+ })
+
+ it("limits the visible stack to three and keeps the motion and swipe contract", () => {
+ renderToaster()
+
+ act(() => {
+ for (let index = 1; index <= 4; index += 1) {
+ messageNotification.add({ id: `stack-${index}`, title: `Message ${index}` })
+ }
+ })
+
+ const roots = renderer.root.findAllByType("toast-root")
+ expect(roots).toHaveLength(4)
+ expect(roots.filter((root) => root.props["data-limited"])).toHaveLength(1)
+ expect(roots[0].props.swipeDirection).toEqual(["up", "left", "right"])
+ expect(roots[0].props.className).toContain("300ms_cubic-bezier(0.2,0.8,0.2,1)")
+ expect(roots[0].props.className).toContain("motion-reduce:transition-none")
+ })
+
+ it("runs onClose for action dismissal, close, and swipe dismissal", () => {
+ renderToaster()
+ const onActionClose = vi.fn()
+ const onButtonClose = vi.fn()
+ const onSwipeClose = vi.fn()
+ let actionId = ""
+
+ act(() => {
+ actionId = messageNotification.add({
+ actionProps: {
+ children: "View machines",
+ onClick: () => messageNotification.close(actionId),
+ },
+ id: "action",
+ onClose: onActionClose,
+ title: "Action",
+ })
+ messageNotification.add({ id: "button", onClose: onButtonClose, title: "Close" })
+ messageNotification.add({ id: "swipe", onClose: onSwipeClose, title: "Swipe" })
+ })
+
+ const roots = renderer.root.findAllByType("toast-root")
+ const actionRoot = roots.find((root) => root.findAllByType("toast-title")[0]?.children[0] === "Action")
+ const buttonRoot = roots.find((root) => root.findAllByType("toast-title")[0]?.children[0] === "Close")
+ const swipeRoot = roots.find((root) => root.findAllByType("toast-title")[0]?.children[0] === "Swipe")
+ if (!actionRoot || !buttonRoot || !swipeRoot) throw new Error("Expected all interaction fixtures")
+
+ const actionButton = actionRoot.findAllByType("button").find((button) => button.props["data-slot"] === "message-notification-action")
+ const closeButton = buttonRoot.findAllByType("button").find((button) => button.props["data-slot"] === "message-notification-close")
+ if (!actionButton || !closeButton) throw new Error("Expected action and close controls")
+
+ act(() => actionButton.props.onClick())
+ act(() => closeButton.props.onClick())
+ act(() => swipeRoot.props.onSwipeDismiss())
+
+ expect(onActionClose).toHaveBeenCalledOnce()
+ expect(onButtonClose).toHaveBeenCalledOnce()
+ expect(onSwipeClose).toHaveBeenCalledOnce()
+ })
+})
diff --git a/src/web/src/components/ui/toast.tsx b/src/web/src/components/ui/toast.tsx
new file mode 100644
index 000000000..b00b82854
--- /dev/null
+++ b/src/web/src/components/ui/toast.tsx
@@ -0,0 +1,256 @@
+"use client"
+
+import * as React from "react"
+import { Toast as ToastPrimitive } from "@base-ui/react/toast"
+import {
+ CircleCheckIcon,
+ InfoIcon,
+ Loader2Icon,
+ OctagonXIcon,
+ TriangleAlertIcon,
+ XIcon,
+} from "lucide-react"
+import { Button } from "@/components/ui/button"
+import { cn } from "@/lib/utils"
+
+export type MessageNotificationData = {
+ bareIcon?: boolean
+ closeLabel?: string
+ icon?: React.ReactNode
+ testId?: string
+}
+
+const messageNotification = ToastPrimitive.createToastManager<MessageNotificationData>()
+
+function ToastProvider(props: ToastPrimitive.Provider.Props) {
+ return <ToastPrimitive.Provider {...props} />
+}
+
+function ToastPortal(props: ToastPrimitive.Portal.Props) {
+ return <ToastPrimitive.Portal data-slot="message-notification-portal" {...props} />
+}
+
+function ToastViewport({ className, ...props }: ToastPrimitive.Viewport.Props) {
+ return (
+ <ToastPrimitive.Viewport
+ aria-label="Notifications"
+ data-slot="message-notification-viewport"
+ className={cn(
+ "pointer-events-none fixed inset-x-4 top-[calc(env(safe-area-inset-top)+1rem)] z-100 mx-auto w-auto max-w-lg outline-none sm:w-full",
+ className,
+ )}
+ {...props}
+ />
+ )
+}
+
+function Toast({ className, ...props }: ToastPrimitive.Root.Props) {
+ return (
+ <ToastPrimitive.Root
+ data-slot="message-notification"
+ swipeDirection={["up", "left", "right"]}
+ className={cn(
+ "group/message-notification pointer-events-auto absolute top-0 left-0 z-[calc(1000-var(--toast-index))] w-full origin-top rounded-xl border border-border bg-popover text-popover-foreground shadow-(--e2) outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",
+ "[--gap:0.5rem] [--height:var(--toast-frontmost-height,var(--toast-height))] [--offset-y:calc(var(--toast-offset-y)+calc(var(--toast-index)*var(--gap))+var(--toast-swipe-movement-y))] [--peek:0.5rem] [--scale:calc(max(0,1-(var(--toast-index)*0.04)))] [--shrink:calc(1-var(--scale))]",
+ "h-(--height) transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--peek))+(var(--shrink)*var(--height))))_scale(var(--scale))] [transition:transform_300ms_cubic-bezier(0.2,0.8,0.2,1),opacity_200ms,height_150ms] motion-reduce:transition-none",
+ "after:absolute after:bottom-full after:left-0 after:h-[calc(var(--gap)+1px)] after:w-full after:content-['']",
+ "data-expanded:h-(--toast-height) data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--offset-y))]",
+ "data-limited:opacity-0 data-starting-style:transform-[translateY(-150%)]",
+ "[&[data-ending-style]:not([data-limited]):not([data-swipe-direction])]:transform-[translateY(-150%)]",
+ "data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-150%))]",
+ "data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))]",
+ "data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))]",
+ className,
+ )}
+ {...props}
+ />
+ )
+}
+
+function ToastContent({ className, ...props }: ToastPrimitive.Content.Props) {
+ return (
+ <ToastPrimitive.Content
+ data-slot="message-notification-content"
+ className={cn(
+ "grid h-full grid-cols-[auto_minmax(0,1fr)_auto] items-start gap-x-3 gap-y-3 overflow-hidden p-4 transition-opacity duration-200 ease-out data-behind:opacity-0 data-expanded:opacity-100 motion-reduce:transition-none sm:grid-cols-[auto_minmax(0,1fr)_auto_auto] sm:items-center",
+ className,
+ )}
+ {...props}
+ />
+ )
+}
+
+function ToastTitle({ className, ...props }: ToastPrimitive.Title.Props) {
+ return (
+ <ToastPrimitive.Title
+ data-slot="message-notification-title"
+ className={cn("text-sm font-semibold leading-5", className)}
+ {...props}
+ />
+ )
+}
+
+function ToastDescription({ className, ...props }: ToastPrimitive.Description.Props) {
+ return (
+ <ToastPrimitive.Description
+ data-slot="message-notification-description"
+ className={cn("text-sm leading-5 text-muted-foreground", className)}
+ {...props}
+ />
+ )
+}
+
+function ToastAction({
+ className,
+ render = <Button />,
+ ...props
+}: ToastPrimitive.Action.Props) {
+ return (
+ <ToastPrimitive.Action
+ data-slot="message-notification-action"
+ render={render}
+ className={cn(
+ "col-span-2 col-start-2 row-start-2 h-11 w-full shrink-0 sm:col-span-1 sm:col-start-3 sm:row-start-1 sm:h-8 sm:w-auto",
+ className,
+ )}
+ {...props}
+ />
+ )
+}
+
+function ToastClose({
+ className,
+ children,
+ render = <Button variant="ghost" size="icon-sm" />,
+ ...props
+}: ToastPrimitive.Close.Props) {
+ return (
+ <ToastPrimitive.Close
+ data-slot="message-notification-close"
+ render={render}
+ className={cn(
+ "relative col-start-3 row-start-1 size-11 shrink-0 text-muted-foreground after:absolute after:-inset-2 after:content-[''] hover:text-foreground sm:col-start-4 sm:size-7",
+ className,
+ )}
+ {...props}
+ >
+ {children ?? <XIcon aria-hidden="true" />}
+ </ToastPrimitive.Close>
+ )
+}
+
+function ToastIcon({ toastItem }: { toastItem: ToastPrimitive.Root.ToastObject<MessageNotificationData> }) {
+ const customIcon = toastItem.data?.icon
+ const statusIcon = toastItem.type === "success"
+ ? <CircleCheckIcon />
+ : toastItem.type === "info"
+ ? <InfoIcon />
+ : toastItem.type === "warning"
+ ? <TriangleAlertIcon />
+ : toastItem.type === "error"
+ ? <OctagonXIcon />
+ : toastItem.type === "loading"
+ ? <Loader2Icon className="animate-spin motion-reduce:animate-none" />
+ : null
+ const icon = customIcon ?? statusIcon
+ if (!icon) return null
+
+ return (
+ <span
+ aria-hidden="true"
+ data-slot="message-notification-icon"
+ className={cn(
+ "flex size-10 shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-5",
+ !toastItem.data?.bareIcon && "rounded-lg",
+ !toastItem.data?.bareIcon && (
+ toastItem.type === "warning"
+ ? "bg-warning/15 text-warning"
+ : toastItem.type === "error"
+ ? "bg-destructive/10 text-destructive"
+ : toastItem.type === "success"
+ ? "bg-primary/10 text-primary"
+ : "bg-muted text-muted-foreground"
+ ),
+ )}
+ >
+ {icon}
+ </span>
+ )
+}
+
+function ToastList() {
+ const { toasts } = ToastPrimitive.useToastManager<MessageNotificationData>()
+
+ return toasts.map((toastItem) => {
+ const hasIcon = Boolean(
+ toastItem.data?.icon
+ || ["success", "info", "warning", "error", "loading"].includes(toastItem.type ?? ""),
+ )
+ const closeLabel = toastItem.data?.closeLabel ?? "Close notification"
+
+ return (
+ <Toast
+ key={toastItem.id}
+ toast={toastItem}
+ data-testid={toastItem.data?.testId}
+ >
+ <ToastContent
+ className={hasIcon
+ ? undefined
+ : "grid-cols-[minmax(0,1fr)_auto] sm:grid-cols-[minmax(0,1fr)_auto_auto]"}
+ >
+ <ToastIcon toastItem={toastItem} />
+ <div className={cn(
+ "row-start-1 flex min-w-0 flex-col gap-1",
+ hasIcon ? "col-start-2" : "col-start-1",
+ )}>
+ <ToastTitle />
+ <ToastDescription />
+ </div>
+ <ToastAction
+ className={hasIcon
+ ? undefined
+ : "col-span-2 col-start-1 sm:col-span-1 sm:col-start-2"}
+ />
+ <ToastClose
+ aria-label={closeLabel}
+ title={closeLabel}
+ className={hasIcon ? undefined : "col-start-2 sm:col-start-3"}
+ >
+ <XIcon aria-hidden="true" />
+ <span className="sr-only">{closeLabel}</span>
+ </ToastClose>
+ </ToastContent>
+ </Toast>
+ )
+ })
+}
+
+function MessageNotificationToaster({
+ toastManager = messageNotification,
+ ...props
+}: ToastPrimitive.Provider.Props) {
+ return (
+ <ToastProvider toastManager={toastManager} limit={3} {...props}>
+ <ToastPortal>
+ <ToastViewport>
+ <ToastList />
+ </ToastViewport>
+ </ToastPortal>
+ </ToastProvider>
+ )
+}
+
+export {
+ MessageNotificationToaster,
+ Toast,
+ ToastAction,
+ ToastClose,
+ ToastContent,
+ ToastDescription,
+ ToastPortal,
+ ToastProvider,
+ ToastTitle,
+ ToastViewport,
+ messageNotification,
+}
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 47e725445..b33ba1021 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -73,6 +73,8 @@ export const tid = {
machineActions: (id: string) => `machine-actions-${id}`,
machineUpdate: (id: string) => `machine-update-${id}`,
machineUpdateConfirm: "machine-update-confirm",
+ daemonUpdateNotice: "daemon-update-notice",
+ daemonUpdateAction: "daemon-update-action",
homeButton: "community-home-button",
alookLogo: "community-alook-logo",
botReportProblemItem: "bot-report-problem-item",
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.ts
new file mode 100644
index 000000000..a6dbec9ed
--- /dev/null
+++ b/src/web/src/test/e2e-ui/50-daemon-update-notice.spec.ts
@@ -0,0 +1,190 @@
+import { readFileSync } from "node:fs"
+import type { BrowserContext, Locator, Page } from "@playwright/test"
+import { test, expect } from "./_fixtures/community-fixture"
+import { gotoAfterUserWsAuth } from "./_fixtures/actions"
+import { tid } from "./_fixtures/testids"
+import { REPO_ROOT } from "./_setup/paths"
+
+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 }).version
+
+const outdatedMachine = {
+ id: "machine_daemon_notice",
+ hostname: "studio-mac",
+ displayName: "Studio Mac",
+ platform: "darwin",
+ arch: "arm64",
+ osRelease: "26.0",
+ daemonVersion: "0.1.7",
+ lastSeenAt: null,
+ status: "online",
+ availableRuntimes: [],
+ createdAt: "2026-08-30T00:00:00.000Z",
+ updatedAt: "2026-08-30T00:00:00.000Z",
+ quota: [],
+}
+
+async function serveMachines(page: Page, machines = [outdatedMachine]) {
+ let requestCount = 0
+ const updateRequests: string[] = []
+ await page.route("**/api/community/machines", async (route) => {
+ requestCount += 1
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({ machines }),
+ })
+ })
+ 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]!)
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({ dispatched: true }),
+ })
+ })
+ return {
+ machineRequestCount: () => requestCount,
+ updateRequests: () => [...updateRequests],
+ }
+}
+
+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)
+ }
+ 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; }",
+ })
+}
+
+test("daemon reminder checks once, respects reduced motion, and stays dismissed", async ({ asUser }, testInfo) => {
+ const { context, page } = await asUser("alice")
+ await clearSavedDaemonCheckOnce(context)
+ 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.")
+ await expect(page.getByTestId(tid.daemonUpdateAction)).toHaveText("Update")
+ await waitForNoticeLogo(notice)
+ 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",
+ })
+
+ await notice.locator('[data-slot="message-notification-close"]').click()
+ await expect(notice).toBeHidden()
+ await expect.poll(() => page.evaluate(() => {
+ const savedVersions: Array<string | null> = []
+ 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))
+ }
+ }
+ return savedVersions
+ })).toEqual([currentWebVersion])
+ await page.reload()
+ await expect(notice).toHaveCount(0)
+ expect(requests.updateRequests()).toEqual([])
+})
+
+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(),
+ ])
+ 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",
+ })
+
+ 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 },
+ ])
+ 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",
+ ])
+})