Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(channels): open threads at the bottom without jank (#4958)
teof5a899671d31
diff --git a/apps/web/src/features/channel/Channel/ThreadList.tsx b/apps/web/src/features/channel/Channel/ThreadList.tsxindex 7124ce8916..a9839abf07 100644--- a/apps/web/src/features/channel/Channel/ThreadList.tsx+++ b/apps/web/src/features/channel/Channel/ThreadList.tsx@@ -326,9 +326,20 @@ export function ThreadList(props: ThreadListProps) {let rafId = 0;const start = performance.now();+ const virtualContent = Array.from(el.children).find(+ (child): child is HTMLElement =>+ child instanceof HTMLElement && child.style.contain.includes('size')+ );+ const resizeObserver = virtualContent+ ? new ResizeObserver(() => {+ if (getDistanceFromBottom(handle) > 1) el.scrollTop = el.scrollHeight;+ })+ : undefined;+ if (virtualContent) resizeObserver?.observe(virtualContent);const stop = () => {if (rafId) cancelAnimationFrame(rafId);+ resizeObserver?.disconnect();el.removeEventListener('wheel', onWheel);el.removeEventListener('pointerdown', onPointerDown);if (cancelPinToBottom === stop) cancelPinToBottom = undefined;@@ -418,7 +429,10 @@ export function ThreadList(props: ThreadListProps) {viewportSize: handle.viewportSize,});- const didScroll = scrollToInitialTarget(handle, target);+ const didScroll =+ target.tag === 'bottom'+ ? pinToBottom(handle)+ : scrollToInitialTarget(handle, target);if (!didScroll) {// Empty list or target not found — nothing to verify.@@ -462,26 +476,33 @@ export function ThreadList(props: ThreadListProps) {);}- function scrollOnMount(handle: VirtualizerHandle) {- if (initialScrollStarted) return;- initialScrollStarted = true;-+ const getInitialScrollTarget = (): InitialScrollTarget => {const snapshot = props.initialScrollSnapshot;if (snapshot) {- if (snapshot.isNearBottom) {- beginInitialTargetScroll(handle, DEFAULT_INITIAL_SCROLL_TARGET);- } else {- beginInitialTargetScroll(handle, {- tag: 'offset',- scrollOffset: snapshot.scrollOffset,- });- }-- return;+ return snapshot.isNearBottom+ ? DEFAULT_INITIAL_SCROLL_TARGET+ : { tag: 'offset', scrollOffset: snapshot.scrollOffset };}- const target = props.initialScrollTarget ?? DEFAULT_INITIAL_SCROLL_TARGET;- beginInitialTargetScroll(handle, target);+ return props.initialScrollTarget ?? DEFAULT_INITIAL_SCROLL_TARGET;+ };++ // Virtua publishes its handle before ResizeObserver has populated+ // `viewportSize`. Waiting for that measurement before doing anything leaves+ // an overflowing channel visibly parked at scrollTop=0 for one or more+ // frames. A bottom target is safe to issue immediately: with a zero viewport+ // Virtua overshoots the final offset and the browser clamps it to the DOM's+ // current maximum, putting the first painted frame at the bottom. The normal+ // measured pass below still corrects the exact end alignment afterwards.+ const prepositionInitialBottom = (handle: VirtualizerHandle) => {+ const target = getInitialScrollTarget();+ if (target.tag === 'bottom') pinToBottom(handle);+ };++ function scrollOnMount(handle: VirtualizerHandle) {+ if (initialScrollStarted) return;+ initialScrollStarted = true;+ beginInitialTargetScroll(handle, getInitialScrollTarget());}const handleScrollEnd = () => {@@ -510,10 +531,10 @@ export function ThreadList(props: ThreadListProps) {});requestAnimationFrame(() => {const offsetBeforeRetry = handle.scrollOffset;- const retryScrolled = scrollToInitialTarget(- handle,- initialScrollTarget- );+ const retryScrolled =+ initialScrollTarget.tag === 'bottom'+ ? pinToBottom(handle)+ : scrollToInitialTarget(handle, initialScrollTarget);if (!retryScrolled) {// Target disappeared between mount and retry — finalize now since// no scroll events will fire to trigger another onScrollEnd.@@ -649,6 +670,7 @@ export function ThreadList(props: ThreadListProps) {props.onNavigationReady(createNavigation(ref));}resetInitialScroll();+ prepositionInitialBottom(ref);scrollOnMountWhenMeasured(ref);}}scrollRef={scrollRef}diff --git a/apps/web/tests/e2e/helpers/scroll-presentation.ts b/apps/web/tests/e2e/helpers/scroll-presentation.tsnew file mode 100644index 0000000000..eb5db56260--- /dev/null+++ b/apps/web/tests/e2e/helpers/scroll-presentation.ts@@ -0,0 +1,171 @@+import type { Page } from '@playwright/test';++type ResizeObserverDelayState = {+ matchedCallbacks: number;+ releaseAt?: number;+};++type BottomPresentationSample = {+ time: number;+ distanceFromBottom: number;+};++export type BottomPresentationReport = {+ first?: BottomPresentationSample;+ firstViolation?: BottomPresentationSample;+ violationCount: number;+};++declare global {+ interface Window {+ __e2eResizeObserverDelay?: ResizeObserverDelayState;+ __e2eBottomPresentation?: BottomPresentationReport;+ }+}++/** Delay ResizeObserver callbacks for a DOM subtree to make layout races deterministic. */+export async function delayResizeObserverFor(+ page: Page,+ selector: string,+ delayMs: number+) {+ await page.addInitScript(+ ({ selector, delayMs }) => {+ const NativeResizeObserver = window.ResizeObserver;+ const state: ResizeObserverDelayState = { matchedCallbacks: 0 };+ window.__e2eResizeObserverDelay = state;++ class DelayedResizeObserver implements ResizeObserver {+ private readonly observer: ResizeObserver;+ private queuedEntries?: ResizeObserverEntry[];+ private timer?: number;+ private disconnected = false;++ constructor(callback: ResizeObserverCallback) {+ this.observer = new NativeResizeObserver((entries) => {+ const matchesSubtree = entries.some(+ ({ target }) =>+ target.matches(selector) || target.closest(selector) !== null+ );+ if (!matchesSubtree) {+ callback(entries, this);+ return;+ }++ state.matchedCallbacks += 1;+ state.releaseAt ??= performance.now() + delayMs;+ const remaining = state.releaseAt - performance.now();+ if (remaining <= 0) {+ callback(entries, this);+ return;+ }++ this.queuedEntries = entries;+ if (this.timer !== undefined) return;+ this.timer = window.setTimeout(() => {+ this.timer = undefined;+ const pendingEntries = this.queuedEntries;+ this.queuedEntries = undefined;+ if (!this.disconnected && pendingEntries) {+ callback(pendingEntries, this);+ }+ }, remaining);+ });+ }++ observe(target: Element, options?: ResizeObserverOptions) {+ this.observer.observe(target, options);+ }++ unobserve(target: Element) {+ this.observer.unobserve(target);+ }++ disconnect() {+ this.disconnected = true;+ if (this.timer !== undefined) window.clearTimeout(this.timer);+ this.observer.disconnect();+ }+ }++ window.ResizeObserver = DelayedResizeObserver;+ },+ { selector, delayMs }+ );++ return {+ async waitForRelease() {+ await page.waitForFunction(() => {+ const releaseAt = window.__e2eResizeObserverDelay?.releaseAt;+ return releaseAt !== undefined && performance.now() >= releaseAt;+ });+ // Let released measurements and their resulting render commit.+ await page.evaluate(+ () =>+ new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ })+ );+ return page.evaluate(() => window.__e2eResizeObserverDelay);+ },+ };+}++/** Observe the post-paint bottom distance of every visible overflowing frame. */+export async function observeBottomPresentation(+ page: Page,+ selector: string,+ tolerancePx = 1+) {+ await page.addInitScript(+ ({ selector, tolerancePx }) => {+ const report: BottomPresentationReport = { violationCount: 0 };+ window.__e2eBottomPresentation = report;++ const verify = () => {+ const scroller = document.querySelector<HTMLElement>(selector);+ if (scroller) {+ const style = getComputedStyle(scroller);+ const visible =+ style.display !== 'none' &&+ style.visibility !== 'hidden' &&+ scroller.getClientRects().length > 0;+ const overflowing = scroller.scrollHeight > scroller.clientHeight;++ if (visible && overflowing) {+ const sample = {+ time: performance.now(),+ distanceFromBottom:+ scroller.scrollHeight -+ scroller.clientHeight -+ scroller.scrollTop,+ };+ report.first ??= sample;+ if (sample.distanceFromBottom > tolerancePx) {+ report.firstViolation ??= sample;+ report.violationCount += 1;+ }+ }+ }++ schedulePostPaintCheck();+ };++ // Timers queued from rAF run after that frame's paint. This observes what+ // a user could see without racing the app's own rAF corrections.+ const schedulePostPaintCheck = () => {+ requestAnimationFrame(() => window.setTimeout(verify, 0));+ };++ schedulePostPaintCheck();+ },+ { selector, tolerancePx }+ );++ return {+ read: () =>+ page.evaluate(+ () => window.__e2eBottomPresentation as BottomPresentationReport+ ),+ };+}diff --git a/apps/web/tests/e2e/local-channel-scroll.spec.ts b/apps/web/tests/e2e/local-channel-scroll.spec.tsnew file mode 100644index 0000000000..913c0c458c--- /dev/null+++ b/apps/web/tests/e2e/local-channel-scroll.spec.ts@@ -0,0 +1,63 @@+import { expect, test } from '@playwright/test';+import { entityIdSelector } from '../../src/lib/core/dom-selectors';++import { localE2ESeed } from './fixtures/local-e2e-seed';+import {+ expectEntityInCurrentList,+ gotoApp,+ LOCAL_E2E,+} from './helpers/local-app';+import {+ delayResizeObserverFor,+ observeBottomPresentation,+} from './helpers/scroll-presentation';++const CHANNEL_SCROLL_SELECTOR = '[data-channel-scroll]';+const BOTTOM_TOLERANCE_PX = 1;++test.skip(!LOCAL_E2E, 'requires the seeded local E2E stack');++test('presents an overflowing channel at the bottom before measurement settles', async ({+ page,+}) => {+ const resizeDelay = await delayResizeObserverFor(+ page,+ CHANNEL_SCROLL_SELECTOR,+ 150+ );+ const presentation = await observeBottomPresentation(+ page,+ CHANNEL_SCROLL_SELECTOR,+ BOTTOM_TOLERANCE_PX+ );++ const channel = localE2ESeed.smoke.generalChannel;+ const channelName = channel.channel_name ?? 'general';++ await gotoApp(page, '/component/channels');+ await expectEntityInCurrentList(page, channel.channel_id, channelName);+ await page.locator(entityIdSelector(channel.channel_id)).first().click();++ await expect(page).toHaveURL(+ new RegExp(`/app/channel/${channel.channel_id}(?:[/?#]|$)`)+ );++ const scroller = page.locator(CHANNEL_SCROLL_SELECTOR);+ await expect(scroller).toBeVisible({ timeout: 30_000 });+ const resizeFault = await resizeDelay.waitForRelease();+ await expect(+ page.getByText('Scroll fixture message 5000', { exact: true })+ ).toBeInViewport({ timeout: 30_000 });++ const report = await presentation.read();+ expect(resizeFault?.matchedCallbacks).toBeGreaterThan(0);+ expect(resizeFault?.releaseAt).toBeDefined();+ expect(report.first).toBeDefined();++ expect(report.first?.distanceFromBottom).toBeLessThanOrEqual(+ BOTTOM_TOLERANCE_PX+ );+ expect(report.first?.time).toBeLessThan(resizeFault?.releaseAt ?? 0);+ expect(report.firstViolation).toBeUndefined();+ expect(report.violationCount).toBe(0);+});diff --git a/tooling/seed_cli/seed/local_e2e/channel_messages.sql b/tooling/seed_cli/seed/local_e2e/channel_messages.sqlnew file mode 100644index 0000000000..d99677253e--- /dev/null+++ b/tooling/seed_cli/seed/local_e2e/channel_messages.sql@@ -0,0 +1,26 @@+WITH local_e2e_channels AS (+ SELECT+ channel.id,+ array_agg(participant.user_id ORDER BY participant.user_id) AS sender_ids+ FROM comms_channels AS channel+ JOIN comms_channel_participants AS participant+ ON participant.channel_id = channel.id+ AND participant.left_at IS NULL+ WHERE channel.id::text LIKE '00000000-0000-0000-0000-00000000000%'+ GROUP BY channel.id+)+INSERT INTO comms_messages (id, channel_id, sender_id, content, created_at, updated_at)+SELECT+ md5('local-e2e-scroll-' || channel.id::text || '-' || message_number)::uuid,+ channel.id,+ channel.sender_ids[+ 1 + ((message_number - 1) % cardinality(channel.sender_ids))::integer+ ],+ CASE+ WHEN message_number % 7 = 0 THEN repeat('Variable-height scroll fixture message ' || message_number || '. ', 12)+ ELSE 'Scroll fixture message ' || message_number+ END,+ now() + (message_number || ' milliseconds')::interval,+ now() + (message_number || ' milliseconds')::interval+FROM local_e2e_channels AS channel+CROSS JOIN generate_series(1, 5000) AS message_number;diff --git a/tooling/seed_cli/src/entity/scenario/mod.rs b/tooling/seed_cli/src/entity/scenario/mod.rsindex b682d6fe49..61dc8c8894 100644--- a/tooling/seed_cli/src/entity/scenario/mod.rs+++ b/tooling/seed_cli/src/entity/scenario/mod.rs@@ -12,6 +12,8 @@ use crate::entity::{channel, channel_message, document};const LOCAL_E2E_MANIFEST_JSON: &str = include_str!("../../../seed/local_e2e/manifest.json");const LOCAL_E2E_RESET_SQL: &str = include_str!("../../../seed/local_e2e/reset.sql");const LOCAL_E2E_USERS_JSON: &str = include_str!("../../../seed/local_e2e/users.json");+const LOCAL_E2E_CHANNEL_MESSAGES_SQL: &str =+ include_str!("../../../seed/local_e2e/channel_messages.sql");#[derive(Debug, Deserialize)]struct LocalE2eManifest {@@ -345,6 +347,11 @@ async fn local_e2e_smoke(ctx: &SeedCliContext) -> anyhow::Result<()> {let channel_messages_path = seed_path("seed/channel_messages.json");channel_message::seed_from_file_ref(ctx, &channel_messages_path).await?;+ tracing::info!("seeding 5,000 local e2e messages per channel");+ ctx.db+ .execute_sql_script(LOCAL_E2E_CHANNEL_MESSAGES_SQL)+ .await?;+println!("Local e2e smoke seed data ready for {local_e2e_user_id}");Ok(())}