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(activity): show teammates' activity in a Team tab (#8626)

teoc982c833030c
diff --git a/.sqlx/query-c5890947b333902d164537b40ed6ae9b774c08eabbfe70bc0473504531ce3071.json b/.sqlx/query-c5890947b333902d164537b40ed6ae9b774c08eabbfe70bc0473504531ce3071.json
new file mode 100644
index 0000000000..85214ba5bc
--- /dev/null
+++ b/.sqlx/query-c5890947b333902d164537b40ed6ae9b774c08eabbfe70bc0473504531ce3071.json
@@ -0,0 +1,75 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "-- One page of the viewer's teammates' activity on entities shared with the\n-- viewer. See `team_feed.rs` for the paging contract.\n--\n-- $1 viewer id, $2/$3 cursor position (NULL for the first page),\n-- $4 rows to return, $5 fewest raw rows one teammate's scan reads,\n-- $6 raw rows one page reads across all teammates.\nWITH viewer_source AS (\n -- The principals an `entity_access` grant can name to reach the viewer:\n -- the viewer, their teams, and the channels they are active in.\n SELECT 'user'::entity_access_source_type AS source_type, $1::text AS source_id\n UNION ALL\n SELECT 'team', tu.team_id::text FROM team_user tu WHERE tu.user_id = $1\n UNION ALL\n SELECT 'channel', cp.channel_id::text\n FROM comms_channel_participants cp\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n),\nviewer_inbox AS (\n -- Inboxes whose threads the viewer owns: their own links and those\n -- delegated to them as primary.\n SELECT l.id AS link_id FROM email_links l WHERE l.macro_id = $1\n UNION\n SELECT mul.link_id FROM macro_user_links mul WHERE mul.primary_macro_id = $1\n),\nteammate AS (\n SELECT DISTINCT member.user_id\n FROM team_user viewer\n JOIN team_user member ON member.team_id = viewer.team_id\n WHERE viewer.user_id = $1 AND member.user_id <> $1\n),\nscan AS (\n SELECT GREATEST($5, $6 / GREATEST(count(*), 1))::bigint AS rows FROM teammate\n),\nscanned AS (\n -- Per teammate, one seek of the subject index that stops at $4 visible\n -- rows or after `scan.rows` raw rows. A scan that stops at that cap\n -- also emits its last raw row (`scan_rank = scan.rows`) as a frontier.\n SELECT s.*\n FROM teammate t\n CROSS JOIN LATERAL (\n SELECT w.*\n FROM (\n SELECT e.*,\n row_number() OVER (ORDER BY e.occurred_at DESC, e.id DESC) AS scan_rank,\n -- Mirrors `EntityAccessService::get_users_by_entity` for\n -- every entity type activity records; anything else is\n -- hidden. Forms are hidden too: their rows name\n -- respondents, so they reach only their subject.\n CASE\n WHEN e.entity_type = 'channel' THEN e.entity_id IN (\n SELECT vs.source_id FROM viewer_source vs\n WHERE vs.source_type = 'channel'\n )\n -- A call's audience is its channel's, or its direct\n -- user grants when it has none.\n WHEN e.entity_type = 'call' THEN EXISTS (\n SELECT 1 FROM call_entities ce\n WHERE ce.id = e.entity_uuid\n AND CASE\n WHEN ce.channel_id IS NULL THEN EXISTS (\n SELECT 1 FROM entity_access ea\n WHERE ea.entity_id = ce.id AND ea.entity_type = 'call'\n AND ea.source_type = 'user' AND ea.source_id = $1\n AND ea.granted_from_project_id IS NULL\n )\n ELSE ce.channel_id::text IN (\n SELECT vs.source_id FROM viewer_source vs\n WHERE vs.source_type = 'channel'\n )\n END\n )\n WHEN e.entity_type IN (\n 'document', 'project', 'chat', 'initiative', 'database',\n 'crm_company', 'email_thread'\n ) THEN EXISTS (\n SELECT 1 FROM entity_access ea\n WHERE ea.entity_id::text = e.entity_id\n AND ea.entity_type = e.entity_type\n AND (ea.source_type, ea.source_id) IN (\n SELECT vs.source_type, vs.source_id FROM viewer_source vs\n )\n ) OR (e.entity_type = 'email_thread' AND EXISTS (\n SELECT 1 FROM email_threads et\n WHERE et.id = e.entity_uuid\n AND et.link_id IN (SELECT vi.link_id FROM viewer_inbox vi)\n ))\n ELSE false\n END AS visible\n FROM (\n SELECT e.id, e.actor_id, e.action, e.action_payload, e.subject_id,\n e.entity_type, e.entity_id, e.occurred_at,\n -- Only these id columns are uuids; a malformed id\n -- must hide its row, not fail the page.\n CASE WHEN e.entity_type IN ('call', 'email_thread') THEN\n CASE WHEN e.entity_id ~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'\n THEN e.entity_id::uuid\n END\n END AS entity_uuid\n FROM activity_events e\n WHERE e.subject_id = t.user_id\n -- No cursor reads from the top. COALESCE, unlike an\n -- `IS NULL OR` branch, keeps this an index condition in\n -- generic plans.\n AND (e.occurred_at, e.id) < (\n COALESCE($2::timestamptz, 'infinity'),\n COALESCE($3::uuid, 'ffffffff-ffff-ffff-ffff-ffffffffffff')\n )\n ORDER BY e.occurred_at DESC, e.id DESC\n LIMIT (SELECT rows FROM scan)\n ) e\n ) w\n WHERE w.visible OR w.scan_rank = (SELECT rows FROM scan)\n LIMIT $4\n ) s\n),\nboundary AS (\n -- The newest frontier: below it some teammate's rows were not read.\n SELECT * FROM scanned\n WHERE scan_rank = (SELECT rows FROM scan)\n ORDER BY occurred_at DESC, id DESC\n LIMIT 1\n)\n(\n SELECT s.id AS \"id!\", s.actor_id AS \"actor_id!\", s.action AS \"action!\",\n s.action_payload, s.subject_id AS \"subject_id!\",\n s.entity_type AS \"entity_type!\", s.entity_id AS \"entity_id!\",\n s.occurred_at AS \"occurred_at!\", false AS \"is_boundary!\"\n FROM scanned s\n WHERE s.visible\n AND NOT EXISTS (\n SELECT 1 FROM boundary b WHERE (s.occurred_at, s.id) < (b.occurred_at, b.id)\n )\n ORDER BY s.occurred_at DESC, s.id DESC\n LIMIT $4\n)\nUNION ALL\nSELECT b.id, b.actor_id, b.action, b.action_payload, b.subject_id, b.entity_type,\n b.entity_id, b.occurred_at, true\nFROM boundary b\n",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "actor_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "action!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "action_payload",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 4,
+ "name": "subject_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "entity_type!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "entity_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "occurred_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "is_boundary!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz",
+ "Uuid",
+ "Int8",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null
+ ]
+ },
+ "hash": "c5890947b333902d164537b40ed6ae9b774c08eabbfe70bc0473504531ce3071"
+}
diff --git a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx
index 240c1cb7e9..337a9eee54 100644
--- a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx
+++ b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx
@@ -41,6 +41,7 @@ vi.mock('@service-connection/websocket', () => ({
vi.mock('@app/lib/split-router', async (importOriginal) => ({
...(await importOriginal<typeof import('@app/lib/split-router')>()),
useSplitRouter: () => ({ entry: () => undefined }),
+ createSearchParams: () => [{ scope: 'mine' }, vi.fn()],
}));
vi.mock('@core/auth', () => ({
useIsAuthenticated: () => () => state.authenticated(),
diff --git a/apps/web/src/features/activity/activity-search.ts b/apps/web/src/features/activity/activity-search.ts
new file mode 100644
index 0000000000..c6e3f50fd2
--- /dev/null
+++ b/apps/web/src/features/activity/activity-search.ts
@@ -0,0 +1,9 @@
+import { z } from 'zod';
+import type { ActivityScope } from './core/event';
+
+/** The Activity screen's search namespace: which feed tab is open. */
+export const activitySearch = {
+ namespace: 'activity',
+ schema: z.object({ scope: z.enum(['mine', 'team']) }),
+ defaults: { scope: 'mine' as ActivityScope },
+};
diff --git a/apps/web/src/features/activity/components/activity-scope-tabs.tsx b/apps/web/src/features/activity/components/activity-scope-tabs.tsx
new file mode 100644
index 0000000000..8fe5c37e31
--- /dev/null
+++ b/apps/web/src/features/activity/components/activity-scope-tabs.tsx
@@ -0,0 +1,37 @@
+import { PillTabs } from '@components/app/mobile/PillTabs';
+import { Tabs } from '@ui';
+import type { ActivityScope } from '../core/event';
+
+const SCOPE_TABS: { value: ActivityScope; label: string }[] = [
+ { value: 'mine', label: 'You' },
+ { value: 'team', label: 'Team' },
+];
+
+/** The You / Team switch, as view tabs after the split header title. */
+export function ActivityScopeTabs(props: {
+ value: ActivityScope;
+ onChange: (scope: ActivityScope) => void;
+}) {
+ return (
+ <Tabs
+ aria-label="Whose activity"
+ options={SCOPE_TABS}
+ value={props.value}
+ onChange={props.onChange}
+ />
+ );
+}
+
+/** The same switch as the touch pill strip, under the floating header. */
+export function ActivityScopePills(props: {
+ value: ActivityScope;
+ onChange: (scope: ActivityScope) => void;
+}) {
+ return (
+ <PillTabs
+ items={SCOPE_TABS}
+ value={props.value}
+ onChange={props.onChange}
+ />
+ );
+}
diff --git a/apps/web/src/features/activity/core/event.ts b/apps/web/src/features/activity/core/event.ts
index 9ae020e1b4..2d4a7495fc 100644
--- a/apps/web/src/features/activity/core/event.ts
+++ b/apps/web/src/features/activity/core/event.ts
@@ -17,6 +17,12 @@ export type ActivityAction =
| { kind: 'task-removed'; taskId?: string }
| { kind: 'unknown'; tag: string };
+/**
+ * Whose activity the Activity screen reads: the viewer's own, or their
+ * teammates' on items shared with the viewer.
+ */
+export type ActivityScope = 'mine' | 'team';
+
export type ActivityEntityType =
| 'document'
| 'project'
diff --git a/apps/web/src/features/activity/primitives/my-activity.test.ts b/apps/web/src/features/activity/primitives/my-activity.test.ts
index b4a51a6c3b..5e5a441579 100644
--- a/apps/web/src/features/activity/primitives/my-activity.test.ts
+++ b/apps/web/src/features/activity/primitives/my-activity.test.ts
@@ -1,6 +1,7 @@
-import { createRoot } from 'solid-js';
+import { createRoot, createSignal } from 'solid-js';
import { afterEach, describe, expect, it } from 'vitest';
import { entryHead } from '../core/collapse-runs';
+import type { ActivityScope } from '../core/event';
import { createdEvent, editedEvent } from '../queries/fixtures';
import { createMockActivityContext } from '../tests/mock-context';
import { feedPage, overviewPage } from '../tests/wire';
@@ -17,7 +18,7 @@ function setup() {
const context = createMockActivityContext();
let state!: MyActivityState;
const dispose = createRoot((rootDispose) => {
- state = createMyActivityState(context);
+ state = createMyActivityState(context, () => 'mine');
return rootDispose;
});
disposals.push(dispose);
@@ -64,7 +65,7 @@ describe('createMyActivityState', () => {
let state!: MyActivityState;
disposals.push(
createRoot((dispose) => {
- state = createMyActivityState(context);
+ state = createMyActivityState(context, () => 'mine');
return dispose;
})
);
@@ -235,4 +236,84 @@ describe('createMyActivityState', () => {
if (overview.t !== 'ready') throw new Error(overview.t);
expect(overview.overview.total).toBe(3);
});
+
+ describe('team scope', () => {
+ const teammateEdit = {
+ ...editedEvent,
+ id: 'evt-team',
+ actorId: 'macro|[email protected]',
+ subjectId: 'macro|[email protected]',
+ };
+
+ function setupScoped(initial: ActivityScope) {
+ const context = createMockActivityContext();
+ const [scope, setScope] = createSignal<ActivityScope>(initial);
+ let state!: MyActivityState;
+ disposals.push(
+ createRoot((dispose) => {
+ state = createMyActivityState(context, scope);
+ return dispose;
+ })
+ );
+ return { state, setScope, graphql: context.graphqlMock };
+ }
+
+ const feedRequests = (graphql: ReturnType<typeof setupScoped>['graphql']) =>
+ graphql.pending
+ .filter((op) => op.name === 'MyActivity')
+ .map((op) => op.variables);
+
+ const feedIds = (state: MyActivityState) => {
+ const feed = state.feed();
+ if (feed.t !== 'ready') return feed.t;
+ return feed.groups.flatMap((g) => g.entries.map((e) => entryHead(e).id));
+ };
+
+ it('reads the team feed and leaves out the overview row', () => {
+ const { state, graphql } = setupScoped('team');
+
+ expect(feedRequests(graphql)).toEqual([
+ { input: { limit: 50, cursor: null, scope: 'TEAM' } },
+ ]);
+ expect(state.rows().map((row) => row.kind)).toEqual(['status']);
+
+ graphql.latest('MyActivity').resolve(feedPage([teammateEdit]));
+
+ expect(feedIds(state)).toEqual(['evt-team']);
+ expect(state.rows().map((row) => row.kind)).toEqual(['day', 'entry']);
+ });
+
+ it('keeps paging through empty pages before calling the feed empty', () => {
+ const { state, graphql } = setupScoped('team');
+ graphql.latest('MyActivity').resolve(feedPage([], 'c2'));
+
+ // Nothing visible yet, but more pages remain: the tail, not the empty copy.
+ expect(state.rows().map((row) => row.kind)).toEqual(['tail']);
+ state.loadMore();
+ expect(graphql.latest('MyActivity').variables).toEqual({
+ input: { limit: 50, cursor: 'c2', scope: 'TEAM' },
+ });
+ graphql.latest('MyActivity').resolve(feedPage([], null));
+
+ expect(state.feed().t).toBe('empty');
+ });
+
+ it("never shows one tab the other tab's rows, and keeps both feeds", () => {
+ const { state, setScope, graphql } = setupScoped('mine');
+ graphql.latest('MyActivity').resolve(feedPage([createdEvent]));
+ expect(feedIds(state)).toEqual(['evt-1']);
+
+ setScope('team');
+ expect(state.feed().t).toBe('loading');
+ expect(graphql.latest('MyActivity').variables).toEqual({
+ input: { limit: 50, cursor: null, scope: 'TEAM' },
+ });
+ graphql.latest('MyActivity').resolve(feedPage([teammateEdit]));
+ expect(feedIds(state)).toEqual(['evt-team']);
+
+ setScope('mine');
+ expect(feedIds(state)).toEqual(['evt-1']);
+ expect(state.rows()[0]?.kind).toBe('overview');
+ });
+ });
});
diff --git a/apps/web/src/features/activity/primitives/my-activity.ts b/apps/web/src/features/activity/primitives/my-activity.ts
index 3e5308ec9e..e3d992fcb9 100644
--- a/apps/web/src/features/activity/primitives/my-activity.ts
+++ b/apps/web/src/features/activity/primitives/my-activity.ts
@@ -1,7 +1,7 @@
import { fireAndForget } from '@core/util/fireAndForget';
import { type Accessor, createMemo } from 'solid-js';
import type { ActivityContext } from '../context/activity-context';
-import type { ActivityOverview } from '../core/event';
+import type { ActivityOverview, ActivityScope } from '../core/event';
import { type FeedRow, flattenFeed, reuseRows } from '../core/feed-rows';
import { type FeedGroup, groupEventsByDay } from '../core/group-events';
import { createMyActivityQuery } from '../queries/feed-query';
@@ -28,7 +28,11 @@ export type OverviewView =
export type MyActivityState = {
overview: Accessor<OverviewView>;
feed: Accessor<FeedView>;
- /** Every virtualized row of the screen: the overview first, then the feed. */
+ /**
+ * Every virtualized row of the screen: on the viewer's own feed the
+ * overview first, then the feed. The overview is the viewer's own, so the
+ * team feed has none.
+ */
rows: Accessor<FeedRow[]>;
/**
* Fetch the next feed page. No-op while one is in flight, none remain, or
@@ -42,19 +46,30 @@ export type MyActivityState = {
/**
* The Activity screen as data: overview and feed view states plus the one
- * action the screen exposes. Data wins over status flags so a background
- * refetch never blanks rows the user is reading.
+ * action the screen exposes, for the feed `scope` selects. Each scope keeps
+ * its own query, so switching tabs never shows the other feed's rows and
+ * switching back finds the pages already loaded. Data wins over status
+ * flags so a background refetch never blanks rows the user is reading.
*/
export function createMyActivityState(
- context: Pick<ActivityContext, 'graphql' | 'entityTypeShown'>
+ context: Pick<ActivityContext, 'graphql' | 'entityTypeShown'>,
+ scope: Accessor<ActivityScope>
): MyActivityState {
const overviewQuery = createMyActivityOverviewQuery(context, {
enabled: () => true,
});
- const feedQuery = createMyActivityQuery(context, { enabled: () => true });
+ const mineQuery = createMyActivityQuery(context, {
+ scope: 'mine',
+ enabled: () => scope() === 'mine',
+ });
+ const teamQuery = createMyActivityQuery(context, {
+ scope: 'team',
+ enabled: () => scope() === 'team',
+ });
+ const feedQuery = () => (scope() === 'team' ? teamQuery : mineQuery);
const groups = createMemo(() =>
groupEventsByDay(
- (feedQuery.data ?? []).filter((event) =>
+ (feedQuery().data ?? []).filter((event) =>
context.entityTypeShown(event.entityType)
)
)
@@ -77,17 +92,20 @@ export function createMyActivityState(
});
const feed = createMemo<FeedView>(() => {
- if (groups().length > 0) {
+ const query = feedQuery();
+ // A team page can arrive empty while older pages remain (the server
+ // bounds each page's scan), so only the last page decides "empty".
+ if (groups().length > 0 || query.hasNextPage) {
return {
t: 'ready',
groups: groups(),
- hasMore: feedQuery.hasNextPage,
- loadingMore: feedQuery.isFetchingNextPage,
- moreFailed: feedQuery.isFetchNextPageError,
+ hasMore: query.hasNextPage,
+ loadingMore: query.isFetchingNextPage,
+ moreFailed: query.isFetchNextPageError,
};
}
- if (feedQuery.isLoading) return { t: 'loading' };
- if (feedQuery.isError) return { t: 'error' };
+ if (query.isLoading) return { t: 'loading' };
+ if (query.isError) return { t: 'error' };
return { t: 'empty' };
});
@@ -97,12 +115,16 @@ export function createMyActivityState(
current.t === 'ready'
? flattenFeed(current.groups, { hasMore: current.hasMore })
: [{ kind: 'status', status: current.t }];
- return reuseRows(previous, [{ kind: 'overview' }, ...feedRows]);
+ return reuseRows(
+ previous,
+ scope() === 'team' ? feedRows : [{ kind: 'overview' }, ...feedRows]
+ );
}, []);
const fetchNext = () => {
- if (!feedQuery.hasNextPage || feedQuery.isFetchingNextPage) return;
- fireAndForget(feedQuery.fetchNextPage(), 'activity');
+ const query = feedQuery();
+ if (!query.hasNextPage || query.isFetchingNextPage) return;
+ fireAndForget(query.fetchNextPage(), 'activity');
};
return {
@@ -110,7 +132,7 @@ export function createMyActivityState(
feed,
rows,
loadMore: () => {
- if (feedQuery.isFetchNextPageError) return;
+ if (feedQuery().isFetchNextPageError) return;
fetchNext();
},
retryMore: fetchNext,
diff --git a/apps/web/src/features/activity/queries/feed-query.ts b/apps/web/src/features/activity/queries/feed-query.ts
index f4f14e83f3..21a275434f 100644
--- a/apps/web/src/features/activity/queries/feed-query.ts
+++ b/apps/web/src/features/activity/queries/feed-query.ts
@@ -1,5 +1,6 @@
import { createUrqlInfiniteQuery } from '@app/lib/urql-solid/create-urql-infinite-query';
import {
+ type ActivityFeedInput,
MyActivityDocument,
type MyActivityQuery,
type MyActivityQueryVariables,
@@ -7,19 +8,32 @@ import {
import { type Accessor, createMemo, onCleanup } from 'solid-js';
import { registerActivityRevalidator } from '../../../lib/queries/activity/push-registry';
import type { ActivityContext } from '../context/activity-context';
-import type { ActivityEvent } from '../core/event';
+import type { ActivityEvent, ActivityScope } from '../core/event';
import { decodeActivityEvent } from './decode';
/** Rows fetched per feed page. */
export const ACTIVITY_FEED_PAGE_LIMIT = 50;
/**
- * Infinite query over the authenticated user's own activity, newest first.
- * Pages chase the server's opaque keyset cursor until it comes back null.
+ * One page request for a feed. The viewer's own feed leaves `scope` out, so
+ * it reads the same against servers that predate the team scope.
+ */
+function feedInput(
+ scope: ActivityScope,
+ cursor: string | null
+): ActivityFeedInput {
+ const page = { limit: ACTIVITY_FEED_PAGE_LIMIT, cursor };
+ return scope === 'team' ? { ...page, scope: 'TEAM' } : page;
+}
+
+/**
+ * Infinite query over one activity feed, newest first: the authenticated
+ * user's own, or their teammates' on items shared with the user. Pages chase
+ * the server's opaque keyset cursor until it comes back null.
*/
export function createMyActivityQuery(
context: Pick<ActivityContext, 'graphql'>,
- options: { enabled: Accessor<boolean> }
+ options: { scope: ActivityScope; enabled: Accessor<boolean> }
) {
const client = createMemo(context.graphql);
const result = createUrqlInfiniteQuery<
@@ -31,9 +45,7 @@ export function createMyActivityQuery(
query: MyActivityDocument,
client: client(),
initialPageParam: null,
- variables: (cursor) => ({
- input: { limit: ACTIVITY_FEED_PAGE_LIMIT, cursor },
- }),
+ variables: (cursor) => ({ input: feedInput(options.scope, cursor) }),
getNextPageParam: (lastPage) =>
lastPage.user.activity.nextCursor ?? undefined,
enabled: options.enabled(),
diff --git a/apps/web/src/features/activity/queries/realtime.test.ts b/apps/web/src/features/activity/queries/realtime.test.ts
index f952bb9dea..ca16e0bca0 100644
--- a/apps/web/src/features/activity/queries/realtime.test.ts
+++ b/apps/web/src/features/activity/queries/realtime.test.ts
@@ -23,7 +23,10 @@ describe('mounted activity realtime queries', () => {
const queries = createRoot((dispose) => {
disposals.push(dispose);
return {
- feed: createMyActivityQuery(context, { enabled: () => true }),
+ feed: createMyActivityQuery(context, {
+ scope: 'mine',
+ enabled: () => true,
+ }),
overview: createMyActivityOverviewQuery(context, {
enabled: () => true,
}),
@@ -74,7 +77,10 @@ describe('mounted activity realtime queries', () => {
let dispose!: () => void;
createRoot((cleanup) => {
dispose = cleanup;
- createMyActivityQuery({ graphql: client }, { enabled: () => true });
+ createMyActivityQuery(
+ { graphql: client },
+ { scope: 'mine', enabled: () => true }
+ );
});
disposals.push(dispose);
first.latest('MyActivity').resolve(feedPage([]));
diff --git a/apps/web/src/features/activity/route-views.tsx b/apps/web/src/features/activity/route-views.tsx
index 4f1c1856c5..55e946358c 100644
--- a/apps/web/src/features/activity/route-views.tsx
+++ b/apps/web/src/features/activity/route-views.tsx
@@ -1,10 +1,12 @@
import { usePosthog } from '@app/lib/analytics/posthog';
+import { createSearchParams } from '@app/lib/split-router';
import {
RedirectSplit,
usePageViewTracking,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
import { lazy, Show } from 'solid-js';
+import { activitySearch } from './activity-search';
import { openEntityInSplit } from './open-entity-in-split';
import { useActivityFeedFlag } from './use-activity-feed-flag';
@@ -14,7 +16,14 @@ const MyActivityView = lazy(async () => ({
function TrackedActivityView() {
usePageViewTracking('activity');
- return <MyActivityView onOpen={openEntityInSplit} />;
+ const [search, setSearch] = createSearchParams(activitySearch);
+ return (
+ <MyActivityView
+ scope={search.scope}
+ onScopeChange={(scope) => setSearch({ scope }, { history: 'replace' })}
+ onOpen={openEntityInSplit}
+ />
+ );
}
export const ActivityRouteView = withAuth(() => {
diff --git a/apps/web/src/features/activity/views/my-activity-view.test.tsx b/apps/web/src/features/activity/views/my-activity-view.test.tsx
index 12f7e6b97a..e67672b40e 100644
--- a/apps/web/src/features/activity/views/my-activity-view.test.tsx
+++ b/apps/web/src/features/activity/views/my-activity-view.test.tsx
@@ -1,7 +1,8 @@
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
-import type { JSX } from 'solid-js';
+import { createSignal, type JSX } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { ActivityContextProvider } from '../context/activity-context';
+import type { ActivityScope } from '../core/event';
import { placeholderOverview } from '../core/placeholder-overview';
import {
createdEvent,
@@ -30,6 +31,7 @@ const virtual = vi.hoisted(() => {
viewportSize: 800,
scrollOffset: 0,
findItemIndex: (offset: number) => Math.floor(offset / rowPx),
+ scrollTo: vi.fn(),
},
};
});
@@ -97,15 +99,21 @@ afterEach(cleanup);
const settle = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
-function renderView() {
+function renderView(initialScope: ActivityScope = 'mine') {
const context = createMockActivityContext();
const onOpen = vi.fn();
+ const [scope, setScope] = createSignal<ActivityScope>(initialScope);
+ const onScopeChange = vi.fn(setScope);
const result = render(() => (
<ActivityContextProvider value={context}>
- <MyActivityView onOpen={onOpen} />
+ <MyActivityView
+ scope={scope()}
+ onScopeChange={onScopeChange}
+ onOpen={onOpen}
+ />
</ActivityContextProvider>
));
- return { ...result, onOpen, graphql: context.graphqlMock };
+ return { ...result, onOpen, onScopeChange, graphql: context.graphqlMock };
}
const rows = () => document.querySelectorAll('[data-activity-row]');
@@ -340,6 +348,69 @@ describe('MyActivityView', () => {
expect(container.textContent).toContain('No activity yet.');
});
+ it('switches to the team feed from the header tabs', () => {
+ const { container, graphql, onScopeChange } = renderView();
+ graphql.latest('MyActivity').resolve(feedPage([createdEvent]));
+ graphql.latest('MyActivityOverview').resolve(overviewPage());
+ expect(container.querySelector('[data-activity-day]')).not.toBeNull();
+ expect(screen.getByText('sarah')).toBeTruthy();
+ virtual.handle.scrollTo.mockClear();
+
+ fireEvent.click(screen.getByRole('radio', { name: 'Team' }));
+
+ expect(onScopeChange).toHaveBeenLastCalledWith('team');
+ expect(virtual.handle.scrollTo).toHaveBeenCalledWith(0);
+ expect(graphql.latest('MyActivity').variables).toEqual({
+ input: { limit: 50, cursor: null, scope: 'TEAM' },
+ });
+ // The overview is the viewer's own, so the team feed has no graph.
+ expect(container.querySelector('[data-activity-day]')).toBeNull();
+ expect(screen.queryByText('sarah')).toBeNull();
+
+ graphql.latest('MyActivity').resolve(
+ feedPage([
+ {
+ ...editedEvent,
+ id: 'evt-team',
+ actorId: 'macro|[email protected]',
+ subjectId: 'macro|[email protected]',
+ },
+ ])
+ );
+ expect(rows()).toHaveLength(1);
+ expect(screen.getByText('priya')).toBeTruthy();
+ });
+
+ it('pins no day header over the team feed until it scrolls', () => {
+ const { container, graphql } = renderView('team');
+ graphql.latest('MyActivity').resolve(
+ feedPage([
+ {
+ ...createdEvent,
+ id: 't-today',
+ occurredAt: new Date().toISOString(),
+ },
+ ])
+ );
+ const pinned = () => container.querySelector('[data-activity-pinned-day]');
+ const scroll = virtual.onScroll;
+ if (!scroll) throw new Error('virtualizer did not register onScroll');
+
+ expect(pinned()).toBeNull();
+
+ scroll(virtual.rowPx);
+ expect(pinned()?.textContent).toBe('Today');
+
+ scroll(0);
+ expect(pinned()).toBeNull();
+ });
+
+ it('shows team empty copy when teammates have no activity', () => {
+ const { container, graphql } = renderView('team');
+ graphql.latest('MyActivity').resolve(feedPage([]));
+ expect(container.textContent).toContain('No activity from your team yet.');
+ });
+
it('renders the most active entities as chips under the graph and opens them', () => {
const { container, onOpen, graphql } = renderView();
graphql.latest('MyActivityOverview').resolve(
diff --git a/apps/web/src/features/activity/views/my-activity-view.tsx b/apps/web/src/features/activity/views/my-activity-view.tsx
index fa3873ee68..a325c6b328 100644
--- a/apps/web/src/features/activity/views/my-activity-view.tsx
+++ b/apps/web/src/features/activity/views/my-activity-view.tsx
@@ -1,6 +1,7 @@
import { SoupSectionHeader } from '@app/features/next-soup/soup-view/section-header';
import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeader';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { createElementSize } from '@solid-primitives/resize-observer';
import {
createEffect,
@@ -16,6 +17,10 @@ import {
import { match } from 'ts-pattern';
import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';
import { ActionGraph } from '../components/action-graph';
+import {
+ ActivityScopePills,
+ ActivityScopeTabs,
+} from '../components/activity-scope-tabs';
import { ActivityTimelineRow as ActivityTimelineRowView } from '../components/activity-timeline-row';
import { TopEntitiesSection, TopEntityChip } from '../components/top-entities';
import {
@@ -23,7 +28,7 @@ import {
useActivityContext,
} from '../context/activity-context';
import { entryHead, type FeedEntry } from '../core/collapse-runs';
-import type { ActivityTopEntity } from '../core/event';
+import type { ActivityScope, ActivityTopEntity } from '../core/event';
import {
type FeedRow,
pinnedDayLabel,
@@ -59,9 +64,10 @@ function FeedStatus(props: { children: JSX.Element }) {
}
/**
- * The user's own activity, newest first, as one virtualized list with the
- * overview card as its first row. Scrolling near the end fetches the next
- * page. Reads `ActivityContext`; the host decides what a row click opens.
+ * The user's own activity or their team's, newest first, as one virtualized
+ * list; the user's own feed has the overview card as its first row. The
+ * host owns the selected `scope` and decides what a row click opens.
+ * Scrolling near the end fetches the next page. Reads `ActivityContext`.
*
* Rows are absolutely positioned by the virtualizer, so a day header cannot
* stick on its own. Instead a zero-height sticky slot at the head of the
@@ -69,22 +75,31 @@ function FeedStatus(props: { children: JSX.Element }) {
*
* On full-frame touch devices the split header floats over the content, so
* an in-scroll spacer (measured, then handed to virtua as `startMargin`, the
- * `SoupList` pattern) rests the list below it and the pinned header sticks
- * under it; a matching spacer clears the bottom toolbar.
+ * `SoupList` pattern) rests the list and the You / Team pills below it and
+ * the pinned header sticks under it; a matching spacer clears the bottom
+ * toolbar.
*/
export function MyActivityView(props: {
+ scope: ActivityScope;
+ onScopeChange: (scope: ActivityScope) => void;
onOpen: (target: OpenEntityTarget) => void;
}) {
const context = useActivityContext();
- const state = createMyActivityState(context);
+ const state = createMyActivityState(context, () => props.scope);
const [scroller, setScroller] = createSignal<HTMLDivElement>();
const [topSpacer, setTopSpacer] = createSignal<HTMLDivElement>();
const topSpacerSize = createElementSize(topSpacer);
const [startIndex, setStartIndex] = createSignal(0);
+ const [scrollOffset, setScrollOffset] = createSignal(0);
let handle: VirtualizerHandle | undefined;
+ // Until the list itself reaches the top edge its first day header is in
+ // view, so nothing pins (the team feed has no overview row above it, and
+ // on touch the You / Team pills sit where the pinned copy would).
const pinnedDay = createMemo(() =>
- pinnedDayLabel(state.rows(), startIndex())
+ scrollOffset() > (topSpacerSize.height ?? 0)
+ ? pinnedDayLabel(state.rows(), startIndex())
+ : undefined
);
const fetchMoreIfNearEnd = (offset: number) => {
@@ -101,10 +116,20 @@ export function MyActivityView(props: {
};
const onScroll = (offset: number) => {
+ setScrollOffset(offset);
if (handle) setStartIndex(handle.findItemIndex(offset));
fetchMoreIfNearEnd(offset);
};
+ // The other tab's rows replace these wholesale, so its feed opens at the top.
+ createEffect(
+ on(
+ () => props.scope,
+ () => handle?.scrollTo(0),
+ { defer: true }
+ )
+ );
+
// A page that does not fill the viewport never scrolls, so re-check once
// virtua has laid out the new rows.
createEffect(
@@ -119,7 +144,15 @@ export function MyActivityView(props: {
return (
<div class="@container/u-list flex size-full flex-col">
<SplitHeaderLeft>
- <span class="font-semibold text-sm">Activity</span>
+ <div class="flex items-center gap-3">
+ <span class="font-semibold text-sm">Activity</span>
+ <Show when={!isTouchDevice()}>
+ <ActivityScopeTabs
+ value={props.scope}
+ onChange={props.onScopeChange}
+ />
+ </Show>
+ </div>
</SplitHeaderLeft>
<StaticMarkdownContext>
<div ref={setScroller} class="min-h-0 flex-1 overflow-y-auto py-1">
@@ -132,11 +165,16 @@ export function MyActivityView(props: {
)}
</Show>
</div>
- <div
- ref={setTopSpacer}
- aria-hidden
- class="h-0 touch:h-(--mobile-content-inset-top)"
- />
+ <div ref={setTopSpacer} class="touch:pt-(--mobile-content-inset-top)">
+ <Show when={isTouchDevice()}>
+ <div class="px-(--mobile-chrome-gutter) pb-2">
+ <ActivityScopePills
+ value={props.scope}
+ onChange={props.onScopeChange}
+ />
+ </div>
+ </Show>
+ </div>
<div class="mx-auto w-full max-w-[1000px]">
<Virtualizer
data={state.rows()}
@@ -149,7 +187,12 @@ export function MyActivityView(props: {
onScroll={onScroll}
>
{(row) => (
- <FeedRowView row={row} state={state} onOpen={props.onOpen} />
+ <FeedRowView
+ row={row}
+ state={state}
+ scope={props.scope}
+ onOpen={props.onOpen}
+ />
)}
</Virtualizer>
</div>
@@ -166,6 +209,7 @@ export function MyActivityView(props: {
function FeedRowView(props: {
row: FeedRow;
state: MyActivityState;
+ scope: ActivityScope;
onOpen: (target: OpenEntityTarget) => void;
}) {
return match(props.row)
@@ -191,7 +235,11 @@ function FeedRowView(props: {
</FeedStatus>
))
.with({ kind: 'status', status: 'empty' }, () => (
- <FeedStatus>No activity yet.</FeedStatus>
+ <FeedStatus>
+ {props.scope === 'team'
+ ? 'No activity from your team yet.'
+ : 'No activity yet.'}
+ </FeedStatus>
))
.with({ kind: 'tail' }, () => <FeedTail state={props.state} />)
.exhaustive();
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
index a83a9027a0..49b47e18bd 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
@@ -7,13 +7,27 @@ import type { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-
export type ActivityFeedInput = {
/**
* Opaque cursor from the previous page's `nextCursor`; absent for the
- * first page.
+ * first page. Pass it back with the same `scope`.
*/
cursor?: string | null | undefined;
/** Page size; defaults to 25, capped at 100. */
limit?: number | null | undefined;
+ /** Whose activity to read; defaults to the user's own. */
+ scope?: ActivityFeedScope;
};
+/** Whose activity an activity feed page reads. */
+export type ActivityFeedScope =
+ /** The authenticated user's own activity, delegated actions included. */
+ | 'MINE'
+ /**
+ * Activity by the authenticated user's teammates, on entities shared
+ * with the user (link sharing alone does not count; forms never). A
+ * page may hold fewer items than its limit, or none, while
+ * `nextCursor` is set: keep paging until it is absent.
+ */
+ | 'TEAM';
+
/** Request for the authenticated user's trailing-year activity overview. */
export type ActivityOverviewInput = {
/** IANA time zone used for local dates. Omitted or empty means UTC. */
diff --git a/crates/activity/AGENTS.md b/crates/activity/AGENTS.md
index d7266188de..c60159a619 100644
--- a/crates/activity/AGENTS.md
+++ b/crates/activity/AGENTS.md
@@ -32,6 +32,11 @@ distribution.
- Depends on: `macro_event_broker`, `macro_event_topics`, `channel_sender`,
`model-entity`, `model_owner`.
+- `teammate_feed` (`src/outbound/pg_activity_repo/team_feed.sql`) reads other
+ domains' tables to decide in SQL which teammate rows the viewer may see:
+ `team_user`, `entity_access`, `comms_channel_participants`, `email_links`,
+ `macro_user_links`, `email_threads`, and `call_entities`. It mirrors
+ `EntityAccessService::get_users_by_entity`; change both together.
- Used by: most domain crates with activity surfaces (`documents`, `forms`,
`databases`, `initiative`, `messages`, `channels`, `soup`, `call`, `chat`,
`work_feed`, `projects`, `github`, `email`, `properties`) and `ai_tools`.
@@ -40,7 +45,8 @@ distribution.
- Add a new activity source in a domain: implement `DomainActivity` for the
domain's event type → map it in the domain crate's own consumer → register
- the topic in the hosting service's composition root.
+ the topic in the hosting service's composition root. A new entity type stays
+ out of the team feed until `team_feed.sql` gets a visibility case for it.
- Add a feed/timeline query: `src/domain/timeline.rs` or
`src/domain/overview.rs` → `src/domain/ports.rs` → `src/outbound/pg_activity_repo.rs`.
diff --git a/crates/activity/src/domain/ports.rs b/crates/activity/src/domain/ports.rs
index 890c60a39a..b493a7bf94 100644
--- a/crates/activity/src/domain/ports.rs
+++ b/crates/activity/src/domain/ports.rs
@@ -181,6 +181,23 @@ pub trait ActivityReads {
limit: NonZeroU32,
) -> impl Future<Output = Result<ActivityFeedPage, Self::Err>> + Send;
+ /// One page of the activity of everyone who shares a team with
+ /// `viewer_id`, the viewer excluded, newest first, on entities shared
+ /// with the viewer: the same audience `get_users_by_entity` resolves
+ /// (grants to the viewer, their teams, or their channels; channel
+ /// participation; owned inboxes), so a link share alone does not count.
+ /// Form rows are never included: they name respondents.
+ ///
+ /// Each page reads a bounded number of rows, so it may hold fewer than
+ /// `limit` rows, or none, while `next` is set; callers keep paging
+ /// until `next` is `None`. No visible row is skipped between pages.
+ fn teammate_feed(
+ &self,
+ viewer_id: &str,
+ cursor: Option<(DateTime<Utc>, Uuid)>,
+ limit: NonZeroU32,
+ ) -> impl Future<Output = Result<ActivityFeedPage, Self::Err>> + Send;
+
/// The newest `per_entity_limit` activities for each requested entity,
/// in one round trip. Entities with no activity are absent from the map.
fn entity_activity(
diff --git a/crates/activity/src/domain/service/test.rs b/crates/activity/src/domain/service/test.rs
index 2187d35d9c..23d8b1ca69 100644
--- a/crates/activity/src/domain/service/test.rs
+++ b/crates/activity/src/domain/service/test.rs
@@ -32,6 +32,15 @@ impl ActivityReads for FakeReads {
unreachable!()
}
+ async fn teammate_feed(
+ &self,
+ _viewer_id: &str,
+ _cursor: Option<(DateTime<Utc>, Uuid)>,
+ _limit: NonZeroU32,
+ ) -> Result<ActivityFeedPage, Self::Err> {
+ unreachable!()
+ }
+
async fn entity_activity(
&self,
_keys: &[(crate::EntityType, String)],
diff --git a/crates/activity/src/inbound/toolset/test.rs b/crates/activity/src/inbound/toolset/test.rs
index 13aeebceda..cb6d44974b 100644
--- a/crates/activity/src/inbound/toolset/test.rs
+++ b/crates/activity/src/inbound/toolset/test.rs
@@ -70,6 +70,15 @@ impl ActivityReads for FakeReads {
})
}
+ async fn teammate_feed(
+ &self,
+ _viewer_id: &str,
+ _cursor: Option<(DateTime<Utc>, Uuid)>,
+ _limit: NonZeroU32,
+ ) -> Result<ActivityFeedPage, Self::Err> {
+ unreachable!()
+ }
+
async fn entity_activity(
&self,
_keys: &[(crate::EntityType, String)],
diff --git a/crates/activity/src/outbound/pg_activity_repo.rs b/crates/activity/src/outbound/pg_activity_repo.rs
index 14a55275b5..e1743fa195 100644
--- a/crates/activity/src/outbound/pg_activity_repo.rs
+++ b/crates/activity/src/outbound/pg_activity_repo.rs
@@ -1,5 +1,6 @@
//! Postgres adapter for the `activity_events` table (MacroDB).
+mod team_feed;
#[cfg(test)]
mod test;
mod timeline;
@@ -238,6 +239,15 @@ impl ActivityReads for PgActivityRepo {
})
}
+ async fn teammate_feed(
+ &self,
+ viewer_id: &str,
+ cursor: Option<(DateTime<Utc>, Uuid)>,
+ limit: NonZeroU32,
+ ) -> Result<ActivityFeedPage, Self::Err> {
+ team_feed::teammate_feed(&self.pool, viewer_id, cursor, limit, team_feed::TEAM_SCAN).await
+ }
+
async fn entity_activity(
&self,
keys: &[(EntityType, String)],
diff --git a/crates/activity/src/outbound/pg_activity_repo/team_feed.rs b/crates/activity/src/outbound/pg_activity_repo/team_feed.rs
new file mode 100644
index 0000000000..1599339157
--- /dev/null
+++ b/crates/activity/src/outbound/pg_activity_repo/team_feed.rs
@@ -0,0 +1,123 @@
+//! The team feed read: teammates' activity on entities shared with the viewer.
+//!
+//! Visibility is decided in SQL so every page holds visible rows only and
+//! costs one round trip. Each teammate's scan of the subject index stops
+//! after enough visible rows or a raw-row cap that keeps a page's total read
+//! near [`TEAM_SCAN`]'s budget however large the team is. When some teammate's
+//! scan hits its cap, its last raw row is a frontier below which that
+//! teammate was not read: the page returns only rows at or above the newest
+//! frontier, and that frontier becomes the cursor when the page comes up
+//! short. A page may therefore hold fewer than `limit` rows, or none, while
+//! `next` is set; no visible row is ever skipped.
+
+use std::num::NonZeroU32;
+
+use chrono::{DateTime, Utc};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use super::StoredRow;
+use crate::domain::ports::ActivityFeedPage;
+
+/// How many raw rows one team page reads.
+#[derive(Debug, Clone, Copy)]
+pub(super) struct TeamScan {
+ /// Raw rows one page may read across all teammates' scans.
+ pub(super) page_budget: i64,
+ /// Fewest raw rows one teammate's scan reads, however large the team.
+ pub(super) min_per_teammate: i64,
+}
+
+/// The scan every team page uses: enough rows that a page is rarely short
+/// even when most of the team's activity is hidden, few enough that a page
+/// stays a cheap read whatever the team size.
+pub(super) const TEAM_SCAN: TeamScan = TeamScan {
+ page_budget: 8_000,
+ min_per_teammate: 8,
+};
+
+/// One row of the team feed query: a visible row, or the frontier.
+struct TeamFeedRow {
+ id: Uuid,
+ actor_id: String,
+ action: String,
+ action_payload: Option<serde_json::Value>,
+ subject_id: String,
+ entity_type: String,
+ entity_id: String,
+ occurred_at: DateTime<Utc>,
+ is_boundary: bool,
+}
+
+impl TeamFeedRow {
+ fn position(&self) -> (DateTime<Utc>, Uuid) {
+ (self.occurred_at, self.id)
+ }
+
+ fn into_stored(self) -> StoredRow {
+ StoredRow {
+ id: self.id,
+ actor_id: self.actor_id,
+ action: self.action,
+ action_payload: self.action_payload,
+ subject_id: self.subject_id,
+ entity_type: self.entity_type,
+ entity_id: self.entity_id,
+ occurred_at: self.occurred_at,
+ }
+ }
+}
+
+#[tracing::instrument(
+ name = "activity.team_feed",
+ skip_all,
+ fields(limit = limit.get(), row_count, short_page),
+ err
+)]
+pub(super) async fn teammate_feed(
+ pool: &PgPool,
+ viewer_id: &str,
+ cursor: Option<(DateTime<Utc>, Uuid)>,
+ limit: NonZeroU32,
+ scan: TeamScan,
+) -> Result<ActivityFeedPage, sqlx::Error> {
+ // One extra visible row as the has-more probe.
+ let fetch = i64::from(limit.get()) + 1;
+ let limit = limit.get() as usize;
+ let rows = sqlx::query_file_as!(
+ TeamFeedRow,
+ "src/outbound/pg_activity_repo/team_feed.sql",
+ viewer_id,
+ cursor.map(|(occurred_at, _)| occurred_at),
+ cursor.map(|(_, id)| id),
+ fetch,
+ scan.min_per_teammate,
+ scan.page_budget,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ let (boundary, mut visible): (Vec<_>, Vec<_>) =
+ rows.into_iter().partition(|row| row.is_boundary);
+ visible.sort_unstable_by_key(|row| std::cmp::Reverse(row.position()));
+ let has_more = visible.len() > limit;
+ visible.truncate(limit);
+ // A full page continues below its last row. A short one has every
+ // visible row above the frontier, so it continues below the frontier.
+ let next = if has_more {
+ visible.last().map(TeamFeedRow::position)
+ } else {
+ boundary.first().map(TeamFeedRow::position)
+ };
+
+ let span = tracing::Span::current();
+ span.record("row_count", visible.len());
+ span.record("short_page", !has_more && next.is_some());
+ Ok(ActivityFeedPage {
+ records: visible
+ .into_iter()
+ .filter_map(|row| row.into_stored().decode())
+ .collect(),
+ next,
+ })
+}
diff --git a/crates/activity/src/outbound/pg_activity_repo/team_feed.sql b/crates/activity/src/outbound/pg_activity_repo/team_feed.sql
new file mode 100644
index 0000000000..9935d7b354
--- /dev/null
+++ b/crates/activity/src/outbound/pg_activity_repo/team_feed.sql
@@ -0,0 +1,139 @@
+-- One page of the viewer's teammates' activity on entities shared with the
+-- viewer. See `team_feed.rs` for the paging contract.
+--
+-- $1 viewer id, $2/$3 cursor position (NULL for the first page),
+-- $4 rows to return, $5 fewest raw rows one teammate's scan reads,
+-- $6 raw rows one page reads across all teammates.
+WITH viewer_source AS (
+ -- The principals an `entity_access` grant can name to reach the viewer:
+ -- the viewer, their teams, and the channels they are active in.
+ SELECT 'user'::entity_access_source_type AS source_type, $1::text AS source_id
+ UNION ALL
+ SELECT 'team', tu.team_id::text FROM team_user tu WHERE tu.user_id = $1
+ UNION ALL
+ SELECT 'channel', cp.channel_id::text
+ FROM comms_channel_participants cp
+ WHERE cp.user_id = $1 AND cp.left_at IS NULL
+),
+viewer_inbox AS (
+ -- Inboxes whose threads the viewer owns: their own links and those
+ -- delegated to them as primary.
+ SELECT l.id AS link_id FROM email_links l WHERE l.macro_id = $1
+ UNION
+ SELECT mul.link_id FROM macro_user_links mul WHERE mul.primary_macro_id = $1
+),
+teammate AS (
+ SELECT DISTINCT member.user_id
+ FROM team_user viewer
+ JOIN team_user member ON member.team_id = viewer.team_id
+ WHERE viewer.user_id = $1 AND member.user_id <> $1
+),
+scan AS (
+ SELECT GREATEST($5, $6 / GREATEST(count(*), 1))::bigint AS rows FROM teammate
+),
+scanned AS (
+ -- Per teammate, one seek of the subject index that stops at $4 visible
+ -- rows or after `scan.rows` raw rows. A scan that stops at that cap
+ -- also emits its last raw row (`scan_rank = scan.rows`) as a frontier.
+ SELECT s.*
+ FROM teammate t
+ CROSS JOIN LATERAL (
+ SELECT w.*
+ FROM (
+ SELECT e.*,
+ row_number() OVER (ORDER BY e.occurred_at DESC, e.id DESC) AS scan_rank,
+ -- Mirrors `EntityAccessService::get_users_by_entity` for
+ -- every entity type activity records; anything else is
+ -- hidden. Forms are hidden too: their rows name
+ -- respondents, so they reach only their subject.
+ CASE
+ WHEN e.entity_type = 'channel' THEN e.entity_id IN (
+ SELECT vs.source_id FROM viewer_source vs
+ WHERE vs.source_type = 'channel'
+ )
+ -- A call's audience is its channel's, or its direct
+ -- user grants when it has none.
+ WHEN e.entity_type = 'call' THEN EXISTS (
+ SELECT 1 FROM call_entities ce
+ WHERE ce.id = e.entity_uuid
+ AND CASE
+ WHEN ce.channel_id IS NULL THEN EXISTS (
+ SELECT 1 FROM entity_access ea
+ WHERE ea.entity_id = ce.id AND ea.entity_type = 'call'
+ AND ea.source_type = 'user' AND ea.source_id = $1
+ AND ea.granted_from_project_id IS NULL
+ )
+ ELSE ce.channel_id::text IN (
+ SELECT vs.source_id FROM viewer_source vs
+ WHERE vs.source_type = 'channel'
+ )
+ END
+ )
+ WHEN e.entity_type IN (
+ 'document', 'project', 'chat', 'initiative', 'database',
+ 'crm_company', 'email_thread'
+ ) THEN EXISTS (
+ SELECT 1 FROM entity_access ea
+ WHERE ea.entity_id::text = e.entity_id
+ AND ea.entity_type = e.entity_type
+ AND (ea.source_type, ea.source_id) IN (
+ SELECT vs.source_type, vs.source_id FROM viewer_source vs
+ )
+ ) OR (e.entity_type = 'email_thread' AND EXISTS (
+ SELECT 1 FROM email_threads et
+ WHERE et.id = e.entity_uuid
+ AND et.link_id IN (SELECT vi.link_id FROM viewer_inbox vi)
+ ))
+ ELSE false
+ END AS visible
+ FROM (
+ SELECT e.id, e.actor_id, e.action, e.action_payload, e.subject_id,
+ e.entity_type, e.entity_id, e.occurred_at,
+ -- Only these id columns are uuids; a malformed id
+ -- must hide its row, not fail the page.
+ CASE WHEN e.entity_type IN ('call', 'email_thread') THEN
+ CASE WHEN e.entity_id ~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
+ THEN e.entity_id::uuid
+ END
+ END AS entity_uuid
+ FROM activity_events e
+ WHERE e.subject_id = t.user_id
+ -- No cursor reads from the top. COALESCE, unlike an
+ -- `IS NULL OR` branch, keeps this an index condition in
+ -- generic plans.
+ AND (e.occurred_at, e.id) < (
+ COALESCE($2::timestamptz, 'infinity'),
+ COALESCE($3::uuid, 'ffffffff-ffff-ffff-ffff-ffffffffffff')
+ )
+ ORDER BY e.occurred_at DESC, e.id DESC
+ LIMIT (SELECT rows FROM scan)
+ ) e
+ ) w
+ WHERE w.visible OR w.scan_rank = (SELECT rows FROM scan)
+ LIMIT $4
+ ) s
+),
+boundary AS (
+ -- The newest frontier: below it some teammate's rows were not read.
+ SELECT * FROM scanned
+ WHERE scan_rank = (SELECT rows FROM scan)
+ ORDER BY occurred_at DESC, id DESC
+ LIMIT 1
+)
+(
+ SELECT s.id AS "id!", s.actor_id AS "actor_id!", s.action AS "action!",
+ s.action_payload, s.subject_id AS "subject_id!",
+ s.entity_type AS "entity_type!", s.entity_id AS "entity_id!",
+ s.occurred_at AS "occurred_at!", false AS "is_boundary!"
+ FROM scanned s
+ WHERE s.visible
+ AND NOT EXISTS (
+ SELECT 1 FROM boundary b WHERE (s.occurred_at, s.id) < (b.occurred_at, b.id)
+ )
+ ORDER BY s.occurred_at DESC, s.id DESC
+ LIMIT $4
+)
+UNION ALL
+SELECT b.id, b.actor_id, b.action, b.action_payload, b.subject_id, b.entity_type,
+ b.entity_id, b.occurred_at, true
+FROM boundary b
diff --git a/crates/activity/src/outbound/pg_activity_repo/test.rs b/crates/activity/src/outbound/pg_activity_repo/test.rs
index add24c4da0..21b0c9dd10 100644
--- a/crates/activity/src/outbound/pg_activity_repo/test.rs
+++ b/crates/activity/src/outbound/pg_activity_repo/test.rs
@@ -7,6 +7,8 @@ use super::*;
use crate::domain::models::{Action, ActionTag, Actor, CommonAction, PropertyChange};
use crate::domain::ports::EntityActivityReads;
+mod teammate_feed;
+
fn user(id: &str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from(id.to_string()).expect("valid user id")
}
diff --git a/crates/activity/src/outbound/pg_activity_repo/test/teammate_feed.rs b/crates/activity/src/outbound/pg_activity_repo/test/teammate_feed.rs
new file mode 100644
index 0000000000..87587de1ea
--- /dev/null
+++ b/crates/activity/src/outbound/pg_activity_repo/test/teammate_feed.rs
@@ -0,0 +1,386 @@
+use super::super::team_feed::{TeamScan, teammate_feed};
+use super::*;
+
+const VIEWER: &str = "macro|[email protected]";
+const ALICE: &str = "macro|[email protected]";
+const BOB: &str = "macro|[email protected]";
+const OUTSIDER: &str = "macro|[email protected]";
+const LONER: &str = "macro|[email protected]";
+
+async fn insert_user(pool: &PgPool, id: &str) {
+ let macro_user_id = Uuid::now_v7();
+ sqlx::query!(
+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $2, $2)"#,
+ macro_user_id,
+ id,
+ )
+ .execute(pool)
+ .await
+ .expect("macro_user should insert");
+ sqlx::query!(
+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $1, $2)"#,
+ id,
+ macro_user_id,
+ )
+ .execute(pool)
+ .await
+ .expect("user should insert");
+}
+
+async fn insert_team(pool: &PgPool, members: &[&str]) -> Uuid {
+ let team_id = Uuid::now_v7();
+ sqlx::query!(
+ r#"INSERT INTO team (id, owner_id, name) VALUES ($1, $2, 'team')"#,
+ team_id,
+ members[0],
+ )
+ .execute(pool)
+ .await
+ .expect("team should insert");
+ for member in members {
+ sqlx::query!(
+ r#"INSERT INTO team_user (user_id, team_id, team_role) VALUES ($1, $2, 'member')"#,
+ *member,
+ team_id,
+ )
+ .execute(pool)
+ .await
+ .expect("team member should insert");
+ }
+ team_id
+}
+
+/// Grants `source` access to an entity, as sharing writes it.
+async fn grant(
+ pool: &PgPool,
+ entity_type: &str,
+ entity_id: Uuid,
+ source_type: &str,
+ source_id: &str,
+ access_level: &str,
+) {
+ sqlx::query!(
+ r#"
+ INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ($1, $2, $3, $4::text::entity_access_source_type, $5::text::"AccessLevel")
+ "#,
+ entity_id,
+ entity_type,
+ source_id,
+ source_type,
+ access_level,
+ )
+ .execute(pool)
+ .await
+ .expect("grant should insert");
+}
+
+/// A channel with `active` participants and `left` former ones.
+async fn insert_channel(pool: &PgPool, active: &[&str], left: &[&str]) -> Uuid {
+ let channel_id = Uuid::now_v7();
+ sqlx::query!(
+ r#"INSERT INTO comms_channels (id, channel_type, owner_id) VALUES ($1, 'private', $2)"#,
+ channel_id,
+ ALICE,
+ )
+ .execute(pool)
+ .await
+ .expect("channel should insert");
+ for (users, has_left) in [(active, false), (left, true)] {
+ for user_id in users {
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_channel_participants (channel_id, role, user_id, left_at)
+ VALUES ($1, 'member', $2, CASE WHEN $3 THEN now() END)
+ "#,
+ channel_id,
+ *user_id,
+ has_left,
+ )
+ .execute(pool)
+ .await
+ .expect("participant should insert");
+ }
+ }
+ channel_id
+}
+
+/// A connected inbox owned by `owner`.
+async fn insert_inbox(pool: &PgPool, owner: &str) -> Uuid {
+ let link_id = Uuid::now_v7();
+ sqlx::query!(
+ r#"
+ INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider)
+ VALUES ($1, $2::text, $2::text, $2::text, 'GMAIL')
+ "#,
+ link_id,
+ owner,
+ )
+ .execute(pool)
+ .await
+ .expect("email link should insert");
+ link_id
+}
+
+async fn insert_thread(pool: &PgPool, link_id: Uuid) -> Uuid {
+ let thread_id = Uuid::now_v7();
+ sqlx::query!(
+ r#"INSERT INTO email_threads (id, link_id) VALUES ($1, $2)"#,
+ thread_id,
+ link_id,
+ )
+ .execute(pool)
+ .await
+ .expect("thread should insert");
+ thread_id
+}
+
+async fn insert_call(pool: &PgPool, channel_id: Option<Uuid>) -> Uuid {
+ let call_id = Uuid::now_v7();
+ let share_permission_id = Uuid::now_v7().to_string();
+ sqlx::query!(
+ r#"INSERT INTO "SharePermission" (id) VALUES ($1)"#,
+ share_permission_id,
+ )
+ .execute(pool)
+ .await
+ .expect("share permission should insert");
+ sqlx::query!(
+ r#"
+ INSERT INTO call_entities (id, user_id, created_via, share_permission_id, channel_id)
+ VALUES ($1, $2, 'manual', $3, $4)
+ "#,
+ call_id,
+ ALICE,
+ share_permission_id,
+ channel_id,
+ )
+ .execute(pool)
+ .await
+ .expect("call should insert");
+ call_id
+}
+
+/// `subject` edited an entity at `seconds` past the base time.
+fn edit(
+ source_event: u128,
+ subject: &str,
+ entity_type: model_entity::EntityType,
+ entity_id: impl ToString,
+ seconds: i64,
+) -> Activity {
+ Activity::common(
+ Uuid::from_u128(source_event),
+ 0,
+ Actor::new_from_user(user(subject)),
+ Some(user(subject)),
+ entity_type,
+ entity_id.to_string(),
+ CommonAction::Edited,
+ base_time() + chrono::Duration::seconds(seconds),
+ )
+}
+
+fn entity_ids(page: &ActivityFeedPage) -> Vec<String> {
+ page.records
+ .iter()
+ .map(|record| record.entity_id.clone())
+ .collect()
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn teammate_feed_shows_teammates_rows_on_entities_shared_with_the_viewer(pool: PgPool) {
+ use model_entity::EntityType as E;
+
+ for id in [VIEWER, ALICE, BOB, OUTSIDER, LONER] {
+ insert_user(&pool, id).await;
+ }
+ let team = insert_team(&pool, &[VIEWER, ALICE, BOB]).await;
+ insert_team(&pool, &[OUTSIDER]).await;
+ let joined = insert_channel(&pool, &[VIEWER, ALICE], &[]).await;
+ let left = insert_channel(&pool, &[ALICE], &[VIEWER]).await;
+ let other_channel = insert_channel(&pool, &[ALICE, BOB], &[]).await;
+ let (team_source, joined_source, left_source) =
+ (team.to_string(), joined.to_string(), left.to_string());
+
+ let [
+ granted_doc,
+ team_doc,
+ channel_doc,
+ left_channel_doc,
+ link_only_doc,
+ team_project,
+ form,
+ ] = std::array::from_fn(|_| Uuid::now_v7());
+ grant(&pool, "document", granted_doc, "user", VIEWER, "view").await;
+ grant(&pool, "document", team_doc, "team", &team_source, "view").await;
+ grant(
+ &pool,
+ "document",
+ channel_doc,
+ "channel",
+ &joined_source,
+ "view",
+ )
+ .await;
+ grant(
+ &pool,
+ "document",
+ left_channel_doc,
+ "channel",
+ &left_source,
+ "view",
+ )
+ .await;
+ // Sharing with a teammate, or by link, puts no row in the viewer's audience.
+ grant(&pool, "document", link_only_doc, "user", ALICE, "owner").await;
+ grant(&pool, "project", team_project, "team", &team_source, "edit").await;
+ // Form rows name respondents, so they stay out even for editors.
+ grant(&pool, "form", form, "user", VIEWER, "edit").await;
+
+ let viewer_inbox = insert_inbox(&pool, VIEWER).await;
+ let alice_inbox = insert_inbox(&pool, ALICE).await;
+ let viewers_thread = insert_thread(&pool, viewer_inbox).await;
+ let shared_thread = insert_thread(&pool, alice_inbox).await;
+ let private_thread = insert_thread(&pool, alice_inbox).await;
+ grant(&pool, "email_thread", shared_thread, "user", VIEWER, "view").await;
+
+ let channel_call = insert_call(&pool, Some(joined)).await;
+ let direct_call = insert_call(&pool, None).await;
+ let uninvited_call = insert_call(&pool, None).await;
+ grant(&pool, "call", direct_call, "user", VIEWER, "view").await;
+
+ let repo = PgActivityRepo::new(pool.clone());
+ repo.insert_activities(&[
+ edit(1, ALICE, E::Document, granted_doc, 1),
+ edit(2, BOB, E::Document, team_doc, 2),
+ edit(3, ALICE, E::Document, channel_doc, 3),
+ edit(4, ALICE, E::Document, left_channel_doc, 4),
+ edit(5, ALICE, E::Document, link_only_doc, 5),
+ edit(6, BOB, E::Project, team_project, 6),
+ edit(7, ALICE, E::Form, form, 7),
+ edit(8, ALICE, E::Channel, joined, 8),
+ edit(9, BOB, E::Channel, other_channel, 9),
+ edit(10, ALICE, E::EmailThread, viewers_thread, 10),
+ edit(11, ALICE, E::EmailThread, shared_thread, 11),
+ edit(12, ALICE, E::EmailThread, private_thread, 12),
+ // A malformed id hides its row instead of failing the page.
+ edit(13, ALICE, E::EmailThread, "not-a-uuid", 13),
+ edit(14, ALICE, E::Call, channel_call, 14),
+ edit(15, BOB, E::Call, direct_call, 15),
+ edit(16, BOB, E::Call, uninvited_call, 16),
+ // Neither the viewer's own rows nor an outsider's belong here.
+ edit(17, VIEWER, E::Document, granted_doc, 17),
+ edit(18, OUTSIDER, E::Document, team_doc, 18),
+ ])
+ .await
+ .unwrap();
+
+ let page = repo.teammate_feed(VIEWER, None, nz(50)).await.unwrap();
+
+ assert_eq!(
+ entity_ids(&page),
+ [
+ direct_call,
+ channel_call,
+ shared_thread,
+ viewers_thread,
+ joined,
+ team_project,
+ channel_doc,
+ team_doc,
+ granted_doc,
+ ]
+ .map(|id| id.to_string())
+ );
+ assert_eq!(page.next, None, "exhausted feed carries no cursor");
+
+ let alone = repo.teammate_feed(OUTSIDER, None, nz(10)).await.unwrap();
+ assert!(alone.records.is_empty(), "a team of one has no teammates");
+ let teamless = repo.teammate_feed(LONER, None, nz(10)).await.unwrap();
+ assert!(teamless.records.is_empty());
+ assert_eq!(teamless.next, None);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn teammate_feed_pages_past_capped_scans_without_skipping_rows(pool: PgPool) {
+ for id in [VIEWER, ALICE, BOB] {
+ insert_user(&pool, id).await;
+ }
+ let team = insert_team(&pool, &[VIEWER, ALICE, BOB]).await;
+ let shared = Uuid::now_v7();
+ grant(&pool, "document", shared, "team", &team.to_string(), "view").await;
+ let hidden = Uuid::now_v7();
+
+ // Alice's history is mostly hidden; Bob's is mostly visible. Rows
+ // interleave in time so both scans bound every page.
+ let pattern = [
+ (ALICE, false),
+ (BOB, true),
+ (ALICE, false),
+ (ALICE, false),
+ (BOB, false),
+ (ALICE, true),
+ (BOB, true),
+ (ALICE, false),
+ (ALICE, false),
+ (ALICE, false),
+ (BOB, true),
+ (ALICE, true),
+ (BOB, false),
+ (BOB, true),
+ (ALICE, false),
+ (ALICE, true),
+ ];
+ let rows: Vec<Activity> = pattern
+ .iter()
+ .enumerate()
+ .map(|(n, &(subject, visible))| {
+ let entity = if visible { shared } else { hidden };
+ let n = n as u128 + 1;
+ edit(
+ n,
+ subject,
+ model_entity::EntityType::Document,
+ entity,
+ n as i64,
+ )
+ })
+ .collect();
+ PgActivityRepo::new(pool.clone())
+ .insert_activities(&rows)
+ .await
+ .unwrap();
+ let mut expected: Vec<Uuid> = rows
+ .iter()
+ .filter(|row| row.entity_id == shared.to_string())
+ .map(|row| row.id)
+ .collect();
+ expected.reverse();
+
+ // Two raw rows per teammate per page: every page stops at a frontier.
+ let scan = TeamScan {
+ page_budget: 4,
+ min_per_teammate: 2,
+ };
+ let mut seen = Vec::new();
+ let mut short_pages = 0;
+ let mut cursor = None;
+ for _ in 0..pattern.len() {
+ let page = teammate_feed(&pool, VIEWER, cursor, nz(2), scan)
+ .await
+ .unwrap();
+ if page.records.len() < 2 && page.next.is_some() {
+ short_pages += 1;
+ }
+ seen.extend(page.records.iter().map(|record| record.id));
+ cursor = page.next;
+ if cursor.is_none() {
+ break;
+ }
+ }
+
+ assert_eq!(cursor, None, "paging reaches the end");
+ assert_eq!(seen, expected, "every visible row, once, newest first");
+ assert!(short_pages > 0, "the scan cap produced short pages");
+}
diff --git a/crates/complete_graph/src/lib.rs b/crates/complete_graph/src/lib.rs
index e2362f261f..8f6cea2ffe 100644
--- a/crates/complete_graph/src/lib.rs
+++ b/crates/complete_graph/src/lib.rs
@@ -19,7 +19,7 @@ pub use edges::{
SoupEdges, SoupEmailThreadEdges, agent_session_bot_loader, agent_session_log_loader,
};
pub use graphql_activity::{
- ActivityEdgeKey, ActivityEdgeLoad, ActivityFeedInput, ActivityFeedReader,
+ ActivityEdgeKey, ActivityEdgeLoad, ActivityFeedInput, ActivityFeedReader, ActivityFeedScope,
ActivityOverviewInput, ActivityPortReader, ActivityReader, EntityActivityLoader,
GraphqlActivityAction, GraphqlActivityDay, GraphqlActivityEntityRank, GraphqlActivityEvent,
GraphqlActivityOverview, GraphqlActivityPage, NoOpActivityReader, SoupActivityEdgeReader,
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index 6e5073331e..3667024d7f 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -776,8 +776,9 @@ where
resolve_folders(ctx, &self.user_id).await
}
- /// A page of the authenticated user's own activity, newest first.
- /// Delegated actions performed on the user's behalf are included.
+ /// A page of activity, newest first: by default the authenticated
+ /// user's own, delegated actions included; in the `TEAM` scope, their
+ /// teammates' activity on entities shared with the user.
async fn activity(
&self,
ctx: &Context<'_>,
diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rs
index 94718592ab..60f23d8454 100644
--- a/crates/complete_graph/src/schema/test.rs
+++ b/crates/complete_graph/src/schema/test.rs
@@ -55,6 +55,7 @@ mod initiative;
mod scheduled_actions;
mod soup_patches;
mod stale_client;
+mod team_activity;
mod work_feed;
const VALID_USER_ID: &str = "macro|[email protected]";
@@ -942,6 +943,36 @@ impl graphql_activity::ActivityFeedReader for RecordingActivityReader {
})
}
+ async fn teammate_feed(
+ &self,
+ viewer_id: &str,
+ cursor: Option<(chrono::DateTime<chrono::Utc>, Uuid)>,
+ limit: std::num::NonZeroU32,
+ ) -> Result<activity::ActivityFeedPage, graphql_activity::ActivityReadFailed> {
+ // Emulate the repo with everyone but the viewer as a teammate, in
+ // the same keyset order and raw-row `next` as `subject_feed`.
+ let limit = limit.get() as usize;
+ let records = self.records.lock().expect("activity records lock").clone();
+ let mut page: Vec<activity::ActivityRecord> = records
+ .into_iter()
+ .filter(|record| record.subject_id != viewer_id)
+ .filter(|record| {
+ cursor.is_none_or(|(occurred_at, id)| {
+ (record.occurred_at, record.id) < (occurred_at, id)
+ })
+ })
+ .collect();
+ let has_more = page.len() > limit;
+ page.truncate(limit);
+ let next = has_more
+ .then(|| page.last().map(|record| (record.occurred_at, record.id)))
+ .flatten();
+ Ok(activity::ActivityFeedPage {
+ records: page,
+ next,
+ })
+ }
+
async fn subject_overview(
&self,
subject_id: &str,
diff --git a/crates/complete_graph/src/schema/test/team_activity.rs b/crates/complete_graph/src/schema/test/team_activity.rs
new file mode 100644
index 0000000000..dacc821855
--- /dev/null
+++ b/crates/complete_graph/src/schema/test/team_activity.rs
@@ -0,0 +1,63 @@
+use super::*;
+
+const TEAMMATE_ID: &str = "macro|[email protected]";
+
+/// A teammate's edit, as ingestion records it.
+fn teammates_edit(id: u128) -> activity::ActivityRecord {
+ activity::ActivityRecord {
+ id: Uuid::from_u128(id),
+ actor: activity::Actor::new_from_user(MacroUserIdStr::parse_from_str(TEAMMATE_ID).unwrap()),
+ subject_id: TEAMMATE_ID.to_owned(),
+ entity_type: ModelEntityType::Document,
+ entity_id: Uuid::from_u128(id + 100).to_string(),
+ action: activity::RecordedAction::Known(activity::Action::Edited),
+ occurred_at: chrono::DateTime::from_timestamp(i64::try_from(id).unwrap() * 100, 0)
+ .expect("valid timestamp"),
+ }
+}
+
+async fn team_page(harness: &TestHarness, cursor: Option<&str>) -> serde_json::Value {
+ let cursor = cursor.map_or(String::new(), |cursor| format!(r#", cursor: "{cursor}""#));
+ let response = harness
+ .execute(&format!(
+ r#"{{ user {{ activity(input: {{scope: TEAM, limit: 2{cursor}}}) {{ items {{ id actorId }} nextCursor }} }} }}"#
+ ))
+ .await;
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ response.data.into_json().unwrap()["user"]["activity"].clone()
+}
+
+#[tokio::test]
+async fn team_activity_pages_the_teammate_feed_of_the_authenticated_user() {
+ let harness = harness();
+ harness.activity_reader.set_records(vec![
+ teammates_edit(4),
+ // The viewer's own row belongs to the MINE scope.
+ activity_record(
+ 3,
+ ModelEntityType::Document,
+ &Uuid::from_u128(103).to_string(),
+ activity::RecordedAction::Known(activity::Action::Edited),
+ 300,
+ ),
+ teammates_edit(2),
+ teammates_edit(1),
+ ]);
+
+ let first = team_page(&harness, None).await;
+ assert_eq!(
+ first["items"],
+ serde_json::json!([
+ { "id": Uuid::from_u128(4).to_string(), "actorId": TEAMMATE_ID },
+ { "id": Uuid::from_u128(2).to_string(), "actorId": TEAMMATE_ID },
+ ])
+ );
+ let cursor = first["nextCursor"].as_str().expect("more rows exist");
+
+ let last = team_page(&harness, Some(cursor)).await;
+ assert_eq!(
+ last["items"],
+ serde_json::json!([{ "id": Uuid::from_u128(1).to_string(), "actorId": TEAMMATE_ID }])
+ );
+ assert!(last["nextCursor"].is_null());
+}
diff --git a/crates/entity_access/src/domain/ports.rs b/crates/entity_access/src/domain/ports.rs
index a343784214..8fc38e5bee 100644
--- a/crates/entity_access/src/domain/ports.rs
+++ b/crates/entity_access/src/domain/ports.rs
@@ -563,6 +563,10 @@ pub trait EntityAccessService: Clone + Send + Sync + 'static {
/// access or inherited access through the project hierarchy via `entity_access`.
/// For Channel: returns active channel participants.
/// Returns `AccessError::BadRequest` for unsupported types (Team, User).
+ ///
+ /// The activity team feed applies this audience in SQL
+ /// (`crates/activity/src/outbound/pg_activity_repo/team_feed.sql`); keep
+ /// the two in step.
fn get_users_by_entity(
&self,
entity_id: &str,
diff --git a/crates/graphql_activity/AGENTS.md b/crates/graphql_activity/AGENTS.md
index 4df2b63af8..eafe1bc011 100644
--- a/crates/graphql_activity/AGENTS.md
+++ b/crates/graphql_activity/AGENTS.md
@@ -15,6 +15,10 @@ DataLoader) — plus database/form timelines and a realtime subscription.
- `src/loaders.rs`: `EntityActivityLoader` — the batched per-entity edge;
touch this when activity needs to appear on a new Soup entity type.
- `src/feed.rs` / `src/overview.rs`: the viewer feed and yearly aggregate.
+ The feed's `scope` input picks the viewer's own activity (`MINE`) or their
+ teammates' (`TEAM`). `TEAM` rows are filtered to entities shared with the
+ viewer in storage (`activity`'s `teammate_feed`); its pages can come up
+ short, or empty, with a cursor, and clients keep paging.
- `src/timeline.rs`: by-id, access-checked timelines for databases/forms
(not Soup items, so not loader-batched).
- `src/subscriptions.rs`: the realtime `activityUpdates` subscription.
diff --git a/crates/graphql_activity/src/feed.rs b/crates/graphql_activity/src/feed.rs
index aad2f54046..4e6740488e 100644
--- a/crates/graphql_activity/src/feed.rs
+++ b/crates/graphql_activity/src/feed.rs
@@ -1,6 +1,6 @@
use std::num::NonZeroU32;
-use async_graphql::{Context, InputObject, SimpleObject};
+use async_graphql::{Context, Enum, InputObject, SimpleObject};
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{Base64Str, CursorVal, CursorWithVal, Sortable};
@@ -29,17 +29,33 @@ impl Sortable for OccurredAt {
/// of the last item on the previous page.
type ActivityFeedCursor = CursorWithVal<Uuid, OccurredAt>;
+/// Whose activity an activity feed page reads.
+#[derive(Enum, Debug, Default, Clone, Copy, PartialEq, Eq)]
+pub enum ActivityFeedScope {
+ /// The authenticated user's own activity, delegated actions included.
+ #[default]
+ Mine,
+ /// Activity by the authenticated user's teammates, on entities shared
+ /// with the user (link sharing alone does not count; forms never). A
+ /// page may hold fewer items than its limit, or none, while
+ /// `nextCursor` is set: keep paging until it is absent.
+ Team,
+}
+
/// Page request for the authenticated user's activity feed.
#[derive(InputObject)]
pub struct ActivityFeedInput {
/// Opaque cursor from the previous page's `nextCursor`; absent for the
- /// first page.
+ /// first page. Pass it back with the same `scope`.
pub cursor: Option<String>,
/// Page size; defaults to 25, capped at 100.
pub limit: Option<i32>,
+ /// Whose activity to read; defaults to the user's own.
+ #[graphql(default)]
+ pub scope: ActivityFeedScope,
}
-/// One page of the authenticated user's activity, newest first.
+/// One page of activity, newest first.
#[derive(SimpleObject)]
pub struct GraphqlActivityPage {
/// The page's activity events.
@@ -79,10 +95,13 @@ fn encode_cursor(occurred_at: DateTime<Utc>, id: Uuid, limit: u32) -> String {
/// Resolve one page of the authenticated user's activity feed, newest first.
///
-/// The subject is the viewer's principal string, so delegated actions a bot
-/// performed on the user's behalf appear in the user's own feed. Pagination
-/// follows the page's `next` position, which storage derives from raw rows —
-/// a corrupt row shrinks a page but never ends the feed.
+/// In the `MINE` scope the subject is the viewer's principal string, so
+/// delegated actions a bot performed on the user's behalf appear in the
+/// user's own feed. In the `TEAM` scope storage keeps only teammates' rows on
+/// entities shared with the viewer. Pagination follows the page's `next`
+/// position, which storage derives from raw rows — a corrupt row, or a team
+/// page's bounded scan, shrinks a page (possibly to empty) but never ends the
+/// feed.
pub async fn resolve_activity_feed<R>(
ctx: &Context<'_>,
user_id: &MacroUserIdStr<'static>,
@@ -95,10 +114,11 @@ where
let limit = parse_feed_limit(input.limit)?;
let cursor = input.cursor.map(decode_cursor).transpose()?;
- let page = reader
- .subject_feed(user_id.as_ref(), cursor, limit)
- .await
- .map_err(|_| async_graphql::Error::new("activity feed is unavailable"))?;
+ let page = match input.scope {
+ ActivityFeedScope::Mine => reader.subject_feed(user_id.as_ref(), cursor, limit).await,
+ ActivityFeedScope::Team => reader.teammate_feed(user_id.as_ref(), cursor, limit).await,
+ }
+ .map_err(|_| async_graphql::Error::new("activity feed is unavailable"))?;
Ok(GraphqlActivityPage {
items: page.records.into_iter().map(Into::into).collect(),
diff --git a/crates/graphql_activity/src/lib.rs b/crates/graphql_activity/src/lib.rs
index f6ab14171c..6331137ea3 100644
--- a/crates/graphql_activity/src/lib.rs
+++ b/crates/graphql_activity/src/lib.rs
@@ -4,8 +4,9 @@
//!
//! Three read surfaces over the `activity_events` log:
//!
-//! - the authenticated user's own feed ([`resolve_activity_feed`]), a
-//! keyset-paginated field on `GraphqlUser`;
+//! - the authenticated user's feed ([`resolve_activity_feed`]), a
+//! keyset-paginated field on `GraphqlUser` scoped to the user's own
+//! activity or to their teammates' activity on entities shared with the user;
//! - the authenticated user's trailing-year aggregate
//! ([`resolve_activity_overview`]);
//! - a lazily-loaded `activity` edge on every Soup entity, batched across
@@ -35,8 +36,8 @@ mod timeline;
pub use activity::{ActivitySubscriptionService, NoOpActivitySubscriptionService};
pub use feed::{
- ActivityFeedInput, DEFAULT_ACTIVITY_FEED_LIMIT, GraphqlActivityPage, MAX_ACTIVITY_FEED_LIMIT,
- resolve_activity_feed,
+ ActivityFeedInput, ActivityFeedScope, DEFAULT_ACTIVITY_FEED_LIMIT, GraphqlActivityPage,
+ MAX_ACTIVITY_FEED_LIMIT, resolve_activity_feed,
};
pub use loaders::{
ActivityEdgeKey, ActivityEdgeLoad, ActivityFeedReader, ActivityPortReader, ActivityReadFailed,
diff --git a/crates/graphql_activity/src/loaders.rs b/crates/graphql_activity/src/loaders.rs
index bf77930d4b..f015b6f77a 100644
--- a/crates/graphql_activity/src/loaders.rs
+++ b/crates/graphql_activity/src/loaders.rs
@@ -78,6 +78,17 @@ pub trait ActivityFeedReader: Send + Sync + 'static {
limit: NonZeroU32,
) -> impl Future<Output = Result<ActivityFeedPage, ActivityReadFailed>> + Send + 'a;
+ /// One page of the activity of the viewer's teammates on entities
+ /// shared with the viewer, paginated like
+ /// [`subject_feed`](Self::subject_feed). A page may come up short, or
+ /// empty, while `next` is set.
+ fn teammate_feed<'a>(
+ &'a self,
+ viewer_id: &'a str,
+ cursor: Option<(DateTime<Utc>, Uuid)>,
+ limit: NonZeroU32,
+ ) -> impl Future<Output = Result<ActivityFeedPage, ActivityReadFailed>> + Send + 'a;
+
/// Aggregate the subject's activity inside one local-date window.
fn subject_overview<'a>(
&'a self,
@@ -120,6 +131,18 @@ impl ActivityFeedReader for NoOpActivityReader {
})
}
+ async fn teammate_feed(
+ &self,
+ _viewer_id: &str,
+ _cursor: Option<(DateTime<Utc>, Uuid)>,
+ _limit: NonZeroU32,
+ ) -> Result<ActivityFeedPage, ActivityReadFailed> {
+ Ok(ActivityFeedPage {
+ records: Vec::new(),
+ next: None,
+ })
+ }
+
async fn subject_overview(
&self,
_subject_id: &str,
@@ -219,6 +242,21 @@ where
})
}
+ async fn teammate_feed(
+ &self,
+ viewer_id: &str,
+ cursor: Option<(DateTime<Utc>, Uuid)>,
+ limit: NonZeroU32,
+ ) -> Result<ActivityFeedPage, ActivityReadFailed> {
+ self.reads
+ .teammate_feed(viewer_id, cursor, limit)
+ .await
+ .map_err(|error| {
+ tracing::error!(?error, "team activity feed load failed");
+ ActivityReadFailed
+ })
+ }
+
async fn subject_overview(
&self,
subject_id: &str,
diff --git a/crates/initiative/src/domain/personal_activity.rs b/crates/initiative/src/domain/personal_activity.rs
index 6075ca6135..b7895bd420 100644
--- a/crates/initiative/src/domain/personal_activity.rs
+++ b/crates/initiative/src/domain/personal_activity.rs
@@ -110,6 +110,20 @@ impl<R: ActivityReads + Send + Sync, A: EntityAccessService> ActivityReads
})
}
+ async fn teammate_feed(
+ &self,
+ viewer_id: &str,
+ cursor: Option<(DateTime<Utc>, Uuid)>,
+ limit: NonZeroU32,
+ ) -> Result<ActivityFeedPage, Self::Err> {
+ // Storage keeps only rows on entities shared with the viewer,
+ // initiatives included, so there is nothing to filter here.
+ self.reads
+ .teammate_feed(viewer_id, cursor, limit)
+ .await
+ .map_err(|error| InitiativeError::Internal(rootcause::report!(error).into()))
+ }
+
async fn subject_activity_range(
&self,
subject_id: &str,
diff --git a/docs/agent-guide/activity.md b/docs/agent-guide/activity.md
index d3150d1f7d..19e81bf73b 100644
--- a/docs/agent-guide/activity.md
+++ b/docs/agent-guide/activity.md
@@ -16,6 +16,21 @@ restored splits wait for flags to load; when disabled, they redirect to Home
Open it from **More → Activity** in the sidebar rail (or `g y`); Customize sidebar
can pin it to the rail.
+The header has **You** and **Team** tabs (view tabs after the title on desktop,
+a pill strip above the list on touch); the choice is stored in the split's URL as
+`sN.activity.scope=team` and survives reloads. You is the user's own feed. Team
+lists teammates' activity, newest first, on items shared with the user directly
+or through a project, team, or channel, on channels the user is in, and on
+threads in the user's own inbox (a link share alone does not count; forms never
+appear), with each row naming the teammate. Team has no heatmap or Most active
+section. Each server page reads a bounded slice of the team's history, so a page
+can add few rows or none; the list keeps showing `Loading…` and paging on its own
+until rows arrive or the history ends, and only then reads `No activity from your
+team yet.` (also when the user is not on a team). Switching tabs opens the other feed at
+the top; switching back shows the pages already loaded. Team needs a backend that
+accepts `scope: TEAM` on `user.activity`; against an older one only that tab
+fails, with the feed's unavailable copy.
+
When checking Activity, enable GraphQL Soup as well as the activity flag. Verify
that an initial visit resolves entity names in both the feed and Most active,
then reload and scroll through another page. Preview loading and live name
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index 51a12bb89a..c8d41dbfc2 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -4,13 +4,34 @@ Page request for the authenticated user's activity feed.
input ActivityFeedInput {
"""
Opaque cursor from the previous page's `nextCursor`; absent for the
- first page.
+ first page. Pass it back with the same `scope`.
"""
cursor: String
"""
Page size; defaults to 25, capped at 100.
"""
limit: Int
+ """
+ Whose activity to read; defaults to the user's own.
+ """
+ scope: ActivityFeedScope! = MINE
+}
+
+"""
+Whose activity an activity feed page reads.
+"""
+enum ActivityFeedScope {
+ """
+ The authenticated user's own activity, delegated actions included.
+ """
+ MINE
+ """
+ Activity by the authenticated user's teammates, on entities shared
+ with the user (link sharing alone does not count; forms never). A
+ page may hold fewer items than its limit, or none, while
+ `nextCursor` is set: keep paging until it is absent.
+ """
+ TEAM
}
"""
@@ -1151,7 +1172,7 @@ type GraphqlActivityOverview {
}
"""
-One page of the authenticated user's activity, newest first.
+One page of activity, newest first.
"""
type GraphqlActivityPage {
"""
@@ -9202,8 +9223,9 @@ type GraphqlUser {
"""
folders: [GraphqlSoupProject!]!
"""
- A page of the authenticated user's own activity, newest first.
- Delegated actions performed on the user's behalf are included.
+ A page of activity, newest first: by default the authenticated
+ user's own, delegated actions included; in the `TEAM` scope, their
+ teammates' activity on entities shared with the user.
"""
activity(input: ActivityFeedInput!): GraphqlActivityPage!
"""