Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(soup): recents view (#5671)

teod714094479a4
diff --git a/apps/web/src/components/app/app-sidebar/sidebar.tsx b/apps/web/src/components/app/app-sidebar/sidebar.tsx
index 7f100579c4..6f2739645e 100644
--- a/apps/web/src/components/app/app-sidebar/sidebar.tsx
+++ b/apps/web/src/components/app/app-sidebar/sidebar.tsx
@@ -17,6 +17,7 @@ import {
requestInboxFilter,
} from '@app/features/next-soup/soup-view/inbox-filter-controllers';
import { requestSearchFocus } from '@app/features/next-soup/soup-view/search-controllers';
+import { useRecentViewFlag } from '@app/features/next-soup/use-recent-view-flag';
import {
InviteModal,
setInviteModalOpen,
@@ -414,11 +415,13 @@ export const GoToHotkeys = () => {
const gettingStartedEnabled = useGettingStartedEnabled();
const calendarUiEnabled = useCalendarUiFlag();
const activityFeedEnabled = useActivityFeedFlag();
+ const recentViewEnabled = useRecentViewFlag();
const links = createMemo((): SidebarItem[] =>
buildSidebarLinks(
gettingStartedEnabled(),
calendarUiEnabled(),
- activityFeedEnabled()
+ activityFeedEnabled(),
+ recentViewEnabled()
)
);
@@ -1034,6 +1037,17 @@ const ACTIVITY_LINK: SidebarItem = {
hotkeyToken: TOKENS.sidebar.goTo.activity,
};
+const RECENT_LINK: SidebarItem = {
+ id: 'recent',
+ label: 'Recent',
+ href: LIST_VIEW_PATHS.recent,
+ icon: AnimatedActivityIcon,
+ // `r` is Calendar and `e`/`c`/`t` are taken; `n` is the only letter of
+ // "recent" that is not already a sidebar destination.
+ hotkey: 'n',
+ hotkeyToken: TOKENS.sidebar.goTo.recent,
+};
+
const REMINDERS_LINK: SidebarItem = {
id: 'reminders',
label: 'Reminders',
@@ -1061,7 +1075,8 @@ const REMINDERS_LINK: SidebarItem = {
const buildSidebarLinks = (
showGettingStarted: boolean,
showCalendar: boolean,
- showActivity: boolean
+ showActivity: boolean,
+ showRecent: boolean
): SidebarItem[] => {
let links: SidebarItem[] = [
DASHBOARD_LINK,
@@ -1069,8 +1084,15 @@ const buildSidebarLinks = (
...SIDEBAR_LINKS.filter((link) => showCalendar || link.id !== 'calendar'),
];
- if (showActivity) {
+ if (showRecent) {
+ // Directly below Inbox; Activity and Reminders anchor after it.
const idx = links.findIndex((link) => link.id === 'inbox');
+ links = [...links.slice(0, idx + 1), RECENT_LINK, ...links.slice(idx + 1)];
+ }
+
+ if (showActivity) {
+ const anchorId = showRecent ? 'recent' : 'inbox';
+ const idx = links.findIndex((link) => link.id === anchorId);
links = [
...links.slice(0, idx + 1),
ACTIVITY_LINK,
@@ -1079,8 +1101,12 @@ const buildSidebarLinks = (
}
if (ENABLE_REMINDERS()) {
- // Directly below Activity, or below Inbox when Activity is off.
- const anchorId = showActivity ? 'activity' : 'inbox';
+ // Directly below Activity, or below Recent/Inbox when Activity is off.
+ const anchorId = showActivity
+ ? 'activity'
+ : showRecent
+ ? 'recent'
+ : 'inbox';
const idx = links.findIndex((l) => l.id === anchorId);
links = [
...links.slice(0, idx + 1),
@@ -1166,11 +1192,13 @@ export const AppSidebar = (props: AppSidebarProps) => {
const gettingStartedEnabled = useGettingStartedEnabled();
const calendarUiEnabled = useCalendarUiFlag();
const activityFeedEnabled = useActivityFeedFlag();
+ const recentViewEnabled = useRecentViewFlag();
const allLinks = createMemo((): SidebarItem[] =>
buildSidebarLinks(
gettingStartedEnabled(),
calendarUiEnabled(),
- activityFeedEnabled()
+ activityFeedEnabled(),
+ recentViewEnabled()
)
);
@@ -1346,7 +1374,7 @@ export const AppSidebar = (props: AppSidebarProps) => {
// lives in the collapsible Workspace section. `findLink` drops ids that
// `buildSidebarLinks` gated out, so flag-gated rows need no filter here.
const topLinks = createMemo(() =>
- ['home', 'getting-started', 'inbox', 'activity', 'reminders']
+ ['home', 'getting-started', 'inbox', 'recent', 'activity', 'reminders']
.filter(
(id) => id !== 'getting-started' || !gettingStartedVisibility.hidden()
)
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index 004ab9c3b3..6c90dba8b1 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -10,6 +10,7 @@ import type { Query } from '@app/features/next-soup/filters/filter-store/types';
import { getViewPreset } from '@app/features/next-soup/sidebar/soup-filter-presets';
import { NonMemberChannelPreview } from '@app/features/next-soup/soup-view/non-member-channel-preview';
import { SoupView } from '@app/features/next-soup/soup-view/soup-view';
+import { useRecentViewFlag } from '@app/features/next-soup/use-recent-view-flag';
import { SettingsPanelComponentWrapper } from '@app/features/settings/Settings';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { usePosthog } from '@app/lib/analytics/posthog';
@@ -178,6 +179,47 @@ registerComponent(
})
);
+registerComponent('recent', withAuth(RecentViewWrapper));
+
+function TrackedRecentView() {
+ usePageViewTracking('recent');
+ const preset = getViewPreset('recent');
+ return (
+ <SoupView
+ viewName="Recent"
+ initialFilters={preset?.filters}
+ initialClientFilters={preset?.clientFilters}
+ // Rows carry the server's touched_at, so sorting on it preserves
+ // the touched-by-me order and lets optimistic bumps reorder locally.
+ initialClientSort={['touched_at']}
+ disableLocalSearch
+ />
+ );
+}
+
+function RecentViewWrapper() {
+ const recentViewEnabled = useRecentViewFlag();
+ const posthog = usePosthog();
+
+ // Registered even when the flag is off so a bookmarked /recent or a
+ // restored split recovers to the inbox instead of an empty split, and the
+ // touched query is never issued. The redirect replaces the split
+ // irreversibly, so it must wait for PostHog to actually answer — on a
+ // fresh reload the flag reads false until flags load.
+ return (
+ <Show
+ when={recentViewEnabled()}
+ fallback={
+ <Show when={posthog.flagsLoaded()}>
+ <RedirectSplit to={{ type: 'component', id: 'inbox' }} />
+ </Show>
+ }
+ >
+ <TrackedRecentView />
+ </Show>
+ );
+}
+
const MyActivityView = lazy(() =>
import('@app/features/activity/my-activity-view').then((module) => ({
default: module.MyActivityView,
diff --git a/apps/web/src/features/entity/queries/dss.ts b/apps/web/src/features/entity/queries/dss.ts
index 177beec791..0bcddc1f34 100644
--- a/apps/web/src/features/entity/queries/dss.ts
+++ b/apps/web/src/features/entity/queries/dss.ts
@@ -21,6 +21,7 @@ import {
removeSoupEntitiesFromQueriesReferencing,
} from '@queries/soup/cache';
import { soupKeys } from '@queries/soup/keys';
+import { ownTouchStamp } from '@queries/soup/normalized-cache/own-touch';
import { callServiceClient } from '@service-call/client';
import { scheduledActionClient } from '@service-scheduled-action/client';
import type { ItemType } from '@service-storage/client';
@@ -227,6 +228,8 @@ export function createBulkRemoveFromProjectDssEntityMutation() {
tag,
data: { id: e.id, projectId: null },
frecency_score: current?.frecency_score ?? 0,
+ // A move is an Edited activity, i.e. a touch (own-touch.ts).
+ touched_at: ownTouchStamp(e.id),
});
});
@@ -411,6 +414,8 @@ export function createBulkMoveToProjectDssEntityMutation() {
tag,
data: { id: e.id, projectId: project.id },
frecency_score: current?.frecency_score ?? 0,
+ // A move is an Edited activity, i.e. a touch (own-touch.ts).
+ touched_at: ownTouchStamp(e.id),
});
});
},
diff --git a/apps/web/src/features/entity/queries/file-type.ts b/apps/web/src/features/entity/queries/file-type.ts
index 70ad7fa104..5c62a926b6 100644
--- a/apps/web/src/features/entity/queries/file-type.ts
+++ b/apps/web/src/features/entity/queries/file-type.ts
@@ -8,6 +8,7 @@ import {
optimisticUpdateSoupEntity,
type SoupTransaction,
} from '@queries/soup/cache';
+import { ownTouchStamp } from '@queries/soup/normalized-cache/own-touch';
import type { FileType } from '@service-storage/generated/schemas/fileType';
import { useMutation } from '@tanstack/solid-query';
@@ -27,6 +28,8 @@ function performOptimisticFileTypeUpdate(id: string, fileType: string) {
tag: 'document',
data: { id, fileType },
frecency_score: score,
+ // A file-type change is an Edited activity, i.e. a touch (own-touch.ts).
+ touched_at: ownTouchStamp(id),
});
return { soupTransaction };
diff --git a/apps/web/src/features/entity/queries/rename.ts b/apps/web/src/features/entity/queries/rename.ts
index fd9d746d43..ad69f84c4b 100644
--- a/apps/web/src/features/entity/queries/rename.ts
+++ b/apps/web/src/features/entity/queries/rename.ts
@@ -11,6 +11,7 @@ import {
optimisticUpdateSoupEntity,
type SoupTransaction,
} from '@queries/soup/cache';
+import { ownTouchStamp } from '@queries/soup/normalized-cache/own-touch';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import type { CallRecord } from '@service-call/client';
import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';
@@ -185,6 +186,7 @@ const renameDssSetData = (
entities: EntityRenameOptimisticInfo[]
): SoupTransactionMap => {
const txns: SoupTransactionMap = new Map();
+ // A rename is an Edited activity, i.e. a touch (own-touch.ts).
for (const { id, itemType, newName } of entities) {
const current = getSoupEntityById(id);
const score = current?.frecency_score ?? 0;
@@ -195,6 +197,7 @@ const renameDssSetData = (
tag: 'channel',
data: { channel: { id, name: newName } },
frecency_score: score,
+ touched_at: ownTouchStamp(id),
})
);
} else if (itemType === 'call') {
@@ -225,6 +228,7 @@ const renameDssSetData = (
tag: itemType,
data: { id, name: newName },
frecency_score: score,
+ touched_at: ownTouchStamp(id),
})
);
}
diff --git a/apps/web/src/features/entity/types/entity.ts b/apps/web/src/features/entity/types/entity.ts
index 87988692c9..9ab655a307 100644
--- a/apps/web/src/features/entity/types/entity.ts
+++ b/apps/web/src/features/entity/types/entity.ts
@@ -17,6 +17,12 @@ export type EntityBase = {
name: string;
ownerId: string;
frecencyScore?: number;
+ /**
+ * The viewer's latest own mutation of this entity, present only on rows
+ * from `touched_by_me` pages. The Recent feed sorts on it, so mutation
+ * helpers may bump it optimistically.
+ */
+ touchedAt?: DateValue | null;
createdAt?: DateValue | null;
updatedAt?: DateValue | null;
viewedAt?: DateValue | null;
diff --git a/apps/web/src/features/next-soup/sidebar/soup-filter-presets.test.ts b/apps/web/src/features/next-soup/sidebar/soup-filter-presets.test.ts
index e15d6ef70e..de4e8b8875 100644
--- a/apps/web/src/features/next-soup/sidebar/soup-filter-presets.test.ts
+++ b/apps/web/src/features/next-soup/sidebar/soup-filter-presets.test.ts
@@ -228,3 +228,37 @@ describe('tab lists and filter presets agree', () => {
);
});
});
+
+describe('recent view preset', () => {
+ it('forces the touched-by-me server sort', () => {
+ expect(getViewPreset('recent')?.sortMethod).toBe('touched_by_me');
+ });
+
+ it('never compiles channel or email filter trees', () => {
+ // The touched-by-me query rejects channel/email trees with a 400, so
+ // even the NIL-id opt-in trees other views send must be absent.
+ const filters = getViewPreset('recent')?.filters;
+ const ast = compileToAst(queryStateFrom(filters!));
+ expect(ast.chanf).toBeUndefined();
+ expect(ast.ef).toBeUndefined();
+ expect(ast.emailView).toBeUndefined();
+ });
+
+ it('keeps documents, chats, and folders unrestricted', () => {
+ const filters = getViewPreset('recent')?.filters;
+ expect(filters?.include?.documentId).toBeUndefined();
+ expect(filters?.include?.chatId).toBeUndefined();
+ expect(filters?.include?.folderId).toBeUndefined();
+ });
+
+ it('excludes the types the touched feed can never return', () => {
+ const filters = getViewPreset('recent')?.filters;
+ const ast = compileToAst(queryStateFrom(filters!));
+ // Calendar events, CRM companies, foreign entities, and channel threads
+ // keep their match-nothing trees; the touched query ignores them.
+ expect(ast.calf).toBeDefined();
+ expect(ast.ccf).toBeDefined();
+ expect(ast.fef).toBeDefined();
+ expect(ast.cthf).toBeDefined();
+ });
+});
diff --git a/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts b/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts
index 075215b6a3..e193be3e3b 100644
--- a/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts
+++ b/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts
@@ -14,6 +14,7 @@ import {
ENABLE_SUPPORTED_SOUP_FOREIGN_ENTITIES_OVERRIDE,
} from '@core/constant/featureFlags';
import { PROPERTY_OPTION_IDS, SYSTEM_PROPERTY_IDS } from '@property/constants';
+import type { Params } from '@service-storage/generated/schemas/params';
import { startOfDay, subWeeks } from 'date-fns';
type SoupFiltersPreset = {
@@ -32,6 +33,15 @@ type SoupFiltersPreset = {
* matching every feed that reads newest-first.
*/
sortDirection?: 'asc' | 'desc';
+ /**
+ * Server sort this tab's meaning requires (e.g. `touched_by_me`), taking
+ * precedence over the client sort state. Tabs that force one usually also
+ * clear the client sort (`SoupView`'s `initialClientSort={[]}`) so the
+ * server's ordering survives to the rendered rows. Frecency is excluded:
+ * it is a different query flavor with its own client handling, not a
+ * per-tab ordering.
+ */
+ sortMethod?: Exclude<NonNullable<Params['sort_method']>, 'frecency'>;
};
// Tab preset configuration types
@@ -139,7 +149,36 @@ const getInboxNoiseFilters = () =>
emailView: 'inbox',
});
+/**
+ * Filters for the Recent view: the touched-by-me feed over everything the
+ * all view shows. Documents, chats, folders, channels, and emails stay
+ * unrestricted via `skipTargets` — the touched candidate query includes
+ * every touchable type by default, and it rejects channel/email filter
+ * trees outright (400), so even the usual NIL-id opt-in trees must not be
+ * sent for those two. Calendar/CRM/foreign/channel-thread targets keep
+ * their NIL exclusions; the touched query has no candidates of those types
+ * and ignores their trees.
+ */
+const getRecentFilters = () =>
+ defineQueryFilters(
+ { exclude: getDisabledSnippetSubtypeExclude() },
+ { skipTargets: ['df', 'cf', 'pf', 'chanf', 'ef'] }
+ );
+
export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {
+ recent: {
+ default: 'all',
+ tabs: {
+ // One tab: everything the user has touched, newest own-touch first.
+ // The server ordering is the product; the client sort is cleared by
+ // the view registration so rows render in server order.
+ all: () => ({
+ filters: getRecentFilters(),
+ clientFilters: { and: ['explicit-noise'] },
+ sortMethod: 'touched_by_me',
+ }),
+ },
+ },
inbox: {
default: 'signal',
tabs: {
diff --git a/apps/web/src/features/next-soup/soup-view/create-graphql-grouped-soup-queries.ts b/apps/web/src/features/next-soup/soup-view/create-graphql-grouped-soup-queries.ts
index 3c0743840a..95010a5408 100644
--- a/apps/web/src/features/next-soup/soup-view/create-graphql-grouped-soup-queries.ts
+++ b/apps/web/src/features/next-soup/soup-view/create-graphql-grouped-soup-queries.ts
@@ -69,11 +69,7 @@ type GraphqlGroupedInitialPage = {
type CreateGraphqlGroupedSoupQueriesArgs = {
initialPage: Accessor<GraphqlGroupedInitialPage | undefined>;
groupByField: Accessor<GroupByField | undefined>;
- soupParams: Accessor<
- Omit<SoupParams, 'sort_method'> & {
- sort_method: Exclude<SoupParams['sort_method'], 'frecency'>;
- }
- >;
+ soupParams: Accessor<SoupParams>;
soupBody: Accessor<SoupAstBody>;
enabled: Accessor<boolean>;
itemFilter: Accessor<SoupApiItemFilter | undefined>;
diff --git a/apps/web/src/features/next-soup/soup-view/create-grouped-soup-queries.ts b/apps/web/src/features/next-soup/soup-view/create-grouped-soup-queries.ts
index df14fec98c..304bc99d9f 100644
--- a/apps/web/src/features/next-soup/soup-view/create-grouped-soup-queries.ts
+++ b/apps/web/src/features/next-soup/soup-view/create-grouped-soup-queries.ts
@@ -5,6 +5,7 @@ import type { EntityData } from '@entity';
import { useQueryClient } from '@queries/client';
import { groupedCacheVersion } from '@queries/soup/cache';
import {
+ groupedSortMethod,
parseGroupMeta,
serializeGroupByField,
} from '@queries/soup/grouped/api';
@@ -52,14 +53,7 @@ export type GroupQueryData = {
type CreateGroupedSoupQueriesArgs = {
initialPage: Accessor<InitialGroupPage | undefined>;
groupByField: Accessor<GroupByField | undefined>;
- soupParams: Accessor<
- Omit<SoupParams, 'sort_method'> & {
- sort_method: Exclude<
- SoupParams['sort_method'],
- 'frecency' | 'touched_by_me'
- >;
- }
- >;
+ soupParams: Accessor<SoupParams>;
soupBody: Accessor<SoupAstBody>;
/** True only when the live GraphQL grouped parent query owns the view. */
graphqlReactive: Accessor<boolean>;
@@ -158,7 +152,7 @@ export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
group_by: serializeGroupByField(field),
group_key: group.key,
limit: args.soupParams().limit,
- sort_method: args.soupParams().sort_method ?? undefined,
+ sort_method: groupedSortMethod(args.soupParams().sort_method),
},
body: args.soupBody(),
})
diff --git a/apps/web/src/features/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx b/apps/web/src/features/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx
index 8dfb1a6d0f..2806739990 100644
--- a/apps/web/src/features/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx
+++ b/apps/web/src/features/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx
@@ -382,6 +382,9 @@ export function buildContactLabel(
export const VIEW_FILTER_CATEGORIES: Record<ListView, FilterCategory[]> = {
inbox: INBOX_FILTER_CATEGORIES,
+ // No refinements yet: the touched-by-me query rejects channel/email
+ // filter trees, so the inbox categories can't be offered wholesale.
+ recent: [],
agents: [],
mail: MAIL_FILTER_CATEGORIES,
documents: DOCUMENTS_FILTER_CATEGORIES,
diff --git a/apps/web/src/features/next-soup/soup-view/sort-options.tsx b/apps/web/src/features/next-soup/soup-view/sort-options.tsx
index 3889c92f10..6f1f8b5e35 100644
--- a/apps/web/src/features/next-soup/soup-view/sort-options.tsx
+++ b/apps/web/src/features/next-soup/soup-view/sort-options.tsx
@@ -60,6 +60,12 @@ function sortByViewedAt<T extends EntityData>(a: T, b: T) {
return compareDateDesc(a.sortTs ?? a.viewedAt, b.sortTs ?? b.viewedAt);
}
+// The Recent feed's order: the viewer's latest own mutation, newest first.
+// Untouched rows compare as epoch zero and sink below every touched row.
+function sortByTouchedAt<T extends EntityData>(a: T, b: T) {
+ return compareDateDesc(a.touchedAt, b.touchedAt);
+}
+
/**
* Priority sort order: Urgent (highest) -> High -> Medium -> Low -> No priority (lowest)
*/
@@ -149,6 +155,10 @@ export const SORT_CONFIGS = {
id: 'viewed_at',
fn: sortByViewedAt,
},
+ touched_at: {
+ id: 'touched_at',
+ fn: sortByTouchedAt,
+ },
priority: {
id: 'priority',
fn: sortByPriority,
diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx
index 44f18e8a87..253482ce0b 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx
+++ b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx
@@ -660,21 +660,23 @@ export const SoupViewContextProvider: FlowComponent<
: 'created_at';
const view = activeListView();
- // The direction belongs to what the tab means — Reminders' Active list
- // reads soonest-first — not to the sort method, so the preset owns it.
- // Omitted when absent so the server default (desc) applies and the query
- // keys of every existing view stay byte-identical.
- const sortDirection = view
+ // The direction and any forced sort belong to what the tab means —
+ // Reminders' Active list reads soonest-first, Recent reads by the
+ // user's own touches — not to the sort method state, so the preset owns
+ // them. Omitted when absent so the server default (desc) applies and
+ // the query keys of every existing view stay byte-identical.
+ const preset = view
? getViewPreset(view, activeTab(), {
userId: userId(),
isTeamAdmin: isTeamAdmin(),
- })?.sortDirection
+ })
: undefined;
+ const sortDirection = preset?.sortDirection;
return {
// Mail views use a smaller page size
limit: view === 'mail' ? 30 : 100,
- sort_method: sortMethod,
+ sort_method: preset?.sortMethod ?? sortMethod,
...(sortDirection ? { sort_direction: sortDirection } : {}),
};
});
diff --git a/apps/web/src/features/next-soup/soup-view/soup-view.tsx b/apps/web/src/features/next-soup/soup-view/soup-view.tsx
index da0e7a23b2..798bbe6c86 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-view.tsx
+++ b/apps/web/src/features/next-soup/soup-view/soup-view.tsx
@@ -234,6 +234,13 @@ interface SoupViewProps {
*/
initialGroupBy?: string;
disableLocalSearch?: boolean;
+ /**
+ * Client sort ids applied when the user has no persisted sort preference.
+ * Defaults to `['updated_at']`. Pass `[]` for views whose ordering is the
+ * server's (e.g. Recent's touched-by-me order) so rows render as paged —
+ * an explicit user sort still wins once chosen.
+ */
+ initialClientSort?: string[];
/**
* Client-side entities to merge into the soup results. Useful for entity
* types (e.g. automation) that don't come back from the soup API.
@@ -357,7 +364,7 @@ export const SoupView = (props: SoupViewProps) => {
let initialSortIds = initialCrmView?.sort ?? sortPref();
if (initialSortIds.length === 0) {
- initialSortIds = ['updated_at'];
+ initialSortIds = props.initialClientSort ?? ['updated_at'];
}
const persistedViewActiveTab = isListViewID(contentId)
diff --git a/apps/web/src/features/next-soup/use-recent-view-flag.ts b/apps/web/src/features/next-soup/use-recent-view-flag.ts
new file mode 100644
index 0000000000..c0f3bf21fa
--- /dev/null
+++ b/apps/web/src/features/next-soup/use-recent-view-flag.ts
@@ -0,0 +1,18 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import {
+ ENABLE_RECENT_VIEW_FLAG,
+ ENABLE_RECENT_VIEW_OVERRIDE,
+} from '@core/constant/featureFlags';
+import type { Accessor } from 'solid-js';
+
+/**
+ * Whether the Recent view (the touched-by-me feed) and its sidebar entry are
+ * shown. When off, the route redirects to the inbox and the touched query is
+ * never issued.
+ */
+export function useRecentViewFlag(): Accessor<boolean> {
+ const flag = useFeatureFlag(ENABLE_RECENT_VIEW_FLAG, {
+ enabledOverride: ENABLE_RECENT_VIEW_OVERRIDE,
+ });
+ return () => flag().enabled;
+}
diff --git a/apps/web/src/lib/constants/list-views.test.ts b/apps/web/src/lib/constants/list-views.test.ts
new file mode 100644
index 0000000000..256c80b3a3
--- /dev/null
+++ b/apps/web/src/lib/constants/list-views.test.ts
@@ -0,0 +1,41 @@
+import {
+ clearOwnTouchFloors,
+ ownTouchStamp,
+} from '@queries/soup/normalized-cache/own-touch';
+import type { SoupApiItem } from '@service-storage/generated/schemas';
+import { afterEach, describe, expect, it } from 'vitest';
+import { soupItemMatchesListView } from './list-views';
+
+const documentItem = (touched_at?: string): SoupApiItem =>
+ ({
+ tag: 'document',
+ data: { id: 'd-1', title: 'doc' },
+ frecency_score: 0,
+ ...(touched_at ? { touched_at } : {}),
+ }) as unknown as SoupApiItem;
+
+afterEach(() => {
+ clearOwnTouchFloors();
+});
+
+describe('soupItemMatchesListView', () => {
+ it('recent admits only rows carrying a touch timestamp', () => {
+ // Membership in the recent view is "did I touch it": a websocket insert
+ // of someone else's entity (no touched_at) must not enter the feed.
+ expect(soupItemMatchesListView(documentItem(), 'recent')).toBe(false);
+ expect(
+ soupItemMatchesListView(documentItem('2026-08-15T00:00:00Z'), 'recent')
+ ).toBe(true);
+ });
+
+ it('recent admits rows with an outstanding optimistic own-touch', () => {
+ // Own creations arrive via a single-entity fetch that carries no
+ // touched_at; the recorded floor is what admits them.
+ ownTouchStamp('d-1');
+ expect(soupItemMatchesListView(documentItem(), 'recent')).toBe(true);
+ });
+
+ it('inbox admits rows regardless of touch', () => {
+ expect(soupItemMatchesListView(documentItem(), 'inbox')).toBe(true);
+ });
+});
diff --git a/apps/web/src/lib/constants/list-views.ts b/apps/web/src/lib/constants/list-views.ts
index 43cd4718df..520c33a282 100644
--- a/apps/web/src/lib/constants/list-views.ts
+++ b/apps/web/src/lib/constants/list-views.ts
@@ -1,5 +1,6 @@
import type { TagFilterMode } from '@app/features/next-soup/filters/filter-store/types';
import type { EntityData } from '@entity';
+import { hasOwnTouchFloor } from '@queries/soup/normalized-cache/own-touch';
import type {
SoupApiItem,
SoupProperty,
@@ -8,6 +9,7 @@ import { match } from 'ts-pattern';
export const LIST_VIEWS = [
'inbox',
+ 'recent',
'agents',
'mail',
'documents',
@@ -24,6 +26,7 @@ export type ListView = (typeof LIST_VIEWS)[number];
export const LIST_VIEW_PATHS = {
inbox: '/inbox',
+ recent: '/recent',
agents: '/agents',
mail: '/mail',
documents: '/documents',
@@ -38,6 +41,7 @@ export const LIST_VIEW_PATHS = {
export const LIST_VIEW_ID = {
inbox: 'inbox',
+ recent: 'recent',
agents: 'agents',
mail: 'mail',
documents: 'documents',
@@ -70,6 +74,18 @@ export const TAGGABLE_LIST_VIEWS: ReadonlySet<ListView> = new Set<ListView>([
'calls',
]);
+/** The entity id a soup item normalizes under (channels/calls nest theirs). */
+const soupItemEntityId = (item: SoupApiItem): string => {
+ switch (item.tag) {
+ case 'channel':
+ return item.data.channel.id;
+ case 'call':
+ return item.data.callId;
+ default:
+ return item.data.id;
+ }
+};
+
export const soupItemMatchesListView = (
item: SoupApiItem,
view: ListView | undefined
@@ -94,6 +110,15 @@ export const soupItemMatchesListView = (
.with('calls', () => item.tag === 'call')
.with('folders', () => item.tag === 'project')
.with('inbox', 'search', undefined, () => true)
+ // Membership in the recent view is "did I touch it", not a type check:
+ // only rows that carry a touch timestamp (from the touched_by_me page)
+ // or an outstanding optimistic own-touch belong. Without this, any
+ // websocket-inserted entity — including other people's — would enter
+ // the feed.
+ .with(
+ 'recent',
+ () => item.touched_at != null || hasOwnTouchFloor(soupItemEntityId(item))
+ )
.with('companies', () => item.tag === 'crmCompany')
.with('reminders', () => item.tag === 'reminder')
.exhaustive();
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index e50928aa84..a1d124c1fd 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -687,3 +687,12 @@ export function ENABLE_CHAT_V3_AGENTS(): boolean {
analytics.posthog.isFeatureEnabled(ENABLE_CHAT_V3_AGENTS_FLAG) ?? false
);
}
+
+// The Recent view: the touched-by-me feed (everything the viewer mutated,
+// newest own-touch first). Gates the view (the route redirects to the inbox
+// when off) and its sidebar entry. PostHog-gated with a dev-mode default;
+// override with VITE_ENABLE_RECENT_VIEW.
+export const ENABLE_RECENT_VIEW_FLAG = 'enable-recent-view';
+export const ENABLE_RECENT_VIEW_OVERRIDE =
+ getFeatureFlagOverride('ENABLE_RECENT_VIEW') ??
+ (DEV_MODE_ENV ? true : undefined);
diff --git a/apps/web/src/lib/core/hotkey/tokens.ts b/apps/web/src/lib/core/hotkey/tokens.ts
index 7c1385c222..c99a078cce 100644
--- a/apps/web/src/lib/core/hotkey/tokens.ts
+++ b/apps/web/src/lib/core/hotkey/tokens.ts
@@ -113,6 +113,7 @@ export const TOKENS = {
home: 'sidebar.goTo.home',
gettingStarted: 'sidebar.goTo.gettingStarted',
inbox: 'sidebar.goTo.inbox',
+ recent: 'sidebar.goTo.recent',
activity: 'sidebar.goTo.activity',
calendar: 'sidebar.goTo.calendar',
search: 'sidebar.goTo.search',
diff --git a/apps/web/src/lib/core/util/create.ts b/apps/web/src/lib/core/util/create.ts
index f8dd292b7f..623321567d 100644
--- a/apps/web/src/lib/core/util/create.ts
+++ b/apps/web/src/lib/core/util/create.ts
@@ -66,7 +66,7 @@ export async function createMarkdownFile(
name: args?.title ?? '',
fileType: 'md',
});
- refetchSoupEntity(documentId, 'document');
+ refetchSoupEntity(documentId, 'document', { ownTouch: true });
analytics.track('create_entity', {
entityType: 'md',
@@ -162,7 +162,7 @@ async function createTaskResponse(args?: CreateTaskArgs) {
fileType: 'md',
subType: { type: 'task', is_completed: false },
});
- refetchSoupEntity(documentId, 'document');
+ refetchSoupEntity(documentId, 'document', { ownTouch: true });
analytics.track('create_entity', {
entityType: 'task',
@@ -221,7 +221,7 @@ export async function createSnippet(
fileType: 'md',
subType: { type: 'snippet' },
});
- refetchSoupEntity(documentId, 'document');
+ refetchSoupEntity(documentId, 'document', { ownTouch: true });
analytics.track('create_entity', {
entityType: 'snippet',
@@ -269,7 +269,7 @@ export async function createSkill(
fileType: 'md',
subType: { type: 'skill' },
});
- refetchSoupEntity(documentId, 'document');
+ refetchSoupEntity(documentId, 'document', { ownTouch: true });
analytics.track('create_entity', {
entityType: 'skill',
@@ -361,7 +361,9 @@ export async function createCodeFileFromText({
name: title ?? 'New Code File',
fileType: finalExtension,
});
- refetchSoupEntity(document.metadata.documentId, 'document');
+ refetchSoupEntity(document.metadata.documentId, 'document', {
+ ownTouch: true,
+ });
analytics.track('create_entity', {
entityType: 'code',
@@ -411,7 +413,7 @@ export async function createCanvasFileFromJsonString(args: {
name: title ?? 'New Canvas',
fileType: 'canvas',
});
- refetchSoupEntity(canvas.metadata.documentId, 'document');
+ refetchSoupEntity(canvas.metadata.documentId, 'document', { ownTouch: true });
analytics.track('create_entity', {
entityType: 'canvas',
@@ -448,7 +450,7 @@ export async function createChat(
itemType: 'chat',
name: args?.name ?? DEFAULT_CHAT_NAME,
});
- refetchSoupEntity(chat.id, 'chat');
+ refetchSoupEntity(chat.id, 'chat', { ownTouch: true });
analytics.track('create_entity', {
entityType: 'chat',
diff --git a/apps/web/src/lib/queries/channel/message.ts b/apps/web/src/lib/queries/channel/message.ts
index a7f80dc66f..eaed6c0cd4 100644
--- a/apps/web/src/lib/queries/channel/message.ts
+++ b/apps/web/src/lib/queries/channel/message.ts
@@ -4,6 +4,7 @@ import { toast } from '@core/component/Toast/Toast';
import type { DateValue } from '@core/util/date';
import { throwOnErr } from '@core/util/result';
import {
+ bumpSoupEntityTouchedAt,
invalidateSoupEntity,
refetchSoupEntity,
} from '@queries/soup/normalized-cache';
@@ -469,6 +470,11 @@ export function useSendMessageMutation(
threadId,
});
+ // Sending is a `messaged` activity server-side; stamp the touch now
+ // so the Recent order moves the channel up without waiting on the
+ // activity consumer, which the refetch below can outrun.
+ bumpSoupEntityTouchedAt(variables.channelID);
+
// The sender does not receive the notification that normally refreshes
// this soup entity. Refresh root messages here so the channel moves to
// its updated position in soup lists.
diff --git a/apps/web/src/lib/queries/properties/entity.ts b/apps/web/src/lib/queries/properties/entity.ts
index f7821abca5..7f8e2fb2b2 100644
--- a/apps/web/src/lib/queries/properties/entity.ts
+++ b/apps/web/src/lib/queries/properties/entity.ts
@@ -18,6 +18,7 @@ import type {
PropertyDefinitionDomain,
} from '@property/types';
import { isInstantiatedProperty } from '@property/utils';
+import { ownTouchStamp } from '@queries/soup/normalized-cache/own-touch';
import { useMutation, useMutationState, useQuery } from '@tanstack/solid-query';
import { type Accessor, batch } from 'solid-js';
import { propertiesServiceClient } from '../../service-clients/service-properties/client';
@@ -233,6 +234,9 @@ function optimisticUpdateSoupEntityProperties(
properties: nextProperties,
},
frecency_score: current.frecency_score,
+ // A property change is a PropertyChanged activity, i.e. a touch
+ // (own-touch.ts).
+ touched_at: ownTouchStamp(entityId),
});
}
diff --git a/apps/web/src/lib/queries/soup/graphql/ast.ts b/apps/web/src/lib/queries/soup/graphql/ast.ts
index adae3dc033..8cdc986d18 100644
--- a/apps/web/src/lib/queries/soup/graphql/ast.ts
+++ b/apps/web/src/lib/queries/soup/graphql/ast.ts
@@ -526,6 +526,8 @@ function mapSortMethod(
return 'VIEWED_UPDATED';
case 'frecency':
return unsupported('sort_method frecency');
+ case 'touched_by_me':
+ return unsupported('sort_method touched_by_me');
case undefined:
return undefined;
}
diff --git a/apps/web/src/lib/queries/soup/grouped/api.ts b/apps/web/src/lib/queries/soup/grouped/api.ts
index 282d96f954..205604ce71 100644
--- a/apps/web/src/lib/queries/soup/grouped/api.ts
+++ b/apps/web/src/lib/queries/soup/grouped/api.ts
@@ -2,10 +2,32 @@ import { SYSTEM_PROPERTY_IDS } from '@property/constants';
import type { SoupProperty } from '@service-storage/generated/schemas';
import type { ApiGroupByField as ApiGroupedSoupField } from '@service-storage/generated/schemas/apiGroupByField';
import type { ApiGroupMeta } from '@service-storage/generated/schemas/apiGroupMeta';
+import type { Params } from '@service-storage/generated/schemas/params';
import type { SoupApiItem } from '@service-storage/generated/schemas/soupApiItem';
import { match } from 'ts-pattern';
import { type GroupByField, type GroupMeta, NOT_SET_GROUP_KEY } from './types';
+/** Sort methods the grouped soup endpoints accept. */
+export type GroupedSortMethod = Exclude<
+ NonNullable<Params['sort_method']>,
+ 'frecency' | 'touched_by_me'
+>;
+
+/**
+ * Maps a flat-feed sort method onto what the grouped endpoints support.
+ * Frecency and touched-by-me pages are built from their own data sources
+ * (relevance scores / the activity log) that the grouped queries cannot
+ * reproduce, so grouping such a view falls back to update recency within
+ * each group.
+ */
+export function groupedSortMethod(
+ sort: Params['sort_method']
+): GroupedSortMethod | undefined {
+ if (sort == null) return undefined;
+ if (sort === 'frecency' || sort === 'touched_by_me') return 'updated_at';
+ return sort;
+}
+
function hasProperties<T extends SoupApiItem>(
item: T
): item is T & {
diff --git a/apps/web/src/lib/queries/soup/items.ts b/apps/web/src/lib/queries/soup/items.ts
index a6753a9c15..2c4ab5092f 100644
--- a/apps/web/src/lib/queries/soup/items.ts
+++ b/apps/web/src/lib/queries/soup/items.ts
@@ -7,6 +7,7 @@ import {
import { throwOnErr } from '@core/util/result';
import type { EntityData } from '@entity';
import {
+ groupedSortMethod,
makeGroupComparator,
parseGroupMeta,
serializeGroupByField,
@@ -163,14 +164,7 @@ const useRestSoupAstItemsQuery = (
.queryKey,
queryFn: async (ctx): Promise<SoupAstItemsPage> => {
if (groupBy) {
- let sort_method = params.sort_method ?? undefined;
-
- // TODO(dev-rb/soup): This is temporary fix since we don't support
- // 'frecency' or 'touched_by_me' for group by. Replace with proper
- // types
- if (sort_method === 'frecency' || sort_method === 'touched_by_me') {
- sort_method = 'updated_at';
- }
+ const sort_method = groupedSortMethod(params.sort_method);
const fetchRest = async () => {
const response = await throwOnErr(
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/index.ts b/apps/web/src/lib/queries/soup/normalized-cache/index.ts
index a8ac18bc6f..13199b3f3a 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/index.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/index.ts
@@ -1,6 +1,7 @@
export { groupedCacheVersion } from './grouped-operations';
export { initSoupNormalizer } from './normalizer';
export {
+ bumpSoupEntityTouchedAt,
getSoupEntityById,
hasSoupEntity,
invalidateAllSoup,
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
index 948bc31509..9a4f059c95 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
@@ -45,6 +45,7 @@ import { soupKeys } from '../keys';
import {
// biome-ignore lint/correctness/noPrivateImports: testing private export
buildSingleEntityFilter,
+ bumpSoupEntityTouchedAt,
getSoupItemId,
insertSoupEntity,
optimisticUpdateSoupEntity,
@@ -444,6 +445,41 @@ describe('optimisticUpdateSoupEntity', () => {
});
});
+describe('bumpSoupEntityTouchedAt', () => {
+ it('stamps a fresh touch on standard entities', () => {
+ mockNormalizer.getObjectById.mockReturnValueOnce(mockDocumentItem('doc-1'));
+
+ bumpSoupEntityTouchedAt('doc-1');
+
+ expect(mockNormalizer.setNormalizedData).toHaveBeenCalledWith({
+ tag: 'document',
+ data: { id: 'doc-1' },
+ frecency_score: 1,
+ touched_at: expect.any(String),
+ });
+ });
+
+ it('keys channels by their inner channel id', () => {
+ mockNormalizer.getObjectById.mockReturnValueOnce(mockChannelItem('ch-1'));
+
+ bumpSoupEntityTouchedAt('ch-1');
+
+ expect(mockNormalizer.setNormalizedData).toHaveBeenCalledWith({
+ tag: 'channel',
+ data: { channel: { id: 'ch-1' } },
+ frecency_score: 1,
+ touched_at: expect.any(String),
+ });
+ });
+
+ it('is a no-op for entities not in the cache', () => {
+ mockNormalizer.getObjectById.mockReturnValueOnce(null);
+
+ expect(bumpSoupEntityTouchedAt('missing')).toBeUndefined();
+ expect(mockNormalizer.setNormalizedData).not.toHaveBeenCalled();
+ });
+});
+
describe('optimisticUpdateSoupItemUpdatedAt', () => {
it('updates updatedAt for non-channel entities', () => {
mockNormalizer.getObjectById.mockReturnValueOnce(mockDocumentItem('doc-1'));
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
index 0f8d2073ff..d9935773a5 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
@@ -32,6 +32,7 @@ import {
soupNormKey,
stripSoupNormPrefix,
} from './normalizer';
+import { ownTouchStamp } from './own-touch';
import type {
SoupEntityPartial,
SoupEntityTag,
@@ -130,6 +131,48 @@ export function getSoupEntityById(entityId: string): SoupApiItem | undefined {
undefined) as SoupApiItem | undefined;
}
+/**
+ * Optimistically stamp the viewer's own touch on a cached entity so the
+ * touched_by_me (Recent) order moves it to the top immediately, ahead of the
+ * activity consumer. Call it only from mutations whose server side records
+ * an activity — see the allowlist rule in `own-touch.ts`, which also records
+ * the stamp as a floor so touched-mode refetches that outrun the consumer
+ * can't clobber the optimistic order; the floor clears once the server's
+ * value catches up. Non-touched responses omit the field entirely, so the
+ * field-merge never clears the stamp either.
+ */
+export function bumpSoupEntityTouchedAt(
+ entityId: string
+): SoupTransaction | undefined {
+ const current = getSoupEntityById(entityId);
+ if (!current) return undefined;
+ const touched_at = ownTouchStamp(entityId);
+ const frecency_score = current.frecency_score;
+
+ if (current.tag === 'channel') {
+ return optimisticUpdateSoupEntity({
+ tag: 'channel',
+ data: { channel: { id: current.data.channel.id } },
+ frecency_score,
+ touched_at,
+ });
+ }
+ if (current.tag === 'call') {
+ return optimisticUpdateSoupEntity({
+ tag: 'call',
+ data: { callId: current.data.callId },
+ frecency_score,
+ touched_at,
+ });
+ }
+ return optimisticUpdateSoupEntity({
+ tag: current.tag,
+ data: { id: current.data.id },
+ frecency_score,
+ touched_at,
+ } as SoupEntityPartial);
+}
+
/**
* Mark stale only the soup queries containing a specific entity.
* Prefer this over `invalidateAllSoup` when you know the affected entity ID.
@@ -501,11 +544,19 @@ export function removeSearchEntities(entityIds: Set<string>): SoupTransaction {
* Fetch a single entity from the server and merge it into the cache.
* If the entity is already cached, updates it via normy (deep-merge).
* If it's new, prepends it to the first page of every active soup list query.
+ *
+ * `ownTouch` marks the refetch as caused by the viewer's own mutation (e.g.
+ * entity creation): the fetched item is stamped with an optimistic
+ * `touched_at` — the single-entity response never carries one — so the
+ * Recent feed's insert gate admits it, and the touched queries are spared
+ * from the follow-up invalidation, which would replace their pages with
+ * server state that can't include the entity until the activity consumer
+ * catches up.
*/
export async function refetchSoupEntity(
entityId: string,
entityType: SoupEntityTag,
- options?: { includeRoot?: boolean }
+ options?: { includeRoot?: boolean; ownTouch?: boolean }
): Promise<void> {
const { storageServiceClient } = await import('@service-storage/client');
@@ -527,17 +578,47 @@ export async function refetchSoupEntity(
const page = result.value;
if (!page.items.length) return;
- for (const item of page.items) {
+ for (let item of page.items) {
const itemId = getSoupItemId(item);
+ if (options?.ownTouch) {
+ item = { ...item, touched_at: ownTouchStamp(itemId) };
+ }
if (hasSoupEntity(itemId)) {
optimisticUpdateSoupEntity(item);
} else {
insertSoupEntity(item);
- invalidateAllSoup();
+ if (options?.ownTouch) {
+ invalidateAllSoupExceptTouched();
+ } else {
+ invalidateAllSoup();
+ }
}
}
}
+/**
+ * `invalidateAllSoup` minus the touched_by_me queries: an own-touch insert
+ * must survive in the Recent feed until the activity consumer has recorded
+ * the touch, so those pages keep the optimistic row instead of refetching
+ * a server list that would drop it.
+ */
+function invalidateAllSoupExceptTouched(): void {
+ const notTouched = (query: Query) =>
+ !JSON.stringify(query.queryKey).includes('touched_by_me');
+ queryClient.invalidateQueries({
+ queryKey: soupKeys.items._def,
+ predicate: notTouched,
+ });
+ queryClient.invalidateQueries({
+ queryKey: soupKeys.astItems._def,
+ predicate: notTouched,
+ });
+ queryClient.invalidateQueries({
+ queryKey: soupKeys.groupedGroup._def,
+ predicate: notTouched,
+ });
+}
+
/** @private */
export function buildSingleEntityFilter(
entityType: SoupEntityTag,
@@ -632,6 +713,13 @@ export function optimisticUpdateSoupItemViewedAt(itemId: string) {
/**
* Optimistically update the updatedAt/updated_at timestamp for a soup item.
* Updates the item across all soup queries if it exists and matches the expected tag.
+ *
+ * Deliberately does NOT stamp `touched_at`: this helper's caller is the
+ * incoming-notification path, i.e. *other people's* actions (your own don't
+ * notify you). `updated_at` is global recency, `touched_at` is the viewer's
+ * own touch — stamping it here would pull entities a teammate mutated into
+ * the viewer's Recent feed. Own-mutation flows stamp `touched_at` at their
+ * call sites (see `bumpSoupEntityTouchedAt`).
*/
export function optimisticUpdateSoupItemUpdatedAt(
itemId: string,
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/own-touch.test.ts b/apps/web/src/lib/queries/soup/normalized-cache/own-touch.test.ts
new file mode 100644
index 0000000000..031adca825
--- /dev/null
+++ b/apps/web/src/lib/queries/soup/normalized-cache/own-touch.test.ts
@@ -0,0 +1,50 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import {
+ clearOwnTouchFloors,
+ hasOwnTouchFloor,
+ ownTouchStamp,
+ resolveOwnTouch,
+} from './own-touch';
+
+afterEach(() => {
+ clearOwnTouchFloors();
+});
+
+describe('own-touch floors', () => {
+ it('passes the server value through when no floor exists', () => {
+ expect(resolveOwnTouch('e-1', '2026-08-19T00:00:00Z')).toBe(
+ '2026-08-19T00:00:00Z'
+ );
+ expect(resolveOwnTouch('e-1', null)).toBeNull();
+ });
+
+ it('wins over an older or absent server value', () => {
+ const stamp = ownTouchStamp('e-1');
+
+ // A touched refetch that outran the activity consumer returns the old
+ // touched_at (or none) — the optimistic floor must hold.
+ expect(resolveOwnTouch('e-1', '2020-01-01T00:00:00Z')).toBe(stamp);
+ expect(resolveOwnTouch('e-1', null)).toBe(stamp);
+ expect(hasOwnTouchFloor('e-1')).toBe(true);
+ });
+
+ it('clears once the server catches up', () => {
+ ownTouchStamp('e-1');
+ const caughtUp = new Date(Date.now() + 60_000).toISOString();
+
+ expect(resolveOwnTouch('e-1', caughtUp)).toBe(caughtUp);
+ // The floor is gone: subsequent reads are pass-through.
+ expect(hasOwnTouchFloor('e-1')).toBe(false);
+ expect(resolveOwnTouch('e-1', '2020-01-01T00:00:00Z')).toBe(
+ '2020-01-01T00:00:00Z'
+ );
+ });
+
+ it('compares timestamps numerically across precision differences', () => {
+ // Server timestamps carry micros (chrono), the client stamps millis —
+ // lexicographic comparison would misorder these.
+ const stamp = ownTouchStamp('e-1');
+ const equalWithMicros = `${stamp.slice(0, -1)}000Z`;
+ expect(resolveOwnTouch('e-1', equalWithMicros)).toBe(equalWithMicros);
+ });
+});
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/own-touch.ts b/apps/web/src/lib/queries/soup/normalized-cache/own-touch.ts
new file mode 100644
index 0000000000..0816d90658
--- /dev/null
+++ b/apps/web/src/lib/queries/soup/normalized-cache/own-touch.ts
@@ -0,0 +1,65 @@
+/**
+ * The viewer's optimistic own-touch stamps ("floors"), keyed by entity id.
+ *
+ * `touched_at` is the viewer's latest own mutation as recorded by the
+ * activity log, which lands through an async consumer. A touched-mode
+ * refetch triggered right after a mutation can therefore return the OLD
+ * server value, and the normalized cache's field-merge would let it
+ * overwrite a fresher optimistic stamp. Instead of racing the consumer,
+ * stamps are recorded here and reads resolve to max(server, floor); an
+ * entry clears itself the moment the server value catches up.
+ *
+ * Only mutations whose server side records an activity (the domain
+ * `ActivitySource` impls: create, rename, file-type change, project move,
+ * property change, channel message send) may stamp — bumping an
+ * unattributed action would reorder the Recent feed only to snap back once
+ * the server truth arrives. Doc content edits are NOT attributed yet
+ * (`SyncContentUpdated` carries no actor), so typing must not stamp.
+ *
+ * This module is import-free on purpose: it sits below the normalized
+ * cache, the entity mappers, and the list-view gates, which would
+ * otherwise form an import cycle.
+ */
+
+const ownTouchFloors = new Map<string, string>();
+
+/**
+ * Record and return a fresh own-touch stamp for the entity. Every optimistic
+ * `touched_at` write must obtain its value here so the floor is registered.
+ */
+export function ownTouchStamp(entityId: string): string {
+ const stamp = new Date().toISOString();
+ ownTouchFloors.set(entityId, stamp);
+ return stamp;
+}
+
+/**
+ * Resolve the effective touched_at for an entity: the server value unless a
+ * newer optimistic floor exists. Clears the floor once the server catches
+ * up, so steady-state reads are pass-through.
+ */
+export function resolveOwnTouch(
+ entityId: string,
+ serverTouchedAt: string | null | undefined
+): string | null | undefined {
+ const floor = ownTouchFloors.get(entityId);
+ if (floor === undefined) return serverTouchedAt;
+ if (
+ serverTouchedAt &&
+ new Date(serverTouchedAt).getTime() >= new Date(floor).getTime()
+ ) {
+ ownTouchFloors.delete(entityId);
+ return serverTouchedAt;
+ }
+ return floor;
+}
+
+/** Whether the viewer has an outstanding optimistic touch for the entity. */
+export function hasOwnTouchFloor(entityId: string): boolean {
+ return ownTouchFloors.has(entityId);
+}
+
+/** Test-only: reset all floors between cases. */
+export function clearOwnTouchFloors(): void {
+ ownTouchFloors.clear();
+}
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/types.ts b/apps/web/src/lib/queries/soup/normalized-cache/types.ts
index b573f5d9e5..05a6faff7f 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/types.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/types.ts
@@ -29,4 +29,6 @@ export type SoupEntityPartial<T extends SoupEntityTag = SoupEntityTag> = {
tag: T;
data: SoupPartialData<T>;
frecency_score: number;
+ /** Optimistic own-touch stamp; only `bumpSoupEntityTouchedAt` sets it. */
+ touched_at?: string | null;
};
diff --git a/apps/web/src/lib/queries/soup/transform-utils.ts b/apps/web/src/lib/queries/soup/transform-utils.ts
index 44cc51e1fc..3a3dca76e9 100644
--- a/apps/web/src/lib/queries/soup/transform-utils.ts
+++ b/apps/web/src/lib/queries/soup/transform-utils.ts
@@ -31,6 +31,7 @@ import type {
SearchData,
WithSearch,
} from '@entity';
+import { resolveOwnTouch } from '@queries/soup/normalized-cache/own-touch';
import type {
CallRecordSearchResult,
ChannelSearchResult,
@@ -971,7 +972,14 @@ export const mapApiSoupItemToEntity = (
})
.exhaustive();
- return withRawNotifications(entity, item);
+ // Attached once for every tag: only touched_by_me pages carry the field,
+ // and the Recent feed's client sort reads it off the entity. Resolved
+ // through the own-touch floor so a touched refetch that outran the
+ // activity consumer can't move a freshly-touched row back down.
+ const touchedAt = resolveOwnTouch(entity.id, item.touched_at ?? null);
+ const touched = touchedAt ? { ...entity, touchedAt } : entity;
+
+ return withRawNotifications(touched, item);
};
const toCalendarEventTime = (
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 36a4d06b4f..a60a7da13e 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -968,6 +968,7 @@ export * from './shortIdResponse';
export * from './simpleMention';
export * from './soupApiItem';
export * from './soupApiItemAllOf';
+export * from './soupApiItemAllOfTouchedAt';
export * from './soupApiSort';
export * from './soupApiSortDirection';
export * from './soupAttachment';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupApiItem.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupApiItem.ts
index d203a043b8..0b0a65c933 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupApiItem.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupApiItem.ts
@@ -9,6 +9,6 @@ import type { SoupApiItemAllOf } from './soupApiItemAllOf';
import type { SoupItem } from './soupItem';
/**
- * API representation of a soup item with its frecency score.
+ * API representation of a soup item with its per-viewer enrichments.
*/
export type SoupApiItem = SoupItem & SoupApiItemAllOf;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupApiItemAllOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupApiItemAllOf.ts
index 575581f395..e3c1ba1d47 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupApiItemAllOf.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupApiItemAllOf.ts
@@ -4,9 +4,14 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
+import type { SoupApiItemAllOfTouchedAt } from './soupApiItemAllOfTouchedAt';
export type SoupApiItemAllOf = {
frecency_score: number;
/** Whether the requesting user has favorited this entity. */
is_favorited: boolean;
+ /** The caller's latest own mutation of this entity, present only when the
+page was ordered by `touched_by_me`. Clients keep the touched feed
+ordered on this value, so it can be bumped optimistically. */
+ touched_at?: SoupApiItemAllOfTouchedAt;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupApiItemAllOfTouchedAt.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupApiItemAllOfTouchedAt.ts
new file mode 100644
index 0000000000..89d40c1d4a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupApiItemAllOfTouchedAt.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The caller's latest own mutation of this entity, present only when the
+page was ordered by `touched_by_me`. Clients keep the touched feed
+ordered on this value, so it can be bumped optimistically.
+ */
+export type SoupApiItemAllOfTouchedAt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index 490d55d9e2..a1964aca12 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -10859,9 +10859,17 @@ export const getItemsSoupResponse = zod
.describe(
'Whether the requesting user has favorited this entity.'
),
+ touched_at: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ "The caller's latest own mutation of this entity, present only when the\npage was ordered by `touched_by_me`. Clients keep the touched feed\nordered on this value, so it can be bumped optimistically."
+ ),
})
)
- .describe('API representation of a soup item with its frecency score.')
+ .describe(
+ 'API representation of a soup item with its per-viewer enrichments.'
+ )
),
next_cursor: zod.string().nullish(),
})
@@ -14494,9 +14502,17 @@ export const postItemsSoupResponse = zod
.describe(
'Whether the requesting user has favorited this entity.'
),
+ touched_at: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ "The caller's latest own mutation of this entity, present only when the\npage was ordered by `touched_by_me`. Clients keep the touched feed\nordered on this value, so it can be bumped optimistically."
+ ),
})
)
- .describe('API representation of a soup item with its frecency score.')
+ .describe(
+ 'API representation of a soup item with its per-viewer enrichments.'
+ )
),
next_cursor: zod.string().nullish(),
})
@@ -17595,9 +17611,17 @@ export const postItemsSoupAstResponse = zod
.describe(
'Whether the requesting user has favorited this entity.'
),
+ touched_at: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ "The caller's latest own mutation of this entity, present only when the\npage was ordered by `touched_by_me`. Clients keep the touched feed\nordered on this value, so it can be bumped optimistically."
+ ),
})
)
- .describe('API representation of a soup item with its frecency score.')
+ .describe(
+ 'API representation of a soup item with its per-viewer enrichments.'
+ )
),
next_cursor: zod.string().nullish(),
})
@@ -21047,10 +21071,16 @@ export const postItemsSoupAstGroupedResponse = zod
.describe(
'Whether the requesting user has favorited this entity.'
),
+ touched_at: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ "The caller's latest own mutation of this entity, present only when the\npage was ordered by `touched_by_me`. Clients keep the touched feed\nordered on this value, so it can be bumped optimistically."
+ ),
})
)
.describe(
- 'API representation of a soup item with its frecency score.'
+ 'API representation of a soup item with its per-viewer enrichments.'
)
)
.describe(
@@ -24151,10 +24181,16 @@ export const postItemsSoupAstGroupedResponse = zod
.describe(
'Whether the requesting user has favorited this entity.'
),
+ touched_at: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ "The caller's latest own mutation of this entity, present only when the\npage was ordered by `touched_by_me`. Clients keep the touched feed\nordered on this value, so it can be bumped optimistically."
+ ),
})
)
.describe(
- 'API representation of a soup item with its frecency score.'
+ 'API representation of a soup item with its per-viewer enrichments.'
)
)
.describe(
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 4412fefbba..938bdd3904 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -21869,11 +21869,16 @@
"is_favorited": {
"type": "boolean",
"description": "Whether the requesting user has favorited this entity."
+ },
+ "touched_at": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "The caller's latest own mutation of this entity, present only when the\npage was ordered by `touched_by_me`. Clients keep the touched feed\nordered on this value, so it can be bumped optimistically."
}
}
}
],
- "description": "API representation of a soup item with its frecency score."
+ "description": "API representation of a soup item with its per-viewer enrichments."
},
"SoupApiSort": {
"type": "string",
diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsx
index 29bde1c752..410104e69b 100644
--- a/apps/web/src/routes/Root.tsx
+++ b/apps/web/src/routes/Root.tsx
@@ -232,6 +232,10 @@ const ROUTES: RouteDefinition[] = [
path: '/inbox',
component: LAYOUT_ROUTE.component,
},
+ {
+ path: '/recent',
+ component: LAYOUT_ROUTE.component,
+ },
{
path: '/activity',
component: LAYOUT_ROUTE.component,
diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts
index b25f986dea..b4ed10a00e 100644
--- a/apps/web/vitest.config.ts
+++ b/apps/web/vitest.config.ts
@@ -178,6 +178,7 @@ export default defineConfig({
'src/components/**/*.{test,spec}.{ts,tsx}',
'src/features/**/*.{test,spec}.{ts,tsx}',
'src/lib/analytics/**/*.{test,spec}.{ts,tsx}',
+ 'src/lib/constants/**/*.{test,spec}.{ts,tsx}',
'src/lib/fullcalendar-solid/**/*.{test,spec}.{ts,tsx}',
'src/routes/**/*.{test,spec}.{ts,tsx}',
],
diff --git a/crates/soup/src/domain/models.rs b/crates/soup/src/domain/models.rs
index 0568abfc3f..537d99bbbf 100644
--- a/crates/soup/src/domain/models.rs
+++ b/crates/soup/src/domain/models.rs
@@ -777,9 +777,6 @@ pub struct TouchedSoupRequest<'a> {
pub after: Option<TouchedPagePosition>,
/// Entity filters folded into the candidate query.
pub filter: Option<&'a EntityFilterAst>,
- /// Whether project rows belong in the feed (unexpanded soup only —
- /// expanded soup shows project contents rather than project rows).
- pub include_projects: bool,
/// Every inbox the caller can read; gates email-thread candidates.
pub link_ids: &'a [Uuid],
}
@@ -1043,6 +1040,10 @@ pub struct EnrichedSoupItem {
pub item: SoupItem<SoupPropertiesField>,
/// The aggregate frecency score, when requested and available.
pub frecency_score: Option<AggregateFrecency>,
+ /// The caller's latest own mutation of this entity, populated only when
+ /// the page was ordered by `touched_by_me`. Clients sort and optimistic-
+ /// reorder the touched feed on this value.
+ pub touched_at: Option<chrono::DateTime<chrono::Utc>>,
}
/// A soup request with optional grouping configuration.
diff --git a/crates/soup/src/domain/models/grouping.rs b/crates/soup/src/domain/models/grouping.rs
index cacfee24dc..19bbe9aea6 100644
--- a/crates/soup/src/domain/models/grouping.rs
+++ b/crates/soup/src/domain/models/grouping.rs
@@ -113,6 +113,7 @@ pub fn build_grouped_response(
.or_insert_with(|| EnrichedSoupItem {
item: grouped_item.item,
frecency_score: None,
+ touched_at: None,
});
}
diff --git a/crates/soup/src/domain/service.rs b/crates/soup/src/domain/service.rs
index bb6acff681..efe4f6df6e 100644
--- a/crates/soup/src/domain/service.rs
+++ b/crates/soup/src/domain/service.rs
@@ -67,14 +67,16 @@ mod tests;
struct SoupCandidate {
item: SoupItem<()>,
frecency_score: Option<AggregateFrecency>,
+ touched_at: Option<chrono::DateTime<chrono::Utc>>,
}
impl SoupCandidate {
- /// A candidate with no frecency loaded yet.
+ /// A candidate with no frecency or touch timestamp loaded yet.
fn plain(item: SoupItem<()>) -> Self {
SoupCandidate {
item,
frecency_score: None,
+ touched_at: None,
}
}
}
@@ -383,6 +385,7 @@ where
.map(|(soup_item, frecency)| SoupCandidate {
item: soup_item,
frecency_score: Some(frecency),
+ touched_at: None,
});
Ok(match res.len().cmp(&(limit as usize)) {
@@ -434,7 +437,6 @@ where
limit,
after,
filter: cursor.filter().as_ref(),
- include_projects: matches!(soup_type, SoupType::UnExpanded),
link_ids: &link_ids,
})
.await
@@ -454,13 +456,23 @@ where
.flatten();
let mut main_entities = Vec::new();
+ let mut project_entities = Vec::new();
let mut channel_ids = Vec::new();
let mut email_ids = Vec::new();
for candidate in &touched {
match candidate.entity.entity_type {
- EntityType::Document | EntityType::Chat | EntityType::Project => {
+ EntityType::Document | EntityType::Chat => {
main_entities.push(candidate.entity.copied())
}
+ // Projects are rows of this feed in both soup types, but the
+ // expanded by-ids query deliberately omits project rows, so
+ // under Expanded they hydrate through a separate unexpanded
+ // query. Under UnExpanded the main query is already the
+ // unexpanded one — projects ride it, saving a round trip.
+ EntityType::Project => match soup_type {
+ SoupType::Expanded => project_entities.push(candidate.entity.copied()),
+ SoupType::UnExpanded => main_entities.push(candidate.entity.copied()),
+ },
EntityType::Channel => match Uuid::parse_str(&candidate.entity.entity_id) {
Ok(id) => channel_ids.push(id),
Err(error) => {
@@ -525,8 +537,22 @@ where
.map_err(anyhow::Error::from)
.map_err(SoupErr::from)
};
- let (main_items, channel_candidates, email_candidates) = tokio::join!(
+ let project_items_fut = async {
+ if project_entities.is_empty() {
+ return Ok(Vec::new());
+ }
+ self.soup_storage
+ .unexpanded_soup_by_ids(AdvancedSortParams {
+ entities: &project_entities,
+ user_id: user.copied(),
+ })
+ .await
+ .map_err(anyhow::Error::from)
+ .map_err(SoupErr::from)
+ };
+ let (main_items, project_items, channel_candidates, email_candidates) = tokio::join!(
main_items_fut,
+ project_items_fut,
self.handle_comms_request(comms_request),
self.handle_email_request(email_request),
);
@@ -534,6 +560,7 @@ where
let mut items_by_entity: HashMap<(EntityType, String), SoupItem<()>> = HashMap::new();
for item in main_items?
.into_iter()
+ .chain(project_items?)
.chain(channel_candidates?.map(|c| c.item))
.chain(email_candidates?.map(|c| c.item))
{
@@ -557,7 +584,11 @@ where
tracing::warn!(entity_type = ?key.0, "touched entity did not hydrate; skipping");
None
})?;
- Some(SoupCandidate::plain(item))
+ Some(SoupCandidate {
+ item,
+ frecency_score: None,
+ touched_at: Some(candidate.touched_at),
+ })
})
.collect();
@@ -608,6 +639,7 @@ where
|(item, frecency_score)| SoupCandidate {
item,
frecency_score,
+ touched_at: None,
},
)))
}
@@ -633,6 +665,7 @@ where
SoupCandidate {
item: SoupItem::Channel(soup_channel),
frecency_score,
+ touched_at: None,
}
})
})?,
@@ -803,16 +836,16 @@ where
return Ok(Vec::new());
}
- let (items, frecency_scores): (Vec<_>, Vec<_>) = items
+ let (items, enrichments): (Vec<_>, Vec<_>) = items
.into_iter()
- .map(|item| (item.item, item.frecency_score))
+ .map(|item| (item.item, (item.frecency_score, item.touched_at)))
.unzip();
let items = self
.soup_storage
.populate_properties(user_id, items)
.await
.map_err(anyhow::Error::from)?;
- if items.len() != frecency_scores.len() {
+ if items.len() != enrichments.len() {
return Err(SoupErr::SoupDbErr(anyhow::anyhow!(
"property hydration changed the number of Soup items"
)));
@@ -820,10 +853,11 @@ where
Ok(items
.into_iter()
- .zip(frecency_scores)
- .map(|(item, frecency_score)| EnrichedSoupItem {
+ .zip(enrichments)
+ .map(|(item, (frecency_score, touched_at))| EnrichedSoupItem {
item,
frecency_score,
+ touched_at,
})
.collect())
}
@@ -921,6 +955,7 @@ where
.item
.map_extra(|()| SoupPropertiesField::default()),
frecency_score: candidate.frecency_score,
+ touched_at: candidate.touched_at,
})
}
diff --git a/crates/soup/src/domain/service/tests.rs b/crates/soup/src/domain/service/tests.rs
index 1228deecf2..cadcf7666d 100644
--- a/crates/soup/src/domain/service/tests.rs
+++ b/crates/soup/src/domain/service/tests.rs
@@ -2467,6 +2467,7 @@ async fn touched_soup_orders_by_touch_and_drops_unhydrated() {
let doc_1 = Uuid::from_u128(1);
let doc_2 = Uuid::from_u128(2);
let ghost = Uuid::from_u128(3);
+ let project = Uuid::from_u128(4);
let base: DateTime<Utc> = DateTime::default();
let mut soup_mock = MockSoupRepo::new();
@@ -2475,11 +2476,14 @@ async fn touched_soup_orders_by_touch_and_drops_unhydrated() {
.times(1)
.returning(move |req| {
assert!(req.after.is_none());
- assert!(!req.include_projects, "expanded soup excludes projects");
Box::pin(async move {
Ok(vec![
TouchedEntity {
entity: EntityType::Document.with_entity_string(doc_1.to_string()),
+ touched_at: base + Days::new(4),
+ },
+ TouchedEntity {
+ entity: EntityType::Project.with_entity_string(project.to_string()),
touched_at: base + Days::new(3),
},
TouchedEntity {
@@ -2506,6 +2510,42 @@ async fn touched_soup_orders_by_touch_and_drops_unhydrated() {
])
})
});
+ // Projects hydrate through the unexpanded by-ids query even in the
+ // expanded feed (the expanded one omits project rows by design).
+ soup_mock
+ .expect_unexpanded_soup_by_ids()
+ .times(1)
+ .returning(move |params| {
+ assert_eq!(params.entities.len(), 1);
+ assert_eq!(params.entities[0].entity_type, EntityType::Project);
+ Box::pin(async move {
+ Ok(vec![SoupItem::Project(models_soup::project::SoupProject {
+ id: project,
+ name: 'p'.to_string(),
+ owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ parent_id: None,
+ created_at: Default::default(),
+ updated_at: Default::default(),
+ viewed_at: Default::default(),
+ deleted_at: None,
+ extra: (),
+ })])
+ })
+ });
+
+ // Identity property hydration: the enriched page is asserted below so
+ // the per-item touch timestamps are covered too.
+ soup_mock
+ .expect_populate_properties()
+ .times(1)
+ .returning(|_, items| {
+ Box::pin(async move {
+ Ok(items
+ .into_iter()
+ .map(|item| item.map_extra(|()| SoupPropertiesField::default()))
+ .collect())
+ })
+ });
let page = SoupImpl::new(
soup_mock,
@@ -2517,7 +2557,7 @@ async fn touched_soup_orders_by_touch_and_drops_unhydrated() {
NoopForeignEntityService,
NoOpRemindersService,
)
- .get_user_soup(
+ .get_user_soup_with_properties(
SoupRequest {
sort_direction: SoupSortDirection::default(),
email_preview_view: PreviewView::StandardLabel(
@@ -2536,12 +2576,114 @@ async fn touched_soup_orders_by_touch_and_drops_unhydrated() {
.into_touched()
.unwrap();
- let ids: Vec<Uuid> = page.items.iter().map(|item| item.id()).collect();
- assert_eq!(ids, vec![doc_1, doc_2]);
- // Three candidates against a limit of 20: the feed is exhausted.
+ let ids: Vec<Uuid> = page.items.iter().map(|item| item.item.id()).collect();
+ assert_eq!(ids, vec![doc_1, project, doc_2]);
+ // Every touched item carries its own-mutation timestamp — clients sort
+ // and optimistically reorder the feed on it.
+ let touched: Vec<_> = page.items.iter().map(|item| item.touched_at).collect();
+ assert_eq!(
+ touched,
+ vec![
+ Some(base + Days::new(4)),
+ Some(base + Days::new(3)),
+ Some(base + Days::new(1)),
+ ]
+ );
+ // Four candidates against a limit of 20: the feed is exhausted.
assert!(page.next_cursor.is_none());
}
+/// Unexpanded touched pages hydrate projects through the main by-ids query —
+/// one round trip, not a separate project query (that split exists only for
+/// the expanded feed, whose by-ids query omits project rows by design).
+#[tokio::test]
+async fn unexpanded_touched_hydrates_projects_in_the_main_query() {
+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let doc = Uuid::from_u128(1);
+ let project = Uuid::from_u128(2);
+ let base: DateTime<Utc> = DateTime::default();
+
+ let mut soup_mock = MockSoupRepo::new();
+ soup_mock
+ .expect_touched_soup_page()
+ .times(1)
+ .returning(move |_req| {
+ Box::pin(async move {
+ Ok(vec![
+ TouchedEntity {
+ entity: EntityType::Document.with_entity_string(doc.to_string()),
+ touched_at: base + Days::new(2),
+ },
+ TouchedEntity {
+ entity: EntityType::Project.with_entity_string(project.to_string()),
+ touched_at: base + Days::new(1),
+ },
+ ])
+ })
+ });
+ // Exactly one by-ids call, carrying the document AND the project.
+ soup_mock
+ .expect_unexpanded_soup_by_ids()
+ .withf(move |params| {
+ params.entities.len() == 2
+ && params
+ .entities
+ .iter()
+ .any(|e| e.entity_type == EntityType::Project)
+ })
+ .times(1)
+ .returning(move |_params| {
+ Box::pin(async move {
+ Ok(vec![
+ SoupItem::Document(soup_document_uuid_with_updated(doc, Default::default())),
+ SoupItem::Project(models_soup::project::SoupProject {
+ id: project,
+ name: 'p'.to_string(),
+ owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ parent_id: None,
+ created_at: Default::default(),
+ updated_at: Default::default(),
+ viewed_at: Default::default(),
+ deleted_at: None,
+ extra: (),
+ }),
+ ])
+ })
+ });
+
+ let page = SoupImpl::new(
+ soup_mock,
+ FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),
+ NoopEmailPreviewService,
+ RecordingCommsService::new(vec![]),
+ NoopCallRecordQueryService,
+ NoOpCrmService,
+ NoopForeignEntityService,
+ NoOpRemindersService,
+ )
+ .get_user_soup(
+ SoupRequest {
+ sort_direction: SoupSortDirection::default(),
+ email_preview_view: PreviewView::StandardLabel(
+ email::domain::models::PreviewViewStandardLabel::Inbox,
+ ),
+ link_ids: vec![],
+ soup_type: SoupType::UnExpanded,
+ limit: 20,
+ cursor: SoupQuery::new_sort_touched(EntityFilters::default()),
+ user,
+ },
+ None,
+ )
+ .await
+ .unwrap()
+ .into_touched()
+ .unwrap();
+
+ let ids: Vec<Uuid> = page.items.iter().map(|item| item.id()).collect();
+ assert_eq!(ids, vec![doc, project]);
+}
+
#[tokio::test]
async fn touched_soup_full_page_builds_keyset_cursor() {
let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
diff --git a/crates/soup/src/inbound/axum_router.rs b/crates/soup/src/inbound/axum_router.rs
index 12b0968e8e..6201f93c49 100644
--- a/crates/soup/src/inbound/axum_router.rs
+++ b/crates/soup/src/inbound/axum_router.rs
@@ -692,12 +692,17 @@ where
.with_state(state)
}
-/// API representation of a soup item with its frecency score.
+/// API representation of a soup item with its per-viewer enrichments.
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct SoupApiItem {
#[serde(flatten)]
item: SoupItemWithProperties,
frecency_score: f64,
+ /// The caller's latest own mutation of this entity, present only when the
+ /// page was ordered by `touched_by_me`. Clients keep the touched feed
+ /// ordered on this value, so it can be bumped optimistically.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ touched_at: Option<chrono::DateTime<chrono::Utc>>,
/// Whether the requesting user has favorited this entity.
is_favorited: bool,
}
@@ -707,6 +712,7 @@ impl SoupApiItem {
let EnrichedSoupItem {
item,
frecency_score,
+ touched_at,
..
} = item;
SoupApiItem {
@@ -714,6 +720,7 @@ impl SoupApiItem {
frecency_score: frecency_score
.map(|f| f.data.frecency_score)
.unwrap_or_default(),
+ touched_at,
is_favorited: false,
}
}
diff --git a/crates/soup/src/outbound/pg_soup_repo/touched.rs b/crates/soup/src/outbound/pg_soup_repo/touched.rs
index ba886395d7..92aaa7098f 100644
--- a/crates/soup/src/outbound/pg_soup_repo/touched.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/touched.rs
@@ -176,8 +176,7 @@ fn included_types(req: &TouchedSoupRequest<'_>) -> Vec<&'static str> {
{
types.push(EntityType::Chat.into());
}
- if req.include_projects
- && !project_filter_is_impossible(req.filter.and_then(|f| f.project_filter.as_deref()))
+ if !project_filter_is_impossible(req.filter.and_then(|f| f.project_filter.as_deref()))
&& properties_filter_can_apply_to(props, &[PropertyEntityType::Project])
{
types.push(EntityType::Project.into());
diff --git a/crates/soup/src/outbound/pg_soup_repo/touched/test.rs b/crates/soup/src/outbound/pg_soup_repo/touched/test.rs
index f46eac8433..f68241bead 100644
--- a/crates/soup/src/outbound/pg_soup_repo/touched/test.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/touched/test.rs
@@ -25,7 +25,6 @@ fn req<'a>(
limit: 50,
after: None,
filter,
- include_projects: false,
link_ids,
}
}
@@ -40,20 +39,21 @@ fn keys(page: &[TouchedEntity]) -> Vec<(EntityType, String)> {
fixtures(path = "../../../../fixtures", scripts("touched_by_me")),
migrator = "MACRO_DB_MIGRATIONS"
)]
-async fn expanded_feed_orders_by_own_latest_mutation(pool: Pool<Postgres>) -> anyhow::Result<()> {
+async fn feed_orders_by_own_latest_mutation(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_ids = [Uuid::parse_str(LINK_1)?];
let page = touched_soup_page(&pool, req(USER_1, None, &link_ids)).await?;
// Exactly the touchable, visible entities — the deleted doc, isolated
- // doc, opened-only doc, left channel, foreign-inbox thread, and (in
- // expanded feeds) the project are all absent — ordered by user-1's own
- // latest mutation. user-2's newer edit of doc-B must not move it, and
- // chat-A's later `opened` must not outrank doc-A's edit.
+ // doc, opened-only doc, left channel, and foreign-inbox thread are all
+ // absent — ordered by user-1's own latest mutation. user-2's newer edit
+ // of doc-B must not move it, and chat-A's later `opened` must not
+ // outrank doc-A's edit.
assert_eq!(
keys(&page),
vec![
(EntityType::Document, DOC_A.to_string()),
(EntityType::Chat, CHAT_A.to_string()),
+ (EntityType::Project, PROJECT_A.to_string()),
(EntityType::Channel, CHANNEL_X.to_string()),
(EntityType::EmailThread, THREAD_Z.to_string()),
(EntityType::Document, DOC_B.to_string()),
@@ -68,32 +68,7 @@ async fn expanded_feed_orders_by_own_latest_mutation(pool: Pool<Postgres>) -> an
t.touched_at.minute()
})
.collect();
- assert_eq!(minutes, vec![9, 8, 6, 4, 2]);
-
- Ok(())
-}
-
-#[sqlx::test(
- fixtures(path = "../../../../fixtures", scripts("touched_by_me")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn unexpanded_feed_includes_projects(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let link_ids = [Uuid::parse_str(LINK_1)?];
- let mut request = req(USER_1, None, &link_ids);
- request.include_projects = true;
- let page = touched_soup_page(&pool, request).await?;
-
- assert_eq!(
- keys(&page),
- vec![
- (EntityType::Document, DOC_A.to_string()),
- (EntityType::Chat, CHAT_A.to_string()),
- (EntityType::Project, PROJECT_A.to_string()),
- (EntityType::Channel, CHANNEL_X.to_string()),
- (EntityType::EmailThread, THREAD_Z.to_string()),
- (EntityType::Document, DOC_B.to_string()),
- ]
- );
+ assert_eq!(minutes, vec![9, 8, 7, 6, 4, 2]);
Ok(())
}
@@ -127,7 +102,7 @@ async fn keyset_paginates_without_overlap_or_gaps(pool: Pool<Postgres>) -> anyho
// Walking in pages of 2 yields the same feed as one big page.
let one_page = touched_soup_page(&pool, req(USER_1, None, &link_ids)).await?;
assert_eq!(keys(&all), keys(&one_page));
- assert_eq!(all.len(), 5);
+ assert_eq!(all.len(), 6);
Ok(())
}
@@ -152,6 +127,7 @@ async fn entity_filters_compose_with_the_touch_gate(pool: Pool<Postgres>) -> any
vec![
(EntityType::Document, DOC_A.to_string()),
(EntityType::Chat, CHAT_A.to_string()),
+ (EntityType::Project, PROJECT_A.to_string()),
(EntityType::Channel, CHANNEL_X.to_string()),
(EntityType::EmailThread, THREAD_Z.to_string()),
]
@@ -166,19 +142,13 @@ fn view_tags_render_as_quoted_list() {
}
#[test]
-fn no_filter_includes_every_expanded_type_with_inboxes() {
+fn no_filter_includes_every_touchable_type_with_inboxes() {
let link_ids = [uuid::Uuid::from_u128(1)];
let types = included_types(&req("macro|[email protected]", None, &link_ids));
- assert_eq!(types, vec!["document", "chat", "channel", "email_thread"]);
-}
-
-#[test]
-fn projects_join_only_unexpanded_feeds() {
- let link_ids = [uuid::Uuid::from_u128(1)];
- let mut request = req("macro|[email protected]", None, &link_ids);
- request.include_projects = true;
- let types = included_types(&request);
- assert!(types.contains(&"project"));
+ assert_eq!(
+ types,
+ vec!["document", "chat", "project", "channel", "email_thread"]
+ );
}
#[test]
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index bbaea1bc05..7424a49f22 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -6656,7 +6656,7 @@ export type SimpleMention = {
};
/**
- * API representation of a soup item with its frecency score.
+ * API representation of a soup item with its per-viewer enrichments.
*/
export type SoupApiItem = SoupItem & {
frecency_score: number;
@@ -6664,6 +6664,12 @@ export type SoupApiItem = SoupItem & {
* Whether the requesting user has favorited this entity.
*/
is_favorited: boolean;
+ /**
+ * The caller's latest own mutation of this entity, present only when the
+ * page was ordered by `touched_by_me`. Clients keep the touched feed
+ * ordered on this value, so it can be bumped optimistically.
+ */
+ touched_at?: string | null;
};
/**
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 4412fefbba..938bdd3904 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -21869,11 +21869,16 @@
"is_favorited": {
"type": "boolean",
"description": "Whether the requesting user has favorited this entity."
+ },
+ "touched_at": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "The caller's latest own mutation of this entity, present only when the\npage was ordered by `touched_by_me`. Clients keep the touched feed\nordered on this value, so it can be bumped optimistically."
}
}
}
],
- "description": "API representation of a soup item with its frecency score."
+ "description": "API representation of a soup item with its per-viewer enrichments."
},
"SoupApiSort": {
"type": "string",