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
perf(channels): stop forcing a layout per row when a channel opens (#8816)
teofdce62f178ed
diff --git a/apps/web/patches/@tanstack%[email protected] b/apps/web/patches/@tanstack%[email protected]index 36c0bf1054..4455897c05 100644--- a/apps/web/patches/@tanstack%[email protected]+++ b/apps/web/patches/@tanstack%[email protected]@@ -1,53 +1,8 @@-diff --git a/src/index.ts b/src/index.ts---- a/src/index.ts-+++ b/src/index.ts-@@ -367,6 +367,8 @@- followOnAppend?: FollowOnAppend- scrollEndThreshold?: number- isScrollingResetDelay?: number-+ /** Disable only when scrollToFn provides its own touch-safe compensation. */-+ useIOSScrollDeferral?: boolean- useScrollendEvent?: boolean- enabled?: boolean- isRtl?: boolean-@@ -553,6 +555,7 @@- isScrollingResetDelay: 150,- enabled: true,- isRtl: false,-+ useIOSScrollDeferral: true,- useScrollendEvent: false,- useAnimationFrameWithResizeObserver: false,- laneAssignmentMode: 'estimate',-@@ -617,7 +620,8 @@-- if (- behavior &&-- nextCount > prevCount &&-+ // Server acknowledgements can replace the last key without adding a row.-+ nextCount >= prevCount &&- this.isAtEnd(prevOptions.scrollEndThreshold) &&- (prevCount === 0 || merged.getItemKey(nextCount - 1) !== prevLastKey)- ) {-@@ -700,6 +704,7 @@- }-- if (-+ this.options.useIOSScrollDeferral &&- isIOSWebKit() &&- (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)- ) {-@@ -962,6 +967,7 @@- // applyScrollAdjustment does — accumulate the delta and let- // _flushIosDeferredIfReady handle it once the scroll settles.- if (-+ this.options.useIOSScrollDeferral &&- isIOSWebKit() &&- (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)- ) {-diff --git a/dist/esm/index.js b/dist/esm/index.js---- a/dist/esm/index.js-+++ b/dist/esm/index.js-@@ -274,6 +274,7 @@+diff --git a/dist/cjs/index.cjs b/dist/cjs/index.cjs+index e470032a9572b3ced764ca02238a8c6be435a9d4..29006e6bf44bdfa02fb32de5f789ad16d7b63260 100644+--- a/dist/cjs/index.cjs++++ b/dist/cjs/index.cjs+@@ -276,6 +276,7 @@ class Virtualizer {isScrollingResetDelay: 150,enabled: true,isRtl: false,@@ -55,7 +10,7 @@ diff --git a/dist/esm/index.js b/dist/esm/index.jsuseScrollendEvent: false,useAnimationFrameWithResizeObserver: false,laneAssignmentMode: "estimate",-@@ -302,7 +303,7 @@+@@ -304,7 +305,7 @@ class Virtualizer {anchor = [item.key, this.getScrollOffset() - item.start];}const behavior = merged.followOnAppend === true ? "auto" : merged.followOnAppend || null;@@ -64,7 +19,7 @@ diff --git a/dist/esm/index.js b/dist/esm/index.jsfollowOnAppend = behavior;}}-@@ -487,7 +488,7 @@+@@ -489,7 +490,7 @@ class Virtualizer {if (anchor && this.scrollElement && this.options.enabled) {const [key, _offset, followOnAppend, anchorDelta] = anchor;if (key !== null && !followOnAppend) {@@ -73,7 +28,15 @@ diff --git a/dist/esm/index.js b/dist/esm/index.jsif (anchorDelta !== 0) {this._iosDeferredAdjustment += anchorDelta;}-@@ -1132,7 +1133,7 @@+@@ -938,6 +939,7 @@ class Virtualizer {+ };+ this.getMaxScrollOffset = () => {+ if (!this.scrollElement) return 0;++ if (this.options.maxScrollOffset) return this.options.maxScrollOffset(this);+ if ("scrollHeight" in this.scrollElement) {+ return this.options.horizontal ? this.scrollElement.scrollWidth - this.scrollElement.clientWidth : this.scrollElement.scrollHeight - this.scrollElement.clientHeight;+ } else {+@@ -1134,7 +1136,7 @@ class Virtualizer {if (process.env.NODE_ENV !== "production" && this.options.debug) {console.info("correction", delta);}@@ -82,10 +45,49 @@ diff --git a/dist/esm/index.js b/dist/esm/index.jsthis._iosDeferredAdjustment += delta;return false;} else {-diff --git a/dist/cjs/index.cjs b/dist/cjs/index.cjs---- a/dist/cjs/index.cjs-+++ b/dist/cjs/index.cjs-@@ -276,6 +276,7 @@+diff --git a/dist/cjs/index.d.cts b/dist/cjs/index.d.cts+index cc1001b8a14d06aa73a3a9e8f59870557ee9e7d6..7db7e6bb0ceee199af3d5b074aff5829bc527256 100644+--- a/dist/cjs/index.d.cts++++ b/dist/cjs/index.d.cts+@@ -81,6 +81,14 @@ export interface VirtualizerOptions<TScrollElement extends Element | Window, TIt+ followOnAppend?: FollowOnAppend;+ scrollEndThreshold?: number;+ isScrollingResetDelay?: number;++ /** Disable only when scrollToFn provides its own touch-safe compensation. */++ useIOSScrollDeferral?: boolean;++ /**++ * The furthest scroll offset, for scrollers whose extent the virtualizer++ * already knows. Without it the end is read from the DOM, which forces a++ * layout whenever rows just changed.++ */++ maxScrollOffset?: (instance: Virtualizer<TScrollElement, TItemElement>) => number;+ useScrollendEvent?: boolean;+ enabled?: boolean;+ isRtl?: boolean;+diff --git a/dist/esm/index.d.ts b/dist/esm/index.d.ts+index 6b43c0aea7ed9eeef75cbfb1351fcbd243913bdd..fb253293d2e62ebf1cec79e7d3b0a2606add797d 100644+--- a/dist/esm/index.d.ts++++ b/dist/esm/index.d.ts+@@ -81,6 +81,14 @@ export interface VirtualizerOptions<TScrollElement extends Element | Window, TIt+ followOnAppend?: FollowOnAppend;+ scrollEndThreshold?: number;+ isScrollingResetDelay?: number;++ /** Disable only when scrollToFn provides its own touch-safe compensation. */++ useIOSScrollDeferral?: boolean;++ /**++ * The furthest scroll offset, for scrollers whose extent the virtualizer++ * already knows. Without it the end is read from the DOM, which forces a++ * layout whenever rows just changed.++ */++ maxScrollOffset?: (instance: Virtualizer<TScrollElement, TItemElement>) => number;+ useScrollendEvent?: boolean;+ enabled?: boolean;+ isRtl?: boolean;+diff --git a/dist/esm/index.js b/dist/esm/index.js+index 2495b26cf2c3589213546b3958eaadf2eb6b751d..d4a250db1b57b7025a3e4c29ca40372b739e2cc6 100644+--- a/dist/esm/index.js++++ b/dist/esm/index.js+@@ -274,6 +274,7 @@ class Virtualizer {isScrollingResetDelay: 150,enabled: true,isRtl: false,@@ -93,7 +95,7 @@ diff --git a/dist/cjs/index.cjs b/dist/cjs/index.cjsuseScrollendEvent: false,useAnimationFrameWithResizeObserver: false,laneAssignmentMode: "estimate",-@@ -304,7 +305,7 @@+@@ -302,7 +303,7 @@ class Virtualizer {anchor = [item.key, this.getScrollOffset() - item.start];}const behavior = merged.followOnAppend === true ? "auto" : merged.followOnAppend || null;@@ -102,7 +104,7 @@ diff --git a/dist/cjs/index.cjs b/dist/cjs/index.cjsfollowOnAppend = behavior;}}-@@ -489,7 +490,7 @@+@@ -487,7 +488,7 @@ class Virtualizer {if (anchor && this.scrollElement && this.options.enabled) {const [key, _offset, followOnAppend, anchorDelta] = anchor;if (key !== null && !followOnAppend) {@@ -111,7 +113,15 @@ diff --git a/dist/cjs/index.cjs b/dist/cjs/index.cjsif (anchorDelta !== 0) {this._iosDeferredAdjustment += anchorDelta;}-@@ -1134,7 +1135,7 @@+@@ -936,6 +937,7 @@ class Virtualizer {+ };+ this.getMaxScrollOffset = () => {+ if (!this.scrollElement) return 0;++ if (this.options.maxScrollOffset) return this.options.maxScrollOffset(this);+ if ("scrollHeight" in this.scrollElement) {+ return this.options.horizontal ? this.scrollElement.scrollWidth - this.scrollElement.clientWidth : this.scrollElement.scrollHeight - this.scrollElement.clientHeight;+ } else {+@@ -1132,7 +1134,7 @@ class Virtualizer {if (process.env.NODE_ENV !== "production" && this.options.debug) {console.info("correction", delta);}@@ -120,27 +130,64 @@ diff --git a/dist/cjs/index.cjs b/dist/cjs/index.cjsthis._iosDeferredAdjustment += delta;return false;} else {-diff --git a/dist/esm/index.d.ts b/dist/esm/index.d.ts---- a/dist/esm/index.d.ts-+++ b/dist/esm/index.d.ts-@@ -81,6 +81,8 @@- followOnAppend?: FollowOnAppend;- scrollEndThreshold?: number;- isScrollingResetDelay?: number;-+ /** Disable only when scrollToFn provides its own touch-safe compensation. */-+ useIOSScrollDeferral?: boolean;- useScrollendEvent?: boolean;- enabled?: boolean;- isRtl?: boolean;-diff --git a/dist/cjs/index.d.cts b/dist/cjs/index.d.cts---- a/dist/cjs/index.d.cts-+++ b/dist/cjs/index.d.cts-@@ -81,6 +81,8 @@- followOnAppend?: FollowOnAppend;- scrollEndThreshold?: number;- isScrollingResetDelay?: number;-+ /** Disable only when scrollToFn provides its own touch-safe compensation. */-+ useIOSScrollDeferral?: boolean;- useScrollendEvent?: boolean;- enabled?: boolean;- isRtl?: boolean;+diff --git a/src/index.ts b/src/index.ts+index dc6f1010c4d4758de9c46fb8d69209e582e47171..4fd68cc54f16ba0a715a12f5d745236e45a103a6 100644+--- a/src/index.ts++++ b/src/index.ts+@@ -367,6 +367,14 @@ export interface VirtualizerOptions<+ followOnAppend?: FollowOnAppend+ scrollEndThreshold?: number+ isScrollingResetDelay?: number++ /** Disable only when scrollToFn provides its own touch-safe compensation. */++ useIOSScrollDeferral?: boolean++ /**++ * The furthest scroll offset, for scrollers whose extent the virtualizer++ * already knows. Without it the end is read from the DOM, which forces a++ * layout whenever rows just changed.++ */++ maxScrollOffset?: (instance: Virtualizer<TScrollElement, TItemElement>) => number+ useScrollendEvent?: boolean+ enabled?: boolean+ isRtl?: boolean+@@ -553,6 +561,7 @@ export class Virtualizer<+ isScrollingResetDelay: 150,+ enabled: true,+ isRtl: false,++ useIOSScrollDeferral: true,+ useScrollendEvent: false,+ useAnimationFrameWithResizeObserver: false,+ laneAssignmentMode: 'estimate',+@@ -617,7 +626,8 @@ export class Virtualizer<++ if (+ behavior &&+- nextCount > prevCount &&++ // Server acknowledgements can replace the last key without adding a row.++ nextCount >= prevCount &&+ this.isAtEnd(prevOptions.scrollEndThreshold) &&+ (prevCount === 0 || merged.getItemKey(nextCount - 1) !== prevLastKey)+ ) {+@@ -700,6 +710,7 @@ export class Virtualizer<+ }++ if (++ this.options.useIOSScrollDeferral &&+ isIOSWebKit() &&+ (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)+ ) {+@@ -962,6 +973,7 @@ export class Virtualizer<+ // applyScrollAdjustment does — accumulate the delta and let+ // _flushIosDeferredIfReady handle it once the scroll settles.+ if (++ this.options.useIOSScrollDeferral &&+ isIOSWebKit() &&+ (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)+ ) {+@@ -1692,6 +1704,7 @@ export class Virtualizer<++ private getMaxScrollOffset = () => {+ if (!this.scrollElement) return 0++ if (this.options.maxScrollOffset) return this.options.maxScrollOffset(this)++ if ('scrollHeight' in this.scrollElement) {+ // Elementdiff --git a/apps/web/src/features/channel/Channel/Channel.tsx b/apps/web/src/features/channel/Channel/Channel.tsxindex e3820ce370..375b66f47c 100644--- a/apps/web/src/features/channel/Channel/Channel.tsx+++ b/apps/web/src/features/channel/Channel/Channel.tsx@@ -58,10 +58,7 @@ import {} from '@macro-inc/lexical-core';import { Telemetry } from '@macro-inc/observability';import { MessageNotificationIndexContext } from '@notifications/components/MarkMessageNotifications';-import {- invalidateChannelsActivity,- useUpdateChannelsActivityMutation,-} from '@queries/channel/activity';+import { recordChannelViewWhenIdle } from '@queries/channel/activity';import { queryClient } from '@queries/client';import { queryReadyGate } from '@queries/gate';import {@@ -85,7 +82,6 @@ import {import { timelineEntryKey } from '@queries/messages/timeline-entries';import { usePostTypingUpdateMutation } from '@queries/messages/typing';import { ChannelTypeEnum } from '@service-storage/client';-import { useBeforeLeave } from '@solidjs/router';import { tourTarget } from '@ui/components/Tour';import {createEffect,@@ -293,30 +289,21 @@ export function Channel(props: ChannelProps) {const activity = useChannelActivity(props.channelId);- const updateActivityMutation = useUpdateChannelsActivityMutation({- onSuccess: () => {- invalidateChannelsActivity();- },- });-- const markAsViewed = () => {- updateActivityMutation.mutate({- channelId: props.channelId,- activityType: 'view',- });- };-- onMount(() => {- markAsViewed();- });-- onCleanup(() => {- markAsViewed();- });-- useBeforeLeave(() => {- markAsViewed();- });+ // One view on entry, after the first page and away from the open's own+ // requests, and one on leaving. The channel remounts per id, so cleanup+ // covers every way out of it.+ let entryViewRecorded = false;+ createEffect(+ on(+ () => queryReadyGate(messagesQuery),+ (loaded) => {+ if (!loaded || entryViewRecorded) return;+ entryViewRecorded = true;+ recordChannelViewWhenIdle(props.channelId);+ }+ )+ );+ onCleanup(() => recordChannelViewWhenIdle(props.channelId));const unifiedInput = createUnifiedInputManager({initialReplyTarget: props.initialMessagesStateSnapshot?.replyTarget,diff --git a/apps/web/src/features/channel/Channel/ThreadList.tsx b/apps/web/src/features/channel/Channel/ThreadList.tsxindex 69c948f826..3a9b610b95 100644--- a/apps/web/src/features/channel/Channel/ThreadList.tsx+++ b/apps/web/src/features/channel/Channel/ThreadList.tsx@@ -15,6 +15,7 @@ import {type Range,type ScrollToOptions,type VirtualItem,+ type VirtualizerOptions,} from '@tanstack/solid-virtual';import {type Accessor,@@ -31,6 +32,9 @@ import { createScrollCompensation } from './create-scroll-compensation';import { createScrollLifecycle } from './create-scroll-lifecycle';type ScrollAlignment = NonNullable<ScrollToOptions['align']>;+type ScrollToFn = NonNullable<+ VirtualizerOptions<HTMLDivElement, HTMLDivElement>['scrollToFn']+>;const BASE_ITEM_SIZE = 96;const OVERSCAN = 6;@@ -147,6 +151,12 @@ export function ThreadList(props: ThreadListProps) {let previousScrollOffset = snapshot?.scrollOffset ?? 0;let explicitScrollDownDistance = 0;let releaseNavigation: void | (() => void);+ // Rows that mounted or moved in the current tick, measured together.+ const pendingRows = new Set<HTMLDivElement>();+ // Heights read for the batch being applied; see flushRowMeasurements.+ const batchHeights = new Map<Element, number>();+ let applyingBatch = false;+ let deferredScroll: Parameters<ScrollToFn> | undefined;const scrollCompensation =isSafari || isIOS? createScrollCompensation({@@ -229,7 +239,9 @@ export function ThreadList(props: ThreadListProps) {// height. The default sync path returns cached sizes, exposing the old// layout until ResizeObserver fires. Read mounted rows before first paint.measureElement: (element, entry, instance) =>- entry ? measureElement(element, entry, instance) : element.offsetHeight,+ entry+ ? measureElement(element, entry, instance)+ : (batchHeights.get(element) ?? element.offsetHeight),// Apply row and composer measurements before paint. Deferring them to the// next frame exposes stale geometry and can lose the end anchor on send.useAnimationFrameWithResizeObserver: false,@@ -243,6 +255,13 @@ export function ThreadList(props: ThreadListProps) {// Use the same end tolerance for append, resize, navigation, and snapshots.// A loose tolerance also mistakes optimistic row estimates for a pin.scrollEndThreshold: NEAR_BOTTOM_THRESHOLD,+ // The core reads scrollHeight for the end offset, forcing a layout whenever+ // rows just mounted (the initial scroll to latest, each reconcile frame,+ // every end check). The scroller holds only the sizer, max(viewport,+ // total), and writeScroll commits that before scrolling, so the+ // virtualizer's own sizes give the same extent without a layout.+ maxScrollOffset: (instance) =>+ Math.max(0, instance.getTotalSize() - (instance.scrollRect?.height ?? 0)),get paddingStart() {return insets().start;},@@ -281,26 +300,13 @@ export function ThreadList(props: ThreadListProps) {};},scrollToFn: (offset, options, instance) => {- // Size corrections happen before the Solid adapter publishes its new- // total. Commit the sizer first so the browser cannot clamp the requested- // scroll to the old range (especially with padding below a growing row).- if (contentRef) {- contentRef.style.height = `${Math.max(viewportSize(), instance.getTotalSize())}px`;- }- // WebKit ends native momentum on scrollTo writes. Keep TanStack's logical- // offset, but counter-shift the rows until wheel/touch scrolling settles.- // Explicit navigation finishes compensation before calculating its target.- if (- lifecycle.isReady() &&- scrollCompensation?.defer(offset + (options.adjustments ?? 0))- ) {+ // Each correction carries the absolute target, so a batch only needs its+ // last one. Writing every row's correction forces a layout per row.+ if (applyingBatch) {+ deferredScroll = [offset, options, instance];return;}- elementScroll(offset, options, instance);- programmaticOffset =- options.behavior === 'smooth'- ? undefined- : instance.scrollElement?.scrollTop;+ writeScroll(offset, options, instance);},observeElementOffset: (instance, callback) => {const element = instance.scrollElement;@@ -364,6 +370,56 @@ export function ThreadList(props: ThreadListProps) {onChange: scheduleScrollState,});+ function writeScroll(...[offset, options, instance]: Parameters<ScrollToFn>) {+ // Size corrections happen before the Solid adapter publishes its new+ // total. Commit the sizer first so the browser cannot clamp the requested+ // scroll to the old range (especially with padding below a growing row).+ if (contentRef) {+ contentRef.style.height = `${Math.max(viewportSize(), instance.getTotalSize())}px`;+ }+ // WebKit ends native momentum on scrollTo writes. Keep TanStack's logical+ // offset, but counter-shift the rows until wheel/touch scrolling settles.+ // Explicit navigation finishes compensation before calculating its target.+ if (+ lifecycle.isReady() &&+ scrollCompensation?.defer(offset + (options.adjustments ?? 0))+ ) {+ return;+ }+ elementScroll(offset, options, instance);+ programmaticOffset =+ options.behavior === 'smooth'+ ? undefined+ : instance.scrollElement?.scrollTop;+ }++ // Rows mount together, so measure them together: read every height from+ // one layout, then apply the resizes and write the scroll once. Measuring+ // row by row interleaves reads with sizer and scroll writes, which forces a+ // full layout of the list per row.+ function flushRowMeasurements() {+ const rows = [...pendingRows].filter((row) => row.isConnected);+ pendingRows.clear();+ for (const row of rows) batchHeights.set(row, row.offsetHeight);+ applyingBatch = true;+ try {+ for (const row of rows) virtualizer.measureElement(row);+ } finally {+ applyingBatch = false;+ batchHeights.clear();+ }+ const scroll = deferredScroll;+ deferredScroll = undefined;+ if (scroll) writeScroll(...scroll);+ }++ // Markdown fills a row in child effects. Measuring the empty shell can+ // shrink the sizer and clamp scrollTop before paint, so wait a microtask.+ const queueRowMeasurement = (row: HTMLDivElement) => {+ pendingRows.add(row);+ if (pendingRows.size === 1) queueMicrotask(flushRowMeasurements);+ };+if (scrollCompensation) {virtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item,@@ -593,11 +649,7 @@ export function ThreadList(props: ThreadListProps) {on(() => item().index,() => {- // Markdown fills the row in child effects. Measuring the empty- // shell can shrink the sizer and clamp scrollTop before paint.- queueMicrotask(() => {- if (row?.isConnected) virtualizer.measureElement(row);- });+ if (row) queueRowMeasurement(row);}));diff --git a/apps/web/src/features/channel/activity-tracker.ts b/apps/web/src/features/channel/activity-tracker.tsindex 869e3cef77..8e76f859ed 100644--- a/apps/web/src/features/channel/activity-tracker.ts+++ b/apps/web/src/features/channel/activity-tracker.ts@@ -26,8 +26,8 @@ export function createActivityTracker(const openedChannelAt = createMemo<Date>((prev) => prev ?? new Date());// Freeze lastViewedAt at the value present when the channel was first opened.- // This prevents a query refetch (triggered by the activity mutation on mount)- // from resetting viewed_at to "now" and hiding all the new-message indicators.+ // This prevents the entry view write, which updates the activity cache, from+ // resetting viewed_at to "now" and hiding all the new-message indicators.const frozenLastViewedAt = createMemo<DateValue | undefined | null>((prev) =>prev !== undefined ? prev : props.lastViewedAt());diff --git a/apps/web/src/features/channel/docs/sticky-scrolling.md b/apps/web/src/features/channel/docs/sticky-scrolling.mdindex 5e8feb28ed..9d3013d618 100644--- a/apps/web/src/features/channel/docs/sticky-scrolling.md+++ b/apps/web/src/features/channel/docs/sticky-scrolling.md@@ -52,8 +52,8 @@ uses `initialOffset`; replaying the saved offset after measuring would discard tanchor corrections for changed rows.Rows are positioned inside one sizer that includes the floating header/composer-insets. Short conversations are bottom aligned. Before TanStack writes a scroll-correction, `scrollToFn` synchronously commits the current total to the sizer;+insets. Short conversations are bottom aligned. Before a scroll correction is+written, `writeScroll` synchronously commits the current total to the sizer;otherwise a growing last row can clamp the scroll against the old DOM extent.Viewport and inset changes explicitly scroll to the end only if previously pinned.The offset observer distinguishes instant programmatic scrolls from user scrolling,@@ -88,7 +88,15 @@ map lookup can disappear while a queued measurement effect is still running.Measurement effects track index changes and register rows in a microtask after childeffects fill their Markdown, still before paint. Measuring the empty shell cantemporarily shrink the sizer and clamp the browser scroll position, especially-with floating mobile insets. Later size changes belong to ResizeObserver.+with floating mobile insets. Rows registered in the same tick are measured+together: every height is read from one layout, then the resizes are applied and+only the last scroll correction is written. Measuring row by row interleaves+reads with sizer and scroll writes and forces a full list layout per row, which+cost a channel open over 100ms. Later size changes belong to ResizeObserver.+The end offset comes from the virtualizer's own sizes, `max(0, total - viewport)`,+not `scrollHeight`: the scroller holds only the sizer, and reading the DOM there+forced a layout of just-mounted rows on every scroll to latest, reconcile frame,+and end check.`targetId` keeps the pending thread mounted for precise navigation to nested replies;only the list translates that ID into a virtual index. Snapshotrestoration pairs the offset with `takeSnapshot()`.diff --git a/apps/web/src/features/channel/queries/prefetch-channel-target.ts b/apps/web/src/features/channel/queries/prefetch-channel-target.tsindex ff5699b714..462a59ac86 100644--- a/apps/web/src/features/channel/queries/prefetch-channel-target.ts+++ b/apps/web/src/features/channel/queries/prefetch-channel-target.ts@@ -1,3 +1,4 @@+import { fireAndForget } from '@core/util/fireAndForget';import { Telemetry } from '@macro-inc/observability';import { notificationTargetSpan } from '@notifications/notification-open-trace';import { queryClient } from '@queries/client';@@ -36,3 +37,21 @@ export async function prefetchChannelTarget(span.setAttr('channel.target.outcome', 'prefetch_settled');});}++/**+ * Starts a channel's latest page on the press that will open it. The click+ * that follows commits the pane before any request it starts can leave, so a+ * page requested here arrives one press and one commit sooner. A cached page+ * is reused as is.+ */+export function prefetchLatestChannelMessages(channelId: string): void {+ fireAndForget(+ Telemetry.span('channel.timeline.prefetch', async (span) => {+ span.setAttr('channel.id', channelId);+ await queryClient.prefetchInfiniteQuery(+ messageTimelineQueryOptions({ type: 'channel', id: channelId }, null)+ );+ }),+ 'channel-timeline-prefetch'+ );+}diff --git a/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.test.tsx b/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.test.tsxindex 936b1fffda..7bc66a5bc3 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.test.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.test.tsx@@ -15,6 +15,7 @@ import { ChannelFavoriteRow } from './ChannelFavoriteRows';const rail = vi.hoisted(() => ({channelById: (_channelId: string): ChannelEntity | undefined => undefined,activateRow: vi.fn(),+ prefetchRow: vi.fn(),list: { focus: { set: vi.fn() } },}));diff --git a/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.tsx b/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.tsxindex 21c831a8c9..bd3bc8a175 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.tsx@@ -56,6 +56,9 @@ export function ChannelFavoriteRow(props: { favorite: Favorite }) {)}active={item().selected && !isTouchDevice()}aria-current={item().selected ? 'page' : undefined}+ onPointerDown={(event) =>+ rail.prefetchRow(rowKeyForFavorite(props.favorite), event)+ }onClick={(event) => {if (!isPrimaryMouseDown(event)) return;rail.activateRow(rowKeyForFavorite(props.favorite), event);diff --git a/apps/web/src/features/channels-view/components/rail/ChannelRailItems.tsx b/apps/web/src/features/channels-view/components/rail/ChannelRailItems.tsxindex a605f597f6..2e793e7aae 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelRailItems.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelRailItems.tsx@@ -41,6 +41,8 @@ export type ChannelRailItemProps = {selected: boolean;focused: boolean;onActivate: (event: MouseEvent) => void;+ /** The press before activation, for warming what the row opens. */+ onPress?: (event: PointerEvent) => void;};/**@@ -286,6 +288,7 @@ export function ConversationCard(props: ConversationCardProps) {props.class)}aria-current={props.selected ? 'page' : undefined}+ onPointerDown={(event) => props.onPress?.(event)}onMouseDown={(event) => {if (isPrimaryMouseDown(event)) props.onActivate(event);}}diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRail.test.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRail.test.tsxindex 17f3faa210..5eb8fc3296 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelsRail.test.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRail.test.tsx@@ -32,6 +32,8 @@ const mocks = vi.hoisted(() => ({activate: (_event: MouseEvent) => {},row: undefined as ChannelEntity | undefined,failure: vi.fn(),+ prefetch: vi.fn(),+ tab: 'browse' as 'browse' | 'threads',}));vi.mock('@app/components/list', () => ({createListController: (options: {@@ -117,6 +119,9 @@ vi.mock('@core/component/Toast/Toast', () => ({toast: { failure: mocks.failure },}));vi.mock('@core/constant/featureFlags', () => ({ enableChannelTags: {} }));+vi.mock('@channel/queries/prefetch-channel-target', () => ({+ prefetchLatestChannelMessages: mocks.prefetch,+}));vi.mock('@core/hotkey/hotkeys', () => ({createHotkeyGroup: () => ({ dispose: vi.fn() }),registerHotkey: () => ({ withGroup: vi.fn() }),@@ -161,7 +166,7 @@ vi.mock('../../channels-view-context', () => ({expandedGroups: { channels: true, direct_messages: true },collapsedLabels: [],},- tab: () => 'browse',+ tab: () => mocks.tab,threadsEnabled: () => false,selectedChannel: () => mocks.selected,setSelectedChannel: mocks.select,@@ -183,13 +188,22 @@ vi.mock('./hooks/useChannelCalls', () => ({ useChannelCalls: () => ({}) }));vi.mock('./hooks/useChannelRailActivity', () => ({useChannelRailActivity: () => ({}),}));-vi.mock('./ExpandedChannelsRail', () => ({- ExpandedChannelsRail: () => (- <button onClick={(event) => mocks.activate(event)}>- Open conversation- </button>- ),-}));+vi.mock('./ExpandedChannelsRail', async () => {+ const { useChannelsRail } = await import('./ChannelsRailContext');+ return {+ ExpandedChannelsRail: () => {+ const rail = useChannelsRail();+ return (+ <button+ onPointerDown={(event) => rail.prefetchRow('channel:one', event)}+ onClick={(event) => mocks.activate(event)}+ >+ Open conversation+ </button>+ );+ },+ };+});import { ChannelsRail } from './ChannelsRail';@@ -210,7 +224,7 @@ const hydrated: WithNotification<ChannelEntity> = {notifications: () => [],};const source = {- items: () => [channel],+ items: () => [mocks.row ?? channel],isLoading: () => false,isFetching: () => false,error: () => undefined,@@ -241,6 +255,7 @@ beforeEach(() => {vi.clearAllMocks();mocks.row = channel;mocks.favoriteId = undefined;+ mocks.tab = 'browse';mocks.selected = { type: 'channel', id: channel.id };mocks.select.mockReturnValue(true);mocks.hydrate.mockReturnValue(hydrated);@@ -503,3 +518,39 @@ describe('explicit channel activation read marking', () => {});});++describe('channel row presses', () => {+ // jsdom has no PointerEvent, so a press is a MouseEvent tagged as one.+ const press = (init: { pointerType: string; button: number }) => {+ const event = new MouseEvent('pointerdown', {+ bubbles: true,+ button: init.button,+ });+ Object.defineProperty(event, 'pointerType', { value: init.pointerType });+ screen.getByRole('button').dispatchEvent(event);+ };++ it('starts the latest messages on a primary mouse press', () => {+ mount();+ press({ pointerType: 'mouse', button: 0 });+ expect(mocks.prefetch).toHaveBeenCalledExactlyOnceWith('one');+ });++ it('leaves touch presses, other buttons, and the Threads tab alone', () => {+ mount();+ press({ pointerType: 'touch', button: 0 });+ press({ pointerType: 'mouse', button: 2 });+ cleanup();+ mocks.tab = 'threads';+ mount();+ press({ pointerType: 'mouse', button: 0 });+ expect(mocks.prefetch).not.toHaveBeenCalled();+ });++ it('leaves a row that opens at a message to the target prefetch', () => {+ mocks.row = { ...channel, target: { messageId: 'message' } };+ mount();+ press({ pointerType: 'mouse', button: 0 });+ expect(mocks.prefetch).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsxindex 21114880ea..b7dc2d4b50 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx@@ -19,6 +19,7 @@ import {import { withEntityNotifications } from '@app/features/soup/entity-notifications';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { favoriteSplitContent } from '@app/util/favorites';+import { prefetchLatestChannelMessages } from '@channel/queries/prefetch-channel-target';import {useGlobalBlockOrchestrator,useGlobalNotificationSource,@@ -861,6 +862,24 @@ export function ChannelsRail(props: ChannelsRailProps) {});};+ // A mouse press reaches the server before the click that opens its channel.+ // Touch presses also start scrolls, which would fetch every row they cross.+ const prefetchRow = (rowId: ChannelRailRow['id'], event: PointerEvent) => {+ if (event.pointerType !== 'mouse' || event.button !== 0) return;+ // Threads-tab rows filter the thread list in place.+ if (tab() === 'threads') return;+ const row = visibleRows().find((row) => row.id === rowId);+ if (row?.kind === 'conversation') {+ // A message target loads around that message instead.+ if (!row.channel.target) prefetchLatestChannelMessages(row.channel.id);+ } else if (+ row?.kind === 'favorite' &&+ row.favorite.entityType === 'channel'+ ) {+ prefetchLatestChannelMessages(row.favorite.entityId);+ }+ };+// Explain shared versus private scope before creating or changing labels.const createLabelMutation = useCreateChannelLabelMutation();const renameLabelMutation = useRenameChannelLabelMutation();@@ -1215,6 +1234,7 @@ export function ChannelsRail(props: ChannelsRailProps) {setSortBy,registerRootRef: setListRoot,activateRow,+ prefetchRow,registerScrollRef: (group, element) => {setSectionScrollRoots((current) => ({...current,diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts b/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.tsindex 8d78e3b9ba..40eb7d8f92 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts@@ -172,6 +172,8 @@ export type ChannelsRailContext = {setSortBy: (group: ChannelsSortGroup, sort: ChannelListSort) => void;registerRootRef: (element: HTMLDivElement) => void;activateRow: (rowId: ChannelRailRow['id'], event?: MouseEvent) => void;+ /** Warm a channel row's messages on the press that may open it. */+ prefetchRow: (rowId: ChannelRailRow['id'], event: PointerEvent) => void;registerScrollRef: (group: ChannelsRailSection | 'threads',element: HTMLDivElementdiff --git a/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsxindex 4481474976..ee3516bb28 100644--- a/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx+++ b/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx@@ -292,8 +292,9 @@ function ChannelOption(props: {dnd?.droppable.ref(element);}}{...(canLabelChannel(props.channel) ? dnd?.draggable.dragActivators : {})}- onPointerDown={() => {+ onPointerDown={(event) => {didDrag = false;+ rail.prefetchRow(rowId(), event);}}class={cn('min-w-0',@@ -927,6 +928,9 @@ function RecentConversationCard(props: { channel: ChannelEntity }) {onActivate={(event) =>rail.activateRow(rowKeyForChannel(props.channel.id), event)}+ onPress={(event) =>+ rail.prefetchRow(rowKeyForChannel(props.channel.id), event)+ }/></ChannelRailItemContextMenu>);diff --git a/apps/web/src/features/entity/owner/owner-display.test.tsx b/apps/web/src/features/entity/owner/owner-display.test.tsxindex f3430a5d66..a0080eb68a 100644--- a/apps/web/src/features/entity/owner/owner-display.test.tsx+++ b/apps/web/src/features/entity/owner/owner-display.test.tsx@@ -1,4 +1,5 @@import { cleanup, fireEvent, render } from '@solidjs/testing-library';+import { ok } from 'neverthrow';import { createSignal, type JSX } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -9,7 +10,7 @@ const mocks = vi.hoisted(() => ({botProfiles: new Map<string, QueryLike>(),requestedBotIds: [] as string[],teams: { isPending: false, isError: false, data: [] as unknown },- mutate: vi.fn(),+ openDm: vi.fn(),}));vi.mock('@core/context/user', () => ({@@ -44,7 +45,7 @@ vi.mock('@queries/team/teams', () => ({useUserTeamsQuery: () => mocks.teams,}));vi.mock('@queries/channel/get-or-create-dm', () => ({- useGetOrCreateDirectMessageMutation: () => ({ mutate: mocks.mutate }),+ getOrCreateDirectMessage: mocks.openDm,}));vi.mock('@components/app/split-layout/layout', () => ({useSplitLayout: () => ({ openWithSplit: vi.fn() }),@@ -76,7 +77,8 @@ beforeEach(() => {mocks.botProfiles = new Map();mocks.requestedBotIds = [];mocks.teams = settled([{ id: ENGINEERING, name: 'Engineering' }]);- mocks.mutate.mockReset();+ mocks.openDm.mockReset();+ mocks.openDm.mockResolvedValue(ok({ channel_id: 'dm' }));});afterEach(cleanup);@@ -207,8 +209,6 @@ describe('OwnerLabel', () => {fireEvent.mouseDown(getByText('Engineering'));expect(container.querySelectorAll('[data-slot="avatar"]').length).toBe(3);- expect(mocks.mutate.mock.calls.map(([vars]) => vars)).toEqual([- { recipient_id: PETER },- ]);+ expect(mocks.openDm.mock.calls).toEqual([[PETER]]);});});diff --git a/apps/web/src/lib/analytics/analytics.ts b/apps/web/src/lib/analytics/analytics.tsindex 6fe54878fa..10a1cf59e5 100644--- a/apps/web/src/lib/analytics/analytics.ts+++ b/apps/web/src/lib/analytics/analytics.ts@@ -136,6 +136,10 @@ const initializePosthog = (instance: PostHog) => {api_host: 'https://macro-prox.macroverse.workers.dev/i/ph',ui_host: 'https://us.posthog.com',defaults: '2026-01-30',+ // Scroll depth listens to every scroll in the app (capture phase) and+ // reads window geometry, forcing a layout per scroll. The app shell never+ // scrolls the window, so the depth it reports is always zero.+ disable_scroll_properties: true,prepare_external_dependency_script: (script) => {const url = new URL(script.src);diff --git a/apps/web/src/lib/core/component/CustomScrollbar.tsx b/apps/web/src/lib/core/component/CustomScrollbar.tsxindex 17e486f105..3ba54ac7c0 100644--- a/apps/web/src/lib/core/component/CustomScrollbar.tsx+++ b/apps/web/src/lib/core/component/CustomScrollbar.tsx@@ -82,6 +82,22 @@ function InnerCustomScrollbar(props: CustomScrollbarProps) {}};+ // Read the metrics once per frame, from its animation-frame callbacks. A+ // scroll or resize can arrive just after content changed, and reading there+ // forces a layout of everything that changed; the frame's own layout runs+ // once all of those callbacks have had their turn.+ let metricsFrame: number | undefined;+ const scheduleScrollMetrics = () => {+ if (metricsFrame !== undefined) return;+ metricsFrame = requestAnimationFrame(() => {+ metricsFrame = undefined;+ updateScrollMetrics();+ });+ };+ onCleanup(() => {+ if (metricsFrame !== undefined) cancelAnimationFrame(metricsFrame);+ });+const maxScroll = () => Math.max(0, scrollSize() - clientSize());const trackSize = () => Math.max(0, clientSize() - THUMB_INSET * 2);@@ -116,10 +132,8 @@ function InnerCustomScrollbar(props: CustomScrollbarProps) {const container = props.scrollContainer();if (!container) return;- updateScrollMetrics();-const handleScroll = () => {- if (!isDragging()) updateScrollMetrics();+ if (!isDragging()) scheduleScrollMetrics();setIsScrolling(true);debouncedHideScrollbar();if (props.labelVisibilityDebounceMs !== Infinity) {@@ -147,7 +161,10 @@ function InnerCustomScrollbar(props: CustomScrollbarProps) {});container.addEventListener('pointerleave', handleProximityLeave);- const resizeObserver = new ResizeObserver(updateScrollMetrics);+ // Observing reports every target once after the next layout. Earlier+ // observers in that delivery can still change content, so the read waits+ // for the next frame rather than forcing a layout here.+ const resizeObserver = new ResizeObserver(scheduleScrollMetrics);resizeObserver.observe(container);let mutationObserver: MutationObserver | undefined;@@ -156,11 +173,12 @@ function InnerCustomScrollbar(props: CustomScrollbarProps) {resizeObserver.disconnect();resizeObserver.observe(container);for (const child of container.children) resizeObserver.observe(child);- updateScrollMetrics();};observeContent();+ // Only direct children change the scroll extent; their own resizes are+ // observed above. Descendant mutations (every rendered message) are not.mutationObserver = new MutationObserver(observeContent);- mutationObserver.observe(container, { childList: true, subtree: true });+ mutationObserver.observe(container, { childList: true });}onCleanup(() => {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsxindex d0375ff493..7d67818caf 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx@@ -304,7 +304,9 @@ function MentionsMenuInner(props: MentionsMenuProps) {);});+ // Every composer mounts this menu closed; fetch only once it opens.const bookingLinksEnabled = () =>+ props.menu.isOpen() &&!hasCustomEntities() &&(!props.sources || props.sources.includes('bookingLinks'));const { bookingLinks } = useBookingLinkMention({diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/utils/create-composer-layout.ts b/apps/web/src/lib/core/component/LexicalMarkdown/utils/create-composer-layout.tsindex 7d14094a38..79c800f99c 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/utils/create-composer-layout.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/utils/create-composer-layout.ts@@ -1,5 +1,5 @@import { createResizeObserver } from '@solid-primitives/resize-observer';-import type { LexicalEditor } from 'lexical';+import { $getRoot, type LexicalEditor } from 'lexical';import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';import { match } from 'ts-pattern';import { createHasMultilineStructure } from './create-has-multiline-structure';@@ -39,6 +39,14 @@ export function createComposerLayout(const container = options.container();if (!element || !container?.parentElement || !container.contains(element))return;+ // An empty draft cannot wrap. The probe below clones the composer into the+ // page and forces a layout, which on mount delays the surface's first paint.+ if (+ editor.getEditorState().read(() => $getRoot().getTextContentSize() === 0)+ ) {+ setHasWrappedLines(false);+ return;+ }const containerWidth = container.getBoundingClientRect().width;if (containerWidth <= 0) return;diff --git a/apps/web/src/lib/core/component/UserIcon.tsx b/apps/web/src/lib/core/component/UserIcon.tsxindex 4bfcd9b5c7..445937d290 100644--- a/apps/web/src/lib/core/component/UserIcon.tsx+++ b/apps/web/src/lib/core/component/UserIcon.tsx@@ -13,9 +13,10 @@ import {tryMacroId,useIsConnectedSecondaryInbox,} from '@core/user';+import { fireAndForget } from '@core/util/fireAndForget';import RobotIcon from '@icon/system/regular/robot.svg';import Trash from '@icon/system/regular/trash.svg?component-solid';-import { useGetOrCreateDirectMessageMutation } from '@queries/channel/get-or-create-dm';+import { getOrCreateDirectMessage } from '@queries/channel/get-or-create-dm';import { Avatar, type AvatarSize, cn } from '@ui';import { createMemo, Match, Show, Switch } from 'solid-js';import { Dynamic } from 'solid-js/web';@@ -143,22 +144,23 @@ export function UserIcon(props: UserIconProps) {});const { openWithSplit } = useSplitLayout();- const getOrCreateDmMutation = useGetOrCreateDirectMessageMutation();const isConnectedSecondaryInbox = useIsConnectedSecondaryInbox();+ const openDm = async (recipientId: string, preferNewSplit: boolean) => {+ const result = await getOrCreateDirectMessage(recipientId);+ if (result.isErr()) {+ console.error('failed to get or create direct message', result.error);+ return;+ }+ openWithSplit(+ { type: 'channel', id: result.value.channel_id },+ { activate: true, preferNewSplit }+ );+ };+const getOrCreateDm = (event: MouseEvent) => {if (!props.id || isConnectedSecondaryInbox(props.id)) return;- getOrCreateDmMutation.mutate(- { recipient_id: props.id },- {- onSuccess: ({ channel_id }) => {- openWithSplit(- { type: 'channel', id: channel_id },- { activate: true, preferNewSplit: event.shiftKey }- );- },- }- );+ fireAndForget(openDm(props.id, event.shiftKey), 'user-icon-dm');};const showTooltip = () => props.showTooltip !== false;diff --git a/apps/web/src/lib/core/component/firstPartyBotMark.test.tsx b/apps/web/src/lib/core/component/firstPartyBotMark.test.tsxindex 525a00cfd1..a08cebf58e 100644--- a/apps/web/src/lib/core/component/firstPartyBotMark.test.tsx+++ b/apps/web/src/lib/core/component/firstPartyBotMark.test.tsx@@ -18,7 +18,7 @@ vi.mock('@components/app/split-layout/layout', () => ({useSplitLayout: () => ({ openWithSplit: vi.fn() }),}));vi.mock('@queries/channel/get-or-create-dm', () => ({- useGetOrCreateDirectMessageMutation: () => ({ mutate: vi.fn() }),+ getOrCreateDirectMessage: vi.fn(),}));vi.mock('@core/user', () => ({getDisplayName: () => undefined,diff --git a/apps/web/src/lib/queries/channel/activity.test.ts b/apps/web/src/lib/queries/channel/activity.test.tsnew file mode 100644index 0000000000..8f339ca189--- /dev/null+++ b/apps/web/src/lib/queries/channel/activity.test.ts@@ -0,0 +1,85 @@+import { queryClient } from '@queries/client';+import type { ApiActivity } from '@service-storage/generated/schemas/apiActivity';+import { recordChannelActivity } from '@service-storage/graphql-channel-activity';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { recordChannelViewWhenIdle } from './activity';+import { channelKeys } from './keys';++vi.mock('@queries/client', async () => {+ const { QueryClient } = await import('@tanstack/solid-query');+ return { queryClient: new QueryClient() };+});+vi.mock('@service-storage/client', () => ({ storageServiceClient: {} }));+vi.mock('@service-storage/graphql-channel-activity', () => ({+ recordChannelActivity: vi.fn(),+}));++const recordActivity = vi.mocked(recordChannelActivity);+// Past the idle wait, well short of the query cache's garbage collection.+const flushIdle = () => vi.advanceTimersByTimeAsync(2_000);++function activity(channelId: string, viewedAt: string): ApiActivity {+ return {+ id: `activity-${channelId}`,+ user_id: 'user',+ channel_id: channelId,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: viewedAt,+ viewed_at: viewedAt,+ };+}++beforeEach(() => {+ vi.useFakeTimers();+ recordActivity.mockImplementation(async ({ channelId }) =>+ activity(channelId, '2026-02-01T00:00:00Z')+ );+});++afterEach(() => {+ vi.useRealTimers();+ vi.clearAllMocks();+ queryClient.clear();+});++it('records a view only after the current work yields', async () => {+ recordChannelViewWhenIdle('a');+ expect(recordActivity).not.toHaveBeenCalled();++ await flushIdle();+ expect(recordActivity).toHaveBeenCalledExactlyOnceWith({+ channelId: 'a',+ activityType: 'view',+ });+});++it('sends one request for views of a channel that are still pending', async () => {+ recordChannelViewWhenIdle('a');+ recordChannelViewWhenIdle('b');+ recordChannelViewWhenIdle('a');++ await flushIdle();+ expect(recordActivity.mock.calls.map(([args]) => args.channelId)).toEqual([+ 'a',+ 'b',+ ]);+});++it('writes the recorded row into the activity list instead of refetching it', async () => {+ queryClient.setQueryData<ApiActivity[]>(channelKeys.activity.queryKey, [+ activity('a', '2026-01-01T00:00:00Z'),+ activity('c', '2026-01-01T00:00:00Z'),+ ]);++ recordChannelViewWhenIdle('a');+ recordChannelViewWhenIdle('b');+ await flushIdle();++ expect(+ queryClient.getQueryData<ApiActivity[]>(channelKeys.activity.queryKey)+ ).toEqual([+ activity('a', '2026-02-01T00:00:00Z'),+ activity('c', '2026-01-01T00:00:00Z'),+ activity('b', '2026-02-01T00:00:00Z'),+ ]);+});diff --git a/apps/web/src/lib/queries/channel/activity.ts b/apps/web/src/lib/queries/channel/activity.tsindex 738a6e2d9e..7a6cd33809 100644--- a/apps/web/src/lib/queries/channel/activity.ts+++ b/apps/web/src/lib/queries/channel/activity.ts@@ -1,11 +1,11 @@+import { fireAndForget } from '@core/util/fireAndForget';import { throwOnErr } from '@core/util/result';import { queryClient } from '@queries/client';-import { type MutationCallbacks, withCallbacks } from '@queries/utils';import { storageServiceClient } from '@service-storage/client';-import type { ActivityType } from '@service-storage/generated/schemas/activityType';import type { ApiActivity as ChannelsActivity } from '@service-storage/generated/schemas/apiActivity';import { recordChannelActivity } from '@service-storage/graphql-channel-activity';-import { useMutation, useQuery } from '@tanstack/solid-query';+import { scheduleIdle } from '@solid-primitives/scheduled';+import { useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';import { channelKeys } from './keys';@@ -23,39 +23,47 @@ export function useChannelsActivityQuery(}));}-type UpdateChannelActivityMutationVars = {- channelId: string;- activityType: ActivityType;-};--export function useUpdateChannelsActivityMutation(- callbacks?: MutationCallbacks<- ChannelsActivity,- Error,- UpdateChannelActivityMutationVars- >-) {- return useMutation(() => ({- gcTime: 0,- mutationFn: async (vars: UpdateChannelActivityMutationVars) =>- await recordChannelActivity(vars),- ...withCallbacks<- ChannelsActivity,- Error,- UpdateChannelActivityMutationVars- >(- {- onError(error) {- console.error('failed to update activity for channel', error);- },- },- callbacks- ),- }));+/** Replaces the channel's row in the activity list, or adds it. */+function upsertChannelActivity(+ list: ChannelsActivity[],+ activity: ChannelsActivity+): ChannelsActivity[] {+ const index = list.findIndex((row) => row.channel_id === activity.channel_id);+ if (index === -1) return [...list, activity];+ return list.map((row, i) => (i === index ? activity : row));}-export function invalidateChannelsActivity() {- queryClient.invalidateQueries({- queryKey: channelKeys.activity.queryKey,+async function recordChannelView(channelId: string) {+ const activity = await recordChannelActivity({+ channelId,+ activityType: 'view',});+ // The write returns the row, so the list needs no refetch.+ queryClient.setQueryData<ChannelsActivity[]>(+ channelKeys.activity.queryKey,+ (list) => list && upsertChannelActivity(list, activity)+ );+}++/** Idle callbacks wait at most this long behind a busy main thread. */+const CHANNEL_VIEW_MAX_WAIT_MS = 2_000;+const pendingChannelViews = new Set<string>();+// Module scope, so a view recorded as its channel unmounts still lands.+const flushChannelViews = scheduleIdle(() => {+ for (const channelId of pendingChannelViews) {+ fireAndForget(recordChannelView(channelId), 'channel-view-activity');+ }+ pendingChannelViews.clear();+}, CHANNEL_VIEW_MAX_WAIT_MS);++/**+ * Records that the user viewed a channel, in idle time. An acknowledged write+ * makes the normalized cache refetch every GraphQL read still in flight, and a+ * channel switch starts the next channel's detail read, so a write sent with+ * the open costs that read twice. Views of one channel that are still pending+ * share a request.+ */+export function recordChannelViewWhenIdle(channelId: string) {+ pendingChannelViews.add(channelId);+ flushChannelViews();}diff --git a/apps/web/src/lib/queries/channel/get-or-create-dm.ts b/apps/web/src/lib/queries/channel/get-or-create-dm.tsindex 6fc90db67a..59be37696d 100644--- a/apps/web/src/lib/queries/channel/get-or-create-dm.ts+++ b/apps/web/src/lib/queries/channel/get-or-create-dm.ts@@ -52,6 +52,19 @@ export function useGetOrCreateDirectMessageMutation(}));}+/**+ * Resolves the 1:1 DM with a recipient when a control is pressed. Avatars in+ * a message list render by the dozen, and a mutation observer per avatar+ * costs setup for a press that rarely comes.+ */+export async function getOrCreateDirectMessage(recipientId: string) {+ const result = await storageServiceClient.getOrCreateDirectMessage({+ recipient_id: recipientId,+ });+ fireAndForget(invalidateListChannels(), 'channel-list');+ return result;+}+type GetOrCreatePrivateChannelParams = {recipients: string[];};diff --git a/apps/web/src/lib/queries/preview/preview.ts b/apps/web/src/lib/queries/preview/preview.tsindex 6e40f8ac02..b4a8adb325 100644--- a/apps/web/src/lib/queries/preview/preview.ts+++ b/apps/web/src/lib/queries/preview/preview.ts@@ -125,30 +125,39 @@ function useItemPreviewQuery(graphqlRequested,includeProperties);- const usesGraphql = () =>- graphqlRequested() &&- isGraphqlPreviewItem(item()) &&- !graphqlQuery.shouldFallback();+ const usesGraphql = createMemo(+ () =>+ graphqlRequested() &&+ isGraphqlPreviewItem(item()) &&+ !graphqlQuery.shouldFallback()+ );- const restQuery = useQuery(() =>- itemPreviewQueryOptions(item(), !usesGraphql(), restStaleTime)+ // Previews render in every message row and building an observer costs more+ // than the GraphQL read itself, so the REST one exists only while it serves.+ const restQuery = createMemo(() =>+ usesGraphql()+ ? undefined+ : useQuery(() => itemPreviewQueryOptions(item(), true, restStaleTime)));return {- data: () =>- usesGraphql()- ? graphqlQuery.data()- : queryReadyGate(restQuery)- ? restQuery.data- : undefined,+ data: () => {+ if (usesGraphql()) return graphqlQuery.data();+ const rest = restQuery();+ return rest && queryReadyGate(rest) ? rest.data : undefined;+ },isLoading: () =>- usesGraphql() ? graphqlQuery.isLoading() : restQuery.isPending,+ usesGraphql()+ ? graphqlQuery.isLoading()+ : (restQuery()?.isPending ?? true),isSuccess: () =>- usesGraphql() ? graphqlQuery.data() !== undefined : restQuery.isSuccess,+ usesGraphql()+ ? graphqlQuery.data() !== undefined+ : (restQuery()?.isSuccess ?? false),usesGraphql,refetch: async () => {if (usesGraphql()) await graphqlQuery.refetch();- else await restQuery.refetch();+ else await restQuery()?.refetch();},};}@@ -172,28 +181,40 @@ function channelMessagePreviewQueryOptions(export function useItemPreview(item: Accessor<ItemEntity>) {const previewQuery = useItemPreviewQuery(item);- const maybeMessageQuery = useQuery(() => {+ // Only a REST preview of a message link loads its message separately.+ const loadsMessageContext = createMemo(() => {const item_ = item();- const channelId = item_.type === 'channel' ? item_.id : '';- const messageId = item_.type === 'channel' ? (item_.messageId ?? '') : '';- return channelMessagePreviewQueryOptions(- item_.id,- channelId,- messageId,- !previewQuery.usesGraphql() &&- !!channelId &&- !!messageId &&- previewQuery.isSuccess()+ return (+ item_.type === 'channel' &&+ !!item_.messageId &&+ !previewQuery.usesGraphql());});+ const maybeMessageQuery = createMemo(() =>+ loadsMessageContext()+ ? useQuery(() => {+ const item_ = item();+ const channelId = item_.type === 'channel' ? item_.id : '';+ const messageId =+ item_.type === 'channel' ? (item_.messageId ?? '') : '';+ return channelMessagePreviewQueryOptions(+ item_.id,+ channelId,+ messageId,+ !!channelId && !!messageId && previewQuery.isSuccess()+ );+ })+ : undefined+ );const preview = createMemo(() => {const data = previewQuery.data();// Disabled message queries are pending but not loading. Reading their// data still suspends briefly whenever a preview row mounts.+ const messageQuery = maybeMessageQuery();const channelMessageData =- !maybeMessageQuery.isPending && queryReadyGate(maybeMessageQuery)- ? maybeMessageQuery.data+ messageQuery && !messageQuery.isPending && queryReadyGate(messageQuery)+ ? messageQuery.data: undefined;if (!data) {diff --git a/apps/web/src/lib/queries/preview/tests/preview.test.ts b/apps/web/src/lib/queries/preview/tests/preview.test.tsindex 3d4197378e..5d201b4a65 100644--- a/apps/web/src/lib/queries/preview/tests/preview.test.ts+++ b/apps/web/src/lib/queries/preview/tests/preview.test.ts@@ -100,7 +100,7 @@ describe('preview transport facade', () => {});});- it('uses urql-solid data while leaving the regular query disabled', () => {+ it('uses urql-solid data without building the regular queries', () => {createRoot((dispose) => {const [item] = useItemPreview(() => ({id: 'doc-1',@@ -108,8 +108,25 @@ describe('preview transport facade', () => {}));expect(item()).toEqual(preview);- const regularOptions = useQueryOptions[0]?.();- expect(regularOptions).toMatchObject({ enabled: false });+ expect(useQueryOptions).toHaveLength(0);+ dispose();+ });+ });++ it('builds the regular query once the GraphQL preview falls back', () => {+ createRoot((dispose) => {+ const [fallback, setFallback] = createSignal(false);+ createGraphqlItemPreviewQueryMock.mockReturnValue({+ data: () => undefined,+ shouldFallback: fallback,+ refetch: vi.fn(),+ });+ useItemPreview(() => ({ id: 'doc-1', type: 'document' }));+ expect(useQueryOptions).toHaveLength(0);++ setFallback(true);+ expect(useQueryOptions).toHaveLength(1);+ expect(useQueryOptions[0]?.()).toMatchObject({ enabled: true });dispose();});});diff --git a/nix-support/node_modules-hashes.json b/nix-support/node_modules-hashes.jsonindex 16a701865c..aa114f317a 100644--- a/nix-support/node_modules-hashes.json+++ b/nix-support/node_modules-hashes.json@@ -1,6 +1,6 @@{"nodeModules": {- "aarch64-darwin": "sha256-2kDPUYDJR2XAjg2Nqvq/2g25tiyf9KnFTlPFS2MbL28=",- "x86_64-linux": "sha256-56UY+AcJzdWRd0vxnDbeL2UwZMwPkhQj+OckS4SjA/U="+ "aarch64-darwin": "sha256-KwFdy4O78IkrXvPKd0hjY8NLgVbxJPUObyd+Ny50ieo=",+ "x86_64-linux": "sha256-HV7k/t1RjAeQ/q7GhHCZnU9FlqR1mfue7y07ODHBpFk="}}