Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): reveal messages after initial positioning (#776)

Genere730c4093922
diff --git a/src/web/postcss.config.mjs b/src/web/postcss.config.mjs
index f50127cda..c42f31cab 100644
--- a/src/web/postcss.config.mjs
+++ b/src/web/postcss.config.mjs
@@ -1,5 +1,7 @@
const config = {
- plugins: ["@tailwindcss/postcss"],
+ plugins: {
+ "@tailwindcss/postcss": {},
+ },
};
export default config;
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index bdba23362..6b7b75503 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -467,6 +467,14 @@ body.driver-active .community-ws-reconnect-overlay * {
--border: oklch(0.86 0.01 80);
--input: oklch(0.86 0.01 80);
--ring: oklch(0.55 0.03 230);
+ --initial-position-aurora-cyan: oklch(0.76 0.17 205);
+ --initial-position-aurora-blue: oklch(0.67 0.18 250);
+ --initial-position-aurora-violet: oklch(0.67 0.19 292);
+ --initial-position-aurora-magenta: oklch(0.72 0.18 333);
+ --initial-position-aurora-opacity: 0.62;
+ --initial-position-aurora-bloom-opacity: 0.58;
+ --initial-position-aurora-glint-opacity: 0.82;
+ --initial-position-aurora-reduced-opacity: 0.45;
--chart-1: oklch(0.85 0.01 80);
--chart-2: oklch(0.55 0.01 60);
--chart-3: oklch(0.44 0.01 60);
@@ -523,6 +531,14 @@ body.driver-active .community-ws-reconnect-overlay * {
--border: oklch(1 0.005 80 / 10%);
--input: oklch(1 0.005 80 / 15%);
--ring: oklch(0.55 0.01 60);
+ --initial-position-aurora-cyan: oklch(0.78 0.18 205);
+ --initial-position-aurora-blue: oklch(0.67 0.2 252);
+ --initial-position-aurora-violet: oklch(0.7 0.2 294);
+ --initial-position-aurora-magenta: oklch(0.74 0.19 333);
+ --initial-position-aurora-opacity: 0.82;
+ --initial-position-aurora-bloom-opacity: 0.72;
+ --initial-position-aurora-glint-opacity: 0.95;
+ --initial-position-aurora-reduced-opacity: 0.6;
--chart-1: oklch(0.85 0.01 80);
--chart-2: oklch(0.55 0.01 60);
--chart-3: oklch(0.44 0.01 60);
diff --git a/src/web/src/components/community/messages/initial-position-aurora.dom.test.tsx b/src/web/src/components/community/messages/initial-position-aurora.dom.test.tsx
new file mode 100644
index 000000000..e376fe3c8
--- /dev/null
+++ b/src/web/src/components/community/messages/initial-position-aurora.dom.test.tsx
@@ -0,0 +1,109 @@
+import { readFileSync } from "node:fs"
+import { dirname, resolve } from "node:path"
+import { fileURLToPath } from "node:url"
+import React from "react"
+import { describe, expect, it, vi } from "vitest"
+import { render } from "@/test/react-dom-harness"
+import { tid } from "@/lib/community/testids"
+import { InitialPositionAurora } from "./initial-position-aurora"
+
+vi.mock("./initial-position-aurora.module.css", () => ({
+ default: new Proxy({}, { get: (_target, key) => String(key) }),
+}))
+
+const styles = readFileSync(
+ resolve(dirname(fileURLToPath(import.meta.url)), "initial-position-aurora.module.css"),
+ "utf8",
+)
+const globals = readFileSync(
+ resolve(dirname(fileURLToPath(import.meta.url)), "../../../app/globals.css"),
+ "utf8",
+)
+
+describe("InitialPositionAurora", () => {
+ it("renders only for the visible and crossfade phases without interaction or prose", () => {
+ const renderer = render(React.createElement(InitialPositionAurora, { phase: "positioning" }))
+ expect(renderer.queryByTestId(tid.initialPositionAurora)).toBeNull()
+
+ renderer.rerender(React.createElement(InitialPositionAurora, { phase: "aurora" }))
+ const aurora = renderer.getByTestId(tid.initialPositionAurora)
+ expect(aurora).toHaveAttribute("aria-hidden", "true")
+ expect(aurora).toHaveAttribute("data-phase", "aurora")
+ expect(aurora).toHaveTextContent("")
+
+ renderer.rerender(React.createElement(InitialPositionAurora, { phase: "revealing" }))
+ expect(renderer.getByTestId(tid.initialPositionAurora)).toHaveAttribute(
+ "data-phase",
+ "revealing",
+ )
+ renderer.rerender(React.createElement(InitialPositionAurora, { phase: "revealed" }))
+ expect(renderer.queryByTestId(tid.initialPositionAurora)).toBeNull()
+ })
+
+ it("keeps non-layout overlay geometry, semantic aurora paint, reduced-motion static layers, and a 100ms fade", () => {
+ expect(styles).toMatch(/position:\s*absolute/)
+ expect(styles).toMatch(/pointer-events:\s*none/)
+ expect(styles).toMatch(/transition:\s*opacity 100ms var\(--ease-out\)/)
+ expect(styles).toMatch(/\.aurora\s*\{[\s\S]*?height:\s*3\.5rem;/)
+ expect(styles).toMatch(
+ /@media \(max-width: 40rem\)[\s\S]*?\.aurora\s*\{[\s\S]*?height:\s*3rem;/,
+ )
+ const themeTokens = [
+ "--initial-position-aurora-cyan",
+ "--initial-position-aurora-blue",
+ "--initial-position-aurora-violet",
+ "--initial-position-aurora-magenta",
+ "--initial-position-aurora-opacity",
+ "--initial-position-aurora-bloom-opacity",
+ "--initial-position-aurora-glint-opacity",
+ "--initial-position-aurora-reduced-opacity",
+ ]
+ for (const token of themeTokens) {
+ expect(styles).toContain(`var(${token})`)
+ expect(globals.match(new RegExp(`${token}:`, "g"))).toHaveLength(2)
+ }
+ expect(styles).toContain(".peaks::before")
+ expect(styles).toContain(".peaks::after")
+ expect(styles).toContain(".haze::before")
+ expect(styles).not.toContain("clip-path")
+ expect(styles).not.toContain("repeating-linear-gradient")
+ expect(styles).not.toMatch(/\brandom\s*\(/)
+
+ const peakProfiles = ["before", "after"].map((pseudo) => {
+ const block = styles.match(new RegExp(`\\.peaks::${pseudo}\\s*\\{([\\s\\S]*?)\\n\\}`))?.[1]
+ expect(block).toBeTruthy()
+ return Array.from(
+ block!.matchAll(
+ /transparent\)\s+([\d.]+)%\s+100%\s*\/\s*[\d.]+rem\s+([\d.]+)%\s+no-repeat/g,
+ ),
+ ([, position, height]) => ({ position: Number(position), height: Number(height) }),
+ )
+ })
+ const meanHeight = (profile: Array<{ height: number }>) =>
+ profile.reduce((sum, peak) => sum + peak.height, 0) / profile.length
+ const hasRiseAndFall = (profile: Array<{ height: number }>) => {
+ const changes = profile.slice(1).map((peak, index) => peak.height - profile[index]!.height)
+ return changes.some((change) => change > 0) && changes.some((change) => change < 0)
+ }
+ for (const profile of peakProfiles) {
+ expect(profile.find(({ position }) => position === 0)?.height).toBe(0)
+ expect(profile.find(({ position }) => position === 100)?.height).toBe(0)
+ const center = profile.filter(({ position }) => position >= 25 && position <= 75)
+ const leftShoulder = profile.filter(({ position }) => position > 12.5 && position < 25)
+ const leftOuter = profile.filter(({ position }) => position <= 12.5)
+ const rightShoulder = profile.filter(({ position }) => position > 75 && position < 87.5)
+ const rightOuter = profile.filter(({ position }) => position >= 87.5)
+ expect(meanHeight(leftOuter)).toBeLessThan(meanHeight(leftShoulder))
+ expect(meanHeight(leftShoulder)).toBeLessThan(meanHeight(center))
+ expect(meanHeight(rightOuter)).toBeLessThan(meanHeight(rightShoulder))
+ expect(meanHeight(rightShoulder)).toBeLessThan(meanHeight(center))
+ expect(hasRiseAndFall(profile.filter(({ position }) => position <= 25))).toBe(true)
+ expect(hasRiseAndFall(profile.filter(({ position }) => position >= 75).reverse())).toBe(true)
+ }
+ expect(styles).toMatch(
+ /@media \(prefers-reduced-motion: reduce\)[\s\S]*?\.drift,[\s\S]*?\.peaks::before,[\s\S]*?\.peaks::after,[\s\S]*?\.haze,[\s\S]*?\.haze::before[\s\S]*?animation:\s*none/,
+ )
+ expect(styles).not.toMatch(/#[\da-f]{3,8}\b/i)
+ expect(styles).not.toMatch(/oklch\(/)
+ })
+})
diff --git a/src/web/src/components/community/messages/initial-position-aurora.module.css b/src/web/src/components/community/messages/initial-position-aurora.module.css
new file mode 100644
index 000000000..6ba15b5d8
--- /dev/null
+++ b/src/web/src/components/community/messages/initial-position-aurora.module.css
@@ -0,0 +1,252 @@
+.aurora {
+ position: absolute;
+ right: 1rem;
+ bottom: 0;
+ left: 1rem;
+ z-index: 10;
+ height: 3.5rem;
+ overflow: hidden;
+ pointer-events: none;
+ opacity: 0;
+ transition: opacity 100ms var(--ease-out);
+ will-change: opacity;
+}
+
+.visible {
+ opacity: var(--initial-position-aurora-opacity);
+}
+
+.leaving {
+ opacity: 0;
+}
+
+.drift {
+ position: absolute;
+ inset: 0;
+ transform-origin: center bottom;
+ will-change: transform;
+ animation: aurora-drift 5.8s var(--ease-in-out) infinite alternate;
+}
+
+.peaks,
+.haze {
+ position: absolute;
+ inset: 0;
+ transform-origin: center bottom;
+}
+
+.peaks {
+ z-index: 2;
+ background: linear-gradient(
+ 90deg,
+ transparent 0%,
+ var(--initial-position-aurora-cyan) 4%,
+ var(--initial-position-aurora-blue) 30%,
+ var(--initial-position-aurora-violet) 56%,
+ var(--initial-position-aurora-magenta) 82%,
+ var(--initial-position-aurora-cyan) 96%,
+ transparent 100%
+ ) bottom / 100% 2px no-repeat;
+ opacity: var(--initial-position-aurora-glint-opacity);
+ filter:
+ drop-shadow(0 -2px 5px color-mix(in oklab, var(--initial-position-aurora-blue) 48%, transparent))
+ drop-shadow(0 -1px 3px color-mix(in oklab, var(--initial-position-aurora-magenta) 38%, transparent));
+}
+
+.peaks::before,
+.peaks::after,
+.haze::before {
+ position: absolute;
+ inset: 0;
+ content: "";
+ transform-origin: center bottom;
+ will-change: transform, opacity;
+}
+
+.peaks::before {
+ background:
+ linear-gradient(to top, var(--initial-position-aurora-cyan), transparent) 0% 100% / 0.08rem 0% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-cyan), transparent) 2% 100% / 0.16rem 5% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-cyan), transparent) 3.4% 100% / 0.1rem 12% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-cyan), transparent) 5.5% 100% / 0.24rem 8% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-cyan), transparent) 6.8% 100% / 0.12rem 19% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-cyan), transparent) 8.4% 100% / 0.12rem 14% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-blue), transparent) 10.1% 100% / 0.1rem 26% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-cyan), transparent) 12.3% 100% / 0.14rem 21% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-blue), transparent) 17% 100% / 0.18rem 36% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-violet), transparent) 22.5% 100% / 0.14rem 55% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-blue), transparent) 24.2% 100% / 0.1rem 34% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-blue), transparent) 27% 100% / 0.28rem 84% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-blue), transparent) 28.4% 100% / 0.12rem 46% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-violet), transparent) 30.6% 100% / 0.14rem 61% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-magenta), transparent) 34.8% 100% / 0.1rem 31% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-magenta), transparent) 36% 100% / 0.17rem 43% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-violet), transparent) 38.2% 100% / 0.11rem 58% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-violet), transparent) 40.5% 100% / 0.22rem 67% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-blue), transparent) 42.1% 100% / 0.1rem 39% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-magenta), transparent) 45.5% 100% / 0.3rem 91% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-violet), transparent) 47.1% 100% / 0.12rem 48% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-blue), transparent) 55% 100% / 0.13rem 38% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-violet), transparent) 57.3% 100% / 0.1rem 50% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-violet), transparent) 60.5% 100% / 0.2rem 58% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-magenta), transparent) 62.2% 100% / 0.1rem 35% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-magenta), transparent) 64% 100% / 0.26rem 78% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-violet), transparent) 65.7% 100% / 0.12rem 45% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-blue), transparent) 68.2% 100% / 0.1rem 27% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-cyan), transparent) 73.5% 100% / 0.16rem 45% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-cyan), transparent) 75.1% 100% / 0.1rem 63% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-blue), transparent) 77% 100% / 0.12rem 32% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-violet), transparent) 82.1% 100% / 0.11rem 42% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-magenta), transparent) 84.2% 100% / 0.12rem 33% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-magenta), transparent) 86% 100% / 0.28rem 46% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-magenta), transparent) 88.2% 100% / 0.1rem 27% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-violet), transparent) 90% 100% / 0.16rem 34% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-blue), transparent) 92.4% 100% / 0.1rem 15% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-cyan), transparent) 96.5% 100% / 0.22rem 6% no-repeat,
+ linear-gradient(to top, var(--initial-position-aurora-cyan), transparent) 100% 100% / 0.08rem 0% no-repeat;
+ filter: blur(1px);
+ animation: aurora-fine-peaks 3.4s var(--ease-in-out) infinite alternate;
+}
+
+.peaks::after {
+ background:
+ linear-gradient(to top, color-mix(in oklab, var(--initial-position-aurora-cyan) 68%, transparent), transparent) 0% 100% / 0.5rem 0% no-repeat,
+ linear-gradient(to top, color-mix(in oklab, var(--initial-position-aurora-cyan) 78%, transparent), transparent) 4.5% 100% / 1.15rem 11% no-repeat,
+ linear-gradient(to top, color-mix(in oklab, var(--initial-position-aurora-cyan) 68%, transparent), transparent) 11% 100% / 0.7rem 7% no-repeat,
+ linear-gradient(to top, color-mix(in oklab, var(--initial-position-aurora-blue) 70%, transparent), transparent) 18% 100% / 1rem 32% no-repeat,
+ linear-gradient(to top, color-mix(in oklab, var(--initial-position-aurora-blue) 76%, transparent), transparent) 27.5% 100% / 1.2rem 79% no-repeat,
+ linear-gradient(to top, color-mix(in oklab, var(--initial-position-aurora-violet) 74%, transparent), transparent) 39% 100% / 1.65rem 61% no-repeat,
+ linear-gradient(to top, color-mix(in oklab, var(--initial-position-aurora-magenta) 82%, transparent), transparent) 46% 100% / 1.05rem 88% no-repeat,
+ linear-gradient(to top, color-mix(in oklab, var(--initial-position-aurora-violet) 70%, transparent), transparent) 62% 100% / 1.8rem 70% no-repeat,
+ linear-gradient(to top, color-mix(in oklab, var(--initial-position-aurora-cyan) 72%, transparent), transparent) 74% 100% / 0.85rem 47% no-repeat,
+ linear-gradient(to top, color-mix(in oklab, var(--initial-position-aurora-violet) 72%, transparent), transparent) 82% 100% / 1rem 19% no-repeat,
+ linear-gradient(to top, color-mix(in oklab, var(--initial-position-aurora-magenta) 78%, transparent), transparent) 87% 100% / 1.5rem 25% no-repeat,
+ linear-gradient(to top, color-mix(in oklab, var(--initial-position-aurora-cyan) 68%, transparent), transparent) 96% 100% / 0.75rem 8% no-repeat,
+ linear-gradient(to top, color-mix(in oklab, var(--initial-position-aurora-cyan) 68%, transparent), transparent) 100% 100% / 0.5rem 0% no-repeat;
+ opacity: 0.72;
+ filter: blur(5px);
+ animation: aurora-broad-peaks 4.1s var(--ease-in-out) -1.7s infinite alternate;
+}
+
+.haze {
+ z-index: 1;
+ background:
+ radial-gradient(
+ 12% 58% at 10% 100%,
+ color-mix(in oklab, var(--initial-position-aurora-cyan) 58%, transparent),
+ transparent 64%
+ ),
+ radial-gradient(
+ 22% 95% at 31% 100%,
+ color-mix(in oklab, var(--initial-position-aurora-blue) 52%, transparent),
+ transparent 66%
+ ),
+ radial-gradient(
+ 20% 88% at 52% 100%,
+ color-mix(in oklab, var(--initial-position-aurora-violet) 58%, transparent),
+ transparent 64%
+ ),
+ radial-gradient(
+ 16% 92% at 68% 100%,
+ color-mix(in oklab, var(--initial-position-aurora-blue) 46%, transparent),
+ transparent 64%
+ ),
+ radial-gradient(
+ 14% 62% at 90% 100%,
+ color-mix(in oklab, var(--initial-position-aurora-magenta) 62%, transparent),
+ transparent 66%
+ );
+ opacity: var(--initial-position-aurora-bloom-opacity);
+ filter: blur(16px);
+ mask-image: linear-gradient(to top, black 0%, black 34%, transparent 100%);
+ animation: aurora-haze 4.7s var(--ease-in-out) -2.2s infinite alternate;
+}
+
+.haze::before {
+ background:
+ radial-gradient(14% 54% at 18% 100%, color-mix(in oklab, var(--initial-position-aurora-cyan) 58%, transparent), transparent 66%),
+ radial-gradient(18% 82% at 45% 100%, color-mix(in oklab, var(--initial-position-aurora-magenta) 54%, transparent), transparent 64%),
+ radial-gradient(20% 76% at 72% 100%, color-mix(in oklab, var(--initial-position-aurora-violet) 52%, transparent), transparent 66%),
+ radial-gradient(10% 44% at 92% 100%, color-mix(in oklab, var(--initial-position-aurora-cyan) 46%, transparent), transparent 64%);
+ filter: blur(9px);
+ animation: aurora-secondary-haze 5.3s var(--ease-in-out) -0.9s infinite alternate;
+}
+
+@keyframes aurora-drift {
+ from {
+ transform: translateX(-0.4%);
+ }
+
+ to {
+ transform: translateX(0.4%);
+ }
+}
+
+@keyframes aurora-fine-peaks {
+ from {
+ transform: scaleY(0.78);
+ opacity: 0.72;
+ }
+
+ to {
+ transform: scaleY(1);
+ opacity: 1;
+ }
+}
+
+@keyframes aurora-broad-peaks {
+ from {
+ transform: scaleY(0.92) translateX(0.4%);
+ }
+
+ to {
+ transform: scaleY(1.08) translateX(-0.4%);
+ }
+}
+
+@keyframes aurora-haze {
+ from {
+ transform: scaleY(0.88) translateX(-0.8%);
+ }
+
+ to {
+ transform: scaleY(1.04) translateX(0.8%);
+ }
+}
+
+@keyframes aurora-secondary-haze {
+ from {
+ transform: scaleY(1.02) translateX(0.7%);
+ opacity: 0.7;
+ }
+
+ to {
+ transform: scaleY(0.86) translateX(-0.7%);
+ opacity: 1;
+ }
+}
+
+@media (max-width: 40rem) {
+ .aurora {
+ height: 3rem;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .aurora {
+ transition: opacity 100ms var(--ease-out);
+ }
+
+ .visible {
+ opacity: var(--initial-position-aurora-reduced-opacity);
+ }
+
+ .drift,
+ .peaks::before,
+ .peaks::after,
+ .haze,
+ .haze::before {
+ animation: none;
+ transform: none;
+ }
+}
diff --git a/src/web/src/components/community/messages/initial-position-aurora.tsx b/src/web/src/components/community/messages/initial-position-aurora.tsx
new file mode 100644
index 000000000..195cbae0a
--- /dev/null
+++ b/src/web/src/components/community/messages/initial-position-aurora.tsx
@@ -0,0 +1,21 @@
+import { tid } from "@/lib/community/testids"
+import type { InitialPositionPhase } from "./initial-position-transition"
+import styles from "./initial-position-aurora.module.css"
+
+export function InitialPositionAurora({ phase }: { phase: InitialPositionPhase }) {
+ if (phase !== "aurora" && phase !== "revealing") return null
+
+ return (
+ <div
+ aria-hidden="true"
+ data-testid={tid.initialPositionAurora}
+ data-phase={phase}
+ className={`${styles.aurora} ${phase === "aurora" ? styles.visible : styles.leaving}`}
+ >
+ <div className={styles.drift}>
+ <div className={styles.peaks} />
+ <div className={styles.haze} />
+ </div>
+ </div>
+ )
+}
diff --git a/src/web/src/components/community/messages/initial-position-transition.dom.test.ts b/src/web/src/components/community/messages/initial-position-transition.dom.test.ts
new file mode 100644
index 000000000..acaeeff03
--- /dev/null
+++ b/src/web/src/components/community/messages/initial-position-transition.dom.test.ts
@@ -0,0 +1,125 @@
+import React from "react"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { act, render } from "@/test/react-dom-harness"
+import {
+ INITIAL_POSITION_CROSSFADE_MS,
+ INITIAL_POSITION_EFFECT_DELAY_MS,
+ INITIAL_POSITION_MINIMUM_EFFECT_MS,
+ INITIAL_POSITION_TIMEOUT_MS,
+ useInitialPositionTransition,
+} from "./initial-position-transition"
+
+type Input = {
+ firstWindowReady: boolean
+ authoritativeEmpty: boolean
+ positionSettled: boolean
+}
+
+let latest: ReturnType<typeof useInitialPositionTransition>
+
+function Probe(input: Input) {
+ const transition = useInitialPositionTransition(input)
+ React.useLayoutEffect(() => { latest = transition }, [transition])
+ return React.createElement("div", { "data-phase": transition.phase })
+}
+
+const pending = (): Input => ({
+ firstWindowReady: true,
+ authoritativeEmpty: false,
+ positionSettled: false,
+})
+
+describe("useInitialPositionTransition", () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date(0))
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it("holds the skeleton until the first window and reveals an authoritative empty window immediately", () => {
+ const renderer = render(React.createElement(Probe, {
+ firstWindowReady: false,
+ authoritativeEmpty: false,
+ positionSettled: false,
+ }))
+ expect(latest).toMatchObject({ phase: "skeleton", showSkeleton: true })
+
+ renderer.rerender(React.createElement(Probe, {
+ firstWindowReady: true,
+ authoritativeEmpty: true,
+ positionSettled: false,
+ }))
+ expect(latest).toMatchObject({
+ phase: "revealed",
+ showSkeleton: false,
+ contentVisible: true,
+ auroraVisible: false,
+ })
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it("skips aurora when position settles before the 80ms threshold", () => {
+ const renderer = render(React.createElement(Probe, pending()))
+ expect(latest.phase).toBe("positioning")
+
+ act(() => vi.advanceTimersByTime(INITIAL_POSITION_EFFECT_DELAY_MS - 1))
+ renderer.rerender(React.createElement(Probe, { ...pending(), positionSettled: true }))
+ expect(latest).toMatchObject({
+ phase: "revealed",
+ contentVisible: true,
+ contentInteractive: true,
+ auroraVisible: false,
+ })
+
+ act(() => vi.runAllTimers())
+ expect(latest.phase).toBe("revealed")
+ })
+
+ it("holds a shown aurora for its minimum and crossfades for 100ms", () => {
+ const renderer = render(React.createElement(Probe, pending()))
+ act(() => vi.advanceTimersByTime(INITIAL_POSITION_EFFECT_DELAY_MS))
+ expect(latest).toMatchObject({ phase: "aurora", contentVisible: false, auroraVisible: true })
+
+ renderer.rerender(React.createElement(Probe, { ...pending(), positionSettled: true }))
+ act(() => vi.advanceTimersByTime(INITIAL_POSITION_MINIMUM_EFFECT_MS - 1))
+ expect(latest.phase).toBe("aurora")
+ act(() => vi.advanceTimersByTime(1))
+ expect(latest).toMatchObject({ phase: "revealing", contentVisible: true, auroraVisible: true })
+
+ act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS - 1))
+ expect(latest.phase).toBe("revealing")
+ act(() => vi.advanceTimersByTime(1))
+ expect(latest).toMatchObject({ phase: "revealed", auroraVisible: false })
+ })
+
+ it("times out to best-known content and ignores every late readiness change", () => {
+ const renderer = render(React.createElement(Probe, pending()))
+ act(() => vi.advanceTimersByTime(INITIAL_POSITION_TIMEOUT_MS))
+ expect(latest).toMatchObject({ phase: "revealing", contentVisible: true })
+
+ renderer.rerender(React.createElement(Probe, { ...pending(), positionSettled: true }))
+ renderer.rerender(React.createElement(Probe, {
+ firstWindowReady: false,
+ authoritativeEmpty: false,
+ positionSettled: false,
+ }))
+ expect(latest.phase).toBe("revealing")
+
+ act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS))
+ expect(latest).toMatchObject({ phase: "revealed", showSkeleton: false })
+
+ renderer.rerender(React.createElement(Probe, pending()))
+ act(() => vi.runAllTimers())
+ expect(latest).toMatchObject({ phase: "revealed", auroraVisible: false })
+ })
+
+ it("cleans delayed effect and timeout timers when a keyed mount leaves", () => {
+ const renderer = render(React.createElement(Probe, pending()))
+ expect(vi.getTimerCount()).toBe(2)
+ renderer.unmount()
+ expect(vi.getTimerCount()).toBe(0)
+ })
+})
diff --git a/src/web/src/components/community/messages/initial-position-transition.ts b/src/web/src/components/community/messages/initial-position-transition.ts
new file mode 100644
index 000000000..3db2dbaf4
--- /dev/null
+++ b/src/web/src/components/community/messages/initial-position-transition.ts
@@ -0,0 +1,127 @@
+"use client"
+
+import { useEffect, useLayoutEffect, useRef, useState } from "react"
+
+export const INITIAL_POSITION_EFFECT_DELAY_MS = 80
+export const INITIAL_POSITION_MINIMUM_EFFECT_MS = 160
+export const INITIAL_POSITION_CROSSFADE_MS = 100
+export const INITIAL_POSITION_TIMEOUT_MS = 2_000
+
+export type InitialPositionPhase =
+ | "skeleton"
+ | "positioning"
+ | "aurora"
+ | "revealing"
+ | "revealed"
+
+export function useInitialPositionTransition({
+ firstWindowReady,
+ authoritativeEmpty,
+ positionSettled,
+}: {
+ firstWindowReady: boolean
+ authoritativeEmpty: boolean
+ positionSettled: boolean
+}) {
+ const initiallyRevealed = firstWindowReady && (authoritativeEmpty || positionSettled)
+ const [phase, setPhase] = useState<InitialPositionPhase>(() => (
+ !firstWindowReady ? "skeleton" : initiallyRevealed ? "revealed" : "positioning"
+ ))
+ const revealedRef = useRef(initiallyRevealed)
+ const startedAtRef = useRef<number | null>(null)
+ const auroraStartedAtRef = useRef<number | null>(null)
+
+ useLayoutEffect(() => {
+ if (revealedRef.current) return
+ if (!firstWindowReady) {
+ startedAtRef.current = null
+ auroraStartedAtRef.current = null
+ setPhase("skeleton")
+ return
+ }
+ if (authoritativeEmpty || (positionSettled && phase !== "aurora")) {
+ revealedRef.current = true
+ setPhase("revealed")
+ return
+ }
+ if (startedAtRef.current === null) startedAtRef.current = Date.now()
+ if (phase === "skeleton") setPhase("positioning")
+ }, [authoritativeEmpty, firstWindowReady, phase, positionSettled])
+
+ useEffect(() => {
+ if (phase === "revealing") {
+ const crossfadeTimer = window.setTimeout(
+ () => setPhase("revealed"),
+ INITIAL_POSITION_CROSSFADE_MS,
+ )
+ return () => window.clearTimeout(crossfadeTimer)
+ }
+ if (revealedRef.current || !firstWindowReady || authoritativeEmpty) return
+
+ const startedAt = startedAtRef.current ?? Date.now()
+ startedAtRef.current = startedAt
+ const timeoutRemaining = Math.max(
+ 0,
+ INITIAL_POSITION_TIMEOUT_MS - (Date.now() - startedAt),
+ )
+ const timeoutTimer = window.setTimeout(() => {
+ if (revealedRef.current) return
+ revealedRef.current = true
+ setPhase("revealing")
+ }, timeoutRemaining)
+
+ if (phase === "positioning") {
+ const delayRemaining = Math.max(
+ 0,
+ INITIAL_POSITION_EFFECT_DELAY_MS - (Date.now() - startedAt),
+ )
+ const auroraTimer = window.setTimeout(() => {
+ if (revealedRef.current || positionSettled) return
+ auroraStartedAtRef.current = Date.now()
+ setPhase("aurora")
+ }, delayRemaining)
+ return () => {
+ window.clearTimeout(auroraTimer)
+ window.clearTimeout(timeoutTimer)
+ }
+ }
+
+ if (phase === "aurora" && positionSettled) {
+ const auroraStartedAt = auroraStartedAtRef.current ?? Date.now()
+ auroraStartedAtRef.current = auroraStartedAt
+ const minimumRemaining = Math.max(
+ 0,
+ INITIAL_POSITION_MINIMUM_EFFECT_MS - (Date.now() - auroraStartedAt),
+ )
+ const minimumTimer = window.setTimeout(() => {
+ if (revealedRef.current) return
+ revealedRef.current = true
+ setPhase("revealing")
+ }, minimumRemaining)
+ return () => {
+ window.clearTimeout(minimumTimer)
+ window.clearTimeout(timeoutTimer)
+ }
+ }
+
+ return () => window.clearTimeout(timeoutTimer)
+ }, [authoritativeEmpty, firstWindowReady, phase, positionSettled])
+
+ // The first renderable window must mount its real DOM in the same commit
+ // that clears loading. Waiting for the layout effect above to persist the
+ // phase would leave the skeleton branch mounted for that commit, so the
+ // controller's one-shot hero measurement effect would observe no node and
+ // initial anchoring would never arm. This projection changes presentation
+ // only; settlement still comes exclusively from the action-owned callback.
+ const renderedPhase = phase === "skeleton" && firstWindowReady
+ ? authoritativeEmpty || positionSettled ? "revealed" : "positioning"
+ : phase
+
+ return {
+ phase: renderedPhase,
+ showSkeleton: renderedPhase === "skeleton",
+ contentVisible: renderedPhase === "revealing" || renderedPhase === "revealed",
+ contentInteractive: renderedPhase === "revealing" || renderedPhase === "revealed",
+ auroraVisible: renderedPhase === "aurora" || renderedPhase === "revealing",
+ }
+}
diff --git a/src/web/src/components/community/messages/message-list-controller.dom.test.ts b/src/web/src/components/community/messages/message-list-controller.dom.test.ts
index 026b61950..a8f7a4a68 100644
--- a/src/web/src/components/community/messages/message-list-controller.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list-controller.dom.test.ts
@@ -195,6 +195,7 @@ describe("useMessageListController", () => {
viewerUserId: undefined,
heroHeight: 0,
heroMeasured: false,
+ onInitialPositionSettled: expect.any(Function),
})
expect(mocks.sentinelInputs.slice(0, 2)).toEqual([
{
@@ -229,6 +230,43 @@ describe("useMessageListController", () => {
expect(mocks.hookOrder.slice(-3)).toEqual(["anchor", "start", "end"])
})
+ it("reveals an authoritative empty window immediately and skips positioning effects", () => {
+ act(() => {
+ rtlRender(React.createElement(Probe, {
+ value: props({ loading: false, messages: [] }),
+ }))
+ })
+ expect(latest).toMatchObject({
+ isLoading: false,
+ initialPosition: {
+ phase: "revealed",
+ showSkeleton: false,
+ contentVisible: true,
+ auroraVisible: false,
+ },
+ })
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it("waits for the hook-owned post-action settlement callback on ordinary windows", () => {
+ act(() => {
+ rtlRender(React.createElement(Probe, { value: props() }))
+ })
+ expect(latest.initialPosition).toMatchObject({
+ phase: "positioning",
+ contentVisible: false,
+ })
+ const settle = (mocks.scrollInputs.at(-1) as {
+ onInitialPositionSettled: () => void
+ }).onInitialPositionSettled
+ act(() => settle())
+ expect(latest.initialPosition).toMatchObject({
+ phase: "revealed",
+ contentVisible: true,
+ auroraVisible: false,
+ })
+ })
+
it("passes every pagination/anchor input through and gives jump mode server-count precedence", () => {
const loadOlder = vi.fn()
const loadNewer = vi.fn()
@@ -260,6 +298,7 @@ describe("useMessageListController", () => {
viewerUserId: "viewer_1",
heroHeight: 0,
heroMeasured: true,
+ onInitialPositionSettled: expect.any(Function),
})
expect(mocks.sentinelInputs.slice(-2)).toEqual([
{
@@ -330,6 +369,7 @@ describe("useMessageListController", () => {
}))
})
expect((mocks.scrollInputs.at(-1) as { initialScrollReady: boolean }).initialScrollReady).toBe(false)
+ expect(latest.initialPosition.phase).toBe("positioning")
act(() => {
renderer!.rerender(React.createElement(Probe, {
value: props({
@@ -341,8 +381,16 @@ describe("useMessageListController", () => {
})
expect((mocks.scrollInputs.at(-1) as { initialScrollReady: boolean }).initialScrollReady).toBe(true)
expect(consumed).toHaveBeenCalledOnce()
+ const settleAnchor = (mocks.scrollInputs.at(-1) as {
+ onInitialPositionSettled: () => void
+ }).onInitialPositionSettled
+ act(() => settleAnchor())
+ expect(latest.initialPosition.phase).toBe("positioning")
visibleMessageIds = ["m2"]
runNextFrame()
+ expect(latest.initialPosition.phase).toBe("positioning")
+ runNextFrame()
+ expect(latest.initialPosition.phase).toBe("revealed")
act(() => {
latest.onEnterSelectId("m2")
latest.setShareOpen(true)
@@ -571,6 +619,23 @@ describe("useMessageListController", () => {
act(() => renderer!.unmount())
})
+ it("cancels explicit-target frames and transition timers when the keyed mount leaves", () => {
+ let renderer: ReturnType<typeof rtlRender>
+ act(() => {
+ renderer = rtlRender(React.createElement(Probe, {
+ value: props({ scrollToMessageId: "m1" }),
+ }))
+ })
+ const pendingFrames = [...frameCallbacks.keys()]
+ expect(pendingFrames).toHaveLength(2)
+ expect(vi.getTimerCount()).toBe(2)
+
+ act(() => renderer!.unmount())
+ for (const frame of pendingFrames) expect(cancelFrame).toHaveBeenCalledWith(frame)
+ expect(frameCallbacks.size).toBe(0)
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
it("bounds invisible-target polling and gives the newest pending frame and timer ownership", () => {
visibleMessageIds = []
let renderer: ReturnType<typeof rtlRender>
@@ -579,6 +644,10 @@ describe("useMessageListController", () => {
React.createElement(Probe, { value: props() })
)
})
+ act(() => (mocks.scrollInputs.at(-1) as {
+ onInitialPositionSettled: () => void
+ }).onInitialPositionSettled())
+ expect(latest.initialPosition.phase).toBe("revealed")
act(() => latest.jumpTo("m1", "auto"))
for (let index = 0; index < 120; index += 1) runNextFrame()
expect(requestFrame).toHaveBeenCalledTimes(120)
diff --git a/src/web/src/components/community/messages/message-list-controller.ts b/src/web/src/components/community/messages/message-list-controller.ts
index 4bf01df10..1a6c51257 100644
--- a/src/web/src/components/community/messages/message-list-controller.ts
+++ b/src/web/src/components/community/messages/message-list-controller.ts
@@ -5,6 +5,7 @@ import type { RenderMsg } from "@/lib/community/models/message"
import { flattenMessageItems } from "@/lib/community/message-list-items"
import { useScrollAnchor } from "@/hooks/community/use-scroll-anchor"
import { useVirtualCursorSentinel } from "@/hooks/community/use-virtual-cursor-sentinel"
+import { useInitialPositionTransition } from "./initial-position-transition"
import type { ResolvedMessageListProps } from "./message-list-types"
const SELECTION_RAIL_GAP_PX = 8
@@ -30,6 +31,10 @@ export function useMessageListController({
onScrollTargetConsumed,
}: ResolvedMessageListProps) {
const [jumped, setJumped] = useState<string | null>(null)
+ const [anchorPositionSettled, setAnchorPositionSettled] = useState(false)
+ const [targetPositionSettled, setTargetPositionSettled] = useState(!scrollToMessageId)
+ const targetSettleFrameRef = useRef<number | null>(null)
+ const consumedScrollTargetRef = useRef<string | null>(null)
const items = useMemo(
() => flattenMessageItems(messages, newDividerBefore, !!hasMore),
@@ -84,6 +89,8 @@ export function useMessageListController({
const [heroHeight, setHeroHeight] = useState(0)
const [heroMeasured, setHeroMeasured] = useState(false)
const isLoading = !!loading && messages.length === 0
+ const authoritativeEmpty = !loading && messages.length === 0
+ const settleAnchorPosition = useCallback(() => setAnchorPositionSettled(true), [])
useEffect(() => {
const element = heroRef.current
if (!element) return
@@ -114,6 +121,12 @@ export function useMessageListController({
viewerUserId,
heroHeight,
heroMeasured,
+ onInitialPositionSettled: settleAnchorPosition,
+ })
+ const initialPosition = useInitialPositionTransition({
+ firstWindowReady: !isLoading,
+ authoritativeEmpty,
+ positionSettled: anchorPositionSettled && targetPositionSettled,
})
useLayoutEffect(() => {
@@ -225,7 +238,11 @@ export function useMessageListController({
}
}, [])
- const consumedScrollTargetRef = useRef<string | null>(null)
+ useLayoutEffect(() => {
+ if (!scrollToMessageId) return
+ setTargetPositionSettled(false)
+ }, [scrollToMessageId])
+
useEffect(() => {
if (!scrollToMessageId) {
consumedScrollTargetRef.current = null
@@ -236,6 +253,13 @@ export function useMessageListController({
consumedScrollTargetRef.current = scrollToMessageId
jumpTo(scrollToMessageId, "auto")
onScrollTargetConsumed?.(scrollToMessageId)
+ if (targetSettleFrameRef.current !== null) {
+ window.cancelAnimationFrame(targetSettleFrameRef.current)
+ }
+ targetSettleFrameRef.current = window.requestAnimationFrame(() => {
+ targetSettleFrameRef.current = null
+ setTargetPositionSettled(true)
+ })
}, [
scrollToMessageId,
scrollTargetLoaded,
@@ -243,6 +267,11 @@ export function useMessageListController({
jumpTo,
onScrollTargetConsumed,
])
+ useLayoutEffect(() => () => {
+ if (targetSettleFrameRef.current !== null) {
+ window.cancelAnimationFrame(targetSettleFrameRef.current)
+ }
+ }, [])
const jumpMode = !!hasMoreNewer
const pillCount = jumpMode ? ((unreadCount ?? belowCount) || 0) : belowCount
@@ -258,6 +287,7 @@ export function useMessageListController({
return {
items,
isLoading,
+ initialPosition,
jumped,
selectMode,
selectedIds,
diff --git a/src/web/src/components/community/messages/message-list-facade.contract.test.ts b/src/web/src/components/community/messages/message-list-facade.contract.test.ts
index 9fac2f531..f4dbce688 100644
--- a/src/web/src/components/community/messages/message-list-facade.contract.test.ts
+++ b/src/web/src/components/community/messages/message-list-facade.contract.test.ts
@@ -2,11 +2,15 @@ import { readFileSync } from "node:fs"
import { dirname, resolve } from "node:path"
import { fileURLToPath } from "node:url"
import type { ComponentProps, ComponentRef, ReactNode } from "react"
-import { describe, expect, expectTypeOf, it } from "vitest"
+import { describe, expect, expectTypeOf, it, vi } from "vitest"
import * as facade from "./message-list"
import type { FileAttachment, ImagePreview, Msg } from "@/lib/community/models/message"
import type { OpenProfile } from "@/components/community/social/profile-types"
+vi.mock("./initial-position-aurora.module.css", () => ({
+ default: new Proxy({}, { get: (_target, key) => String(key) }),
+}))
+
type ExpectedMessageListProps = {
channel: string
messages: Msg[]
diff --git a/src/web/src/components/community/messages/message-list-view.dom.test.ts b/src/web/src/components/community/messages/message-list-view.dom.test.ts
index 3f7bd536d..8f24405a3 100644
--- a/src/web/src/components/community/messages/message-list-view.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list-view.dom.test.ts
@@ -14,10 +14,26 @@ vi.mock("./message-share-dialog", () => ({ MessageShareDialog: vi.fn(() => null)
vi.mock("@/components/ui/number-ticker", () => ({
NumberTicker: ({ value }: { value: number }) => React.createElement("ticker", { value }),
}))
+vi.mock("./initial-position-aurora.module.css", () => ({
+ default: new Proxy({}, { get: (_target, key) => String(key) }),
+}))
const mockedRail = vi.mocked(ComposerAccessoryRail)
const mockedShareDialog = vi.mocked(MessageShareDialog)
+function initialPosition(
+ overrides: Partial<MessageListController["initialPosition"]> = {},
+): MessageListController["initialPosition"] {
+ return {
+ phase: "revealed",
+ showSkeleton: false,
+ contentVisible: true,
+ contentInteractive: true,
+ auroraVisible: false,
+ ...overrides,
+ }
+}
+
function props(overrides: Partial<ResolvedMessageListProps> = {}): ResolvedMessageListProps {
return {
channel: "general",
@@ -41,6 +57,7 @@ function controller(overrides: Partial<MessageListController> = {}): MessageList
return {
items: [{ kind: "message", key: "m1", m: props().messages[0] }],
isLoading: false,
+ initialPosition: initialPosition(),
jumped: null,
selectMode: false,
selectedIds: new Set(),
@@ -88,7 +105,16 @@ describe("renderMessageListView", () => {
it("keeps the same wrappers while true empty loading omits the interactive accessory rail", () => {
const listProps = props({ messages: [] })
- const state = controller({ isLoading: true, pillCount: 8 })
+ const state = controller({
+ isLoading: true,
+ initialPosition: initialPosition({
+ phase: "skeleton",
+ showSkeleton: true,
+ contentVisible: false,
+ contentInteractive: false,
+ }),
+ pillCount: 8,
+ })
const renderRows = vi.fn(() => React.createElement("virtual-rows"))
const renderer = render(renderMessageListView(listProps, state, renderRows))
expect(renderer.container.firstElementChild).toHaveClass(
@@ -98,6 +124,77 @@ describe("renderMessageListView", () => {
expect(renderRows).not.toHaveBeenCalled()
expect(renderer.container.querySelectorAll(".mb-6")).toHaveLength(1)
expect(renderer.container.querySelectorAll("[data-message-typing-space]")).toHaveLength(0)
+ const content = renderer.container.querySelector<HTMLElement>("[data-message-list-content]")!
+ expect(content).toHaveClass("opacity-100")
+ expect(content).not.toHaveClass("transition-opacity", "duration-100")
+ })
+
+ it("keeps positioned rows measurable but inert and hidden until reveal starts", () => {
+ const renderRows = vi.fn(() => React.createElement("virtual-rows"))
+ const renderer = render(renderMessageListView(
+ props({ loading: false }),
+ controller({
+ initialPosition: initialPosition({
+ phase: "positioning",
+ contentVisible: false,
+ contentInteractive: false,
+ }),
+ }),
+ renderRows,
+ ))
+ const content = renderer.container.querySelector<HTMLElement>("[data-message-list-content]")!
+ expect(renderRows).toHaveBeenCalledOnce()
+ expect(renderer.container.querySelector("virtual-rows")).toBeInTheDocument()
+ expect(content).toHaveAttribute("data-initial-position-phase", "positioning")
+ expect(content).toHaveAttribute("aria-hidden", "true")
+ expect(content).toHaveAttribute("inert")
+ expect(content).toHaveClass("pointer-events-none", "opacity-0")
+ expect(content).not.toHaveClass("transition-opacity", "duration-100")
+ expect(mockedRail).not.toHaveBeenCalled()
+ })
+
+ it("crossfades content against the pointer-transparent aurora without changing geometry", () => {
+ const renderer = render(renderMessageListView(
+ props({ loading: false }),
+ controller({
+ initialPosition: initialPosition({
+ phase: "aurora",
+ contentVisible: false,
+ contentInteractive: false,
+ auroraVisible: true,
+ }),
+ }),
+ () => React.createElement("virtual-rows"),
+ ))
+ const content = () => renderer.container.querySelector<HTMLElement>("[data-message-list-content]")!
+ expect(content()).toHaveClass("opacity-0")
+ expect(content()).not.toHaveClass("transition-opacity", "duration-100")
+ expect(renderer.getByTestId("community-initial-position-aurora"))
+ .toHaveAttribute("data-phase", "aurora")
+
+ renderer.rerender(renderMessageListView(
+ props({ loading: false }),
+ controller({
+ initialPosition: initialPosition({
+ phase: "revealing",
+ auroraVisible: true,
+ }),
+ }),
+ () => React.createElement("virtual-rows"),
+ ))
+ expect(content()).toHaveClass("opacity-100", "transition-opacity", "duration-100")
+ expect(content()).toHaveAttribute("aria-hidden", "false")
+ expect(content()).not.toHaveAttribute("inert")
+ expect(renderer.getByTestId("community-initial-position-aurora"))
+ .toHaveAttribute("data-phase", "revealing")
+
+ renderer.rerender(renderMessageListView(
+ props({ loading: false }),
+ controller({ initialPosition: initialPosition({ phase: "revealed" }) }),
+ () => React.createElement("virtual-rows"),
+ ))
+ expect(content()).toHaveClass("opacity-100")
+ expect(content()).not.toHaveClass("transition-opacity", "duration-100")
})
it("routes typing through the rail without adding a dynamic flex sibling", () => {
diff --git a/src/web/src/components/community/messages/message-list-view.tsx b/src/web/src/components/community/messages/message-list-view.tsx
index 5e8d90c57..2c4301ed8 100644
--- a/src/web/src/components/community/messages/message-list-view.tsx
+++ b/src/web/src/components/community/messages/message-list-view.tsx
@@ -3,6 +3,7 @@ import { Skeleton } from "@/components/ui/skeleton"
import { tid } from "@/lib/community/testids"
import { ChannelIcon } from "../channels/channel-icon"
import { ComposerAccessoryRail } from "./composer-accessory-rail"
+import { InitialPositionAurora } from "./initial-position-aurora"
import { MessageShareDialog } from "./message-share-dialog"
import type { MessageListController } from "./message-list-controller"
import type { ResolvedMessageListProps } from "./message-list-types"
@@ -22,7 +23,7 @@ export function renderMessageListView(
/>
)}
<div data-message-scroller-boundary className="relative min-h-0 flex-1">
- {!controller.isLoading && (
+ {controller.initialPosition.contentInteractive && (
<ComposerAccessoryRail
typingNames={props.typingUsers ?? []}
scrollCount={controller.pillCount}
@@ -41,9 +42,18 @@ export function renderMessageListView(
>
<div
data-message-list-content
- className="flex min-h-full flex-col justify-end px-4 pb-14 pt-8 sm:pb-18"
+ data-initial-position-phase={controller.initialPosition.phase}
+ aria-hidden={!controller.initialPosition.showSkeleton && !controller.initialPosition.contentVisible}
+ inert={!controller.initialPosition.showSkeleton && !controller.initialPosition.contentInteractive}
+ className={`flex min-h-full flex-col justify-end px-4 pb-14 pt-8 sm:pb-18 ${
+ controller.initialPosition.phase === "revealing"
+ ? "opacity-100 transition-opacity duration-100 ease-out motion-reduce:transition-opacity"
+ : controller.initialPosition.showSkeleton || controller.initialPosition.contentVisible
+ ? "opacity-100"
+ : "pointer-events-none opacity-0"
+ }`}
>
- {controller.isLoading ? (
+ {controller.initialPosition.showSkeleton ? (
<MessageListSkeletonContent variant={props.variant} />
) : (
<>
@@ -84,6 +94,7 @@ export function renderMessageListView(
)}
</div>
</div>
+ <InitialPositionAurora phase={controller.initialPosition.phase} />
</div>
</div>
)
diff --git a/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts b/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts
index c9ae55c35..63e08fcdb 100644
--- a/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts
@@ -43,6 +43,9 @@ vi.mock("./message-row", () => ({
}))
vi.mock("./message-share-dialog", () => ({ MessageShareDialog: () => null }))
vi.mock("./typing-indicator", () => ({ TypingIndicator: () => null }))
+vi.mock("./initial-position-aurora.module.css", () => ({
+ default: new Proxy({}, { get: (_target, key) => String(key) }),
+}))
const target = {
id: "m_target",
diff --git a/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts b/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts
index b64ef77ff..ac91b1de1 100644
--- a/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts
@@ -6,6 +6,9 @@ import { render } from "@/test/react-dom-harness"
vi.mock("@/components/ui/number-ticker", () => ({
NumberTicker: ({ value }: { value: number }) => React.createElement("span", null, value),
}))
+vi.mock("./initial-position-aurora.module.css", () => ({
+ default: new Proxy({}, { get: (_target, key) => String(key) }),
+}))
let scrollToDescriptor: PropertyDescriptor | undefined
@@ -67,6 +70,13 @@ describe("MessageList — loading→loaded mount identity (Phase 4)", () => {
)
expect(scrollTo).toHaveBeenCalledTimes(callsBeforeLoaded + 1)
+ const positionedContent = renderer.container.querySelector(
+ "[data-message-list-content]",
+ )
+ expect(positionedContent).toHaveAttribute("data-initial-position-phase", "positioning")
+ expect(positionedContent).toHaveAttribute("aria-hidden", "true")
+ expect(positionedContent).toHaveAttribute("inert")
+ expect(positionedContent).toHaveClass("pointer-events-none", "opacity-0")
renderer.rerender(
React.createElement(MessageList, {
diff --git a/src/web/src/components/community/messages/message-list.older-load.dom.test.ts b/src/web/src/components/community/messages/message-list.older-load.dom.test.ts
index 9fe5fb6ab..44fb305f1 100644
--- a/src/web/src/components/community/messages/message-list.older-load.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list.older-load.dom.test.ts
@@ -7,6 +7,9 @@ import { MessageList } from "./message-list"
vi.mock("@/components/ui/number-ticker", () => ({
NumberTicker: ({ value }: { value: number }) => React.createElement("span", null, value),
}))
+vi.mock("./initial-position-aurora.module.css", () => ({
+ default: new Proxy({}, { get: (_target, key) => String(key) }),
+}))
let scrollTopDescriptor: PropertyDescriptor | undefined
let scrollToDescriptor: PropertyDescriptor | undefined
diff --git a/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.ts b/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.ts
index ca50901d4..5801a43d2 100644
--- a/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.ts
+++ b/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.ts
@@ -50,7 +50,7 @@ import {
reserveInboxUnreadsResponse,
type ThreadOpenerHandoffTarget,
} from "./inbox-read-reservation"
-import { useTimelineReadObserver } from "./use-read-observer"
+import { useTimelineReadObserver, type ReadCandidate } from "./use-read-observer"
type Lifecycle = "pending" | "ready" | "terminal-error"
@@ -99,23 +99,86 @@ function Harness({
}
const noCatchUp = () => Promise.resolve()
-const emptyScrollRoot = {
- querySelectorAll: () => [],
- contains: () => false,
-} as unknown as HTMLElement
+const defaultChildMessages: ReadCandidate[] = [
+ { id: "message-4", seq: 4, authorId: "other-1", createdAt: "t4" },
+]
+type ReadObserverRecord = {
+ callback: IntersectionObserverCallback
+ observed: Set<Element>
+ disconnected: boolean
+}
+
+let readObservers: ReadObserverRecord[] = []
+
+class FakeReadIntersectionObserver {
+ private readonly record: ReadObserverRecord
+
+ constructor(callback: IntersectionObserverCallback) {
+ this.record = { callback, observed: new Set(), disconnected: false }
+ readObservers.push(this.record)
+ }
+
+ observe(element: Element) {
+ this.record.observed.add(element)
+ }
-function DirectChildHarness() {
+ unobserve(element: Element) {
+ this.record.observed.delete(element)
+ }
+
+ takeRecords() {
+ return []
+ }
+
+ disconnect() {
+ this.record.disconnected = true
+ this.record.observed.clear()
+ }
+}
+
+function emitReadIntersection(record: ReadObserverRecord, target: Element) {
+ record.callback([{
+ target,
+ isIntersecting: true,
+ intersectionRatio: 1,
+ } as IntersectionObserverEntry], {} as IntersectionObserver)
+}
+
+function DirectChildHarness({
+ hidden = false,
+ lifecycle = "error",
+ messages = defaultChildMessages,
+ catchUp = noCatchUp,
+}: {
+ hidden?: boolean
+ lifecycle?: "ready" | "error"
+ messages?: ReadCandidate[]
+ catchUp?: () => Promise<unknown>
+}) {
+ const [scrollRootEl, setScrollRootEl] = React.useState<HTMLElement | null>(null)
useTimelineReadObserver({
channelId: "child-1",
- messages: [],
- scrollRootEl: emptyScrollRoot,
- snapshotStatus: "error",
- feedStatus: "error",
- tailAttached: false,
+ messages: lifecycle === "ready" ? messages : [],
+ scrollRootEl,
+ snapshotStatus: lifecycle,
+ feedStatus: lifecycle,
+ tailAttached: lifecycle === "ready",
confirmedSeq: 0,
- catchUp: noCatchUp,
+ catchUp,
})
- return null
+ return React.createElement(
+ "div",
+ { ref: setScrollRootEl },
+ React.createElement(
+ "div",
+ {
+ "data-message-list-content": "",
+ "aria-hidden": hidden ? "true" : "false",
+ inert: hidden ? true : undefined,
+ },
+ React.createElement("div", { "data-msg-id": messages[0]?.id ?? "message-4" }),
+ ),
+ )
}
function openerResponse() {
@@ -137,6 +200,20 @@ function openerResponse() {
}
}
+function directResponse(lastMessageAt = "2026-08-27T01:00:00.000Z") {
+ return {
+ servers: [{
+ channels: [{
+ channelId: "child-1",
+ lastMessageAt,
+ hasDirectUnread: true,
+ children: [],
+ }],
+ }],
+ dms: [],
+ }
+}
+
async function render(lifecycle: Lifecycle = "pending") {
let renderer!: ReturnType<typeof rtlRender>
await act(async () => {
@@ -152,8 +229,10 @@ describe("thread opener read handoff", () => {
state.queryClient = client()
state.params = "inboxThreadOpener=nonce-1&msg=message-9&tab=all"
state.pathname = "/c/channels/server-1/child-1"
+ readObservers = []
vi.clearAllMocks()
mocks.submit.mockReturnValue(17)
+ vi.stubGlobal("IntersectionObserver", FakeReadIntersectionObserver)
})
afterEach(() => {
@@ -380,6 +459,161 @@ describe("thread opener read handoff", () => {
expect(mocks.submit).not.toHaveBeenCalled()
expect(mocks.replace).not.toHaveBeenCalled()
+ vi.clearAllMocks()
+ await act(async () => {
+ renderer.rerender(
+ React.createElement(
+ React.StrictMode,
+ null,
+ React.createElement(DirectChildHarness, { hidden: true, lifecycle: "ready" }),
+ ),
+ )
+ await Promise.resolve()
+ })
+ const readObserver = readObservers.findLast((record) => !record.disconnected)!
+ const messageRow = renderer.container.querySelector<HTMLElement>("[data-msg-id='message-4']")!
+ expect(readObserver.observed.has(messageRow)).toBe(true)
+
+ emitReadIntersection(readObserver, messageRow)
+ expect(mocks.submit).not.toHaveBeenCalled()
+ expect(mocks.resume).not.toHaveBeenCalled()
+
+ await act(async () => {
+ renderer.rerender(
+ React.createElement(
+ React.StrictMode,
+ null,
+ React.createElement(DirectChildHarness, { lifecycle: "ready" }),
+ ),
+ )
+ await Promise.resolve()
+ })
+ expect(readObserver.observed.has(messageRow)).toBe(true)
+ emitReadIntersection(readObserver, messageRow)
+ expect(mocks.submit).toHaveBeenCalledOnce()
+ expect(mocks.submit).toHaveBeenCalledWith({ lease: "parent" }, {
+ kind: "timeline",
+ channelId: "child-1",
+ messageId: "message-4",
+ seq: 4,
+ })
+
+ await act(async () => renderer.unmount())
+ })
+
+ it("reclassifies an authoritative absent candidate on reveal and releases its held response once", async () => {
+ const messages: ReadCandidate[] = [{
+ id: "message-10",
+ seq: 10,
+ authorId: "other-1",
+ createdAt: "2026-08-27T02:00:00.000Z",
+ }]
+ const catchUp = vi.fn().mockResolvedValue(undefined)
+ let renderer!: ReturnType<typeof rtlRender>
+ await act(async () => {
+ renderer = rtlRender(React.createElement(DirectChildHarness, {
+ hidden: true,
+ lifecycle: "ready",
+ messages,
+ catchUp,
+ }))
+ })
+
+ let held!: Promise<ReturnType<typeof directResponse>>
+ let settled = false
+ await act(async () => {
+ held = reserveInboxUnreadsResponse(state.queryClient!, directResponse())
+ void held.then(() => { settled = true }, () => { settled = true })
+ await Promise.resolve()
+ })
+ const readObserver = readObservers.findLast((record) => !record.disconnected)!
+ const messageRow = renderer.container.querySelector<HTMLElement>("[data-msg-id='message-10']")!
+ emitReadIntersection(readObserver, messageRow)
+
+ expect(settled).toBe(false)
+ expect(catchUp).not.toHaveBeenCalled()
+ expect(mocks.submit).not.toHaveBeenCalled()
+ expect(mocks.resume).not.toHaveBeenCalled()
+ expect(state.queryClient!.refetchQueries).not.toHaveBeenCalled()
+
+ await act(async () => {
+ renderer.rerender(React.createElement(DirectChildHarness, {
+ lifecycle: "ready",
+ messages,
+ catchUp,
+ }))
+ await Promise.resolve()
+ })
+
+ await expect(held).rejects.toMatchObject({ name: "AbortError" })
+ expect(settled).toBe(true)
+ expect(catchUp).not.toHaveBeenCalled()
+ expect(mocks.submit).not.toHaveBeenCalled()
+ expect(state.queryClient!.refetchQueries).toHaveBeenCalledOnce()
+ await act(async () => renderer.unmount())
+ })
+
+ it("runs one behind-tail catch-up after reveal, then settles the still-absent held response", async () => {
+ const messages: ReadCandidate[] = [{
+ id: "message-1",
+ seq: 1,
+ authorId: "other-1",
+ createdAt: "2026-08-27T00:00:00.000Z",
+ }]
+ let resolveCatchUp!: () => void
+ const catchUp = vi.fn(() => new Promise<void>((resolve) => {
+ resolveCatchUp = resolve
+ }))
+ let renderer!: ReturnType<typeof rtlRender>
+ await act(async () => {
+ renderer = rtlRender(React.createElement(DirectChildHarness, {
+ hidden: true,
+ lifecycle: "ready",
+ messages,
+ catchUp,
+ }))
+ })
+
+ let held!: Promise<ReturnType<typeof directResponse>>
+ let settled = false
+ await act(async () => {
+ held = reserveInboxUnreadsResponse(state.queryClient!, directResponse())
+ void held.then(() => { settled = true }, () => { settled = true })
+ await Promise.resolve()
+ })
+ const readObserver = readObservers.findLast((record) => !record.disconnected)!
+ const messageRow = renderer.container.querySelector<HTMLElement>("[data-msg-id='message-1']")!
+ emitReadIntersection(readObserver, messageRow)
+
+ expect(settled).toBe(false)
+ expect(catchUp).not.toHaveBeenCalled()
+ expect(mocks.submit).not.toHaveBeenCalled()
+ expect(mocks.resume).not.toHaveBeenCalled()
+
+ await act(async () => {
+ renderer.rerender(React.createElement(DirectChildHarness, {
+ lifecycle: "ready",
+ messages,
+ catchUp,
+ }))
+ await Promise.resolve()
+ })
+
+ expect(catchUp).toHaveBeenCalledOnce()
+ expect(settled).toBe(false)
+ expect(state.queryClient!.refetchQueries).not.toHaveBeenCalled()
+
+ await act(async () => {
+ resolveCatchUp()
+ await catchUp.mock.results[0]!.value
+ await Promise.resolve()
+ })
+
+ await expect(held).rejects.toMatchObject({ name: "AbortError" })
+ expect(settled).toBe(true)
+ expect(catchUp).toHaveBeenCalledOnce()
+ expect(mocks.submit).not.toHaveBeenCalled()
+ expect(state.queryClient!.refetchQueries).toHaveBeenCalledOnce()
await act(async () => renderer.unmount())
})
diff --git a/src/web/src/hooks/community/use-read-observer.test.ts b/src/web/src/hooks/community/use-read-observer.test.ts
index 0fc87efcc..419035e92 100644
--- a/src/web/src/hooks/community/use-read-observer.test.ts
+++ b/src/web/src/hooks/community/use-read-observer.test.ts
@@ -99,6 +99,8 @@ import { useTimelineReadObserver } from "./use-read-observer"
type ObserverRecord = {
callback: IntersectionObserverCallback
observed: Set<Element>
+ queued: IntersectionObserverEntry[]
+ actions: string[]
disconnected: boolean
}
@@ -107,23 +109,38 @@ let visibility: DocumentVisibilityState
let visibilityListeners: Set<() => void>
let pageShowListeners: Set<() => void>
let mutationCallback: MutationCallback | undefined
+let mutationObserveOptions: MutationObserverInit | undefined
+let mutationObservedTarget: Node | undefined
class FakeIntersectionObserver {
private readonly record: ObserverRecord
constructor(callback: IntersectionObserverCallback) {
- this.record = { callback, observed: new Set(), disconnected: false }
+ this.record = {
+ callback,
+ observed: new Set(),
+ queued: [],
+ actions: [],
+ disconnected: false,
+ }
observers.push(this.record)
}
observe(element: Element) {
+ this.record.actions.push(`observe:${(element as HTMLElement).dataset.msgId ?? "unknown"}`)
this.record.observed.add(element)
}
unobserve(element: Element) {
+ this.record.actions.push(`unobserve:${(element as HTMLElement).dataset.msgId ?? "unknown"}`)
this.record.observed.delete(element)
}
+ takeRecords() {
+ this.record.actions.push("takeRecords")
+ return this.record.queued.splice(0)
+ }
+
disconnect() {
this.record.disconnected = true
this.record.observed.clear()
@@ -139,8 +156,39 @@ function makeRow(id: string) {
} as unknown as HTMLElement
}
-function makeRoot(rows: HTMLElement[]) {
+type ContentBoundary = HTMLElement & {
+ setAriaHidden: (hidden: boolean) => void
+ setInert: (inert: boolean) => void
+ setReadable: (readable: boolean) => void
+}
+
+function makeContentBoundary(initiallyReadable = true) {
+ let ariaHidden = !initiallyReadable
+ let inert = !initiallyReadable
return {
+ nodeType: 1,
+ getAttribute: (name: string) => name === "aria-hidden"
+ ? ariaHidden ? "true" : "false"
+ : null,
+ hasAttribute: (name: string) => name === "inert" && inert,
+ setAriaHidden: (hidden: boolean) => {
+ ariaHidden = hidden
+ },
+ setInert: (next: boolean) => {
+ inert = next
+ },
+ setReadable: (next: boolean) => {
+ ariaHidden = !next
+ inert = !next
+ },
+ } as unknown as ContentBoundary
+}
+
+function makeRoot(rows: HTMLElement[], boundary: ContentBoundary | null = makeContentBoundary()) {
+ return {
+ querySelector: (selector: string) => selector === "[data-message-list-content]"
+ ? boundary
+ : null,
querySelectorAll: () => rows,
contains: (node: Element) => rows.includes(node as HTMLElement),
} as unknown as HTMLElement
@@ -153,11 +201,44 @@ function runEffects() {
}
function trigger(record: ObserverRecord, target: Element, ratio = 1) {
- record.callback([{
+ const entry = {
+ target,
+ isIntersecting: true,
+ intersectionRatio: ratio,
+ } as IntersectionObserverEntry
+ record.callback([entry], {} as IntersectionObserver)
+}
+
+function queueEntry(record: ObserverRecord, target: Element, ratio = 1) {
+ record.queued.push({
target,
isIntersecting: true,
intersectionRatio: ratio,
- } as IntersectionObserverEntry], {} as IntersectionObserver)
+ } as IntersectionObserverEntry)
+}
+
+function deliverQueued(record: ObserverRecord) {
+ record.callback(record.queued.splice(0), {} as IntersectionObserver)
+}
+
+function presentationAttributeRecord(
+ boundary: ContentBoundary,
+ attributeName: "aria-hidden" | "inert",
+) {
+ return {
+ type: "attributes",
+ target: boundary,
+ attributeName,
+ addedNodes: [] as unknown as NodeList,
+ } as MutationRecord
+}
+
+function setPresentationAttributeReadable(
+ boundary: ContentBoundary,
+ attributeName: "aria-hidden" | "inert",
+) {
+ if (attributeName === "aria-hidden") boundary.setAriaHidden(false)
+ else boundary.setInert(false)
}
function useTestRender(options: Partial<Parameters<typeof useTimelineReadObserver>[0]> = {}) {
@@ -186,6 +267,8 @@ describe("useTimelineReadObserver", () => {
visibilityListeners = new Set()
pageShowListeners = new Set()
mutationCallback = undefined
+ mutationObserveOptions = undefined
+ mutationObservedTarget = undefined
hookState.candidate = null
refState.reset()
vi.clearAllMocks()
@@ -195,7 +278,10 @@ describe("useTimelineReadObserver", () => {
mutationCallback = callback
}
- observe() {}
+ observe(target: Node, options?: MutationObserverInit) {
+ mutationObservedTarget = target
+ mutationObserveOptions = options
+ }
disconnect() {}
})
vi.stubGlobal("document", {
@@ -274,9 +360,15 @@ describe("useTimelineReadObserver", () => {
expect(observers[0]!.disconnected).toBe(true)
})
- it("submits only the visible forum-card prefix candidate and preserves unseen newer siblings", () => {
+ it("keeps a no-boundary forum surface readable for intent, negative classification, and resume", () => {
+ hookState.candidate = {
+ channelId: "forum-1",
+ lastMessageAt: "t3",
+ fingerprint: "forum-t3",
+ openerUnread: true,
+ }
const rows = [makeRow("opener-a"), makeRow("opener-b"), makeRow("opener-c")]
- const root = makeRoot(rows)
+ const root = makeRoot(rows, null)
useTestRender({
channelId: "forum-1",
messages: [
@@ -285,10 +377,14 @@ describe("useTimelineReadObserver", () => {
{ id: "opener-c", seq: 3, authorId: "alice" },
],
scrollRootEl: root,
+ tailAttached: false,
confirmedSeq: 0,
})
runEffects()
+ expect(root.querySelector("[data-message-list-content]")).toBeNull()
+ expect(reservation.negative).toHaveBeenCalledWith({ lease: "reservation" })
+ expect(coordinator.resume).toHaveBeenCalledWith(queryClient)
trigger(observers[0]!, rows[0]!)
expect(coordinator.submit).toHaveBeenCalledOnce()
@@ -316,6 +412,32 @@ describe("useTimelineReadObserver", () => {
expect(coordinator.submit).toHaveBeenCalledOnce()
})
+ it("keeps all read side effects silent while presentation is hidden and inert", () => {
+ hookState.candidate = {
+ channelId: "channel-1",
+ lastMessageAt: "t4",
+ fingerprint: "focused-t4",
+ openerUnread: false,
+ }
+ const row = makeRow("message-4")
+ const boundary = makeContentBoundary(false)
+ useTestRender({
+ scrollRootEl: makeRoot([row], boundary),
+ tailAttached: false,
+ })
+ runEffects()
+
+ trigger(observers[0]!, row)
+ for (const listener of visibilityListeners) listener()
+ for (const listener of pageShowListeners) listener()
+
+ expect(coordinator.submit).not.toHaveBeenCalled()
+ expect(projection.recordOptimisticRead).not.toHaveBeenCalled()
+ expect(reservation.promote).not.toHaveBeenCalled()
+ expect(reservation.negative).not.toHaveBeenCalled()
+ expect(coordinator.resume).not.toHaveBeenCalled()
+ })
+
it.each([
{ snapshotStatus: "error" as const },
{ feedStatus: "error" as const },
@@ -449,6 +571,9 @@ describe("useTimelineReadObserver", () => {
trigger(record, row)
expect(coordinator.submit).not.toHaveBeenCalled()
expect(coordinator.release).toHaveBeenCalledWith({ lease: "timeline" })
+ expect(reservation.release.mock.invocationCallOrder[0]).toBeLessThan(
+ coordinator.release.mock.invocationCallOrder[0]!,
+ )
})
it("binds direct and nested message rows added after the observer mounts", () => {
@@ -470,4 +595,156 @@ describe("useTimelineReadObserver", () => {
expect(observers[0]!.observed.has(direct)).toBe(true)
expect(observers[0]!.observed.has(nested)).toBe(true)
})
+
+ it("drains a hidden queued entry before rebinding the same node for reveal", () => {
+ const row = makeRow("message-4")
+ const boundary = makeContentBoundary(false)
+ const root = makeRoot([row], boundary)
+ useTestRender({ scrollRootEl: root })
+ runEffects()
+ const record = observers[0]!
+ expect(mutationObservedTarget).toBe(root)
+ expect(mutationObserveOptions).toEqual({
+ attributes: true,
+ attributeFilter: ["aria-hidden", "inert"],
+ childList: true,
+ subtree: true,
+ })
+ queueEntry(record, row)
+ record.actions.length = 0
+
+ boundary.setReadable(true)
+ mutationCallback?.([{
+ type: "attributes",
+ target: boundary,
+ attributeName: "aria-hidden",
+ addedNodes: [] as unknown as NodeList,
+ } as MutationRecord], {} as MutationObserver)
+
+ const drainIndex = record.actions.indexOf("takeRecords")
+ expect(drainIndex).toBeGreaterThan(record.actions.indexOf("unobserve:message-4"))
+ expect(record.actions.findIndex((action, index) => (
+ index > drainIndex && action === "observe:message-4"
+ ))).toBeGreaterThan(drainIndex)
+
+ deliverQueued(record)
+ expect(coordinator.submit).not.toHaveBeenCalled()
+
+ queueEntry(record, row)
+ deliverQueued(record)
+ expect(coordinator.submit).toHaveBeenCalledOnce()
+ })
+
+ it.each([
+ {
+ label: "aria-hidden then inert across two deliveries",
+ first: "aria-hidden" as const,
+ second: "inert" as const,
+ },
+ {
+ label: "inert then aria-hidden across two deliveries",
+ first: "inert" as const,
+ second: "aria-hidden" as const,
+ },
+ ])("resamples once for $label", ({ first, second }) => {
+ const row = makeRow("message-4")
+ const boundary = makeContentBoundary(false)
+ useTestRender({ scrollRootEl: makeRoot([row], boundary) })
+ runEffects()
+ const record = observers[0]!
+ record.actions.length = 0
+
+ setPresentationAttributeReadable(boundary, first)
+ mutationCallback?.([
+ presentationAttributeRecord(boundary, first),
+ ], {} as MutationObserver)
+ expect(record.actions.filter((action) => action === "takeRecords")).toHaveLength(0)
+ expect(coordinator.resume).not.toHaveBeenCalled()
+
+ setPresentationAttributeReadable(boundary, second)
+ mutationCallback?.([
+ presentationAttributeRecord(boundary, second),
+ ], {} as MutationObserver)
+ expect(record.actions.filter((action) => action === "takeRecords")).toHaveLength(1)
+ expect(coordinator.resume).toHaveBeenCalledOnce()
+
+ mutationCallback?.([
+ presentationAttributeRecord(boundary, second),
+ ], {} as MutationObserver)
+ expect(record.actions.filter((action) => action === "takeRecords")).toHaveLength(1)
+ expect(coordinator.resume).toHaveBeenCalledOnce()
+ })
+
+ it("resamples once when both presentation attributes become readable in one delivery", () => {
+ const row = makeRow("message-4")
+ const boundary = makeContentBoundary(false)
+ useTestRender({ scrollRootEl: makeRoot([row], boundary) })
+ runEffects()
+ const record = observers[0]!
+ record.actions.length = 0
+
+ boundary.setAriaHidden(false)
+ expect(record.actions.filter((action) => action === "takeRecords")).toHaveLength(0)
+ expect(coordinator.resume).not.toHaveBeenCalled()
+
+ boundary.setInert(false)
+ mutationCallback?.([
+ presentationAttributeRecord(boundary, "aria-hidden"),
+ presentationAttributeRecord(boundary, "inert"),
+ ], {} as MutationObserver)
+ expect(record.actions.filter((action) => action === "takeRecords")).toHaveLength(1)
+ expect(coordinator.resume).toHaveBeenCalledOnce()
+
+ mutationCallback?.([
+ presentationAttributeRecord(boundary, "aria-hidden"),
+ presentationAttributeRecord(boundary, "inert"),
+ ], {} as MutationObserver)
+ expect(record.actions.filter((action) => action === "takeRecords")).toHaveLength(1)
+ expect(coordinator.resume).toHaveBeenCalledOnce()
+ })
+
+ it("drains reveal entries but preserves the document-hidden negative return", () => {
+ const row = makeRow("message-4")
+ const boundary = makeContentBoundary(false)
+ useTestRender({ scrollRootEl: makeRoot([row], boundary) })
+ runEffects()
+ const record = observers[0]!
+ queueEntry(record, row)
+ record.actions.length = 0
+ visibility = "hidden"
+
+ boundary.setReadable(true)
+ mutationCallback?.([{
+ type: "attributes",
+ target: boundary,
+ attributeName: "aria-hidden",
+ addedNodes: [] as unknown as NodeList,
+ } as MutationRecord], {} as MutationObserver)
+
+ expect(record.actions).toEqual(["unobserve:message-4", "takeRecords"])
+ expect(record.queued).toHaveLength(0)
+ expect(reservation.negative).toHaveBeenCalledOnce()
+ expect(coordinator.resume).not.toHaveBeenCalled()
+
+ visibility = "visible"
+ for (const listener of visibilityListeners) listener()
+ expect(record.actions.filter((action) => action === "takeRecords")).toHaveLength(1)
+ expect(record.actions.at(-1)).toBe("observe:message-4")
+ expect(coordinator.resume).toHaveBeenCalledOnce()
+ })
+
+ it("keeps ordinary visibility and pageshow samples independent and undrained", () => {
+ const { row } = useTestRender()
+ runEffects()
+ const record = observers[0]!
+ coordinator.resume.mockClear()
+ record.actions.length = 0
+
+ for (const listener of visibilityListeners) listener()
+ for (const listener of pageShowListeners) listener()
+
+ expect(coordinator.resume).toHaveBeenCalledTimes(2)
+ expect(record.actions.filter((action) => action === "takeRecords")).toHaveLength(0)
+ expect(record.observed.has(row)).toBe(true)
+ })
})
diff --git a/src/web/src/hooks/community/use-read-observer.ts b/src/web/src/hooks/community/use-read-observer.ts
index cb8f237e3..b14f36639 100644
--- a/src/web/src/hooks/community/use-read-observer.ts
+++ b/src/web/src/hooks/community/use-read-observer.ts
@@ -1,6 +1,6 @@
"use client"
-import { useEffect, useLayoutEffect, useRef, useState } from "react"
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"
import { useQueryClient } from "@tanstack/react-query"
import { useCurrentUser } from "@/contexts/community/current-user"
import {
@@ -21,6 +21,14 @@ import {
import { getAccountUnreadProjection } from "./account-unread-projection"
const READ_VISIBILITY_THRESHOLD = 0.2
+const MESSAGE_LIST_CONTENT_SELECTOR = "[data-message-list-content]"
+
+function readPresentationReadable(scrollRootEl: HTMLElement) {
+ const content = scrollRootEl.querySelector<HTMLElement>(MESSAGE_LIST_CONTENT_SELECTOR)
+ if (!content) return true
+ return content.getAttribute("aria-hidden") === "false"
+ && !content.hasAttribute("inert")
+}
export type ReadCandidate = {
id: string
@@ -60,7 +68,8 @@ export function useTimelineReadObserver({
const catchUpStartedRef = useRef(new Set<string>())
const catchUpSettledRef = useRef(new Set<string>())
const [candidate, setCandidate] = useState<InboxReadCandidate | null>(null)
- const [, setCatchUpVersion] = useState(0)
+ const [catchUpVersion, setCatchUpVersion] = useState(0)
+ const classifyCandidateRef = useRef<() => void>(() => undefined)
useLayoutEffect(() => {
messagesRef.current = messages
@@ -97,11 +106,12 @@ export function useTimelineReadObserver({
confirmReadSurface(lease, confirmedSeq)
}, [confirmedSeq, snapshotStatus])
- useEffect(() => {
+ const classifyCandidate = useCallback(() => {
if (!candidate || !channelId) return
const reservationLease = reservationLeaseRef.current
if (!reservationLease) return
if (snapshotStatus === "pending" || feedStatus === "pending" || !scrollRootEl) return
+ if (!readPresentationReadable(scrollRootEl)) return
if (
snapshotStatus === "error"
|| feedStatus === "error"
@@ -155,6 +165,14 @@ export function useTimelineReadObserver({
tailAttached,
])
+ useLayoutEffect(() => {
+ classifyCandidateRef.current = classifyCandidate
+ }, [classifyCandidate])
+
+ useEffect(() => {
+ classifyCandidate()
+ }, [catchUpVersion, classifyCandidate])
+
useEffect(() => {
if (!channelId || !scrollRootEl) return
if (typeof IntersectionObserver === "undefined") return
@@ -162,6 +180,7 @@ export function useTimelineReadObserver({
const reservationLease = reservationLeaseRef.current
if (!readLease || !reservationLease) return
let observerGeneration = 0
+ let presentationReadable = readPresentationReadable(scrollRootEl)
const bindings = new WeakMap<Element, { id: string; generation: number }>()
const bind = (node: Element) => {
const id = (node as HTMLElement).dataset.msgId
@@ -170,6 +189,7 @@ export function useTimelineReadObserver({
observer.observe(node)
}
const observer = new IntersectionObserver((entries) => {
+ if (!readPresentationReadable(scrollRootEl)) return
if (!readyRef.current) return
if (document.visibilityState !== "visible") {
takeInboxReadReservationNegative(reservationLease)
@@ -205,6 +225,7 @@ export function useTimelineReadObserver({
}, { root: scrollRootEl, threshold: READ_VISIBILITY_THRESHOLD })
const sample = () => {
+ if (!readPresentationReadable(scrollRootEl)) return
if (document.visibilityState !== "visible") {
takeInboxReadReservationNegative(reservationLease)
return
@@ -221,6 +242,18 @@ export function useTimelineReadObserver({
const mutations = typeof MutationObserver === "undefined"
? null
: new MutationObserver((records) => {
+ const nextPresentationReadable = readPresentationReadable(scrollRootEl)
+ const presentationRevealed = !presentationReadable && nextPresentationReadable
+ presentationReadable = nextPresentationReadable
+ if (presentationRevealed) {
+ scrollRootEl.querySelectorAll<HTMLElement>("[data-msg-id]").forEach((node) => {
+ observer.unobserve(node)
+ })
+ observer.takeRecords()
+ sample()
+ if (document.visibilityState === "visible") classifyCandidateRef.current()
+ return
+ }
for (const record of records) {
for (const node of record.addedNodes) {
if ((node as { nodeType?: number }).nodeType !== 1) continue
@@ -230,7 +263,12 @@ export function useTimelineReadObserver({
}
}
})
- mutations?.observe(scrollRootEl, { childList: true, subtree: true })
+ mutations?.observe(scrollRootEl, {
+ attributes: true,
+ attributeFilter: ["aria-hidden", "inert"],
+ childList: true,
+ subtree: true,
+ })
document.addEventListener("visibilitychange", sample)
window.addEventListener("pageshow", sample)
return () => {
@@ -243,7 +281,13 @@ export function useTimelineReadObserver({
}, [channelId, currentUser.id, feedStatus, queryClient, scrollRootEl, snapshotStatus])
useEffect(() => {
- if (!channelId || snapshotStatus !== "ready" || document.visibilityState !== "visible") return
+ if (
+ !channelId
+ || !scrollRootEl
+ || snapshotStatus !== "ready"
+ || document.visibilityState !== "visible"
+ || !readPresentationReadable(scrollRootEl)
+ ) return
resumeReadCoordinator(queryClient)
- }, [channelId, messages, queryClient, snapshotStatus])
+ }, [channelId, messages, queryClient, scrollRootEl, snapshotStatus])
}
diff --git a/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts b/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts
index b196c7728..cfa3520bb 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts
@@ -4,7 +4,7 @@
* deferred bottom re-pin contract stay covered without duplicating that logic
* in a test-only export.
*/
-import { beforeEach, describe, expect, it, vi } from "vitest"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import type { VirtualizerOptions } from "@tanstack/react-virtual"
import type { FlatItem } from "@/lib/community/message-list-items"
@@ -52,6 +52,10 @@ function resetHarness() {
virtualizer.isAtEnd.mockReturnValue(true)
virtualizer.scrollToEnd.mockReset()
virtualizer.scrollToIndex.mockReset()
+ vi.stubGlobal("window", {
+ requestAnimationFrame: vi.fn(() => 1),
+ cancelAnimationFrame: vi.fn(),
+ })
vi.stubGlobal("ResizeObserver", class {
constructor(callback: ResizeObserverCallback) {
resizeCallbacks.push(callback)
@@ -70,9 +74,11 @@ async function mountHook({
items = [] as FlatItem[],
initialScrollReady = false,
heroMeasured = false,
+ newDividerBefore,
hasMoreNewer,
presentVersion,
viewerUserId,
+ onInitialPositionSettled,
}: {
distanceToEnd?: number
initialClientHeight?: number
@@ -80,9 +86,11 @@ async function mountHook({
items?: FlatItem[]
initialScrollReady?: boolean
heroMeasured?: boolean
+ newDividerBefore?: string
hasMoreNewer?: boolean
presentVersion?: number
viewerUserId?: string
+ onInitialPositionSettled?: () => void
} = {}) {
const { useScrollAnchor } = await import("./use-scroll-anchor")
const hookInput = {
@@ -90,9 +98,11 @@ async function mountHook({
initialScrollReady,
heroHeight: 0,
heroMeasured,
+ newDividerBefore,
hasMoreNewer,
presentVersion,
viewerUserId,
+ onInitialPositionSettled,
}
// The React module is intentionally mocked above; this calls a deterministic
// hook shim rather than mounting a real component tree.
@@ -216,8 +226,46 @@ function growingRow(requestFrame: (callback: FrameRequestCallback) => void) {
}
beforeEach(resetHarness)
+afterEach(() => vi.unstubAllGlobals())
describe("useScrollAnchor delayed row-growth re-pin", () => {
+ it("publishes settlement one frame after the final initial convergence action", async () => {
+ const frameCallbacks: FrameRequestCallback[] = []
+ const cancelFrame = vi.fn()
+ const settled = vi.fn()
+ vi.stubGlobal("window", {
+ requestAnimationFrame: (callback: FrameRequestCallback) => {
+ frameCallbacks.push(callback)
+ return frameCallbacks.length
+ },
+ cancelAnimationFrame: cancelFrame,
+ })
+
+ const mounted = await mountHook({
+ items: [messageItem("m1")],
+ initialScrollReady: false,
+ heroMeasured: true,
+ onInitialPositionSettled: settled,
+ })
+ expect(virtualizer.scrollToEnd).toHaveBeenCalledOnce()
+ expect(frameCallbacks).toHaveLength(0)
+ expect(settled).not.toHaveBeenCalled()
+
+ mounted.rerender({
+ initialScrollReady: true,
+ newDividerBefore: "m1",
+ })
+ expect(virtualizer.scrollToIndex).toHaveBeenCalledOnce()
+ expect(frameCallbacks).toHaveLength(1)
+ expect(settled).not.toHaveBeenCalled()
+
+ frameCallbacks[0](0)
+ expect(settled).toHaveBeenCalledOnce()
+ mounted.rerender({ newDividerBefore: undefined })
+ expect(frameCallbacks).toHaveLength(1)
+ expect(settled).toHaveBeenCalledOnce()
+ })
+
it("measures live growth and re-pins after the direct-DOM size write settles", async () => {
const { scrollWrites } = await mountHook()
let frame: FrameRequestCallback | undefined
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index 28dbc1984..7c12f8934 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -395,6 +395,7 @@ export function useScrollAnchor({
viewerUserId,
heroHeight,
heroMeasured,
+ onInitialPositionSettled,
}: {
items: FlatItem[]
newDividerBefore?: string
@@ -414,6 +415,7 @@ export function useScrollAnchor({
// `DecideScrollActionInput.heroMeasured`'s doc comment for the bug this
// prevents (mount firing on a stale, default-0 `scrollMargin`).
heroMeasured: boolean
+ onInitialPositionSettled?: () => void
}): {
scrollRef: React.RefObject<HTMLDivElement | null>
virtualizer: ReactVirtualizer<HTMLDivElement, Element>
@@ -424,6 +426,8 @@ export function useScrollAnchor({
} {
const scrollRef = useRef<HTMLDivElement>(null)
const stateRef = useRef<ScrollAnchorState>(createScrollAnchorState())
+ const initialSettleFrameRef = useRef<number | null>(null)
+ const initialPositionSettledRef = useRef(false)
const messages = extractScrollAnchorMessages(items)
const tailId = messages[messages.length - 1]?.id ?? null
const wasAtEndRef = useRef(true)
@@ -436,6 +440,21 @@ export function useScrollAnchor({
const liveResizeAnchor = wasExactlyPinnedRef.current && !userScrolledAwayRef.current
? "end"
: "start"
+ const cancelInitialSettleFrame = useCallback(() => {
+ if (initialSettleFrameRef.current === null) return
+ window.cancelAnimationFrame(initialSettleFrameRef.current)
+ initialSettleFrameRef.current = null
+ }, [])
+ const scheduleInitialPositionSettled = useCallback(() => {
+ if (initialPositionSettledRef.current || initialSettleFrameRef.current !== null) return
+ initialSettleFrameRef.current = window.requestAnimationFrame(() => {
+ initialSettleFrameRef.current = null
+ if (initialPositionSettledRef.current) return
+ initialPositionSettledRef.current = true
+ onInitialPositionSettled?.()
+ })
+ }, [onInitialPositionSettled])
+ useLayoutEffect(() => cancelInitialSettleFrame, [cancelInitialSettleFrame])
// eslint-disable-next-line react-hooks/incompatible-library -- library limitation, same as member-list.tsx
const virtualizer = useVirtualizer({
@@ -619,6 +638,8 @@ export function useScrollAnchor({
userScrolledAway: userScrolledAwayRef.current,
})
stateRef.current = nextState
+ const initialSequenceComplete = nextState.didInitialScroll && nextState.didDividerConverge
+ if (!initialSequenceComplete) cancelInitialSettleFrame()
switch (action.type) {
case "mount": {
@@ -630,21 +651,32 @@ export function useScrollAnchor({
virtualizer.options.anchorTo = "end"
virtualizer.scrollToEnd()
}
- return
+ break
}
case "scrollToEnd":
wasExactlyPinnedRef.current = true
virtualizer.options.anchorTo = "end"
virtualizer.scrollToEnd()
- return
+ break
case "none":
- return
+ break
}
+ if (initialSequenceComplete) scheduleInitialPositionSettled()
// messages/items share identity per render (extractScrollAnchorMessages
// derives from items) — `items` alone is the correct dep, not a
// secondary `messages` dep, avoiding a re-derivation-triggered re-fire.
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [items, newDividerBefore, initialScrollReady, heroMeasured, hasMoreNewer, viewerUserId, virtualizer])
+ }, [
+ items,
+ newDividerBefore,
+ initialScrollReady,
+ heroMeasured,
+ hasMoreNewer,
+ viewerUserId,
+ virtualizer,
+ cancelInitialSettleFrame,
+ scheduleInitialPositionSettled,
+ ])
const consumedPresentVersionRef = useRef(0)
useLayoutEffect(() => {
@@ -661,7 +693,8 @@ export function useScrollAnchor({
userScrolledAwayRef.current = false
virtualizer.options.anchorTo = "end"
virtualizer.scrollToEnd()
- }, [hasMoreNewer, presentVersion, tailId, virtualizer])
+ scheduleInitialPositionSettled()
+ }, [hasMoreNewer, presentVersion, scheduleInitialPositionSettled, tailId, virtualizer])
// Hero-swap compensation — NOT delegated to `scrollMargin` (verified it
// never triggers a `scrollOffset` write on its own). Tracks the hero's
diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.ts
index b79d6dcb3..5282872c4 100644
--- a/src/web/src/lib/community/testids.test.ts
+++ b/src/web/src/lib/community/testids.test.ts
@@ -78,6 +78,7 @@ describe("community QA selectors", () => {
expect(tid.memberRow("member_1")).toBe("community-member-row-member_1")
expect(tid.composerFileInput).toBe("community-composer-file-input")
expect(tid.messageScroller).toBe("community-message-scroller")
+ expect(tid.initialPositionAurora).toBe("community-initial-position-aurora")
expect(tid.reactionGroup("message_1")).toBe("community-reaction-group-message_1")
expect(tid.reactionChip("message_1", "🔥"))
.toBe("community-reaction-chip-message_1-%F0%9F%94%A5")
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index dadecce7c..026b4a7fa 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -11,6 +11,7 @@ export const tid = {
scrollToPresent: "community-scroll-to-present",
messageSelectionToolbar: "community-message-selection-toolbar",
messageScroller: "community-message-scroller",
+ initialPositionAurora: "community-initial-position-aurora",
wsReconnectOverlay: "community-ws-reconnect-overlay",
wsRetry: "community-ws-retry",
initialFrame: "community-initial-frame",