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
feat(new-channels): improved scrolling stability (#2433)
teoe7e220eaa304
diff --git a/js/app/packages/channel/Channel/Channel.tsx b/js/app/packages/channel/Channel/Channel.tsxindex 6c8c73d05e..7fe9c496ba 100644--- a/js/app/packages/channel/Channel/Channel.tsx+++ b/js/app/packages/channel/Channel/Channel.tsx@@ -60,6 +60,7 @@ import { createChannelHotkeys } from './create-channel-hotkeys';import { createInlineInputKeyboardHandler } from './create-inline-input-keyboard-handler';import type { ChannelInputProps } from '@channel/Input/ChannelInput';import {+ clearStaleRestoredChannelData,createTargetMessageController,type TargetMessageController,} from './create-target-message-controller';@@ -105,6 +106,12 @@ export function Channel(props: ChannelProps) {const [messageListElement, setMessageListElement] =createSignal<HTMLDivElement>();+ // When opening without a target, clear stale data that was previously+ // restored from a load-around session so the query fetches from the bottom.+ if (!props.targetMessageId) {+ clearStaleRestoredChannelData(props.channelId);+ }+const targetMessageController = createTargetMessageController({channelId: () => props.channelId,initialTargetMessageId: props.targetMessageId,diff --git a/js/app/packages/channel/Channel/ThreadList.tsx b/js/app/packages/channel/Channel/ThreadList.tsxindex 58ba443d48..09f073b3d3 100644--- a/js/app/packages/channel/Channel/ThreadList.tsx+++ b/js/app/packages/channel/Channel/ThreadList.tsx@@ -109,6 +109,17 @@ export function ThreadList(props: ThreadListProps) {const scrollIntent = createScrollIntentTracker();+ let initialScrollStarted = false;+ let initialScrollRetried = false;+ let initialScrollTarget: ThreadListScrollTarget =+ DEFAULT_INITIAL_SCROLL_TARGET;++ const resetInitialScroll = () => {+ initialScrollStarted = false;+ initialScrollRetried = false;+ initialScrollTarget = DEFAULT_INITIAL_SCROLL_TARGET;+ };+const resolveTargetIndex = (target: ThreadListScrollTarget): number => {const keys = props.keys();const maxIndex = keys.length - 1;@@ -138,6 +149,30 @@ export function ThreadList(props: ThreadListProps) {return true;};+ const getDistanceFromBottom = (handle: VirtualizerHandle): number =>+ handle.scrollSize - handle.viewportSize - handle.scrollOffset;++ const isScrollPositionCorrect = (+ handle: VirtualizerHandle,+ target: ThreadListScrollTarget+ ): boolean => {+ switch (target.tag) {+ case 'bottom':+ return getDistanceFromBottom(handle) <= NEAR_BOTTOM_THRESHOLD;+ case 'top':+ return handle.scrollOffset <= NEAR_BOTTOM_THRESHOLD;+ case 'id':+ case 'index': {+ const targetIndex = resolveTargetIndex(target);+ if (targetIndex < 0) return true; // target gone, nothing to verify+ const currentIndex = handle.findItemIndex(handle.scrollOffset);+ // Consider correct if the target is within a reasonable range of+ // the current viewport (within ±5 items accounts for alignment).+ return Math.abs(currentIndex - targetIndex) <= 5;+ }+ }+ };+const getCurrentIndex = (handle: VirtualizerHandle): number => {const itemCount = props.keys().length;if (!itemCount) return -1;@@ -150,8 +185,7 @@ export function ThreadList(props: ThreadListProps) {) => {if (!props.onScrollStateChange) return;const distanceFromTop = handle.scrollOffset;- const distanceFromBottom =- handle.scrollSize - handle.viewportSize - handle.scrollOffset;+ const distanceFromBottom = getDistanceFromBottom(handle);props.onScrollStateChange({didInitialScroll: didInitialScroll(),isNearBottom: distanceFromBottom <= NEAR_BOTTOM_THRESHOLD,@@ -162,6 +196,12 @@ export function ThreadList(props: ThreadListProps) {});};+ /** Mark the initial scroll as complete and broadcast the scroll state. */+ const completeInitialScroll = (handle: VirtualizerHandle) => {+ setDidInitialScroll(true);+ emitScrollState(handle, false);+ };+const createNavigation = (handle: VirtualizerHandle): ThreadListNavigation => ({@@ -207,12 +247,92 @@ export function ThreadList(props: ThreadListProps) {});function scrollOnMount(handle: VirtualizerHandle) {+ if (initialScrollStarted) return;+ initialScrollStarted = true;+const target = props.initialScrollTarget ?? DEFAULT_INITIAL_SCROLL_TARGET;- scrollToTarget(handle, target);- setDidInitialScroll(true);- emitScrollState(handle, false);+ initialScrollTarget = target;++ console.debug('ThreadList: scrollOnMount', {+ target,+ itemCount: props.keys().length,+ scrollOffset: handle.scrollOffset,+ scrollSize: handle.scrollSize,+ viewportSize: handle.viewportSize,+ });++ const didScroll = scrollToTarget(handle, target);++ if (!didScroll) {+ // Empty list or target not found — nothing to verify.+ console.debug(+ 'ThreadList: target not resolvable, completing immediately'+ );+ completeInitialScroll(handle);+ return;+ }++ // If no actual scrolling was needed (content fits in viewport),+ // onScrollEnd will never fire. Use a RAF to detect this case and+ // finalize immediately.+ requestAnimationFrame(() => {+ if (didInitialScroll()) return;+ if (isScrollPositionCorrect(handle, target)) {+ console.debug(+ 'ThreadList: position already correct (RAF fallback), completing'+ );+ completeInitialScroll(handle);+ }+ });}+ const handleScrollEnd = () => {+ if (didInitialScroll()) return;++ const handle = virtualHandle();+ if (!handle) return;++ if (isScrollPositionCorrect(handle, initialScrollTarget)) {+ console.debug('ThreadList: onScrollEnd confirmed position, completing', {+ scrollOffset: handle.scrollOffset,+ distanceFromBottom: getDistanceFromBottom(handle),+ });+ completeInitialScroll(handle);+ return;+ }++ if (!initialScrollRetried) {+ initialScrollRetried = true;+ console.debug('ThreadList: initial scroll missed target, retrying', {+ target: initialScrollTarget,+ scrollOffset: handle.scrollOffset,+ scrollSize: handle.scrollSize,+ viewportSize: handle.viewportSize,+ distanceFromBottom: getDistanceFromBottom(handle),+ });+ requestAnimationFrame(() => {+ const retryScrolled = scrollToTarget(handle, initialScrollTarget);+ if (!retryScrolled) {+ // Target disappeared between mount and retry — finalize now since+ // no scroll events will fire to trigger another onScrollEnd.+ completeInitialScroll(handle);+ }+ });+ return;+ }+ console.warn(+ 'ThreadList: initial scroll did not reach target after retry',+ {+ target: initialScrollTarget,+ scrollOffset: handle.scrollOffset,+ scrollSize: handle.scrollSize,+ viewportSize: handle.viewportSize,+ distanceFromBottom: getDistanceFromBottom(handle),+ }+ );+ completeInitialScroll(handle);+ };+const handleScroll = () => {const handle = virtualHandle();if (!handle) {@@ -223,8 +343,7 @@ export function ThreadList(props: ThreadListProps) {}const distanceFromTop = handle.scrollOffset;- const distanceFromBottom =- handle.scrollSize - handle.viewportSize - handle.scrollOffset;+ const distanceFromBottom = getDistanceFromBottom(handle);const nearTop = distanceFromTop <= NEAR_TOP_THRESHOLD;const nearBottom = distanceFromBottom <= NEAR_BOTTOM_THRESHOLD;@@ -296,6 +415,7 @@ export function ThreadList(props: ThreadListProps) {if (props.onNavigationReady) {props.onNavigationReady(createNavigation(ref));}+ resetInitialScroll();scrollOnMount(ref);}}scrollRef={scrollRef}@@ -303,6 +423,7 @@ export function ThreadList(props: ThreadListProps) {bufferSize={BASE_BUFFER_SIZE}data={props.keys()}onScroll={handleScroll}+ onScrollEnd={handleScrollEnd}shift={props.shift?.() ?? false}>{(key) => props.children({ id: key })}diff --git a/js/app/packages/channel/Channel/create-target-message-controller.ts b/js/app/packages/channel/Channel/create-target-message-controller.tsindex 5b4ba658e5..4f93eba73c 100644--- a/js/app/packages/channel/Channel/create-target-message-controller.ts+++ b/js/app/packages/channel/Channel/create-target-message-controller.ts@@ -129,5 +129,28 @@ export function restoreDefaultChannelPaginationAfterTargetLoad(if (!aroundData) return false;queryClient.setQueryData(defaultKey, aroundData);+ // Remove the around-query variant so it doesn't linger in cache across+ // component mounts.+ queryClient.removeQueries({ queryKey: aroundKey });return true;}++/**+ * When opening a channel without a target, the default query may still hold+ * stale data that was restored from a previous load-around session. A normal+ * latest-messages load never has `previous_cursor` on its first page (there+ * are no newer messages). If we detect that cursor, the data is stale and+ * centered on an old target — remove it so the query fetches from the bottom.+ */+export function clearStaleRestoredChannelData(channelId: string) {+ const defaultKey = getChannelMessagesQueryKey(channelId, null);+ const cached = queryClient.getQueryData<ChannelMessagesData>(defaultKey);+ if (!cached?.pages.length) return;++ // First page (index 0) is the newest page in the infinite query.+ // A genuine latest-messages fetch never has previous_cursor on its+ // first page because there are no newer messages.+ if (cached.pages[0].previous_cursor) {+ queryClient.removeQueries({ queryKey: defaultKey });+ }+}diff --git a/js/app/packages/notifications/notification-navigation.ts b/js/app/packages/notifications/notification-navigation.tsindex 1dca4d9c78..877ac632fa 100644--- a/js/app/packages/notifications/notification-navigation.ts+++ b/js/app/packages/notifications/notification-navigation.ts@@ -22,7 +22,7 @@ function openSplitIfNotOpen(layoutManager: SplitManager,type: BlockName | BlockAlias | 'component',id: string,- newSplit: boolean = false+ options: { newSplit?: boolean; params?: Record<string, string> } = {}) {const existing = layoutManager.getSplitByContent(type, id);if (existing) {@@ -30,11 +30,11 @@ function openSplitIfNotOpen(return;}layoutManager.openWithSplit(- { type, id },+ { type, id, params: options.params },{activate: true,referredFrom: null,- preferNewSplit: newSplit,+ preferNewSplit: options.newSplit,});}@@ -62,10 +62,17 @@ async function openChannelNotification(threadId = notification.notification_metadata.content.threadId;}- openSplitIfNotOpen(layoutManager, 'channel', channelId, newSplit);+ const params = messageId ? getChannelParams(messageId, threadId) : undefined;++ openSplitIfNotOpen(layoutManager, 'channel', channelId, {+ newSplit,+ params,+ });if (!messageId) return;+ // Also call goToLocationFromParams for already-open channels where+ // the split existed before and params weren't applied as initial props.const orchestrator = layoutManager.getOrchestrator();const handle = await orchestrator.getBlockHandle(channelId, 'channel');@@ -104,20 +111,22 @@ function getSupportedHandler('ai_response',() =>async (lm: SplitManager, newSplit: boolean = false) =>- openSplitIfNotOpen(lm, 'chat', notification.entity_id, newSplit)+ openSplitIfNotOpen(lm, 'chat', notification.entity_id, { newSplit })).with('new_email', () => {const meta = notification.notification_metadata;if (meta.tag !== 'new_email') return null;return async (lm: SplitManager, newSplit: boolean = false) => {- openSplitIfNotOpen(lm, 'email', meta.content.threadId, newSplit);+ openSplitIfNotOpen(lm, 'email', meta.content.threadId, { newSplit });};}).with('channel_invite',() =>async (lm: SplitManager, newSplit: boolean = false) =>- openSplitIfNotOpen(lm, 'channel', notification.entity_id, newSplit)+ openSplitIfNotOpen(lm, 'channel', notification.entity_id, {+ newSplit,+ })).with('document_mention', () => {const meta = notification.notification_metadata;@@ -127,7 +136,7 @@ function getSupportedHandler(lm,safeFileTypeToBlockName(meta.content.fileType),notification.entity_id,- newSplit+ { newSplit });}).with('invite_to_team', () => null)@@ -135,7 +144,7 @@ function getSupportedHandler(const meta = notification.notification_metadata;if (meta.tag !== 'task_assigned') return null;return async (lm: SplitManager, newSplit: boolean = false) => {- openSplitIfNotOpen(lm, 'task', meta.content.taskId, newSplit);+ openSplitIfNotOpen(lm, 'task', meta.content.taskId, { newSplit });};}).with('mentioned_in_document_comment', () => {@@ -146,7 +155,7 @@ function getSupportedHandler(lm,safeFileTypeToBlockName(meta.content.fileType),notification.entity_id,- newSplit+ { newSplit });}).with('replied_to_document_comment_thread', () => {@@ -157,7 +166,7 @@ function getSupportedHandler(lm,safeFileTypeToBlockName(meta.content.fileType),notification.entity_id,- newSplit+ { newSplit });}).with('commented_on_document', () => {@@ -168,7 +177,7 @@ function getSupportedHandler(lm,safeFileTypeToBlockName(meta.content.fileType),notification.entity_id,- newSplit+ { newSplit });}).exhaustive();diff --git a/js/app/packages/queries/channel/thread-replies.ts b/js/app/packages/queries/channel/thread-replies.tsindex 80174681f1..94b252dfe9 100644--- a/js/app/packages/queries/channel/thread-replies.ts+++ b/js/app/packages/queries/channel/thread-replies.ts@@ -32,6 +32,7 @@ export function threadRepliesQueryOptions();},staleTime: Infinity,+ placeholderData: (prev: ApiThreadReply[]) => prev,};}