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): layered feature layout with injected deps (#6176)

teof598574d760c
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 3aa68a00bc..0c2b08d565 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -79,6 +79,7 @@ Then trigger the interaction and read `window.__inst.log`. `'1,2,3' → '' → '
- Keep reusable components small, atomic, and decoupled from queries/complex state. Push data-fetching and mutations up to use-case-specific composed components.
- Context should be scoped to a component subtree — Message.Content consuming a MessageContext is fine because the ownership boundary is clear.
- Composed primitives must not depend on use-case-specific context — a RecipientsSelector should never require an EmailComposeContext.
+- New features use the layered layout in docs/STYLE_GUIDE.md FE-33 (`core / queries / primitives / components / views` plus an injected `context/`). `src/features/activity` is the reference.
## Styling
- Use semantic color tokens, not raw Tailwind color classes.
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index 5fde403214..a7f3b6e7b5 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -1,3 +1,4 @@
+import { openEntityInSplit } from '@app/features/activity/open-entity-in-split';
import { useActivityFeedFlag } from '@app/features/activity/use-activity-feed-flag';
import type { EventEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';
import type { CalendarEvent } from '@app/features/calendar/types';
@@ -292,14 +293,14 @@ function RecentViewWrapper() {
}
const MyActivityView = lazy(() =>
- import('@app/features/activity/my-activity-view').then((module) => ({
+ import('@app/features/activity/views/my-activity-view').then((module) => ({
default: module.MyActivityView,
}))
);
function TrackedMyActivityView() {
usePageViewTracking('activity');
- return <MyActivityView />;
+ return <MyActivityView onOpen={openEntityInSplit} />;
}
function MyActivityViewWrapper() {
diff --git a/apps/web/src/features/activity/EntityActivitySection.tsx b/apps/web/src/features/activity/EntityActivitySection.tsx
deleted file mode 100644
index a65de9a12f..0000000000
--- a/apps/web/src/features/activity/EntityActivitySection.tsx
+++ /dev/null
@@ -1,126 +0,0 @@
-import { SidePanel } from '@components/app/side-panel/SidePanel';
-import { formatRelativeTimestamp } from '@entity/utils/timestamp';
-import CaretRightIcon from '@phosphor/caret-right.svg';
-import {
- type ActivityEvent,
- createEntityActivityQuery,
-} from '@queries/activity/graphql/entity';
-import type { EntityType } from '@service-properties/generated/schemas/entityType';
-import { cn } from '@ui';
-import { createSignal, For, Show, Suspense } from 'solid-js';
-import { ActionPhrase } from './action-phrase';
-import { ActorName } from './actor-name';
-import { useEntityActivityFlag } from './use-entity-activity-flag';
-
-/** Rows shown before the section collapses behind a "Show all" toggle. */
-const COLLAPSED_ROW_LIMIT = 10;
-
-export interface EntityActivitySectionProps {
- entityId: string;
- entityType: EntityType;
- order?: number;
-}
-
-/**
- * The side-panel Activity section, mounted only when the feature flag is on
- * so the activity query is never issued while the rollout is off.
- */
-export function EntityActivitySectionConditional(
- props: EntityActivitySectionProps
-) {
- const enabled = useEntityActivityFlag();
- return (
- <Show when={enabled()}>
- <EntityActivitySection {...props} />
- </Show>
- );
-}
-
-function EntityActivitySection(props: EntityActivitySectionProps) {
- const query = createEntityActivityQuery({
- entityType: () => props.entityType,
- entityId: () => props.entityId,
- enabled: () => true,
- });
- const events = () => query.result.data ?? [];
-
- // Collapsed to the newest rows, expandable like the History pane's
- // "Show activity" toggle, so a busy entity doesn't swallow the side panel.
- const [expanded, setExpanded] = createSignal(false);
- const visibleEvents = () =>
- expanded() ? events() : events().slice(0, COLLAPSED_ROW_LIMIT);
- const hasOverflow = () => events().length > COLLAPSED_ROW_LIMIT;
-
- return (
- <Show when={query.isEnabled()}>
- <SidePanel.Section id="activity" title="Activity" order={props.order}>
- {/* Two loading layers: the urql store never suspends, so the query's
- own fetch/error need explicit branches (or they'd render as a
- false "No activity yet"), while the Suspense boundary scopes
- resource reads inside the rows (display names, property
- definitions) to this section instead of an ancestor boundary. */}
- <Suspense fallback={<SidePanel.Loading />}>
- <Show when={!query.result.isLoading} fallback={<SidePanel.Loading />}>
- <Show
- when={!query.result.isError}
- fallback={<SidePanel.EmptyPill label="Activity is unavailable" />}
- >
- <Show
- when={events().length > 0}
- fallback={<SidePanel.EmptyPill label="No activity yet" />}
- >
- <div class="text-xs">
- <SidePanel.Card>
- <For each={visibleEvents()}>
- {(event) => <ActivityRow event={event} />}
- </For>
- </SidePanel.Card>
- <Show when={hasOverflow()}>
- <button
- type="button"
- aria-expanded={expanded()}
- class="mt-1 flex w-full items-center gap-1.5 rounded-md px-1 py-1 text-ink-muted text-xs hover:bg-hover hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40"
- onClick={() => setExpanded((current) => !current)}
- >
- <CaretRightIcon
- class={cn(
- 'size-3 shrink-0 transition-transform duration-90',
- expanded() && 'rotate-90'
- )}
- />
- <span>
- {expanded()
- ? 'Show less'
- : `Show all (${events().length})`}
- </span>
- </button>
- </Show>
- </div>
- </Show>
- </Show>
- </Show>
- </Suspense>
- </SidePanel.Section>
- </Show>
- );
-}
-
-function ActivityRow(props: { event: ActivityEvent }) {
- return (
- <div class="flex min-h-7 min-w-0 items-center gap-2 px-2 py-1">
- <span class="flex min-w-0 flex-1 flex-wrap items-center gap-x-1 gap-y-0.5">
- <span class="font-medium text-ink">
- <ActorName actorId={props.event.actorId} />
- </span>
- <span class="min-w-0 text-ink-muted">
- <ActionPhrase event={props.event} />
- </span>
- </span>
- <span class="ml-auto shrink-0 text-ink-extra-muted">
- {formatRelativeTimestamp(new Date(props.event.occurredAt), {
- condensed: true,
- })}
- </span>
- </div>
- );
-}
diff --git a/apps/web/src/features/activity/activity-timeline-row.tsx b/apps/web/src/features/activity/activity-timeline-row.tsx
deleted file mode 100644
index ed5093a4d4..0000000000
--- a/apps/web/src/features/activity/activity-timeline-row.tsx
+++ /dev/null
@@ -1,162 +0,0 @@
-import { openDocument } from '@core/component/LexicalMarkdown/component/core/BlockLink';
-import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';
-import { formatRelativeTimestamp } from '@entity/utils/timestamp';
-import { usePropertyEntityDisplay } from '@property/hooks';
-import type { ActivityEvent } from '@queries/activity/graphql/entity';
-import type { EntityType } from '@service-properties/generated/schemas/entityType';
-import type { GraphqlEntityType } from '@service-storage/graphql/generated/graphql';
-import { Show } from 'solid-js';
-import { match } from 'ts-pattern';
-import { ActionGlyph } from './action-glyph';
-import { ActionPhrase } from './action-phrase';
-import { ActorName } from './actor-name';
-import {
- actionAsPropertyChange,
- describeActionForEntity,
-} from './describe-action';
-import { EntityMention } from './entity-mention';
-import { PropertyChangeText } from './property-change';
-
-/**
- * Maps an activity event's canonical entity type onto the display vocabulary
- * used by the shared entity name/icon/link resolver. Unsupported entity kinds
- * render without a reference instead of leaking a raw identifier.
- */
-function displayEntityType(
- entityType: GraphqlEntityType
-): EntityType | undefined {
- return match<GraphqlEntityType, EntityType | undefined>(entityType)
- .with('DOCUMENT', () => 'DOCUMENT')
- .with('PROJECT', () => 'PROJECT')
- .with('CHAT', () => 'CHAT')
- .with('EMAIL_THREAD', () => 'THREAD')
- .with('CHANNEL', () => 'CHANNEL')
- .with('USER', () => 'USER')
- .otherwise(() => undefined);
-}
-
-function Timestamp(props: { event: ActivityEvent }) {
- return (
- <time
- class="ml-auto shrink-0 text-right font-medium text-ink-extra-muted text-xs"
- dateTime={props.event.occurredAt}
- >
- {formatRelativeTimestamp(new Date(props.event.occurredAt), {
- condensed: true,
- })}
- </time>
- );
-}
-
-function capitalize(value: string): string {
- return value.length === 0 ? value : value[0].toUpperCase() + value.slice(1);
-}
-
-/**
- * Shared glyph-rail activity row used by the activity feed and AI activity
- * results. Entity references, property definitions, and option/tag values all
- * flow through the same resolvers regardless of where the row is rendered.
- */
-export function ActivityTimelineRow(props: {
- event: ActivityEvent;
- /** Activity feeds name the actor; caller-scoped tool results can omit it. */
- showActor?: boolean;
-}) {
- const entityType = () => displayEntityType(props.event.entityType);
- const showActor = () => props.showActor !== false;
-
- return (
- <div class="mx-1 flex w-[calc(100%-0.5rem)] items-stretch gap-1 px-2 text-sm">
- <div class="relative flex w-6 shrink-0 items-center justify-center">
- <div class="absolute inset-y-0 w-px bg-edge-muted" />
- <span class="relative flex size-5 items-center justify-center rounded-full bg-surface ring ring-edge-muted">
- <ActionGlyph
- action={props.event.action}
- class="size-3 text-ink-muted"
- />
- </span>
- </div>
- <Show
- when={entityType()}
- fallback={
- <div class={ROW_BODY_CLASS}>
- <Show when={showActor()}>
- <span class="shrink-0 font-medium">
- <ActorName actorId={props.event.actorId} />
- </span>
- </Show>
- <span class="min-w-0 truncate text-ink-muted">
- <ActionPhrase event={props.event} capitalize={!showActor()} />
- </span>
- <Timestamp event={props.event} />
- </div>
- }
- >
- {(type) => (
- <EntityRow
- event={props.event}
- entityType={type()}
- showActor={showActor()}
- />
- )}
- </Show>
- </div>
- );
-}
-
-const ROW_BODY_CLASS =
- 'flex min-h-10 min-w-0 flex-1 items-center gap-1.5 rounded-lg px-2 py-0.5 hover:bg-hover/30';
-
-function EntityRow(props: {
- event: ActivityEvent;
- entityType: EntityType;
- showActor: boolean;
-}) {
- const parts = () => describeActionForEntity(props.event.action);
- const display = usePropertyEntityDisplay(
- () => props.event.entityId,
- () => props.entityType
- );
- const navHandlers = useSplitNavigationHandler<HTMLDivElement>((event) => {
- const block = display.blockOrFileType();
- if (!block) return;
- openDocument(
- block,
- props.event.entityId,
- display.linkParams(),
- event.shiftKey
- );
- });
-
- return (
- <div {...navHandlers} class={ROW_BODY_CLASS}>
- <Show when={props.showActor}>
- <span class="shrink-0 font-medium">
- <ActorName actorId={props.event.actorId} />
- </span>
- </Show>
- <span class="min-w-0 text-ink-muted">
- <Show
- when={actionAsPropertyChange(props.event.action)}
- fallback={props.showActor ? parts().verb : capitalize(parts().verb)}
- >
- {(change) => (
- <PropertyChangeText
- action={change()}
- capitalize={!props.showActor}
- />
- )}
- </Show>
- </span>
- <Show when={parts().connector}>
- {(connector) => (
- <span class="shrink-0 text-ink-muted">{connector()}</span>
- )}
- </Show>
- <span class="min-w-0 truncate">
- <EntityMention entityId={props.event.entityId} display={display} />
- </span>
- <Timestamp event={props.event} />
- </div>
- );
-}
diff --git a/apps/web/src/features/activity/actor-name.tsx b/apps/web/src/features/activity/actor-name.tsx
deleted file mode 100644
index e2cdfb8a7b..0000000000
--- a/apps/web/src/features/activity/actor-name.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import { useUserId } from '@core/context/user';
-import { tryMacroId, useDisplayName } from '@core/user';
-import type { MacroId } from '@core/user/macroId';
-import { Show } from 'solid-js';
-
-/**
- * The actor of an activity row: "You" for the viewer, the display name
- * (local-part email fallback, never the full address) for other users, and
- * "Automation" for bot principals.
- */
-export function ActorName(props: { actorId: string }) {
- const userId = useUserId();
- const macroId = () => tryMacroId(props.actorId);
-
- return (
- <Show when={macroId()} fallback={<>Automation</>}>
- {(id) => (
- <Show
- when={props.actorId === userId()}
- fallback={<RemoteName id={id()} />}
- >
- You
- </Show>
- )}
- </Show>
- );
-}
-
-function RemoteName(props: { id: MacroId }) {
- const [name] = useDisplayName(props.id, { emailFallback: 'local-part' });
- return <>{name()}</>;
-}
diff --git a/apps/web/src/features/activity/action-glyph.tsx b/apps/web/src/features/activity/components/action-glyph.tsx
similarity index 51%
rename from apps/web/src/features/activity/action-glyph.tsx
rename to apps/web/src/features/activity/components/action-glyph.tsx
index 39282c810c..1fd66b9a0e 100644
--- a/apps/web/src/features/activity/action-glyph.tsx
+++ b/apps/web/src/features/activity/components/action-glyph.tsx
@@ -8,31 +8,28 @@ import SlidersHorizontal from '@phosphor/sliders-horizontal.svg';
import Trash from '@phosphor/trash.svg';
import UserMinus from '@phosphor/user-minus.svg';
import UserPlus from '@phosphor/user-plus.svg';
-import type { ActivityEvent } from '@queries/activity/graphql/entity';
import { Dynamic } from 'solid-js/web';
+import type { ActivityAction } from '../core/event';
const GLYPHS = {
- GraphqlActivityCreated: Plus,
- GraphqlActivityEdited: PencilSimple,
- GraphqlActivityOpened: Eye,
- GraphqlActivityDeleted: Trash,
- GraphqlActivityMessaged: ChatCircle,
- GraphqlActivitySent: PaperPlaneTilt,
- GraphqlActivityPropertyChanged: SlidersHorizontal,
- GraphqlActivityParticipantAdded: UserPlus,
- GraphqlActivityParticipantRemoved: UserMinus,
- GraphqlActivityCallStarted: Phone,
- GraphqlActivityUnknownAction: PencilSimple,
+ created: Plus,
+ edited: PencilSimple,
+ opened: Eye,
+ deleted: Trash,
+ messaged: ChatCircle,
+ 'email-sent': PaperPlaneTilt,
+ 'property-changed': SlidersHorizontal,
+ 'participant-added': UserPlus,
+ 'participant-removed': UserMinus,
+ 'call-started': Phone,
+ unknown: PencilSimple,
} as const;
/** A small icon for the kind of action, for glyph-led activity rows. */
-export function ActionGlyph(props: {
- action: ActivityEvent['action'];
- class?: string;
-}) {
+export function ActionGlyph(props: { action: ActivityAction; class?: string }) {
return (
<Dynamic
- component={GLYPHS[props.action.__typename]}
+ component={GLYPHS[props.action.kind]}
class={props.class ?? 'size-3'}
/>
);
diff --git a/apps/web/src/features/activity/action-graph.tsx b/apps/web/src/features/activity/components/action-graph.tsx
similarity index 86%
rename from apps/web/src/features/activity/action-graph.tsx
rename to apps/web/src/features/activity/components/action-graph.tsx
index 830e3aa48e..668023cd8a 100644
--- a/apps/web/src/features/activity/action-graph.tsx
+++ b/apps/web/src/features/activity/components/action-graph.tsx
@@ -1,21 +1,22 @@
-import type { ActivityOverview } from '@queries/activity/graphql/overview';
import { cn, Layer, Tooltip } from '@ui';
import { format } from 'date-fns';
import { createMemo, For, type JSX } from 'solid-js';
-import { OVERVIEW_TZ, parseOverviewDate } from './activity-dates';
+import { match } from 'ts-pattern';
+import { OVERVIEW_TZ, parseOverviewDate } from '../core/activity-dates';
import {
type ActivityStats,
formatDayLabel,
formatMonthName,
formatStreak,
summarizeActivity,
-} from './activity-stats';
+} from '../core/activity-stats';
import {
buildContributionGrid,
type ContributionDay,
type ContributionWeek,
-} from './contribution-grid';
-import { INTENSITY_CLASS } from './intensity';
+} from '../core/contribution-grid';
+import type { ActivityOverview } from '../core/event';
+import type { ActivityIntensity } from '../core/intensity';
const WEEKDAY_LABELS = ['', 'M', '', 'W', '', 'F', ''];
@@ -102,7 +103,7 @@ function IntensityLegend() {
<span>Fewer</span>
<For each={[0, 1, 2, 3, 4] as const}>
{(level) => (
- <span class={`size-2.5 rounded-[3px] ${INTENSITY_CLASS[level]}`} />
+ <IntensitySwatch level={level} class="size-2.5 rounded-[3px]" />
)}
</For>
<span>More</span>
@@ -181,14 +182,37 @@ function DaySquare(props: { day: ContributionDay | null }) {
class="aspect-square w-full shrink-0"
label={label}
>
- <span
+ <IntensitySwatch
+ level={day.intensity}
+ class="block size-full rounded-[3px]"
aria-label={label}
- class={`block size-full rounded-[3px] ${INTENSITY_CLASS[day.intensity]}`}
/>
</Tooltip>
);
}
+function IntensitySwatch(props: {
+ level: ActivityIntensity;
+ class?: string;
+ 'aria-label'?: string;
+}) {
+ return (
+ <span
+ aria-label={props['aria-label']}
+ class={cn(
+ match(props.level)
+ .with(0, () => 'bg-ink/10')
+ .with(1, () => 'bg-accent/25')
+ .with(2, () => 'bg-accent/45')
+ .with(3, () => 'bg-accent/70')
+ .with(4, () => 'bg-accent')
+ .exhaustive(),
+ props.class
+ )}
+ />
+ );
+}
+
/**
* One week column. Grows to fill the card width, floored at the day-cell
* size (a very narrow panel scrolls horizontally rather than squashing the
diff --git a/apps/web/src/features/activity/action-phrase.tsx b/apps/web/src/features/activity/components/action-phrase.tsx
similarity index 58%
rename from apps/web/src/features/activity/action-phrase.tsx
rename to apps/web/src/features/activity/components/action-phrase.tsx
index f04bbea37e..49d48e0368 100644
--- a/apps/web/src/features/activity/action-phrase.tsx
+++ b/apps/web/src/features/activity/components/action-phrase.tsx
@@ -1,6 +1,7 @@
-import type { ActivityEvent } from '@queries/activity/graphql/entity';
+import type { PropertyDefinitionDomain } from '@property/types';
import { Show } from 'solid-js';
-import { actionAsPropertyChange, describeAction } from './describe-action';
+import { describeAction } from '../core/describe-action';
+import type { ActivityEvent } from '../core/event';
import { PropertyChangeText } from './property-change';
function capitalize(value: string): string {
@@ -14,11 +15,16 @@ function capitalize(value: string): string {
*/
export function ActionPhrase(props: {
event: ActivityEvent;
+ propertyDefinition?: PropertyDefinitionDomain;
capitalize?: boolean;
}) {
return (
<Show
- when={actionAsPropertyChange(props.event.action)}
+ when={
+ props.event.action.kind === 'property-changed'
+ ? props.event.action
+ : undefined
+ }
fallback={
props.capitalize
? capitalize(describeAction(props.event.action))
@@ -26,7 +32,11 @@ export function ActionPhrase(props: {
}
>
{(change) => (
- <PropertyChangeText action={change()} capitalize={props.capitalize} />
+ <PropertyChangeText
+ action={change()}
+ definition={props.propertyDefinition}
+ capitalize={props.capitalize}
+ />
)}
</Show>
);
diff --git a/apps/web/src/features/activity/components/activity-timeline-row.tsx b/apps/web/src/features/activity/components/activity-timeline-row.tsx
new file mode 100644
index 0000000000..05d197dfbf
--- /dev/null
+++ b/apps/web/src/features/activity/components/activity-timeline-row.tsx
@@ -0,0 +1,153 @@
+import { formatRelativeTimestamp } from '@entity/utils/timestamp';
+import type { PropertyDefinitionDomain } from '@property/types';
+import { type JSX, Show } from 'solid-js';
+import type { EntityDisplay } from '../context/activity-context';
+import { describeActionForEntity } from '../core/describe-action';
+import type { ActivityEvent } from '../core/event';
+import { ActionGlyph } from './action-glyph';
+import { ActionPhrase } from './action-phrase';
+import { ActorName } from './actor-name';
+import { EntityMention } from './entity-mention';
+import { PropertyChangeText } from './property-change';
+
+function Timestamp(props: { event: ActivityEvent }) {
+ return (
+ <time
+ class="ml-auto shrink-0 text-right font-medium text-ink-extra-muted text-xs"
+ dateTime={props.event.occurredAt}
+ >
+ {formatRelativeTimestamp(new Date(props.event.occurredAt), {
+ condensed: true,
+ })}
+ </time>
+ );
+}
+
+function capitalize(value: string): string {
+ return value.length === 0 ? value : value[0].toUpperCase() + value.slice(1);
+}
+
+/**
+ * Glyph-rail activity row. Mentions and click-to-open handlers are passed
+ * in already resolved so this leaf stays presentational.
+ */
+export function ActivityTimelineRow(props: {
+ event: ActivityEvent;
+ actorName?: string;
+ showActor?: boolean;
+ display?: EntityDisplay;
+ propertyDefinition?: PropertyDefinitionDomain;
+ rowProps?: JSX.HTMLAttributes<HTMLDivElement>;
+}) {
+ const showActor = () => props.showActor !== false;
+ const actorName = () => props.actorName ?? '';
+
+ return (
+ <div
+ class="mx-1 flex w-[calc(100%-0.5rem)] items-stretch gap-1 px-2 text-sm"
+ data-activity-row
+ data-activity-action={props.event.action.kind}
+ >
+ <div class="relative flex w-6 shrink-0 items-center justify-center">
+ <div class="absolute inset-y-0 w-px bg-edge-muted" />
+ <span class="relative flex size-5 items-center justify-center rounded-full bg-surface ring ring-edge-muted">
+ <ActionGlyph
+ action={props.event.action}
+ class="size-3 text-ink-muted"
+ />
+ </span>
+ </div>
+ <Show
+ when={props.display}
+ fallback={
+ <RowBody>
+ <Show when={showActor()}>
+ <span class="shrink-0 font-medium">
+ <ActorName name={actorName()} />
+ </span>
+ </Show>
+ <span class="min-w-0 truncate text-ink-muted">
+ <ActionPhrase
+ event={props.event}
+ propertyDefinition={props.propertyDefinition}
+ capitalize={!showActor()}
+ />
+ </span>
+ <Timestamp event={props.event} />
+ </RowBody>
+ }
+ >
+ {(display) => (
+ <EntityRow
+ event={props.event}
+ display={display()}
+ showActor={showActor()}
+ actorName={actorName()}
+ propertyDefinition={props.propertyDefinition}
+ rowProps={props.rowProps}
+ />
+ )}
+ </Show>
+ </div>
+ );
+}
+
+function RowBody(props: JSX.HTMLAttributes<HTMLDivElement>) {
+ return (
+ <div
+ {...props}
+ class="flex min-h-10 min-w-0 flex-1 items-center gap-1.5 rounded-lg px-2 py-0.5 hover:bg-hover/30"
+ />
+ );
+}
+
+function EntityRow(props: {
+ event: ActivityEvent;
+ display: EntityDisplay;
+ showActor: boolean;
+ actorName: string;
+ propertyDefinition?: PropertyDefinitionDomain;
+ rowProps?: JSX.HTMLAttributes<HTMLDivElement>;
+}) {
+ const parts = () => describeActionForEntity(props.event.action);
+
+ return (
+ <RowBody {...props.rowProps}>
+ <Show when={props.showActor}>
+ <span class="shrink-0 font-medium">
+ <ActorName name={props.actorName} />
+ </span>
+ </Show>
+ <span class="min-w-0 text-ink-muted">
+ <Show
+ when={
+ props.event.action.kind === 'property-changed'
+ ? props.event.action
+ : undefined
+ }
+ fallback={props.showActor ? parts().verb : capitalize(parts().verb)}
+ >
+ {(change) => (
+ <PropertyChangeText
+ action={change()}
+ definition={props.propertyDefinition}
+ capitalize={!props.showActor}
+ />
+ )}
+ </Show>
+ </span>
+ <Show when={parts().connector}>
+ {(connector) => (
+ <span class="shrink-0 text-ink-muted">{connector()}</span>
+ )}
+ </Show>
+ <span class="min-w-0 truncate">
+ <EntityMention
+ entityId={props.event.entityId}
+ display={props.display}
+ />
+ </span>
+ <Timestamp event={props.event} />
+ </RowBody>
+ );
+}
diff --git a/apps/web/src/features/activity/components/actor-name.tsx b/apps/web/src/features/activity/components/actor-name.tsx
new file mode 100644
index 0000000000..b708f4c84a
--- /dev/null
+++ b/apps/web/src/features/activity/components/actor-name.tsx
@@ -0,0 +1,3 @@
+export function ActorName(props: { name: string }) {
+ return <>{props.name}</>;
+}
diff --git a/apps/web/src/features/activity/entity-mention.tsx b/apps/web/src/features/activity/components/entity-mention.tsx
similarity index 75%
rename from apps/web/src/features/activity/entity-mention.tsx
rename to apps/web/src/features/activity/components/entity-mention.tsx
index 962c279e3f..acf3282e58 100644
--- a/apps/web/src/features/activity/entity-mention.tsx
+++ b/apps/web/src/features/activity/components/entity-mention.tsx
@@ -1,10 +1,7 @@
import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { unifiedListMarkdownTheme } from '@core/component/LexicalMarkdown/theme';
-import type { usePropertyEntityDisplay } from '@property/hooks';
import { Show } from 'solid-js';
-
-/** The resolved display accessors for one entity, from the shared resolver. */
-export type EntityDisplay = ReturnType<typeof usePropertyEntityDisplay>;
+import type { EntityDisplay } from '../context/activity-context';
/**
* An activity row's entity reference rendered as a real document mention —
@@ -12,10 +9,9 @@ export type EntityDisplay = ReturnType<typeof usePropertyEntityDisplay>;
* preview, access states, and click-to-open. Entity kinds without a block
* mapping fall back to a plain icon + name chip.
*
- * Takes the already-resolved display from the row (which also needs it for
- * click-to-open) rather than resolving its own, so each row subscribes to
- * the entity's preview once. Must render under a `<StaticMarkdownContext>`
- * ancestor.
+ * Takes the already-resolved display from the view so each row
+ * subscribes to the entity's preview once. Must render under a
+ * `<StaticMarkdownContext>` ancestor.
*/
export function EntityMention(props: {
entityId: string;
diff --git a/apps/web/src/features/activity/property-change.tsx b/apps/web/src/features/activity/components/property-change.tsx
similarity index 89%
rename from apps/web/src/features/activity/property-change.tsx
rename to apps/web/src/features/activity/components/property-change.tsx
index fcce3ba89d..184f50d4c6 100644
--- a/apps/web/src/features/activity/property-change.tsx
+++ b/apps/web/src/features/activity/components/property-change.tsx
@@ -1,17 +1,16 @@
import { PropertyValueIcon } from '@property/component/propertyValue/PropertyValueIcon';
-import { useAllProperties } from '@property/editor/hooks/useAllProperties';
import { TagDot } from '@property/tags/TagDot';
import type { PropertyDefinitionDomain } from '@property/types';
-import type { ActivityEvent } from '@queries/activity/graphql/entity';
import { For, Show } from 'solid-js';
+import type { ActivityAction } from '../core/event';
import {
propertyValueLabel,
selectOptionEntries,
-} from './property-change-label';
+} from '../queries/property-value';
type PropertyChangedAction = Extract<
- ActivityEvent['action'],
- { __typename: 'GraphqlActivityPropertyChanged' }
+ ActivityAction,
+ { kind: 'property-changed' }
>;
/**
@@ -25,11 +24,10 @@ type PropertyChangedAction = Extract<
*/
export function PropertyChangeText(props: {
action: PropertyChangedAction;
+ definition: PropertyDefinitionDomain | undefined;
capitalize?: boolean;
}) {
- const definitions = useAllProperties();
- const definition = () =>
- definitions().find((def) => def.id === props.action.property);
+ const definition = () => props.definition;
const name = () => definition()?.displayName ?? 'a property';
const cleared = () =>
props.action.to === null || props.action.to === undefined;
diff --git a/apps/web/src/features/activity/components/top-entities.tsx b/apps/web/src/features/activity/components/top-entities.tsx
new file mode 100644
index 0000000000..7a5498ab9e
--- /dev/null
+++ b/apps/web/src/features/activity/components/top-entities.tsx
@@ -0,0 +1,63 @@
+import { SoupSectionHeader } from '@app/features/next-soup/soup-view/section-header';
+import { type JSX, Show } from 'solid-js';
+import type { EntityDisplay } from '../context/activity-context';
+import type { ActivityTopEntity } from '../core/event';
+import { EntityMention } from './entity-mention';
+
+/** The "Most active" section chrome; the view supplies the rows. */
+export function TopEntitiesSection(props: {
+ empty: boolean;
+ children: JSX.Element;
+}) {
+ return (
+ <section class="min-w-0" aria-label="Most active">
+ <SoupSectionHeader>Most active</SoupSectionHeader>
+ <Show
+ when={!props.empty}
+ fallback={
+ <p class="px-2 py-2 text-ink-muted text-sm">No entities yet.</p>
+ }
+ >
+ {props.children}
+ </Show>
+ </section>
+ );
+}
+
+/**
+ * One most-active row sharing the feed's row chrome: mention on the left,
+ * action count on the right. Without a resolved display the entity kind is
+ * not linkable and the row reads "Item".
+ */
+export function TopEntityRow(props: {
+ entity: ActivityTopEntity;
+ display?: EntityDisplay;
+ rowProps?: JSX.HTMLAttributes<HTMLDivElement>;
+}) {
+ return (
+ <div class="mx-1 flex w-[calc(100%-0.5rem)] items-stretch px-2 text-sm">
+ <div
+ {...props.rowProps}
+ class="flex min-h-10 min-w-0 flex-1 items-center gap-1.5 rounded-lg px-2 py-0.5 hover:bg-hover/30"
+ >
+ <span class="min-w-0 truncate">
+ <Show
+ when={props.display}
+ fallback={<span class="text-ink-extra-muted">Item</span>}
+ >
+ {(display) => (
+ <EntityMention
+ entityId={props.entity.entityId}
+ display={display()}
+ />
+ )}
+ </Show>
+ </span>
+ <span class="ml-auto shrink-0 text-right font-medium text-ink-extra-muted text-xs tabular-nums">
+ {props.entity.count.toLocaleString()}{' '}
+ {props.entity.count === 1 ? 'action' : 'actions'}
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/activity/context/activity-context.tsx b/apps/web/src/features/activity/context/activity-context.tsx
new file mode 100644
index 0000000000..2bbade0d5a
--- /dev/null
+++ b/apps/web/src/features/activity/context/activity-context.tsx
@@ -0,0 +1,87 @@
+import { useUserId } from '@core/context/user';
+import { tryMacroId, useDisplayName } from '@core/user';
+import { useAllProperties } from '@property/editor/hooks/useAllProperties';
+import { usePropertyEntityDisplay } from '@property/hooks';
+import type { PropertyDefinitionDomain } from '@property/types';
+import type { EntityType } from '@service-properties/generated/schemas/entityType';
+import { getGraphqlSoupClient } from '@service-storage/graphql-soup';
+import type { Client } from '@urql/core';
+import { type Accessor, createContext, type JSX, useContext } from 'solid-js';
+
+/** Resolved display for one referenced entity: name, icon, and link target. */
+export type EntityDisplay = {
+ name: Accessor<string>;
+ icon: Accessor<JSX.Element>;
+ isLoading: Accessor<boolean>;
+ blockOrFileType: Accessor<string | null>;
+ linkParams: Accessor<Record<string, string> | undefined>;
+};
+
+/** What a row asks its host to open. The host decides how. */
+export type OpenEntityTarget = {
+ block: string;
+ id: string;
+ params?: Record<string, string>;
+ newSplit: boolean;
+};
+
+/**
+ * The ambient capabilities activity reads the same way on every surface.
+ * Production resolves them from the app below; tests swap them through
+ * `ActivityContextProvider`. Per-surface policy (what a click opens) is a
+ * callback prop, not a context field. No file under `queries/`,
+ * `primitives/`, `components/`, or `views/` imports these capabilities
+ * directly.
+ */
+export type ActivityContext = {
+ /** GraphQL client for the activity queries. */
+ graphql: Accessor<Client>;
+ /** The signed-in user, so their own rows read "You". */
+ currentUserId: Accessor<string>;
+ /**
+ * Display name for an actor id. Resolves to `undefined` when the id is
+ * not a user (automation rows), `''` while loading, else the name.
+ */
+ displayName: (actorId: Accessor<string>) => Accessor<string | undefined>;
+ /** Name, icon, and link target for a referenced entity. */
+ entityDisplay: (
+ entityId: Accessor<string>,
+ entityType: Accessor<EntityType>
+ ) => EntityDisplay;
+ /** The property definition behind a property-changed row, when known. */
+ propertyDefinition: (
+ propertyId: Accessor<string | undefined>
+ ) => Accessor<PropertyDefinitionDomain | undefined>;
+};
+
+const ActivityContextValue = createContext<ActivityContext>();
+
+/** Test seam. Production never mounts this; `useActivityContext` falls back to the app. */
+export const ActivityContextProvider = ActivityContextValue.Provider;
+
+export function useActivityContext(): ActivityContext {
+ return useContext(ActivityContextValue) ?? appActivityContext();
+}
+
+function appActivityContext(): ActivityContext {
+ const userId = useUserId();
+ return {
+ graphql: () => getGraphqlSoupClient(),
+ currentUserId: () => userId() ?? '',
+ displayName: (actorId) => {
+ const id = tryMacroId(actorId());
+ if (!id) return () => undefined;
+ const [name] = useDisplayName(id, { emailFallback: 'local-part' });
+ return name;
+ },
+ entityDisplay: (entityId, entityType) =>
+ usePropertyEntityDisplay(entityId, entityType),
+ propertyDefinition: (propertyId) => {
+ const definitions = useAllProperties();
+ return () => {
+ const id = propertyId();
+ return id ? definitions().find((def) => def.id === id) : undefined;
+ };
+ },
+ };
+}
diff --git a/apps/web/src/features/activity/activity-dates.ts b/apps/web/src/features/activity/core/activity-dates.ts
similarity index 100%
rename from apps/web/src/features/activity/activity-dates.ts
rename to apps/web/src/features/activity/core/activity-dates.ts
diff --git a/apps/web/src/features/activity/activity-stats.test.ts b/apps/web/src/features/activity/core/activity-stats.test.ts
similarity index 100%
rename from apps/web/src/features/activity/activity-stats.test.ts
rename to apps/web/src/features/activity/core/activity-stats.test.ts
diff --git a/apps/web/src/features/activity/activity-stats.ts b/apps/web/src/features/activity/core/activity-stats.ts
similarity index 100%
rename from apps/web/src/features/activity/activity-stats.ts
rename to apps/web/src/features/activity/core/activity-stats.ts
diff --git a/apps/web/src/features/activity/contribution-grid.test.ts b/apps/web/src/features/activity/core/contribution-grid.test.ts
similarity index 100%
rename from apps/web/src/features/activity/contribution-grid.test.ts
rename to apps/web/src/features/activity/core/contribution-grid.test.ts
diff --git a/apps/web/src/features/activity/contribution-grid.ts b/apps/web/src/features/activity/core/contribution-grid.ts
similarity index 100%
rename from apps/web/src/features/activity/contribution-grid.ts
rename to apps/web/src/features/activity/core/contribution-grid.ts
diff --git a/apps/web/src/features/activity/core/describe-action.test.ts b/apps/web/src/features/activity/core/describe-action.test.ts
new file mode 100644
index 0000000000..298c926acd
--- /dev/null
+++ b/apps/web/src/features/activity/core/describe-action.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from 'vitest';
+import { describeAction, describeActionForEntity } from './describe-action';
+import type { ActivityAction } from './event';
+
+const DESCRIBE_CASES: Array<[ActivityAction, string]> = [
+ [{ kind: 'created' }, 'created this'],
+ [{ kind: 'edited' }, 'made an edit'],
+ [{ kind: 'opened' }, 'opened this'],
+ [{ kind: 'deleted' }, 'deleted this'],
+ [{ kind: 'messaged' }, 'sent a message'],
+ [{ kind: 'email-sent' }, 'sent an email'],
+ [
+ { kind: 'property-changed', property: 'prop-1', from: null, to: 'Done' },
+ 'changed a property',
+ ],
+ [
+ { kind: 'participant-added', participant: 'macro|[email protected]' },
+ 'added a participant',
+ ],
+ [
+ { kind: 'participant-removed', participant: 'macro|[email protected]' },
+ 'removed a participant',
+ ],
+ [{ kind: 'call-started' }, 'started a call'],
+];
+
+const ENTITY_CASES: Array<
+ [ActivityAction, { verb: string; connector?: string }]
+> = [
+ [{ kind: 'created' }, { verb: 'created' }],
+ [{ kind: 'messaged' }, { verb: 'sent a message', connector: 'in' }],
+ [
+ { kind: 'participant-added', participant: 'macro|[email protected]' },
+ { verb: 'added a participant', connector: 'to' },
+ ],
+ [
+ { kind: 'property-changed', property: 'prop-1', from: null, to: 'Done' },
+ { verb: 'changed a property', connector: 'on' },
+ ],
+];
+
+describe('describeAction', () => {
+ it.each(DESCRIBE_CASES)('describes %j', (action, expected) => {
+ expect(describeAction(action)).toBe(expected);
+ });
+
+ it.each(ENTITY_CASES)(
+ 'pairs %j with its entity connector',
+ (action, expected) => {
+ expect(describeActionForEntity(action)).toEqual(expected);
+ }
+ );
+
+ it('humanizes the raw tag of an unknown action instead of hiding it', () => {
+ expect(
+ describeAction({
+ kind: 'unknown',
+ tag: 'transmogrified_thoroughly',
+ })
+ ).toBe('transmogrified thoroughly');
+ });
+});
diff --git a/apps/web/src/features/activity/core/describe-action.ts b/apps/web/src/features/activity/core/describe-action.ts
new file mode 100644
index 0000000000..37f086aaf0
--- /dev/null
+++ b/apps/web/src/features/activity/core/describe-action.ts
@@ -0,0 +1,74 @@
+import { match } from 'ts-pattern';
+import type { ActivityAction } from './event';
+
+/**
+ * Short verb phrase for one activity action, phrased to follow an actor
+ * name: "Sarah <created this>". Unknown actions (rows written by a newer
+ * deployment) fall back to their humanized raw tag rather than hiding the
+ * row.
+ */
+export function describeAction(action: ActivityAction): string {
+ return match(action)
+ .with({ kind: 'created' }, () => 'created this')
+ .with({ kind: 'edited' }, () => 'made an edit')
+ .with({ kind: 'opened' }, () => 'opened this')
+ .with({ kind: 'deleted' }, () => 'deleted this')
+ .with({ kind: 'messaged' }, () => 'sent a message')
+ .with({ kind: 'email-sent' }, () => 'sent an email')
+ .with({ kind: 'property-changed' }, () => 'changed a property')
+ .with({ kind: 'participant-added' }, () => 'added a participant')
+ .with({ kind: 'participant-removed' }, () => 'removed a participant')
+ .with({ kind: 'call-started' }, () => 'started a call')
+ .with({ kind: 'unknown' }, (unknown) => unknown.tag.replaceAll('_', ' '))
+ .exhaustive();
+}
+
+/**
+ * The verb for a row that names its entity: "<actor> <verb> [connector]
+ * <entity>". Direct-object actions carry no connector ("created *Doc*");
+ * located actions carry the natural preposition ("sent a message *in*
+ * #general", "changed Status *on* *Doc*").
+ */
+export function describeActionForEntity(action: ActivityAction): {
+ verb: string;
+ connector?: string;
+} {
+ return match(action)
+ .with({ kind: 'created' }, () => ({
+ verb: 'created',
+ }))
+ .with({ kind: 'edited' }, () => ({ verb: 'edited' }))
+ .with({ kind: 'opened' }, () => ({ verb: 'opened' }))
+ .with({ kind: 'deleted' }, () => ({
+ verb: 'deleted',
+ }))
+ .with({ kind: 'messaged' }, () => ({
+ verb: 'sent a message',
+ connector: 'in',
+ }))
+ .with({ kind: 'email-sent' }, () => ({
+ verb: 'sent an email',
+ connector: 'in',
+ }))
+ .with({ kind: 'property-changed' }, () => ({
+ verb: 'changed a property',
+ connector: 'on',
+ }))
+ .with({ kind: 'participant-added' }, () => ({
+ verb: 'added a participant',
+ connector: 'to',
+ }))
+ .with({ kind: 'participant-removed' }, () => ({
+ verb: 'removed a participant',
+ connector: 'from',
+ }))
+ .with({ kind: 'call-started' }, () => ({
+ verb: 'started a call',
+ connector: 'in',
+ }))
+ .with({ kind: 'unknown' }, (unknown) => ({
+ verb: unknown.tag.replaceAll('_', ' '),
+ connector: 'on',
+ }))
+ .exhaustive();
+}
diff --git a/apps/web/src/features/activity/core/event.ts b/apps/web/src/features/activity/core/event.ts
new file mode 100644
index 0000000000..8a0ec0d510
--- /dev/null
+++ b/apps/web/src/features/activity/core/event.ts
@@ -0,0 +1,69 @@
+import { match } from 'ts-pattern';
+
+export type ActivityAction =
+ | { kind: 'created' }
+ | { kind: 'edited' }
+ | { kind: 'opened' }
+ | { kind: 'deleted' }
+ | { kind: 'messaged' }
+ | { kind: 'email-sent' }
+ | { kind: 'call-started' }
+ | { kind: 'property-changed'; property: string; from: unknown; to: unknown }
+ | { kind: 'participant-added'; participant: string }
+ | { kind: 'participant-removed'; participant: string }
+ | { kind: 'unknown'; tag: string };
+
+export type ActivityEntityType =
+ | 'document'
+ | 'project'
+ | 'chat'
+ | 'email-thread'
+ | 'channel'
+ | 'user'
+ | { kind: 'unsupported'; raw: string };
+
+export type ActivityEvent = {
+ id: string;
+ actorId: string;
+ entityId: string;
+ entityType: ActivityEntityType;
+ occurredAt: string;
+ action: ActivityAction;
+};
+
+export type ActivityTopEntity = {
+ entityId: string;
+ entityType: ActivityEntityType;
+ count: number;
+};
+
+export type ActivityOverview = {
+ from: string;
+ to: string;
+ timeZone: string;
+ total: number;
+ days: Array<{ date: string; count: number }>;
+ topEntities: ActivityTopEntity[];
+};
+
+export type PropertyEntityType =
+ | 'DOCUMENT'
+ | 'PROJECT'
+ | 'CHAT'
+ | 'THREAD'
+ | 'CHANNEL'
+ | 'USER';
+
+export function toPropertyEntityType(
+ entityType: ActivityEntityType
+): PropertyEntityType | undefined {
+ return match(entityType)
+ .with({ kind: 'unsupported' }, () => undefined)
+ .with('document', () => 'DOCUMENT' as const)
+ .with('project', () => 'PROJECT' as const)
+ .with('chat', () => 'CHAT' as const)
+ .with('email-thread', () => 'THREAD' as const)
+ .with('channel', () => 'CHANNEL' as const)
+ .with('user', () => 'USER' as const)
+ .exhaustive();
+}
diff --git a/apps/web/src/features/activity/core/group-events.test.ts b/apps/web/src/features/activity/core/group-events.test.ts
new file mode 100644
index 0000000000..acab3a5fb2
--- /dev/null
+++ b/apps/web/src/features/activity/core/group-events.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+import type { ActivityEvent } from './event';
+import { groupEventsByDay } from './group-events';
+
+function event(id: string, occurredAt: string): ActivityEvent {
+ return {
+ id,
+ actorId: 'macro|[email protected]',
+ entityId: 'doc-1',
+ entityType: 'document',
+ occurredAt,
+ action: { kind: 'created' },
+ };
+}
+
+describe('groupEventsByDay', () => {
+ it('returns an empty list for no events', () => {
+ expect(groupEventsByDay([])).toEqual([]);
+ });
+
+ it('keeps consecutive events that share a date bucket in one group', () => {
+ const groups = groupEventsByDay([
+ event('a', '2026-08-21T10:00:00.000Z'),
+ event('b', '2026-08-21T11:00:00.000Z'),
+ ]);
+
+ expect(groups).toHaveLength(1);
+ expect(groups[0].events.map((item) => item.id)).toEqual(['a', 'b']);
+ expect(groups[0].key).toBe(groups[0].key);
+ });
+
+ it('starts a new group when the date bucket changes', () => {
+ const groups = groupEventsByDay([
+ event('today', '2026-08-21T10:00:00.000Z'),
+ event('older', '2020-01-01T10:00:00.000Z'),
+ ]);
+
+ expect(groups).toHaveLength(2);
+ expect(groups[0].events.map((item) => item.id)).toEqual(['today']);
+ expect(groups[1].events.map((item) => item.id)).toEqual(['older']);
+ expect(groups[0].key).not.toBe(groups[1].key);
+ });
+});
diff --git a/apps/web/src/features/activity/core/group-events.ts b/apps/web/src/features/activity/core/group-events.ts
new file mode 100644
index 0000000000..5a8b931a94
--- /dev/null
+++ b/apps/web/src/features/activity/core/group-events.ts
@@ -0,0 +1,22 @@
+import { dateBucket } from '@app/features/soup/collection/date-buckets';
+import type { ActivityEvent } from './event';
+
+export type FeedGroup = {
+ key: string;
+ label: string;
+ events: ActivityEvent[];
+};
+
+export function groupEventsByDay(events: ActivityEvent[]): FeedGroup[] {
+ const out: FeedGroup[] = [];
+ for (const event of events) {
+ const bucket = dateBucket(event.occurredAt);
+ const last = out[out.length - 1];
+ if (last?.key === bucket.key) {
+ last.events.push(event);
+ } else {
+ out.push({ ...bucket, events: [event] });
+ }
+ }
+ return out;
+}
diff --git a/apps/web/src/features/activity/intensity.test.ts b/apps/web/src/features/activity/core/intensity.test.ts
similarity index 100%
rename from apps/web/src/features/activity/intensity.test.ts
rename to apps/web/src/features/activity/core/intensity.test.ts
diff --git a/apps/web/src/features/activity/intensity.ts b/apps/web/src/features/activity/core/intensity.ts
similarity index 58%
rename from apps/web/src/features/activity/intensity.ts
rename to apps/web/src/features/activity/core/intensity.ts
index a8e7cf2f6b..ce612a899f 100644
--- a/apps/web/src/features/activity/intensity.ts
+++ b/apps/web/src/features/activity/core/intensity.ts
@@ -4,11 +4,3 @@ export function intensityLevel(count: number, max: number): ActivityIntensity {
if (count <= 0 || max <= 0) return 0;
return Math.ceil(Math.min(count / max, 1) * 4) as ActivityIntensity;
}
-
-export const INTENSITY_CLASS: Record<ActivityIntensity, string> = {
- 0: 'bg-ink/10',
- 1: 'bg-accent/25',
- 2: 'bg-accent/45',
- 3: 'bg-accent/70',
- 4: 'bg-accent',
-};
diff --git a/apps/web/src/features/activity/describe-action.test.ts b/apps/web/src/features/activity/describe-action.test.ts
deleted file mode 100644
index b254b88f91..0000000000
--- a/apps/web/src/features/activity/describe-action.test.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { describeAction, describeActionForEntity } from './describe-action';
-
-describe('describeAction', () => {
- it('describes every known action with a verb phrase', () => {
- expect(describeAction({ __typename: 'GraphqlActivityCreated' })).toBe(
- 'created this'
- );
- expect(describeAction({ __typename: 'GraphqlActivityEdited' })).toBe(
- 'made an edit'
- );
- expect(describeAction({ __typename: 'GraphqlActivityOpened' })).toBe(
- 'opened this'
- );
- expect(describeAction({ __typename: 'GraphqlActivityDeleted' })).toBe(
- 'deleted this'
- );
- expect(describeAction({ __typename: 'GraphqlActivityMessaged' })).toBe(
- 'sent a message'
- );
- expect(describeAction({ __typename: 'GraphqlActivitySent' })).toBe(
- 'sent an email'
- );
- expect(
- describeAction({
- __typename: 'GraphqlActivityPropertyChanged',
- property: 'prop-1',
- from: null,
- to: 'Done',
- })
- ).toBe('changed a property');
- expect(
- describeAction({
- __typename: 'GraphqlActivityParticipantAdded',
- participant: 'macro|[email protected]',
- })
- ).toBe('added a participant');
- expect(
- describeAction({
- __typename: 'GraphqlActivityParticipantRemoved',
- participant: 'macro|[email protected]',
- })
- ).toBe('removed a participant');
- expect(
- describeAction({
- __typename: 'GraphqlActivityCallStarted',
- callId: 'call-1',
- })
- ).toBe('started a call');
- });
-
- it('pairs entity-directed verbs with their natural connector', () => {
- expect(
- describeActionForEntity({ __typename: 'GraphqlActivityCreated' })
- ).toEqual({ verb: 'created' });
- expect(
- describeActionForEntity({ __typename: 'GraphqlActivityMessaged' })
- ).toEqual({ verb: 'sent a message', connector: 'in' });
- expect(
- describeActionForEntity({
- __typename: 'GraphqlActivityParticipantAdded',
- participant: 'macro|[email protected]',
- })
- ).toEqual({ verb: 'added a participant', connector: 'to' });
- expect(
- describeActionForEntity({
- __typename: 'GraphqlActivityPropertyChanged',
- property: 'prop-1',
- from: null,
- to: 'Done',
- })
- ).toEqual({ verb: 'changed a property', connector: 'on' });
- });
-
- it('humanizes the raw tag of an unknown action instead of hiding it', () => {
- expect(
- describeAction({
- __typename: 'GraphqlActivityUnknownAction',
- tag: 'transmogrified_thoroughly',
- payload: null,
- })
- ).toBe('transmogrified thoroughly');
- });
-});
diff --git a/apps/web/src/features/activity/describe-action.ts b/apps/web/src/features/activity/describe-action.ts
deleted file mode 100644
index 9d5ed5fb6b..0000000000
--- a/apps/web/src/features/activity/describe-action.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import type { ActivityEvent } from '@queries/activity/graphql/entity';
-import { match } from 'ts-pattern';
-
-type ActivityAction = ActivityEvent['action'];
-
-/**
- * Narrows an action to its property-change member, for rows that render
- * the richer "changed X from A to B" phrase instead of [`describeAction`].
- */
-export function actionAsPropertyChange(
- action: ActivityAction
-):
- | Extract<ActivityAction, { __typename: 'GraphqlActivityPropertyChanged' }>
- | undefined {
- return action.__typename === 'GraphqlActivityPropertyChanged'
- ? action
- : undefined;
-}
-
-/**
- * Short verb phrase for one activity action, phrased to follow an actor
- * name: "Sarah <created this>". Unknown actions (rows written by a newer
- * deployment) fall back to their humanized raw tag rather than hiding the
- * row.
- */
-export function describeAction(action: ActivityAction): string {
- return match(action)
- .with({ __typename: 'GraphqlActivityCreated' }, () => 'created this')
- .with({ __typename: 'GraphqlActivityEdited' }, () => 'made an edit')
- .with({ __typename: 'GraphqlActivityOpened' }, () => 'opened this')
- .with({ __typename: 'GraphqlActivityDeleted' }, () => 'deleted this')
- .with({ __typename: 'GraphqlActivityMessaged' }, () => 'sent a message')
- .with({ __typename: 'GraphqlActivitySent' }, () => 'sent an email')
- .with(
- { __typename: 'GraphqlActivityPropertyChanged' },
- () => 'changed a property'
- )
- .with(
- { __typename: 'GraphqlActivityParticipantAdded' },
- () => 'added a participant'
- )
- .with(
- { __typename: 'GraphqlActivityParticipantRemoved' },
- () => 'removed a participant'
- )
- .with({ __typename: 'GraphqlActivityCallStarted' }, () => 'started a call')
- .with({ __typename: 'GraphqlActivityUnknownAction' }, (unknown) =>
- unknown.tag.replaceAll('_', ' ')
- )
- .exhaustive();
-}
-
-/**
- * The verb for a row that names its entity: "<actor> <verb> [connector]
- * <entity>". Direct-object actions carry no connector ("created *Doc*");
- * located actions carry the natural preposition ("sent a message *in*
- * #general", "changed Status *on* *Doc*").
- */
-export function describeActionForEntity(action: ActivityAction): {
- verb: string;
- connector?: string;
-} {
- return (
- match(action)
- .with({ __typename: 'GraphqlActivityCreated' }, () => ({
- verb: 'created',
- }))
- .with({ __typename: 'GraphqlActivityEdited' }, () => ({ verb: 'edited' }))
- .with({ __typename: 'GraphqlActivityOpened' }, () => ({ verb: 'opened' }))
- .with({ __typename: 'GraphqlActivityDeleted' }, () => ({
- verb: 'deleted',
- }))
- .with({ __typename: 'GraphqlActivityMessaged' }, () => ({
- verb: 'sent a message',
- connector: 'in',
- }))
- .with({ __typename: 'GraphqlActivitySent' }, () => ({
- verb: 'sent an email',
- connector: 'in',
- }))
- // The caller renders the full transition phrase; only the connector
- // is needed for property changes.
- .with({ __typename: 'GraphqlActivityPropertyChanged' }, () => ({
- verb: 'changed a property',
- connector: 'on',
- }))
- .with({ __typename: 'GraphqlActivityParticipantAdded' }, () => ({
- verb: 'added a participant',
- connector: 'to',
- }))
- .with({ __typename: 'GraphqlActivityParticipantRemoved' }, () => ({
- verb: 'removed a participant',
- connector: 'from',
- }))
- .with({ __typename: 'GraphqlActivityCallStarted' }, () => ({
- verb: 'started a call',
- connector: 'in',
- }))
- .with({ __typename: 'GraphqlActivityUnknownAction' }, (unknown) => ({
- verb: unknown.tag.replaceAll('_', ' '),
- connector: 'on',
- }))
- .exhaustive()
- );
-}
diff --git a/apps/web/src/features/activity/display-entity-type.ts b/apps/web/src/features/activity/display-entity-type.ts
deleted file mode 100644
index 4b1a95ce39..0000000000
--- a/apps/web/src/features/activity/display-entity-type.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import type { EntityType } from '@service-properties/generated/schemas/entityType';
-import type { GraphqlEntityType } from '@service-storage/graphql/generated/graphql';
-import { match } from 'ts-pattern';
-
-export function displayEntityType(
- entityType: GraphqlEntityType
-): EntityType | undefined {
- return match<GraphqlEntityType, EntityType | undefined>(entityType)
- .with('DOCUMENT', () => 'DOCUMENT')
- .with('PROJECT', () => 'PROJECT')
- .with('CHAT', () => 'CHAT')
- .with('EMAIL_THREAD', () => 'THREAD')
- .with('CHANNEL', () => 'CHANNEL')
- .with('USER', () => 'USER')
- .otherwise(() => undefined);
-}
diff --git a/apps/web/src/features/activity/my-activity-view.tsx b/apps/web/src/features/activity/my-activity-view.tsx
deleted file mode 100644
index 9414f24da2..0000000000
--- a/apps/web/src/features/activity/my-activity-view.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-import { dateBucket } from '@app/features/next-soup/soup-view/group-by-date';
-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 type { ActivityEvent } from '@queries/activity/graphql/entity';
-import { createMyActivityQuery } from '@queries/activity/graphql/feed';
-import { createMyActivityOverviewQuery } from '@queries/activity/graphql/overview';
-import { Button } from '@ui';
-import { type Component, createMemo, For, Show } from 'solid-js';
-import { ActionGraph } from './action-graph';
-import { ActivityTimelineRow } from './activity-timeline-row';
-import { TopEntities } from './top-entities';
-
-type FeedGroup = { key: string; label: string; events: ActivityEvent[] };
-
-/** The soup list inset shared by section headers, feed rows, and the overview. */
-const INSET_CLASS = 'mx-1 w-[calc(100%-0.5rem)]';
-
-/** The user's own activity, newest first, behind the activity-feed flag. */
-export function MyActivityView() {
- const overview = createMyActivityOverviewQuery({ enabled: () => true });
- const feed = createMyActivityQuery({ enabled: () => true });
- const groups = createMemo<FeedGroup[]>(() => {
- const out: FeedGroup[] = [];
- for (const event of feed.data ?? []) {
- const bucket = dateBucket(event.occurredAt);
- const last = out[out.length - 1];
- if (last?.key === bucket.key) {
- last.events.push(event);
- } else {
- out.push({ ...bucket, events: [event] });
- }
- }
- return out;
- });
-
- return (
- <div class="@container/u-list flex size-full flex-col">
- <SplitHeaderLeft>
- <span class="font-semibold text-sm">Activity</span>
- </SplitHeaderLeft>
- <StaticMarkdownContext>
- <div class="min-h-0 flex-1 overflow-y-auto py-1">
- <div class="mx-auto w-full max-w-[1000px]">
- <div class={`${INSET_CLASS} flex min-w-0 flex-col gap-2 pb-2`}>
- <Show
- when={overview.data}
- fallback={
- <p class="px-2 py-1 text-ink-extra-muted text-xs">
- {overview.isError
- ? 'Activity overview is unavailable right now.'
- : 'Loading activity overview…'}
- </p>
- }
- >
- {(data) => <ActionGraph overview={data()} />}
- </Show>
- </div>
- <Show when={overview.data}>
- {(data) => <TopEntities entities={data().topEntities} />}
- </Show>
- <Show
- when={groups().length > 0}
- fallback={
- <p class={`${INSET_CLASS} px-2 py-2 text-ink-muted text-sm`}>
- {feed.isLoading
- ? 'Loading…'
- : feed.isError
- ? 'Activity is unavailable right now. Try again in a moment.'
- : 'No activity yet.'}
- </p>
- }
- >
- <FeedGroups groups={groups()} row={ActivityTimelineRow} />
- <Show when={feed.hasNextPage}>
- <div class="flex justify-center py-2">
- <Button
- variant="ghost"
- onClick={() => void feed.fetchNextPage()}
- disabled={feed.isFetchingNextPage}
- >
- {feed.isFetchingNextPage ? 'Loading…' : 'Show more'}
- </Button>
- </div>
- </Show>
- </Show>
- </div>
- </div>
- </StaticMarkdownContext>
- </div>
- );
-}
-
-function FeedGroups(props: {
- groups: FeedGroup[];
- row: Component<{ event: ActivityEvent }>;
-}) {
- return (
- <For each={props.groups}>
- {(group) => (
- <>
- <SoupSectionHeader>{group.label}</SoupSectionHeader>
- <For each={group.events}>
- {(event) => <props.row event={event} />}
- </For>
- </>
- )}
- </For>
- );
-}
diff --git a/apps/web/src/features/activity/open-entity-in-split.ts b/apps/web/src/features/activity/open-entity-in-split.ts
new file mode 100644
index 0000000000..0d85c1ae45
--- /dev/null
+++ b/apps/web/src/features/activity/open-entity-in-split.ts
@@ -0,0 +1,12 @@
+import { openDocument } from '@core/component/LexicalMarkdown/component/core/BlockLink';
+import type { OpenEntityTarget } from './context/activity-context';
+
+/** The app's `onOpen` for activity rows: open the entity in the split layout. */
+export function openEntityInSplit({
+ block,
+ id,
+ params,
+ newSplit,
+}: OpenEntityTarget): void {
+ openDocument(block, id, params, newSplit);
+}
diff --git a/apps/web/src/features/activity/primitives/actor-name.test.ts b/apps/web/src/features/activity/primitives/actor-name.test.ts
new file mode 100644
index 0000000000..9a38a7a9e5
--- /dev/null
+++ b/apps/web/src/features/activity/primitives/actor-name.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+import {
+ createMockActivityContext,
+ MOCK_VIEWER_ID,
+} from '../tests/mock-context';
+import { createActorName } from './actor-name';
+
+describe('createActorName', () => {
+ const context = createMockActivityContext();
+
+ it('names the viewer "You"', () => {
+ expect(createActorName(context, () => MOCK_VIEWER_ID)()).toBe('You');
+ });
+
+ it('resolves other users through displayName', () => {
+ expect(createActorName(context, () => 'macro|[email protected]')()).toBe(
+ 'sarah'
+ );
+ });
+
+ it('labels non-user actors as automation', () => {
+ expect(createActorName(context, () => 'system:nightly')()).toBe(
+ 'Automation'
+ );
+ });
+});
diff --git a/apps/web/src/features/activity/primitives/actor-name.ts b/apps/web/src/features/activity/primitives/actor-name.ts
new file mode 100644
index 0000000000..f7e0d92013
--- /dev/null
+++ b/apps/web/src/features/activity/primitives/actor-name.ts
@@ -0,0 +1,16 @@
+import type { Accessor } from 'solid-js';
+import type { ActivityContext } from '../context/activity-context';
+
+/** "You" for the viewer, "Automation" for non-user actors, else the name. */
+export function createActorName(
+ context: Pick<ActivityContext, 'currentUserId' | 'displayName'>,
+ actorId: Accessor<string>
+): Accessor<string> {
+ const remote = context.displayName(actorId);
+ return () => {
+ const name = remote();
+ if (name === undefined) return 'Automation';
+ if (actorId() === context.currentUserId()) return 'You';
+ return name;
+ };
+}
diff --git a/apps/web/src/features/activity/primitives/entity-activity.test.ts b/apps/web/src/features/activity/primitives/entity-activity.test.ts
new file mode 100644
index 0000000000..c52e0e8b63
--- /dev/null
+++ b/apps/web/src/features/activity/primitives/entity-activity.test.ts
@@ -0,0 +1,80 @@
+import { createRoot } from 'solid-js';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createdEvent } from '../queries/fixtures';
+import { createMockActivityContext } from '../tests/mock-context';
+import { soupPage } from '../tests/wire';
+import {
+ createEntityActivityState,
+ type EntityActivityState,
+} from './entity-activity';
+
+const disposals: Array<() => void> = [];
+afterEach(() => {
+ for (const dispose of disposals.splice(0)) dispose();
+});
+
+function setup(entityType: 'DOCUMENT' | 'USER' = 'DOCUMENT') {
+ const context = createMockActivityContext();
+ let state!: EntityActivityState;
+ const dispose = createRoot((rootDispose) => {
+ state = createEntityActivityState(context, {
+ entityId: () => 'doc-1',
+ entityType: () => entityType,
+ });
+ return rootDispose;
+ });
+ disposals.push(dispose);
+ return { state, graphql: context.graphqlMock };
+}
+
+describe('createEntityActivityState', () => {
+ it('loads, then reads the matching soup item', () => {
+ const { state, graphql } = setup();
+ expect(state.isEnabled()).toBe(true);
+ expect(state.view().t).toBe('loading');
+
+ graphql.latest('EntityActivity').resolve(
+ soupPage([
+ {
+ __typename: 'GraphqlSoupDocument',
+ id: 'doc-1',
+ activity: [createdEvent],
+ },
+ ])
+ );
+
+ const view = state.view();
+ if (view.t !== 'ready') throw new Error(view.t);
+ expect(view.events.map((e) => e.id)).toEqual(['evt-1']);
+ });
+
+ it('is empty when the entity exists with no history', () => {
+ const { state, graphql } = setup();
+ graphql
+ .latest('EntityActivity')
+ .resolve(
+ soupPage([
+ { __typename: 'GraphqlSoupDocument', id: 'doc-1', activity: [] },
+ ])
+ );
+ expect(state.view()).toEqual({ t: 'empty' });
+ });
+
+ it('treats a missing soup entity as an error, not as empty', () => {
+ const { state, graphql } = setup();
+ graphql.latest('EntityActivity').resolve(soupPage([]));
+ expect(state.view()).toEqual({ t: 'error' });
+ });
+
+ it('reports transport failures', () => {
+ const { state, graphql } = setup();
+ graphql.latest('EntityActivity').fail('boom');
+ expect(state.view()).toEqual({ t: 'error' });
+ });
+
+ it('stays disabled for entity types the soup cannot address', () => {
+ const { state, graphql } = setup('USER');
+ expect(state.isEnabled()).toBe(false);
+ expect(graphql.pending).toHaveLength(0);
+ });
+});
diff --git a/apps/web/src/features/activity/primitives/entity-activity.ts b/apps/web/src/features/activity/primitives/entity-activity.ts
new file mode 100644
index 0000000000..06ee636c36
--- /dev/null
+++ b/apps/web/src/features/activity/primitives/entity-activity.ts
@@ -0,0 +1,43 @@
+import type { EntityType } from '@service-properties/generated/schemas/entityType';
+import { type Accessor, createMemo } from 'solid-js';
+import type { ActivityContext } from '../context/activity-context';
+import type { ActivityEvent } from '../core/event';
+import { createEntityActivityQuery } from '../queries/entity-query';
+
+export type EntityActivityView =
+ | { t: 'loading' }
+ | { t: 'error' }
+ | { t: 'empty' }
+ | { t: 'ready'; events: ActivityEvent[] };
+
+export type EntityActivityState = {
+ view: Accessor<EntityActivityView>;
+ /** False for entity types the soup query cannot address. */
+ isEnabled: Accessor<boolean>;
+};
+
+/**
+ * The side-panel Activity section as data. An entity the soup does not
+ * know about reads as an error, not as an empty history.
+ */
+export function createEntityActivityState(
+ context: Pick<ActivityContext, 'graphql'>,
+ options: { entityId: Accessor<string>; entityType: Accessor<EntityType> }
+): EntityActivityState {
+ const query = createEntityActivityQuery(context, {
+ entityType: options.entityType,
+ entityId: options.entityId,
+ enabled: () => true,
+ });
+
+ const view = createMemo<EntityActivityView>(() => {
+ if (query.result.isLoading) return { t: 'loading' };
+ if (query.result.isError) return { t: 'error' };
+ const data = query.result.data;
+ if (!data || data.kind === 'entity-missing') return { t: 'error' };
+ if (data.events.length === 0) return { t: 'empty' };
+ return { t: 'ready', events: data.events };
+ });
+
+ return { view, isEnabled: query.isEnabled };
+}
diff --git a/apps/web/src/features/activity/primitives/entity-opener.test.ts b/apps/web/src/features/activity/primitives/entity-opener.test.ts
new file mode 100644
index 0000000000..6946b12b99
--- /dev/null
+++ b/apps/web/src/features/activity/primitives/entity-opener.test.ts
@@ -0,0 +1,79 @@
+import { createRoot } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+import type { OpenEntityTarget } from '../context/activity-context';
+import type { ActivityEntityType } from '../core/event';
+import {
+ createMockActivityContext,
+ type MockActivityContext,
+} from '../tests/mock-context';
+import { createEntityOpener } from './entity-opener';
+
+function click(shiftKey: boolean) {
+ return { shiftKey, preventDefault() {} } as unknown as MouseEvent & {
+ currentTarget: HTMLDivElement;
+ target: Element;
+ };
+}
+
+function setup(
+ context: MockActivityContext,
+ entityType: ActivityEntityType,
+ onOpen?: (target: OpenEntityTarget) => void
+) {
+ return createRoot(() =>
+ createEntityOpener(
+ context,
+ () => 'doc-1',
+ () => entityType,
+ onOpen
+ )
+ );
+}
+
+describe('createEntityOpener', () => {
+ it('hands the host a target, asking for a new split on shift-click', () => {
+ const onOpen = vi.fn();
+ const opener = setup(createMockActivityContext(), 'document', onOpen);
+
+ opener()?.handlers?.onClick(click(false));
+ opener()?.handlers?.onClick(click(true));
+
+ expect(onOpen.mock.calls.map(([target]) => target)).toEqual([
+ { block: 'md', id: 'doc-1', params: undefined, newSplit: false },
+ { block: 'md', id: 'doc-1', params: undefined, newSplit: true },
+ ]);
+ expect(opener()?.display.name()).toBe('Entity doc-1');
+ });
+
+ it('resolves display without handlers when the host does not open', () => {
+ const opener = setup(createMockActivityContext(), 'document');
+ expect(opener()?.display.name()).toBe('Entity doc-1');
+ expect(opener()?.handlers).toBeUndefined();
+ });
+
+ it('is undefined for entity kinds the app cannot link to', () => {
+ const opener = setup(
+ createMockActivityContext(),
+ { kind: 'unsupported', raw: 'TEAM' },
+ vi.fn()
+ );
+ expect(opener()).toBeUndefined();
+ });
+
+ it('does nothing when the display has no block mapping', () => {
+ const onOpen = vi.fn();
+ const context = createMockActivityContext({
+ entityDisplay: () => ({
+ name: () => 'Team',
+ icon: () => null,
+ isLoading: () => false,
+ blockOrFileType: () => null,
+ linkParams: () => undefined,
+ }),
+ });
+
+ setup(context, 'document', onOpen)()?.handlers?.onClick(click(false));
+
+ expect(onOpen).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/activity/primitives/entity-opener.ts b/apps/web/src/features/activity/primitives/entity-opener.ts
new file mode 100644
index 0000000000..5392e913c3
--- /dev/null
+++ b/apps/web/src/features/activity/primitives/entity-opener.ts
@@ -0,0 +1,47 @@
+import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';
+import { type Accessor, createMemo, type JSX } from 'solid-js';
+import type {
+ ActivityContext,
+ EntityDisplay,
+ OpenEntityTarget,
+} from '../context/activity-context';
+import { type ActivityEntityType, toPropertyEntityType } from '../core/event';
+
+export type EntityOpener = {
+ display: EntityDisplay;
+ /** Present only when the host handles opens. */
+ handlers?: {
+ onMouseDown: JSX.EventHandler<HTMLDivElement, MouseEvent>;
+ onClick: JSX.EventHandler<HTMLDivElement, MouseEvent>;
+ };
+};
+
+/**
+ * Resolves an entity's display and, when the host supplies `onOpen`, the
+ * split-aware click handlers that hand it a target (shift-click asks for a
+ * new split). Undefined for entity kinds the app cannot link to.
+ */
+export function createEntityOpener(
+ context: Pick<ActivityContext, 'entityDisplay'>,
+ entityId: Accessor<string>,
+ entityType: Accessor<ActivityEntityType>,
+ onOpen: ((target: OpenEntityTarget) => void) | undefined
+): Accessor<EntityOpener | undefined> {
+ return createMemo(() => {
+ const type = toPropertyEntityType(entityType());
+ if (!type) return undefined;
+ const display = context.entityDisplay(entityId, () => type);
+ if (!onOpen) return { display };
+ const handlers = useSplitNavigationHandler<HTMLDivElement>((event) => {
+ const block = display.blockOrFileType();
+ if (!block) return;
+ onOpen({
+ block,
+ id: entityId(),
+ params: display.linkParams(),
+ newSplit: event.shiftKey,
+ });
+ });
+ return { display, handlers };
+ });
+}
diff --git a/apps/web/src/features/activity/primitives/my-activity.test.ts b/apps/web/src/features/activity/primitives/my-activity.test.ts
new file mode 100644
index 0000000000..48f42adc14
--- /dev/null
+++ b/apps/web/src/features/activity/primitives/my-activity.test.ts
@@ -0,0 +1,99 @@
+import { createRoot } from 'solid-js';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createdEvent, editedEvent } from '../queries/fixtures';
+import { createMockActivityContext } from '../tests/mock-context';
+import { feedPage, overviewPage } from '../tests/wire';
+import { createMyActivityState, type MyActivityState } from './my-activity';
+
+const disposals: Array<() => void> = [];
+afterEach(() => {
+ for (const dispose of disposals.splice(0)) dispose();
+});
+
+function setup() {
+ const context = createMockActivityContext();
+ let state!: MyActivityState;
+ const dispose = createRoot((rootDispose) => {
+ state = createMyActivityState(context);
+ return rootDispose;
+ });
+ disposals.push(dispose);
+ return { context, state, graphql: context.graphqlMock };
+}
+
+describe('createMyActivityState', () => {
+ it('starts loading and issues both queries', () => {
+ const { state, graphql } = setup();
+
+ expect(state.feed().t).toBe('loading');
+ expect(state.overview().t).toBe('loading');
+ expect(graphql.pending.map((op) => op.name).sort()).toEqual([
+ 'MyActivity',
+ 'MyActivityOverview',
+ ]);
+ expect(graphql.latest('MyActivity').variables).toEqual({
+ input: { limit: 50, cursor: null },
+ });
+ expect(graphql.latest('MyActivityOverview').variables).toEqual({
+ input: { timeZone: expect.any(String) },
+ });
+ });
+
+ it('groups a page into a ready feed and exposes the next cursor', () => {
+ const { state, graphql } = setup();
+
+ graphql.latest('MyActivity').resolve(feedPage([createdEvent], 'c2'));
+
+ const feed = state.feed();
+ expect(feed.t).toBe('ready');
+ if (feed.t !== 'ready') return;
+ expect(feed.hasMore).toBe(true);
+ expect(feed.loadingMore).toBe(false);
+ expect(feed.groups.flatMap((g) => g.events.map((e) => e.id))).toEqual([
+ 'evt-1',
+ ]);
+ });
+
+ it('appends the next page on loadMore', () => {
+ const { state, graphql } = setup();
+ graphql.latest('MyActivity').resolve(feedPage([createdEvent], 'c2'));
+
+ state.loadMore();
+ const next = graphql.latest('MyActivity');
+ expect(next.variables).toEqual({ input: { limit: 50, cursor: 'c2' } });
+ next.resolve(feedPage([editedEvent], null));
+
+ const feed = state.feed();
+ if (feed.t !== 'ready') throw new Error(feed.t);
+ expect(feed.groups.flatMap((g) => g.events.map((e) => e.id))).toEqual([
+ 'evt-1',
+ 'evt-2',
+ ]);
+ expect(feed.hasMore).toBe(false);
+ });
+
+ it('is empty when the first page has no rows', () => {
+ const { state, graphql } = setup();
+ graphql.latest('MyActivity').resolve(feedPage([]));
+ expect(state.feed()).toEqual({ t: 'empty' });
+ });
+
+ it('reports an error when the feed fails before any data', () => {
+ const { state, graphql } = setup();
+ graphql.latest('MyActivity').fail('boom');
+ expect(state.feed()).toEqual({ t: 'error' });
+ });
+
+ it('decodes the overview and keeps it over a later error', () => {
+ const { state, graphql } = setup();
+ const op = graphql.latest('MyActivityOverview');
+
+ op.fail('boom');
+ expect(state.overview()).toEqual({ t: 'error' });
+
+ op.resolve(overviewPage({ total: 3 }));
+ const overview = state.overview();
+ if (overview.t !== 'ready') throw new Error(overview.t);
+ expect(overview.overview.total).toBe(3);
+ });
+});
diff --git a/apps/web/src/features/activity/primitives/my-activity.ts b/apps/web/src/features/activity/primitives/my-activity.ts
new file mode 100644
index 0000000000..bd8819e6d4
--- /dev/null
+++ b/apps/web/src/features/activity/primitives/my-activity.ts
@@ -0,0 +1,65 @@
+import { type Accessor, createMemo } from 'solid-js';
+import type { ActivityContext } from '../context/activity-context';
+import type { ActivityOverview } from '../core/event';
+import { type FeedGroup, groupEventsByDay } from '../core/group-events';
+import { createMyActivityQuery } from '../queries/feed-query';
+import { createMyActivityOverviewQuery } from '../queries/overview-query';
+
+export type FeedView =
+ | { t: 'loading' }
+ | { t: 'error' }
+ | { t: 'empty' }
+ | { t: 'ready'; groups: FeedGroup[]; hasMore: boolean; loadingMore: boolean };
+
+export type OverviewView =
+ | { t: 'loading' }
+ | { t: 'error' }
+ | { t: 'ready'; overview: ActivityOverview };
+
+export type MyActivityState = {
+ overview: Accessor<OverviewView>;
+ feed: Accessor<FeedView>;
+ loadMore: () => void;
+};
+
+/**
+ * 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.
+ */
+export function createMyActivityState(
+ context: Pick<ActivityContext, 'graphql'>
+): MyActivityState {
+ const overviewQuery = createMyActivityOverviewQuery(context, {
+ enabled: () => true,
+ });
+ const feedQuery = createMyActivityQuery(context, { enabled: () => true });
+ const groups = createMemo(() => groupEventsByDay(feedQuery.data ?? []));
+
+ const overview = createMemo<OverviewView>(() => {
+ const data = overviewQuery.data;
+ if (data) return { t: 'ready', overview: data };
+ if (overviewQuery.isError) return { t: 'error' };
+ return { t: 'loading' };
+ });
+
+ const feed = createMemo<FeedView>(() => {
+ if (groups().length > 0) {
+ return {
+ t: 'ready',
+ groups: groups(),
+ hasMore: feedQuery.hasNextPage,
+ loadingMore: feedQuery.isFetchingNextPage,
+ };
+ }
+ if (feedQuery.isLoading) return { t: 'loading' };
+ if (feedQuery.isError) return { t: 'error' };
+ return { t: 'empty' };
+ });
+
+ return {
+ overview,
+ feed,
+ loadMore: () => void feedQuery.fetchNextPage(),
+ };
+}
diff --git a/apps/web/src/features/activity/queries/decode.test.ts b/apps/web/src/features/activity/queries/decode.test.ts
new file mode 100644
index 0000000000..5518a2e872
--- /dev/null
+++ b/apps/web/src/features/activity/queries/decode.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from 'vitest';
+import { decodeActivityEvent } from './decode';
+import {
+ callStartedEvent,
+ createdEvent,
+ deletedEvent,
+ editedEvent,
+ messagedEvent,
+ openedEvent,
+ participantAddedEvent,
+ participantRemovedEvent,
+ propertyChangedEvent,
+ sentEvent,
+ unknownActionEvent,
+ unsupportedEntityEvent,
+} from './fixtures';
+
+describe('decodeActivityEvent', () => {
+ it.each([
+ [createdEvent, { kind: 'created' as const }],
+ [editedEvent, { kind: 'edited' as const }],
+ [openedEvent, { kind: 'opened' as const }],
+ [deletedEvent, { kind: 'deleted' as const }],
+ [messagedEvent, { kind: 'messaged' as const }],
+ [sentEvent, { kind: 'email-sent' as const }],
+ [callStartedEvent, { kind: 'call-started' as const }],
+ [
+ propertyChangedEvent,
+ {
+ kind: 'property-changed' as const,
+ property: 'prop-1',
+ from: null,
+ to: 'Done',
+ },
+ ],
+ [
+ participantAddedEvent,
+ {
+ kind: 'participant-added' as const,
+ participant: 'macro|[email protected]',
+ },
+ ],
+ [
+ participantRemovedEvent,
+ {
+ kind: 'participant-removed' as const,
+ participant: 'macro|[email protected]',
+ },
+ ],
+ ] as const)('decodes $0.id', (fragment, action) => {
+ expect(decodeActivityEvent(fragment).action).toEqual(action);
+ });
+
+ it('maps supported entity types onto the owned vocabulary', () => {
+ expect(decodeActivityEvent(createdEvent).entityType).toBe('document');
+ expect(decodeActivityEvent(messagedEvent).entityType).toBe('channel');
+ expect(decodeActivityEvent(sentEvent).entityType).toBe('email-thread');
+ });
+
+ it('keeps the unknown-action tag so describeAction can humanize it', () => {
+ expect(decodeActivityEvent(unknownActionEvent)).toEqual({
+ id: 'evt-11',
+ actorId: 'macro|[email protected]',
+ entityId: 'doc-1',
+ entityType: 'document',
+ occurredAt: '2026-08-21T12:00:00.000Z',
+ action: { kind: 'unknown', tag: 'transmogrified_thoroughly' },
+ });
+ });
+
+ it('does not leak an unsupported entity as a reference type', () => {
+ expect(decodeActivityEvent(unsupportedEntityEvent).entityType).toEqual({
+ kind: 'unsupported',
+ raw: 'TEAM',
+ });
+ });
+
+ it('never drops a row when the action typename is unrecognized', () => {
+ const fragment = {
+ ...createdEvent,
+ action: { __typename: 'GraphqlActivityTimeTravelled' },
+ } as unknown as typeof createdEvent;
+
+ expect(decodeActivityEvent(fragment).action).toEqual({
+ kind: 'unknown',
+ tag: 'GraphqlActivityTimeTravelled',
+ });
+ });
+});
diff --git a/apps/web/src/features/activity/queries/decode.ts b/apps/web/src/features/activity/queries/decode.ts
new file mode 100644
index 0000000000..61b2abb415
--- /dev/null
+++ b/apps/web/src/features/activity/queries/decode.ts
@@ -0,0 +1,113 @@
+import type {
+ ActivityEventFieldsFragment,
+ GraphqlEntityType,
+ MyActivityOverviewQuery,
+} from '@service-storage/graphql/generated/graphql';
+import { match } from 'ts-pattern';
+import type {
+ ActivityAction,
+ ActivityEntityType,
+ ActivityEvent,
+ ActivityOverview,
+} from '../core/event';
+
+export function decodeActivityEvent(
+ fragment: ActivityEventFieldsFragment
+): ActivityEvent {
+ return {
+ id: fragment.id,
+ actorId: fragment.actorId,
+ entityId: fragment.entityId,
+ entityType: decodeEntityType(fragment.entityType),
+ occurredAt: fragment.occurredAt,
+ action: decodeAction(fragment.action),
+ };
+}
+
+export function decodeActivityOverview(
+ overview: MyActivityOverviewQuery['user']['activityOverview']
+): ActivityOverview {
+ return {
+ from: overview.from,
+ to: overview.to,
+ timeZone: overview.timeZone,
+ total: overview.total,
+ days: overview.days.map((day) => ({ date: day.date, count: day.count })),
+ topEntities: overview.topEntities.map((entity) => ({
+ entityId: entity.entityId,
+ entityType: decodeEntityType(entity.entityType),
+ count: entity.count,
+ })),
+ };
+}
+
+export function decodeEntityType(
+ entityType: GraphqlEntityType
+): ActivityEntityType {
+ return match(entityType)
+ .with('DOCUMENT', () => 'document' as const)
+ .with('PROJECT', () => 'project' as const)
+ .with('CHAT', () => 'chat' as const)
+ .with('EMAIL_THREAD', () => 'email-thread' as const)
+ .with('CHANNEL', () => 'channel' as const)
+ .with('USER', () => 'user' as const)
+ .otherwise((raw) => ({ kind: 'unsupported' as const, raw }));
+}
+
+function decodeAction(
+ action: ActivityEventFieldsFragment['action']
+): ActivityAction {
+ return match(action)
+ .with({ __typename: 'GraphqlActivityCreated' }, () => ({
+ kind: 'created' as const,
+ }))
+ .with({ __typename: 'GraphqlActivityEdited' }, () => ({
+ kind: 'edited' as const,
+ }))
+ .with({ __typename: 'GraphqlActivityOpened' }, () => ({
+ kind: 'opened' as const,
+ }))
+ .with({ __typename: 'GraphqlActivityDeleted' }, () => ({
+ kind: 'deleted' as const,
+ }))
+ .with({ __typename: 'GraphqlActivityMessaged' }, () => ({
+ kind: 'messaged' as const,
+ }))
+ .with({ __typename: 'GraphqlActivitySent' }, () => ({
+ kind: 'email-sent' as const,
+ }))
+ .with({ __typename: 'GraphqlActivityCallStarted' }, () => ({
+ kind: 'call-started' as const,
+ }))
+ .with(
+ { __typename: 'GraphqlActivityPropertyChanged' },
+ ({ property, from, to }) => ({
+ kind: 'property-changed' as const,
+ property,
+ from,
+ to,
+ })
+ )
+ .with(
+ { __typename: 'GraphqlActivityParticipantAdded' },
+ ({ participant }) => ({
+ kind: 'participant-added' as const,
+ participant,
+ })
+ )
+ .with(
+ { __typename: 'GraphqlActivityParticipantRemoved' },
+ ({ participant }) => ({
+ kind: 'participant-removed' as const,
+ participant,
+ })
+ )
+ .with({ __typename: 'GraphqlActivityUnknownAction' }, ({ tag }) => ({
+ kind: 'unknown' as const,
+ tag,
+ }))
+ .otherwise((unexpected) => ({
+ kind: 'unknown' as const,
+ tag: (unexpected as { __typename?: string }).__typename ?? 'unknown',
+ }));
+}
diff --git a/apps/web/src/features/activity/queries/entity-query.test.ts b/apps/web/src/features/activity/queries/entity-query.test.ts
new file mode 100644
index 0000000000..46e06e0639
--- /dev/null
+++ b/apps/web/src/features/activity/queries/entity-query.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+import { soupPage } from '../tests/wire';
+import { createdEvent } from './fixtures';
+import { selectEntityActivity } from './select-entity-activity';
+
+describe('selectEntityActivity', () => {
+ it('returns entity-missing when the soup page omits the entity', () => {
+ expect(selectEntityActivity(soupPage([]), 'doc-1')).toEqual({
+ kind: 'entity-missing',
+ });
+ });
+
+ it('returns found when the entity is present, even with no events', () => {
+ expect(
+ selectEntityActivity(
+ soupPage([
+ {
+ __typename: 'GraphqlSoupDocument',
+ id: 'doc-1',
+ activity: [],
+ },
+ ]),
+ 'doc-1'
+ )
+ ).toEqual({ kind: 'found', events: [] });
+ });
+
+ it('decodes events on the matching soup item', () => {
+ expect(
+ selectEntityActivity(
+ soupPage([
+ {
+ __typename: 'GraphqlSoupDocument',
+ id: 'doc-1',
+ activity: [createdEvent],
+ },
+ ]),
+ 'doc-1'
+ )
+ ).toEqual({
+ kind: 'found',
+ events: [
+ {
+ id: 'evt-1',
+ actorId: 'macro|[email protected]',
+ entityId: 'doc-1',
+ entityType: 'document',
+ occurredAt: '2026-08-21T12:00:00.000Z',
+ action: { kind: 'created' },
+ },
+ ],
+ });
+ });
+});
diff --git a/apps/web/src/lib/queries/activity/graphql/entity.ts b/apps/web/src/features/activity/queries/entity-query.ts
similarity index 78%
rename from apps/web/src/lib/queries/activity/graphql/entity.ts
rename to apps/web/src/features/activity/queries/entity-query.ts
index 5718d0611c..73c11f63bc 100644
--- a/apps/web/src/lib/queries/activity/graphql/entity.ts
+++ b/apps/web/src/features/activity/queries/entity-query.ts
@@ -2,16 +2,16 @@ import { createUrqlQuery } from '@app/lib/urql-solid/create-urql-query';
import { buildEntityPropertiesInput } from '@queries/properties/graphql/entity';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
import {
- type ActivityEventFieldsFragment,
EntityActivityDocument,
type EntityActivityQuery,
type EntityActivityQueryVariables,
} from '@service-storage/graphql/generated/graphql';
-import { getGraphqlSoupClient } from '@service-storage/graphql-soup';
import { type Accessor, createMemo } from 'solid-js';
-
-/** One activity event as both activity queries return it. */
-export type ActivityEvent = ActivityEventFieldsFragment;
+import type { ActivityContext } from '../context/activity-context';
+import {
+ type EntityActivityResult,
+ selectEntityActivity,
+} from './select-entity-activity';
/** Rows requested for a side-panel activity preview. */
export const ENTITY_ACTIVITY_PREVIEW_LIMIT = 20;
@@ -29,7 +29,10 @@ type EntityActivityQueryOptions = {
* properties query, so the same entity types are supported (everything but
* `USER`) and the query pauses (`isEnabled` false) for the rest.
*/
-export function createEntityActivityQuery(options: EntityActivityQueryOptions) {
+export function createEntityActivityQuery(
+ context: Pick<ActivityContext, 'graphql'>,
+ options: EntityActivityQueryOptions
+) {
const input = createMemo(() => {
const entityId = options.entityId();
if (!options.enabled() || entityId.length === 0) return undefined;
@@ -39,14 +42,14 @@ export function createEntityActivityQuery(options: EntityActivityQueryOptions) {
const result = createUrqlQuery<
EntityActivityQuery,
EntityActivityQueryVariables,
- ActivityEvent[]
+ EntityActivityResult
>(() => {
const currentInput = input();
const entityId = options.entityId();
return {
query: EntityActivityDocument,
- client: getGraphqlSoupClient(),
+ client: context.graphql(),
variables: {
input: currentInput!,
limit: options.limit ?? ENTITY_ACTIVITY_PREVIEW_LIMIT,
@@ -54,9 +57,7 @@ export function createEntityActivityQuery(options: EntityActivityQueryOptions) {
enabled: currentInput !== undefined,
requestPolicy: 'cache-and-network',
keepPreviousData: false,
- select: (data) =>
- data.user.soup.items.find((item) => item.id === entityId)?.activity ??
- [],
+ select: (data) => selectEntityActivity(data, entityId),
};
});
diff --git a/apps/web/src/lib/queries/activity/graphql/feed.ts b/apps/web/src/features/activity/queries/feed-query.ts
similarity index 68%
rename from apps/web/src/lib/queries/activity/graphql/feed.ts
rename to apps/web/src/features/activity/queries/feed-query.ts
index 75bb044622..103b9acedd 100644
--- a/apps/web/src/lib/queries/activity/graphql/feed.ts
+++ b/apps/web/src/features/activity/queries/feed-query.ts
@@ -4,9 +4,10 @@ import {
type MyActivityQuery,
type MyActivityQueryVariables,
} from '@service-storage/graphql/generated/graphql';
-import { getGraphqlSoupClient } from '@service-storage/graphql-soup';
import type { Accessor } from 'solid-js';
-import type { ActivityEvent } from './entity';
+import type { ActivityContext } from '../context/activity-context';
+import type { ActivityEvent } from '../core/event';
+import { decodeActivityEvent } from './decode';
/** Rows fetched per feed page. */
export const ACTIVITY_FEED_PAGE_LIMIT = 50;
@@ -15,7 +16,10 @@ 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.
*/
-export function createMyActivityQuery(options: { enabled: Accessor<boolean> }) {
+export function createMyActivityQuery(
+ context: Pick<ActivityContext, 'graphql'>,
+ options: { enabled: Accessor<boolean> }
+) {
return createUrqlInfiniteQuery<
MyActivityQuery,
MyActivityQueryVariables,
@@ -23,7 +27,7 @@ export function createMyActivityQuery(options: { enabled: Accessor<boolean> }) {
ActivityEvent[]
>(() => ({
query: MyActivityDocument,
- client: getGraphqlSoupClient(),
+ client: context.graphql(),
initialPageParam: null,
variables: (cursor) => ({
input: { limit: ACTIVITY_FEED_PAGE_LIMIT, cursor },
@@ -33,6 +37,9 @@ export function createMyActivityQuery(options: { enabled: Accessor<boolean> }) {
enabled: options.enabled(),
requestPolicy: 'cache-and-network',
keepPreviousData: true,
- select: ({ pages }) => pages.flatMap((page) => page.user.activity.items),
+ select: ({ pages }) =>
+ pages
+ .flatMap((page) => page.user.activity.items)
+ .map(decodeActivityEvent),
}));
}
diff --git a/apps/web/src/features/activity/queries/fixtures.ts b/apps/web/src/features/activity/queries/fixtures.ts
new file mode 100644
index 0000000000..90a8065453
--- /dev/null
+++ b/apps/web/src/features/activity/queries/fixtures.ts
@@ -0,0 +1,112 @@
+import type { ActivityEventFieldsFragment } from '@service-storage/graphql/generated/graphql';
+
+const BASE = {
+ __typename: 'GraphqlActivityEvent' as const,
+ id: 'evt-1',
+ actorId: 'macro|[email protected]',
+ subjectId: 'macro|[email protected]',
+ entityType: 'DOCUMENT' as const,
+ entityId: 'doc-1',
+ occurredAt: '2026-08-21T12:00:00.000Z',
+};
+
+export const createdEvent: ActivityEventFieldsFragment = {
+ ...BASE,
+ action: { __typename: 'GraphqlActivityCreated' },
+};
+
+export const editedEvent: ActivityEventFieldsFragment = {
+ ...BASE,
+ id: 'evt-2',
+ action: { __typename: 'GraphqlActivityEdited' },
+};
+
+export const openedEvent: ActivityEventFieldsFragment = {
+ ...BASE,
+ id: 'evt-3',
+ action: { __typename: 'GraphqlActivityOpened' },
+};
+
+export const deletedEvent: ActivityEventFieldsFragment = {
+ ...BASE,
+ id: 'evt-4',
+ action: { __typename: 'GraphqlActivityDeleted' },
+};
+
+export const messagedEvent: ActivityEventFieldsFragment = {
+ ...BASE,
+ id: 'evt-5',
+ entityType: 'CHANNEL',
+ entityId: 'channel-1',
+ action: { __typename: 'GraphqlActivityMessaged' },
+};
+
+export const sentEvent: ActivityEventFieldsFragment = {
+ ...BASE,
+ id: 'evt-6',
+ entityType: 'EMAIL_THREAD',
+ entityId: 'thread-1',
+ action: { __typename: 'GraphqlActivitySent' },
+};
+
+export const propertyChangedEvent: ActivityEventFieldsFragment = {
+ ...BASE,
+ id: 'evt-7',
+ action: {
+ __typename: 'GraphqlActivityPropertyChanged',
+ property: 'prop-1',
+ from: null,
+ to: 'Done',
+ },
+};
+
+export const participantAddedEvent: ActivityEventFieldsFragment = {
+ ...BASE,
+ id: 'evt-8',
+ entityType: 'CHANNEL',
+ entityId: 'channel-1',
+ action: {
+ __typename: 'GraphqlActivityParticipantAdded',
+ participant: 'macro|[email protected]',
+ },
+};
+
+export const participantRemovedEvent: ActivityEventFieldsFragment = {
+ ...BASE,
+ id: 'evt-9',
+ entityType: 'CHANNEL',
+ entityId: 'channel-1',
+ action: {
+ __typename: 'GraphqlActivityParticipantRemoved',
+ participant: 'macro|[email protected]',
+ },
+};
+
+export const callStartedEvent: ActivityEventFieldsFragment = {
+ ...BASE,
+ id: 'evt-10',
+ entityType: 'CHANNEL',
+ entityId: 'channel-1',
+ action: {
+ __typename: 'GraphqlActivityCallStarted',
+ callId: 'call-1',
+ },
+};
+
+export const unknownActionEvent: ActivityEventFieldsFragment = {
+ ...BASE,
+ id: 'evt-11',
+ action: {
+ __typename: 'GraphqlActivityUnknownAction',
+ tag: 'transmogrified_thoroughly',
+ payload: null,
+ },
+};
+
+export const unsupportedEntityEvent: ActivityEventFieldsFragment = {
+ ...BASE,
+ id: 'evt-12',
+ entityType: 'TEAM',
+ entityId: 'team-1',
+ action: { __typename: 'GraphqlActivityCreated' },
+};
diff --git a/apps/web/src/lib/queries/activity/graphql/overview.ts b/apps/web/src/features/activity/queries/overview-query.ts
similarity index 63%
rename from apps/web/src/lib/queries/activity/graphql/overview.ts
rename to apps/web/src/features/activity/queries/overview-query.ts
index 0dcbec7141..987ea8b9a3 100644
--- a/apps/web/src/lib/queries/activity/graphql/overview.ts
+++ b/apps/web/src/features/activity/queries/overview-query.ts
@@ -4,32 +4,32 @@ import {
type MyActivityOverviewQuery,
type MyActivityOverviewQueryVariables,
} from '@service-storage/graphql/generated/graphql';
-import { getGraphqlSoupClient } from '@service-storage/graphql-soup';
import type { Accessor } from 'solid-js';
-
-export type ActivityOverview =
- MyActivityOverviewQuery['user']['activityOverview'];
+import type { ActivityContext } from '../context/activity-context';
+import type { ActivityOverview } from '../core/event';
+import { decodeActivityOverview } from './decode';
function browserTimeZone(): string {
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
}
-export function createMyActivityOverviewQuery(options: {
- enabled: Accessor<boolean>;
-}) {
+export function createMyActivityOverviewQuery(
+ context: Pick<ActivityContext, 'graphql'>,
+ options: { enabled: Accessor<boolean> }
+) {
return createUrqlQuery<
MyActivityOverviewQuery,
MyActivityOverviewQueryVariables,
ActivityOverview
>(() => ({
query: MyActivityOverviewDocument,
- client: getGraphqlSoupClient(),
+ client: context.graphql(),
variables: {
input: { timeZone: browserTimeZone() },
},
enabled: options.enabled(),
requestPolicy: 'cache-and-network',
keepPreviousData: true,
- select: (data) => data.user.activityOverview,
+ select: (data) => decodeActivityOverview(data.user.activityOverview),
}));
}
diff --git a/apps/web/src/features/activity/property-change.test.ts b/apps/web/src/features/activity/queries/property-value.test.ts
similarity index 96%
rename from apps/web/src/features/activity/property-change.test.ts
rename to apps/web/src/features/activity/queries/property-value.test.ts
index da54352d30..2f84448115 100644
--- a/apps/web/src/features/activity/property-change.test.ts
+++ b/apps/web/src/features/activity/queries/property-value.test.ts
@@ -1,6 +1,6 @@
import type { PropertyDefinitionDomain } from '@property/types';
import { describe, expect, it } from 'vitest';
-import { propertyValueLabel } from './property-change-label';
+import { propertyValueLabel } from './property-value';
const definition = {
id: 'def-1',
diff --git a/apps/web/src/features/activity/property-change-label.ts b/apps/web/src/features/activity/queries/property-value.ts
similarity index 79%
rename from apps/web/src/features/activity/property-change-label.ts
rename to apps/web/src/features/activity/queries/property-value.ts
index 9383daa060..9dd618f2fd 100644
--- a/apps/web/src/features/activity/property-change-label.ts
+++ b/apps/web/src/features/activity/queries/property-value.ts
@@ -5,6 +5,7 @@ import {
formatNumber,
formatOptionValue,
} from '@property/utils/formatting';
+import { match } from 'ts-pattern';
/** One resolved select option of a stored property value. */
export type SelectOptionEntry = {
@@ -71,22 +72,22 @@ export function propertyValueLabel(
const tagged = asTaggedValue(raw);
if (!tagged) return undefined;
- switch (tagged.type) {
- case 'String':
- return typeof tagged.value === 'string' ? tagged.value : undefined;
- case 'Number':
- return typeof tagged.value === 'number'
- ? formatNumber(tagged.value)
- : undefined;
- case 'Boolean':
- return typeof tagged.value === 'boolean'
+ return match(tagged.type)
+ .with('String', () =>
+ typeof tagged.value === 'string' ? tagged.value : undefined
+ )
+ .with('Number', () =>
+ typeof tagged.value === 'number' ? formatNumber(tagged.value) : undefined
+ )
+ .with('Boolean', () =>
+ typeof tagged.value === 'boolean'
? formatBoolean(tagged.value)
- : undefined;
- case 'Date':
- return typeof tagged.value === 'string'
- ? formatDate(tagged.value)
- : undefined;
- case 'SelectOption': {
+ : undefined
+ )
+ .with('Date', () =>
+ typeof tagged.value === 'string' ? formatDate(tagged.value) : undefined
+ )
+ .with('SelectOption', () => {
if (!Array.isArray(tagged.value)) return undefined;
const labels = tagged.value
.filter((id): id is string => typeof id === 'string')
@@ -96,19 +97,19 @@ export function propertyValueLabel(
})
.filter((label): label is string => label !== undefined);
return labels.length > 0 ? labels.join(', ') : undefined;
- }
- case 'Link':
- return Array.isArray(tagged.value)
+ })
+ .with('Link', () =>
+ Array.isArray(tagged.value)
? tagged.value.filter((v) => typeof v === 'string').join(', ') ||
- undefined
- : undefined;
- case 'EntityReference':
- return Array.isArray(tagged.value) && tagged.value.length > 0
+ undefined
+ : undefined
+ )
+ .with('EntityReference', () =>
+ Array.isArray(tagged.value) && tagged.value.length > 0
? tagged.value.length === 1
? 'an item'
: `${tagged.value.length} items`
- : undefined;
- default:
- return undefined;
- }
+ : undefined
+ )
+ .otherwise(() => undefined);
}
diff --git a/apps/web/src/features/activity/queries/select-entity-activity.ts b/apps/web/src/features/activity/queries/select-entity-activity.ts
new file mode 100644
index 0000000000..a13d853a69
--- /dev/null
+++ b/apps/web/src/features/activity/queries/select-entity-activity.ts
@@ -0,0 +1,19 @@
+import type { EntityActivityQuery } from '@service-storage/graphql/generated/graphql';
+import type { ActivityEvent } from '../core/event';
+import { decodeActivityEvent } from './decode';
+
+export type EntityActivityResult =
+ | { kind: 'found'; events: ActivityEvent[] }
+ | { kind: 'entity-missing' };
+
+export function selectEntityActivity(
+ data: EntityActivityQuery,
+ entityId: string
+): EntityActivityResult {
+ const item = data.user.soup.items.find((entry) => entry.id === entityId);
+ if (!item) return { kind: 'entity-missing' };
+ return {
+ kind: 'found',
+ events: item.activity.map(decodeActivityEvent),
+ };
+}
diff --git a/apps/web/src/features/activity/tests/mock-context.ts b/apps/web/src/features/activity/tests/mock-context.ts
new file mode 100644
index 0000000000..03444b570c
--- /dev/null
+++ b/apps/web/src/features/activity/tests/mock-context.ts
@@ -0,0 +1,40 @@
+import type { Client } from '@urql/core';
+import type { ActivityContext } from '../context/activity-context';
+import { createMockGraphql, type MockGraphql } from './mock-graphql';
+
+export const MOCK_VIEWER_ID = 'macro|[email protected]';
+
+export type MockActivityContext = ActivityContext & {
+ graphqlMock: MockGraphql;
+};
+
+/**
+ * In-memory implementations of every activity dependency. Entities resolve
+ * to `Entity <id>` and link as markdown blocks; actor ids of the form
+ * `macro|name@…` resolve to `name`, anything else reads as automation.
+ */
+export function createMockActivityContext(
+ overrides: Partial<ActivityContext> = {}
+): MockActivityContext {
+ const graphqlMock = createMockGraphql();
+ const client: Client = graphqlMock.client;
+ return {
+ graphql: () => client,
+ currentUserId: () => MOCK_VIEWER_ID,
+ displayName: (actorId) => {
+ const id = actorId();
+ if (!id.startsWith('macro|')) return () => undefined;
+ return () => id.slice('macro|'.length).split('@')[0] ?? '';
+ },
+ entityDisplay: (entityId) => ({
+ name: () => `Entity ${entityId()}`,
+ icon: () => null,
+ isLoading: () => false,
+ blockOrFileType: () => 'md',
+ linkParams: () => undefined,
+ }),
+ propertyDefinition: () => () => undefined,
+ ...overrides,
+ graphqlMock,
+ };
+}
diff --git a/apps/web/src/features/activity/tests/mock-graphql.ts b/apps/web/src/features/activity/tests/mock-graphql.ts
new file mode 100644
index 0000000000..d55511dc57
--- /dev/null
+++ b/apps/web/src/features/activity/tests/mock-graphql.ts
@@ -0,0 +1,70 @@
+import {
+ type AnyVariables,
+ type Client,
+ CombinedError,
+ type GraphQLRequest,
+ type Operation,
+ type OperationContext,
+ type OperationResult,
+} from '@urql/core';
+import { makeSubject } from 'wonka';
+
+/** One in-flight GraphQL operation the test can answer or fail. */
+export type PendingOperation = {
+ name: string;
+ variables: Record<string, unknown>;
+ resolve(data: unknown): void;
+ fail(message: string): void;
+};
+
+export type MockGraphql = {
+ client: Client;
+ pending: PendingOperation[];
+ /** The most recent operation with this name, or throws. */
+ latest(name: string): PendingOperation;
+};
+
+function operationName(query: unknown): string {
+ const doc = query as {
+ definitions?: Array<{ kind: string; name?: { value: string } }>;
+ };
+ const op = doc.definitions?.find((d) => d.kind === 'OperationDefinition');
+ return op?.name?.value ?? 'anonymous';
+}
+
+/**
+ * A urql client whose operations stay pending until the test answers them,
+ * so loading, error, and pagination transitions are observable in order.
+ */
+export function createMockGraphql(): MockGraphql {
+ const pending: PendingOperation[] = [];
+ const executeQuery = <D, V extends AnyVariables>(
+ request: GraphQLRequest<D, V>,
+ context: Partial<OperationContext> = {}
+ ) => {
+ const subject = makeSubject<OperationResult<D, V>>();
+ const operation = { kind: 'query', context } as Operation<D, V>;
+ pending.push({
+ name: operationName(request.query),
+ variables: (request.variables ?? {}) as Record<string, unknown>,
+ resolve: (data) =>
+ subject.next({ operation, data } as OperationResult<D, V>),
+ fail: (message) =>
+ subject.next({
+ operation,
+ error: new CombinedError({ graphQLErrors: [message] }),
+ } as OperationResult<D, V>),
+ });
+ return subject.source;
+ };
+ const client = { executeQuery } as unknown as Client;
+ return {
+ client,
+ pending,
+ latest(name) {
+ const found = [...pending].reverse().find((op) => op.name === name);
+ if (!found) throw new Error(`no pending ${name} operation`);
+ return found;
+ },
+ };
+}
diff --git a/apps/web/src/features/activity/tests/wire.ts b/apps/web/src/features/activity/tests/wire.ts
new file mode 100644
index 0000000000..69fd33d34a
--- /dev/null
+++ b/apps/web/src/features/activity/tests/wire.ts
@@ -0,0 +1,39 @@
+import type {
+ ActivityEventFieldsFragment,
+ EntityActivityQuery,
+ MyActivityOverviewQuery,
+ MyActivityQuery,
+} from '@service-storage/graphql/generated/graphql';
+
+/** One MyActivity page as the server returns it. */
+export function feedPage(
+ items: ActivityEventFieldsFragment[],
+ nextCursor: string | null = null
+): MyActivityQuery {
+ return { user: { id: 'user-1', activity: { nextCursor, items } } };
+}
+
+export function overviewPage(
+ overrides: Partial<MyActivityOverviewQuery['user']['activityOverview']> = {}
+): MyActivityOverviewQuery {
+ return {
+ user: {
+ id: 'user-1',
+ activityOverview: {
+ from: '2025-09-01',
+ to: '2026-09-01',
+ timeZone: 'UTC',
+ total: 0,
+ days: [],
+ topEntities: [],
+ ...overrides,
+ },
+ },
+ };
+}
+
+export function soupPage(
+ items: EntityActivityQuery['user']['soup']['items']
+): EntityActivityQuery {
+ return { user: { id: 'user-1', soup: { items } } };
+}
diff --git a/apps/web/src/features/activity/top-entities.tsx b/apps/web/src/features/activity/top-entities.tsx
deleted file mode 100644
index 0c0a5f1069..0000000000
--- a/apps/web/src/features/activity/top-entities.tsx
+++ /dev/null
@@ -1,101 +0,0 @@
-import { SoupSectionHeader } from '@app/features/next-soup/soup-view/section-header';
-import { openDocument } from '@core/component/LexicalMarkdown/component/core/BlockLink';
-import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';
-import { usePropertyEntityDisplay } from '@property/hooks';
-import type { ActivityOverview } from '@queries/activity/graphql/overview';
-import type { EntityType } from '@service-properties/generated/schemas/entityType';
-import { For, Show } from 'solid-js';
-import { displayEntityType } from './display-entity-type';
-import { EntityMention } from './entity-mention';
-
-type EntityRank = ActivityOverview['topEntities'][number];
-
-const ROW_CLASS = 'mx-1 flex w-[calc(100%-0.5rem)] items-stretch px-2 text-sm';
-const ROW_BODY_CLASS =
- 'flex min-h-10 min-w-0 flex-1 items-center gap-1.5 rounded-lg px-2 py-0.5 hover:bg-hover/30';
-
-/**
- * The entities the viewer touched most, as a list that shares the activity
- * feed's row chrome — mention on the left, action count on the right.
- */
-export function TopEntities(props: {
- entities: ActivityOverview['topEntities'];
-}) {
- return (
- <section class="min-w-0" aria-label="Most active">
- <SoupSectionHeader>Most active</SoupSectionHeader>
- <Show
- when={props.entities.length > 0}
- fallback={
- <p class="px-2 py-2 text-ink-muted text-sm">No entities yet.</p>
- }
- >
- <For each={props.entities}>
- {(entity) => <TopEntityRow entity={entity} />}
- </For>
- </Show>
- </section>
- );
-}
-
-function TopEntityRow(props: { entity: EntityRank }) {
- const displayType = () => displayEntityType(props.entity.entityType);
-
- return (
- <div class={ROW_CLASS}>
- <Show
- when={displayType()}
- fallback={
- <div class={ROW_BODY_CLASS}>
- <span class="min-w-0 truncate text-ink-extra-muted">
- {props.entity.entityType}
- </span>
- <ActionCount count={props.entity.count} />
- </div>
- }
- >
- {(type) => (
- <MappedEntityRow entity={props.entity} entityType={type()} />
- )}
- </Show>
- </div>
- );
-}
-
-function MappedEntityRow(props: {
- entity: EntityRank;
- entityType: EntityType;
-}) {
- const display = usePropertyEntityDisplay(
- () => props.entity.entityId,
- () => props.entityType
- );
- const navHandlers = useSplitNavigationHandler<HTMLDivElement>((event) => {
- const block = display.blockOrFileType();
- if (!block) return;
- openDocument(
- block,
- props.entity.entityId,
- display.linkParams(),
- event.shiftKey
- );
- });
-
- return (
- <div {...navHandlers} class={ROW_BODY_CLASS}>
- <span class="min-w-0 truncate">
- <EntityMention entityId={props.entity.entityId} display={display} />
- </span>
- <ActionCount count={props.entity.count} />
- </div>
- );
-}
-
-function ActionCount(props: { count: number }) {
- const noun = () => (props.count === 1 ? 'action' : 'actions');
- return (
- <span class="ml-auto shrink-0 text-right font-medium text-ink-extra-muted text-xs tabular-nums">
- {props.count.toLocaleString()} {noun()}
- </span>
- );
-}
diff --git a/apps/web/src/features/activity/views/activity-timeline-row.tsx b/apps/web/src/features/activity/views/activity-timeline-row.tsx
new file mode 100644
index 0000000000..bd5e107fff
--- /dev/null
+++ b/apps/web/src/features/activity/views/activity-timeline-row.tsx
@@ -0,0 +1,41 @@
+import { ActivityTimelineRow as ActivityTimelineRowView } from '../components/activity-timeline-row';
+import {
+ type OpenEntityTarget,
+ useActivityContext,
+} from '../context/activity-context';
+import type { ActivityEvent } from '../core/event';
+import { createEntityOpener } from '../primitives/entity-opener';
+
+/**
+ * Feed and tool row: presentational chrome plus the entity mention. Pass
+ * `onOpen` to make the row click-to-open; leave it out for inert rows.
+ */
+export function ActivityTimelineRow(props: {
+ event: ActivityEvent;
+ actorName?: string;
+ showActor?: boolean;
+ onOpen?: (target: OpenEntityTarget) => void;
+}) {
+ const context = useActivityContext();
+ const opener = createEntityOpener(
+ context,
+ () => props.event.entityId,
+ () => props.event.entityType,
+ props.onOpen
+ );
+ const definition = context.propertyDefinition(() => {
+ const action = props.event.action;
+ return action.kind === 'property-changed' ? action.property : undefined;
+ });
+
+ return (
+ <ActivityTimelineRowView
+ event={props.event}
+ actorName={props.actorName}
+ showActor={props.showActor}
+ display={opener()?.display}
+ rowProps={opener()?.handlers}
+ propertyDefinition={definition()}
+ />
+ );
+}
diff --git a/apps/web/src/features/activity/views/entity-activity-section.tsx b/apps/web/src/features/activity/views/entity-activity-section.tsx
new file mode 100644
index 0000000000..92870a951a
--- /dev/null
+++ b/apps/web/src/features/activity/views/entity-activity-section.tsx
@@ -0,0 +1,138 @@
+import { SidePanel } from '@components/app/side-panel/SidePanel';
+import { formatRelativeTimestamp } from '@entity/utils/timestamp';
+import CaretRightIcon from '@phosphor/caret-right.svg';
+import type { EntityType } from '@service-properties/generated/schemas/entityType';
+import { cn } from '@ui';
+import { createSignal, For, Match, Show, Suspense, Switch } from 'solid-js';
+import { ActionPhrase } from '../components/action-phrase';
+import { ActorName } from '../components/actor-name';
+import { useActivityContext } from '../context/activity-context';
+import type { ActivityEvent } from '../core/event';
+import { createActorName } from '../primitives/actor-name';
+import { createEntityActivityState } from '../primitives/entity-activity';
+import { useEntityActivityFlag } from '../use-entity-activity-flag';
+
+/** Rows shown before the section collapses behind a "Show all" toggle. */
+const COLLAPSED_ROW_LIMIT = 10;
+
+export interface EntityActivitySectionProps {
+ entityId: string;
+ entityType: EntityType;
+ order?: number;
+}
+
+/**
+ * The side-panel Activity section behind its flag. Nothing mounts (and no
+ * query is issued) while the rollout is off.
+ */
+export function EntityActivitySectionConditional(
+ props: EntityActivitySectionProps
+) {
+ const enabled = useEntityActivityFlag();
+ return (
+ <Show when={enabled()}>
+ <EntityActivitySection {...props} />
+ </Show>
+ );
+}
+
+/** The section itself. Reads `ActivityContext`. */
+export function EntityActivitySection(props: EntityActivitySectionProps) {
+ const context = useActivityContext();
+ const state = createEntityActivityState(context, {
+ entityType: () => props.entityType,
+ entityId: () => props.entityId,
+ });
+ const ready = () => {
+ const current = state.view();
+ return current.t === 'ready' ? current : undefined;
+ };
+
+ return (
+ <Show when={state.isEnabled()}>
+ <SidePanel.Section id="activity" title="Activity" order={props.order}>
+ <Suspense fallback={<SidePanel.Loading />}>
+ <Switch>
+ <Match when={state.view().t === 'loading'}>
+ <SidePanel.Loading />
+ </Match>
+ <Match when={state.view().t === 'error'}>
+ <SidePanel.EmptyPill label="Activity is unavailable" />
+ </Match>
+ <Match when={state.view().t === 'empty'}>
+ <SidePanel.EmptyPill label="No activity yet" />
+ </Match>
+ <Match when={ready()}>
+ {(current) => <ReadyActivityList events={current().events} />}
+ </Match>
+ </Switch>
+ </Suspense>
+ </SidePanel.Section>
+ </Show>
+ );
+}
+
+function ReadyActivityList(props: { events: ActivityEvent[] }) {
+ const [expanded, setExpanded] = createSignal(false);
+ const visibleEvents = () =>
+ expanded() ? props.events : props.events.slice(0, COLLAPSED_ROW_LIMIT);
+ const hasOverflow = () => props.events.length > COLLAPSED_ROW_LIMIT;
+
+ return (
+ <div class="text-xs">
+ <SidePanel.Card>
+ <For each={visibleEvents()}>
+ {(event) => <ActivityRow event={event} />}
+ </For>
+ </SidePanel.Card>
+ <Show when={hasOverflow()}>
+ <button
+ type="button"
+ aria-expanded={expanded()}
+ class="mt-1 flex w-full items-center gap-1.5 rounded-md px-1 py-1 text-ink-muted text-xs hover:bg-hover hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40"
+ onClick={() => setExpanded((current) => !current)}
+ >
+ <CaretRightIcon
+ class={cn(
+ 'size-3 shrink-0 transition-transform duration-90',
+ expanded() && 'rotate-90'
+ )}
+ />
+ <span>
+ {expanded() ? 'Show less' : `Show all (${props.events.length})`}
+ </span>
+ </button>
+ </Show>
+ </div>
+ );
+}
+
+function ActivityRow(props: { event: ActivityEvent }) {
+ const context = useActivityContext();
+ const name = createActorName(context, () => props.event.actorId);
+ const definition = context.propertyDefinition(() => {
+ const action = props.event.action;
+ return action.kind === 'property-changed' ? action.property : undefined;
+ });
+ return (
+ <div
+ class="flex min-h-7 min-w-0 items-center gap-2 px-2 py-1"
+ data-activity-row
+ data-activity-action={props.event.action.kind}
+ >
+ <span class="flex min-w-0 flex-1 flex-wrap items-center gap-x-1 gap-y-0.5">
+ <span class="font-medium text-ink">
+ <ActorName name={name()} />
+ </span>
+ <span class="min-w-0 text-ink-muted">
+ <ActionPhrase event={props.event} propertyDefinition={definition()} />
+ </span>
+ </span>
+ <span class="ml-auto shrink-0 text-ink-extra-muted">
+ {formatRelativeTimestamp(new Date(props.event.occurredAt), {
+ condensed: true,
+ })}
+ </span>
+ </div>
+ );
+}
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
new file mode 100644
index 0000000000..64840e674c
--- /dev/null
+++ b/apps/web/src/features/activity/views/my-activity-view.test.tsx
@@ -0,0 +1,134 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { ActivityContextProvider } from '../context/activity-context';
+import { createdEvent, messagedEvent } from '../queries/fixtures';
+import { createMockActivityContext } from '../tests/mock-context';
+import { feedPage, overviewPage } from '../tests/wire';
+import { MyActivityView } from './my-activity-view';
+
+vi.mock('@components/app/split-layout/components/SplitHeader', () => ({
+ SplitHeaderLeft: (props: { children: unknown }) => props.children,
+}));
+
+vi.mock(
+ '@core/component/LexicalMarkdown/component/core/StaticMarkdown',
+ () => ({
+ StaticMarkdownContext: (props: { children: unknown }) => props.children,
+ StaticMarkdown: () => null,
+ })
+);
+
+// Module-load quarantine, not a dependency substitute: the connection-gateway
+// websocket connects when imported, which jsdom cannot do.
+vi.mock('@service-connection/websocket', () => ({
+ ws: { send() {}, addEventListener() {}, removeEventListener() {} },
+ state: () => 'closed',
+ createConnectionBlockWebsocketEffect() {},
+ createConnectionWebsocketEffect() {},
+ parseWebsocketPayload: () => undefined,
+}));
+
+vi.mock('@service-storage/websocket', () => ({
+ storageWS: { send() {}, addEventListener() {}, removeEventListener() {} },
+ createWebSocketJob: () => Promise.reject(new Error('no websocket in tests')),
+}));
+
+afterEach(cleanup);
+
+function renderView() {
+ const context = createMockActivityContext();
+ const onOpen = vi.fn();
+ const result = render(() => (
+ <ActivityContextProvider value={context}>
+ <MyActivityView onOpen={onOpen} />
+ </ActivityContextProvider>
+ ));
+ return { ...result, onOpen, graphql: context.graphqlMock };
+}
+
+const rows = () => document.querySelectorAll('[data-activity-row]');
+
+describe('MyActivityView', () => {
+ it('shows loading copy for both the overview and the feed', () => {
+ const { container } = renderView();
+ expect(container.textContent).toContain('Loading activity overview…');
+ expect(container.textContent).toContain('Loading…');
+ });
+
+ it('renders grouped rows with actor names and pages on Show more', async () => {
+ const { graphql } = renderView();
+ graphql
+ .latest('MyActivity')
+ .resolve(feedPage([createdEvent, messagedEvent], 'cursor-2'));
+
+ expect(rows()).toHaveLength(2);
+ expect(rows()[0]?.getAttribute('data-activity-action')).toBe('created');
+ expect(rows()[1]?.getAttribute('data-activity-action')).toBe('messaged');
+ expect(screen.getAllByText('sarah')).toHaveLength(2);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Show more' }));
+ const next = graphql.latest('MyActivity');
+ expect(next.variables).toEqual({
+ input: { limit: 50, cursor: 'cursor-2' },
+ });
+
+ next.resolve(feedPage([{ ...createdEvent, id: 'evt-99' }], null));
+ expect(rows()).toHaveLength(3);
+ expect(screen.queryByRole('button', { name: 'Show more' })).toBeNull();
+ });
+
+ it('asks the host to open the row entity', () => {
+ const { onOpen, graphql } = renderView();
+ graphql.latest('MyActivity').resolve(feedPage([createdEvent]));
+
+ const body = rows()[0]?.querySelector('.hover\\:bg-hover\\/30');
+ if (!body) throw new Error('row body not rendered');
+ fireEvent.click(body);
+
+ expect(onOpen).toHaveBeenCalledExactlyOnceWith({
+ block: 'md',
+ id: 'doc-1',
+ params: undefined,
+ newSplit: false,
+ });
+ });
+
+ it('shows unavailable copy when the feed fails', () => {
+ const { container, graphql } = renderView();
+ graphql.latest('MyActivity').fail('boom');
+ expect(container.textContent).toContain(
+ 'Activity is unavailable right now.'
+ );
+ });
+
+ it('shows empty copy when the feed has no rows', () => {
+ const { container, graphql } = renderView();
+ graphql.latest('MyActivity').resolve(feedPage([]));
+ expect(container.textContent).toContain('No activity yet.');
+ });
+
+ it('lists the most active entities and opens them', () => {
+ const { container, onOpen, graphql } = renderView();
+ graphql.latest('MyActivityOverview').resolve(
+ overviewPage({
+ total: 4,
+ topEntities: [{ entityType: 'DOCUMENT', entityId: 'doc-7', count: 4 }],
+ })
+ );
+
+ expect(container.textContent).toContain('Most active');
+ expect(container.textContent).toContain('4 actions');
+
+ const section = screen.getByLabelText('Most active');
+ const body = section.querySelector('.hover\\:bg-hover\\/30');
+ if (!body) throw new Error('top entity body not rendered');
+ fireEvent.click(body);
+
+ expect(onOpen).toHaveBeenCalledExactlyOnceWith({
+ block: 'md',
+ id: 'doc-7',
+ params: undefined,
+ newSplit: false,
+ });
+ });
+});
diff --git a/apps/web/src/features/activity/views/my-activity-view.tsx b/apps/web/src/features/activity/views/my-activity-view.tsx
new file mode 100644
index 0000000000..a20ce1ed9d
--- /dev/null
+++ b/apps/web/src/features/activity/views/my-activity-view.tsx
@@ -0,0 +1,177 @@
+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 { Button } from '@ui';
+import { For, type JSX, Match, Show, Switch } from 'solid-js';
+import { ActionGraph } from '../components/action-graph';
+import { TopEntitiesSection, TopEntityRow } from '../components/top-entities';
+import {
+ type OpenEntityTarget,
+ useActivityContext,
+} from '../context/activity-context';
+import type { ActivityEvent, ActivityTopEntity } from '../core/event';
+import { createActorName } from '../primitives/actor-name';
+import { createEntityOpener } from '../primitives/entity-opener';
+import { createMyActivityState } from '../primitives/my-activity';
+import { ActivityTimelineRow } from './activity-timeline-row';
+
+function OverviewInset(props: { children: JSX.Element }) {
+ return (
+ <div class="mx-1 flex w-[calc(100%-0.5rem)] min-w-0 flex-col gap-2 pb-2">
+ {props.children}
+ </div>
+ );
+}
+
+function FeedStatus(props: { children: JSX.Element }) {
+ return (
+ <p class="mx-1 w-[calc(100%-0.5rem)] px-2 py-2 text-ink-muted text-sm">
+ {props.children}
+ </p>
+ );
+}
+
+/**
+ * The user's own activity, newest first. Reads `ActivityContext`;
+ * the host decides what a row click opens.
+ */
+export function MyActivityView(props: {
+ onOpen: (target: OpenEntityTarget) => void;
+}) {
+ const context = useActivityContext();
+ const state = createMyActivityState(context);
+ const overview = () => {
+ const current = state.overview();
+ return current.t === 'ready' ? current.overview : undefined;
+ };
+ const feed = () => {
+ const current = state.feed();
+ return current.t === 'ready' ? current : undefined;
+ };
+
+ return (
+ <div class="@container/u-list flex size-full flex-col">
+ <SplitHeaderLeft>
+ <span class="font-semibold text-sm">Activity</span>
+ </SplitHeaderLeft>
+ <StaticMarkdownContext>
+ <div class="min-h-0 flex-1 overflow-y-auto py-1">
+ <div class="mx-auto w-full max-w-[1000px]">
+ <Show
+ when={overview()}
+ fallback={
+ <OverviewInset>
+ <p class="px-2 py-1 text-ink-extra-muted text-xs">
+ {state.overview().t === 'error'
+ ? 'Activity overview is unavailable right now.'
+ : 'Loading activity overview…'}
+ </p>
+ </OverviewInset>
+ }
+ >
+ {(overview) => (
+ <>
+ <OverviewInset>
+ <ActionGraph overview={overview()} />
+ </OverviewInset>
+ <TopEntitiesSection
+ empty={overview().topEntities.length === 0}
+ >
+ <For each={overview().topEntities}>
+ {(entity) => (
+ <OpenableTopEntityRow
+ entity={entity}
+ onOpen={props.onOpen}
+ />
+ )}
+ </For>
+ </TopEntitiesSection>
+ </>
+ )}
+ </Show>
+ <Switch>
+ <Match when={feed()}>
+ {(feed) => (
+ <>
+ <For each={feed().groups}>
+ {(group) => (
+ <>
+ <SoupSectionHeader>{group.label}</SoupSectionHeader>
+ <For each={group.events}>
+ {(event) => (
+ <NamedActivityRow
+ event={event}
+ onOpen={props.onOpen}
+ />
+ )}
+ </For>
+ </>
+ )}
+ </For>
+ <Show when={feed().hasMore}>
+ <div class="flex justify-center py-2">
+ <Button
+ variant="ghost"
+ onClick={state.loadMore}
+ disabled={feed().loadingMore}
+ >
+ {feed().loadingMore ? 'Loading…' : 'Show more'}
+ </Button>
+ </div>
+ </Show>
+ </>
+ )}
+ </Match>
+ <Match when={state.feed().t === 'loading'}>
+ <FeedStatus>Loading…</FeedStatus>
+ </Match>
+ <Match when={state.feed().t === 'error'}>
+ <FeedStatus>
+ Activity is unavailable right now. Try again in a moment.
+ </FeedStatus>
+ </Match>
+ <Match when={state.feed().t === 'empty'}>
+ <FeedStatus>No activity yet.</FeedStatus>
+ </Match>
+ </Switch>
+ </div>
+ </div>
+ </StaticMarkdownContext>
+ </div>
+ );
+}
+
+function NamedActivityRow(props: {
+ event: ActivityEvent;
+ onOpen: (target: OpenEntityTarget) => void;
+}) {
+ const context = useActivityContext();
+ const name = createActorName(context, () => props.event.actorId);
+ return (
+ <ActivityTimelineRow
+ event={props.event}
+ actorName={name()}
+ onOpen={props.onOpen}
+ />
+ );
+}
+
+function OpenableTopEntityRow(props: {
+ entity: ActivityTopEntity;
+ onOpen: (target: OpenEntityTarget) => void;
+}) {
+ const context = useActivityContext();
+ const opener = createEntityOpener(
+ context,
+ () => props.entity.entityId,
+ () => props.entity.entityType,
+ props.onOpen
+ );
+ return (
+ <TopEntityRow
+ entity={props.entity}
+ display={opener()?.display}
+ rowProps={opener()?.handlers}
+ />
+ );
+}
diff --git a/apps/web/src/features/block-call/component/sidepanel/CallSidePanelSections.tsx b/apps/web/src/features/block-call/component/sidepanel/CallSidePanelSections.tsx
index 49a0251ee0..8ff50965da 100644
--- a/apps/web/src/features/block-call/component/sidepanel/CallSidePanelSections.tsx
+++ b/apps/web/src/features/block-call/component/sidepanel/CallSidePanelSections.tsx
@@ -1,4 +1,4 @@
-import { EntityActivitySectionConditional } from '@app/features/activity/EntityActivitySection';
+import { EntityActivitySectionConditional } from '@app/features/activity/views/entity-activity-section';
import { EntityPropertiesSection } from '@app/features/property/side-panel/properties';
import { useCallContextOptional } from '@channel/Call/CallContext';
import { SidePanel } from '@components/app/side-panel';
diff --git a/apps/web/src/features/block-chat/component/sidepanel/ChatSidePanelSections.tsx b/apps/web/src/features/block-chat/component/sidepanel/ChatSidePanelSections.tsx
index 1df4879f80..af69342d73 100644
--- a/apps/web/src/features/block-chat/component/sidepanel/ChatSidePanelSections.tsx
+++ b/apps/web/src/features/block-chat/component/sidepanel/ChatSidePanelSections.tsx
@@ -1,4 +1,4 @@
-import { EntityActivitySectionConditional } from '@app/features/activity/EntityActivitySection';
+import { EntityActivitySectionConditional } from '@app/features/activity/views/entity-activity-section';
import {
EntityPropertiesSection,
EntityTagsSection,
diff --git a/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.tsx b/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.tsx
index 4e5d3e7281..193a02ece3 100644
--- a/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.tsx
+++ b/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.tsx
@@ -1,4 +1,4 @@
-import { EntityActivitySectionConditional } from '@app/features/activity/EntityActivitySection';
+import { EntityActivitySectionConditional } from '@app/features/activity/views/entity-activity-section';
import {
EntityPropertiesSection,
EntityTagsSection,
diff --git a/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx b/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
index d581980025..aff4918fb8 100644
--- a/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
+++ b/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
@@ -1,4 +1,4 @@
-import { EntityActivitySectionConditional } from '@app/features/activity/EntityActivitySection';
+import { EntityActivitySectionConditional } from '@app/features/activity/views/entity-activity-section';
import {
EntityPropertiesSection,
EntityTagsSection,
diff --git a/apps/web/src/features/block-project/component/sidepanel/ProjectSidePanelSections.tsx b/apps/web/src/features/block-project/component/sidepanel/ProjectSidePanelSections.tsx
index 1fada9c0af..28fc95d9fc 100644
--- a/apps/web/src/features/block-project/component/sidepanel/ProjectSidePanelSections.tsx
+++ b/apps/web/src/features/block-project/component/sidepanel/ProjectSidePanelSections.tsx
@@ -1,4 +1,4 @@
-import { EntityActivitySectionConditional } from '@app/features/activity/EntityActivitySection';
+import { EntityActivitySectionConditional } from '@app/features/activity/views/entity-activity-section';
import {
EntityPropertiesSection,
EntityTagsSection,
diff --git a/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.test.tsx
index 261ac9da2c..c6a75b7691 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.test.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.test.tsx
@@ -2,6 +2,8 @@
* @vitest-environment jsdom
*/
+import { ActivityContextProvider } from '@app/features/activity/context/activity-context';
+import { createMockActivityContext } from '@app/features/activity/tests/mock-context';
import type { PropertyDefinitionDomain } from '@property/types';
import type { NamedTool } from '@service-cognition/generated/tools/tool';
import { cleanup, render, screen } from '@solidjs/testing-library';
@@ -27,12 +29,23 @@ const definitions = [
} as unknown as PropertyDefinitionDomain,
];
-vi.mock('@property/editor/hooks/useAllProperties', () => ({
- useAllProperties: () => () => definitions,
+vi.mock('@app/features/activity/open-entity-in-split', () => ({
+ openEntityInSplit: vi.fn(),
}));
-vi.mock('@core/component/LexicalMarkdown/component/core/BlockLink', () => ({
- openDocument: vi.fn(),
+// Module-load quarantine, not a dependency substitute: the connection-gateway
+// websocket connects when imported, which jsdom cannot do.
+vi.mock('@service-connection/websocket', () => ({
+ ws: { send() {}, addEventListener() {}, removeEventListener() {} },
+ state: () => 'closed',
+ createConnectionBlockWebsocketEffect() {},
+ createConnectionWebsocketEffect() {},
+ parseWebsocketPayload: () => undefined,
+}));
+
+vi.mock('@service-storage/websocket', () => ({
+ storageWS: { send() {}, addEventListener() {}, removeEventListener() {} },
+ createWebSocketJob: () => Promise.reject(new Error('no websocket in tests')),
}));
vi.mock(
@@ -43,15 +56,17 @@ vi.mock(
})
);
-vi.mock('@property/hooks', () => ({
- usePropertyEntityDisplay: () => ({
+const context = createMockActivityContext({
+ propertyDefinition: (id) => () =>
+ definitions.find((definition) => definition.id === id()),
+ entityDisplay: () => ({
name: () => 'Launch plan',
icon: () => null,
isLoading: () => false,
blockOrFileType: () => null,
linkParams: () => undefined,
}),
-}));
+});
function renderTool(
activities: NamedTool<'ReadActivity', 'response'>['data']['activities']
@@ -71,18 +86,20 @@ function renderTool(
};
return render(() => (
- <Dynamic
- component={
- readActivityHandler.render as Component<Record<string, unknown>>
- }
- tool={tool}
- response={response}
- chat_id="chat-1"
- message_id="message-1"
- part_index={0}
- isComplete
- renderContext={{ isStreaming: false, grouped: false }}
- />
+ <ActivityContextProvider value={context}>
+ <Dynamic
+ component={
+ readActivityHandler.render as Component<Record<string, unknown>>
+ }
+ tool={tool}
+ response={response}
+ chat_id="chat-1"
+ message_id="message-1"
+ part_index={0}
+ isComplete
+ renderContext={{ isStreaming: false, grouped: false }}
+ />
+ </ActivityContextProvider>
));
}
diff --git a/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.tsx b/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.tsx
index 030553d358..0229f2994a 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.tsx
@@ -1,9 +1,13 @@
-import { ActivityTimelineRow } from '@app/features/activity/activity-timeline-row';
+import type {
+ ActivityAction,
+ ActivityEntityType,
+ ActivityEvent,
+} from '@app/features/activity/core/event';
+import { openEntityInSplit } from '@app/features/activity/open-entity-in-split';
+import { ActivityTimelineRow } from '@app/features/activity/views/activity-timeline-row';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import ClockCounterClockwise from '@phosphor-icons/core/regular/clock-counter-clockwise.svg';
-import type { ActivityEvent } from '@queries/activity/graphql/entity';
import type { NamedTool } from '@service-cognition/generated/tools/tool';
-import type { GraphqlEntityType } from '@service-storage/graphql/generated/graphql';
import { createMemo, createSignal, For } from 'solid-js';
import { match } from 'ts-pattern';
import { BaseTool } from './BaseTool';
@@ -15,79 +19,66 @@ type Activity = NamedTool<
'response'
>['data']['activities'][number];
-const ENTITY_TYPES: Readonly<Record<string, GraphqlEntityType>> = {
- user: 'USER',
- chat: 'CHAT',
- channel: 'CHANNEL',
- channel_message: 'CHANNEL_MESSAGE',
- document: 'DOCUMENT',
- project: 'PROJECT',
- email_thread: 'EMAIL_THREAD',
- calendar_event: 'CALENDAR_EVENT',
- team: 'TEAM',
- call: 'CALL',
- foreign_entity: 'FOREIGN_ENTITY',
- static_file: 'STATIC_FILE',
- crm_company: 'CRM_COMPANY',
- crm_contact: 'CRM_CONTACT',
- reminder: 'REMINDER',
- skill: 'SKILL',
- agent_session: 'AGENT_SESSION',
-};
+function decodeToolEntityType(raw: string): ActivityEntityType {
+ return match(raw)
+ .with('document', () => 'document' as const)
+ .with('project', () => 'project' as const)
+ .with('chat', () => 'chat' as const)
+ .with('email_thread', () => 'email-thread' as const)
+ .with('channel', () => 'channel' as const)
+ .with('user', () => 'user' as const)
+ .otherwise((value) => ({ kind: 'unsupported' as const, raw: value }));
+}
-function activityAction(action: Activity['action']): ActivityEvent['action'] {
+function activityAction(action: Activity['action']): ActivityAction {
return match(action)
.with({ type: 'created' }, () => ({
- __typename: 'GraphqlActivityCreated' as const,
+ kind: 'created' as const,
}))
.with({ type: 'edited' }, () => ({
- __typename: 'GraphqlActivityEdited' as const,
+ kind: 'edited' as const,
}))
.with({ type: 'opened' }, () => ({
- __typename: 'GraphqlActivityOpened' as const,
+ kind: 'opened' as const,
}))
.with({ type: 'deleted' }, () => ({
- __typename: 'GraphqlActivityDeleted' as const,
+ kind: 'deleted' as const,
}))
.with({ type: 'messaged' }, () => ({
- __typename: 'GraphqlActivityMessaged' as const,
+ kind: 'messaged' as const,
}))
.with({ type: 'sent' }, () => ({
- __typename: 'GraphqlActivitySent' as const,
+ kind: 'email-sent' as const,
}))
.with({ type: 'propertyChanged' }, ({ property, from, to }) => ({
- __typename: 'GraphqlActivityPropertyChanged' as const,
+ kind: 'property-changed' as const,
property,
from,
to,
}))
.with({ type: 'participantAdded' }, ({ participant }) => ({
- __typename: 'GraphqlActivityParticipantAdded' as const,
+ kind: 'participant-added' as const,
participant,
}))
.with({ type: 'participantRemoved' }, ({ participant }) => ({
- __typename: 'GraphqlActivityParticipantRemoved' as const,
+ kind: 'participant-removed' as const,
participant,
}))
- .with({ type: 'callStarted' }, ({ callId }) => ({
- __typename: 'GraphqlActivityCallStarted' as const,
- callId,
+ .with({ type: 'callStarted' }, () => ({
+ kind: 'call-started' as const,
}))
- .with({ type: 'unknown' }, ({ tag, payload }) => ({
- __typename: 'GraphqlActivityUnknownAction' as const,
+ .with({ type: 'unknown' }, ({ tag }) => ({
+ kind: 'unknown' as const,
tag,
- payload,
}))
.exhaustive();
}
function activityEvent(activity: Activity, index: number): ActivityEvent {
return {
- __typename: 'GraphqlActivityEvent',
id: `read-activity:${index}:${activity.occurredAt}`,
actorId: activity.actorId,
- subjectId: activity.actorId,
- entityType: ENTITY_TYPES[activity.entityType] ?? 'FOREIGN_ENTITY',
+ entityType: decodeToolEntityType(activity.entityType),
entityId: activity.entityId,
action: activityAction(activity.action),
occurredAt: activity.occurredAt,
@@ -130,7 +121,11 @@ const handler = createToolRenderer({
<div class="max-h-120 overflow-y-auto rounded-md border border-edge-muted/60 py-1">
<For each={events()}>
{(event) => (
- <ActivityTimelineRow event={event} showActor={false} />
+ <ActivityTimelineRow
+ event={event}
+ showActor={false}
+ onOpen={openEntityInSplit}
+ />
)}
</For>
</div>
diff --git a/apps/web/tests/e2e/fixtures/local-e2e-seed.ts b/apps/web/tests/e2e/fixtures/local-e2e-seed.ts
index 454097abcb..99756bc1c7 100644
--- a/apps/web/tests/e2e/fixtures/local-e2e-seed.ts
+++ b/apps/web/tests/e2e/fixtures/local-e2e-seed.ts
@@ -33,6 +33,9 @@ type SeedManifest = {
};
};
};
+ activity: {
+ seededEventCount: number;
+ };
navigation: {
genericChannelMention: {
sourceChannelId: string;
@@ -234,4 +237,7 @@ export const localE2ESeed = {
),
unreadChannelNotificationId: manifest.navigation.unreadNotificationId,
},
+ activity: {
+ seededEventCount: manifest.activity.seededEventCount,
+ },
} as const;
diff --git a/apps/web/tests/e2e/helpers/graphql-stub.ts b/apps/web/tests/e2e/helpers/graphql-stub.ts
new file mode 100644
index 0000000000..06af9a8a1b
--- /dev/null
+++ b/apps/web/tests/e2e/helpers/graphql-stub.ts
@@ -0,0 +1,50 @@
+import type { Page, Route } from '@playwright/test';
+
+export type GraphqlStubRequest = {
+ operationName: string;
+ variables: Record<string, unknown>;
+};
+
+export type GraphqlStubResponse =
+ | { data: unknown }
+ | { errors: Array<{ message: string }> };
+
+/**
+ * Answers selected soup GraphQL operations from the test. Operations the
+ * resolver returns `undefined` for pass through to the real backend, so a
+ * spec stubs only the surface under test. Runs on the page and its workers.
+ */
+export async function stubSoupGraphql(
+ page: Page,
+ resolve: (request: GraphqlStubRequest) => GraphqlStubResponse | undefined
+): Promise<void> {
+ await page.route('**/items/soup/graphql', async (route: Route) => {
+ const request = route.request();
+ if (request.method() !== 'POST') {
+ await route.fallback();
+ return;
+ }
+ const body = request.postDataJSON() as {
+ operationName?: string;
+ query?: string;
+ variables?: Record<string, unknown>;
+ };
+ const operationName =
+ body.operationName ??
+ /\b(?:query|mutation|subscription)\s+(\w+)/.exec(body.query ?? '')?.[1] ??
+ '';
+ const response = resolve({
+ operationName,
+ variables: body.variables ?? {},
+ });
+ if (!response) {
+ await route.fallback();
+ return;
+ }
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(response),
+ });
+ });
+}
diff --git a/apps/web/tests/e2e/helpers/local-app.ts b/apps/web/tests/e2e/helpers/local-app.ts
index 140f5fdf1a..1cfb5a3420 100644
--- a/apps/web/tests/e2e/helpers/local-app.ts
+++ b/apps/web/tests/e2e/helpers/local-app.ts
@@ -49,3 +49,47 @@ export async function fillEditable(locator: Locator, text: string) {
export function uniqueE2EText(prefix: string): string {
return `${prefix} ${Date.now()} ${Math.random().toString(36).slice(2)}`;
}
+
+/** Creates a markdown document through the sidebar and returns its id. */
+export async function createDocument(page: Page): Promise<string> {
+ await page.getByRole('button', { name: 'Create' }).click();
+ await page.getByRole('menuitem', { name: /^Document/ }).click();
+ await page.waitForURL(/\/app\/md\/[0-9a-f-]{36}/, { timeout: 30_000 });
+ const id = /\/app\/md\/([0-9a-f-]{36})/.exec(page.url())?.[1];
+ if (!id) throw new Error(`no document id in ${page.url()}`);
+ return id;
+}
+
+/** Opens the side panel if hidden, then expands the named accordion section. */
+export async function openSidePanelSection(page: Page, title: string) {
+ const show = page.getByRole('button', { name: 'Show Side Panel' });
+ const trigger = page.getByRole('button', { name: title, exact: true });
+ await expect(show.or(trigger).first()).toBeVisible({ timeout: 30_000 });
+ if (await show.isVisible()) {
+ await show.click();
+ }
+ await expect(trigger).toBeVisible({ timeout: 30_000 });
+ if ((await trigger.getAttribute('aria-expanded')) !== 'true') {
+ await trigger.click();
+ }
+}
+
+export async function sendChannelMessage(
+ page: Page,
+ channelId: string,
+ text: string
+): Promise<Locator> {
+ const input = page.locator(`[data-input-id="channel-input-${channelId}"]`);
+ await fillEditable(input.locator('[contenteditable="true"]').first(), text);
+
+ const sendButton = input.locator('[data-input-action="send"]');
+ await expect(sendButton).toBeEnabled({ timeout: 10_000 });
+ await sendButton.click();
+
+ const message = page
+ .locator('[data-message]')
+ .filter({ hasText: text })
+ .last();
+ await expect(message).toBeVisible({ timeout: 30_000 });
+ return message;
+}
diff --git a/apps/web/tests/e2e/local-activity-stubbed.spec.ts b/apps/web/tests/e2e/local-activity-stubbed.spec.ts
new file mode 100644
index 0000000000..bfdc2bcac6
--- /dev/null
+++ b/apps/web/tests/e2e/local-activity-stubbed.spec.ts
@@ -0,0 +1,126 @@
+import { expect, test } from '@playwright/test';
+
+import { localE2ESeed } from './fixtures/local-e2e-seed';
+import { stubSoupGraphql } from './helpers/graphql-stub';
+import {
+ createDocument,
+ gotoApp,
+ LOCAL_E2E,
+ openSidePanelSection,
+} from './helpers/local-app';
+
+test.skip(
+ !LOCAL_E2E,
+ 'local activity tests require LOCAL_E2E=true and a running local stack'
+);
+
+const ACTOR = 'macro|[email protected]';
+
+function wireEvent(
+ id: string,
+ action: Record<string, unknown>,
+ entity: { type: string; id: string } = {
+ type: 'DOCUMENT',
+ id: localE2ESeed.smoke.projectRoadmap.document_id,
+ }
+) {
+ return {
+ __typename: 'GraphqlActivityEvent',
+ id,
+ actorId: ACTOR,
+ subjectId: ACTOR,
+ entityType: entity.type,
+ entityId: entity.id,
+ occurredAt: '2026-08-29T12:00:00.000Z',
+ action,
+ };
+}
+
+const FIRST_PAGE = [
+ wireEvent('stub-1', { __typename: 'GraphqlActivityCreated' }),
+ wireEvent('stub-2', { __typename: 'GraphqlActivityEdited' }),
+ wireEvent('stub-3', { __typename: 'GraphqlActivityOpened' }),
+];
+const SECOND_PAGE = [
+ wireEvent('stub-4', {
+ __typename: 'GraphqlActivityCallStarted',
+ callId: 'c',
+ }),
+ wireEvent('stub-5', { __typename: 'GraphqlActivityDeleted' }),
+];
+
+/**
+ * The feed and side panel against a scripted backend: pagination follows the
+ * cursor the server hands back, and an entity the soup does not know about
+ * reads as unavailable rather than as an empty history. No seed dependence.
+ */
+test.describe('local activity (stubbed GraphQL)', () => {
+ test.describe.configure({ timeout: 60_000 });
+
+ test('pages the feed through the returned cursor', async ({ page }) => {
+ await stubSoupGraphql(page, ({ operationName, variables }) => {
+ if (operationName === 'MyActivityOverview') {
+ return {
+ data: {
+ user: {
+ id: 'user-stub',
+ activityOverview: {
+ from: '2025-09-01',
+ to: '2026-09-01',
+ timeZone: 'UTC',
+ total: 5,
+ days: [{ date: '2026-08-29', count: 5 }],
+ topEntities: [],
+ },
+ },
+ },
+ };
+ }
+ if (operationName === 'MyActivity') {
+ const cursor = (variables.input as { cursor: string | null }).cursor;
+ const page = cursor === 'stub-cursor' ? SECOND_PAGE : FIRST_PAGE;
+ return {
+ data: {
+ user: {
+ id: 'user-stub',
+ activity: {
+ items: page,
+ nextCursor: cursor === 'stub-cursor' ? null : 'stub-cursor',
+ },
+ },
+ },
+ };
+ }
+ return undefined;
+ });
+
+ await gotoApp(page, '/component/activity');
+ const rows = page.locator('[data-activity-row]');
+ await expect(rows).toHaveCount(FIRST_PAGE.length, { timeout: 30_000 });
+ await expect(page.getByText('Actions (5)')).toBeVisible();
+
+ await page.getByRole('button', { name: 'Show more' }).click();
+ await expect(rows).toHaveCount(FIRST_PAGE.length + SECOND_PAGE.length);
+ await expect(
+ page.locator('[data-activity-row][data-activity-action="call-started"]')
+ ).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Show more' })).toHaveCount(
+ 0
+ );
+ });
+
+ test('reads a missing soup entity as unavailable', async ({ page }) => {
+ await stubSoupGraphql(page, ({ operationName }) =>
+ operationName === 'EntityActivity'
+ ? { data: { user: { id: 'user-stub', soup: { items: [] } } } }
+ : undefined
+ );
+
+ await gotoApp(page, '/component/activity');
+ await createDocument(page);
+ await openSidePanelSection(page, 'Activity');
+ await expect(page.getByText('Activity is unavailable')).toBeVisible({
+ timeout: 30_000,
+ });
+ });
+});
diff --git a/apps/web/tests/e2e/local-activity.spec.ts b/apps/web/tests/e2e/local-activity.spec.ts
new file mode 100644
index 0000000000..fb04adb177
--- /dev/null
+++ b/apps/web/tests/e2e/local-activity.spec.ts
@@ -0,0 +1,79 @@
+import { expect, type Page, test } from '@playwright/test';
+
+import { localE2ESeed } from './fixtures/local-e2e-seed';
+import {
+ createDocument,
+ gotoApp,
+ LOCAL_E2E,
+ openSidePanelSection,
+ sendChannelMessage,
+ uniqueE2EText,
+} from './helpers/local-app';
+
+const FEED_PAGE_LIMIT = 50;
+
+test.skip(
+ !LOCAL_E2E,
+ 'local activity tests require LOCAL_E2E=true and seeded local data'
+);
+
+test.describe('local activity', () => {
+ test.describe.configure({ timeout: 60_000 });
+
+ test('records a messaged row after a channel send', async ({ page }) => {
+ const channel = localE2ESeed.smoke.generalChannel;
+ const messageText = uniqueE2EText('local e2e activity message');
+
+ await openSeededChannel(page, channel.channel_id);
+ await sendChannelMessage(page, channel.channel_id, messageText);
+
+ await gotoApp(page, '/component/activity');
+ await expect(
+ page
+ .locator('[data-activity-row][data-activity-action="messaged"]')
+ .first()
+ ).toBeVisible({ timeout: 30_000 });
+ });
+
+ test('pages the seeded feed past the first cursor', async ({ page }) => {
+ expect(localE2ESeed.activity.seededEventCount).toBeGreaterThan(
+ FEED_PAGE_LIMIT
+ );
+
+ await gotoApp(page, '/component/activity');
+ const rows = page.locator('[data-activity-row]');
+ await expect(rows).toHaveCount(FEED_PAGE_LIMIT, { timeout: 30_000 });
+
+ await page.getByRole('button', { name: 'Show more' }).click();
+ await expect
+ .poll(async () => rows.count(), { timeout: 30_000 })
+ .toBeGreaterThanOrEqual(localE2ESeed.activity.seededEventCount);
+ });
+
+ test('shows the created event for a new document in the side panel', async ({
+ page,
+ }) => {
+ await gotoApp(page, '/component/activity');
+ await createDocument(page);
+ await openSidePanelSection(page, 'Activity');
+
+ const created = page.locator(
+ '[data-activity-row][data-activity-action="created"]'
+ );
+ await expect(created).toBeVisible({ timeout: 30_000 });
+ await expect(created).toContainText('You');
+ });
+});
+
+async function openSeededChannel(page: Page, channelId: string) {
+ const channelName =
+ localE2ESeed.smoke.generalChannel.channel_name ?? 'general';
+
+ await gotoApp(page, `/channel/${channelId}`);
+ await expect(
+ page.getByText(channelName, { exact: true }).first()
+ ).toBeVisible({ timeout: 30_000 });
+ await expect(page.locator('[data-channel-message-list]')).toBeVisible({
+ timeout: 30_000,
+ });
+}
diff --git a/apps/web/tests/e2e/local-channel-actions.spec.ts b/apps/web/tests/e2e/local-channel-actions.spec.ts
index e13d853eb6..39c6a346bd 100644
--- a/apps/web/tests/e2e/local-channel-actions.spec.ts
+++ b/apps/web/tests/e2e/local-channel-actions.spec.ts
@@ -2,9 +2,9 @@ import { expect, type Locator, type Page, test } from '@playwright/test';
import { localE2ESeed } from './fixtures/local-e2e-seed';
import {
- fillEditable,
gotoApp,
LOCAL_E2E,
+ sendChannelMessage,
uniqueE2EText,
} from './helpers/local-app';
@@ -72,26 +72,6 @@ async function openSeededChannel(
});
}
-async function sendChannelMessage(
- page: Page,
- channelId: string,
- text: string
-): Promise<Locator> {
- const input = page.locator(`[data-input-id="channel-input-${channelId}"]`);
- await fillEditable(input.locator('[contenteditable="true"]').first(), text);
- await clickSend(input);
-
- const message = messageByText(page, text);
- await expect(message).toBeVisible({ timeout: 30_000 });
- return message;
-}
-
-async function clickSend(input: Locator) {
- const sendButton = input.locator('[data-input-action="send"]');
- await expect(sendButton).toBeEnabled({ timeout: 10_000 });
- await sendButton.click();
-}
-
async function reactToMessage(message: Locator, emoji: string) {
await message.hover();
const reaction = message.locator(
@@ -107,7 +87,3 @@ async function openReplyInput(message: Locator) {
await expect(reply).toBeVisible({ timeout: 10_000 });
await reply.click();
}
-
-function messageByText(page: Page, text: string) {
- return page.locator('[data-message]').filter({ hasText: text }).last();
-}
diff --git a/apps/web/tests/e2e/local-channel-edit.spec.ts b/apps/web/tests/e2e/local-channel-edit.spec.ts
index dc73d28028..0371a41f29 100644
--- a/apps/web/tests/e2e/local-channel-edit.spec.ts
+++ b/apps/web/tests/e2e/local-channel-edit.spec.ts
@@ -1,10 +1,10 @@
-import { expect, type Locator, type Page, test } from '@playwright/test';
+import { expect, type Page, test } from '@playwright/test';
import { localE2ESeed } from './fixtures/local-e2e-seed';
import {
- fillEditable,
gotoApp,
LOCAL_E2E,
+ sendChannelMessage,
uniqueE2EText,
} from './helpers/local-app';
@@ -63,6 +63,8 @@ async function startInlineEditOfOwnMessage(
await openSeededChannel(page, channelId);
const message = await sendChannelMessage(page, channelId, messageText);
+ const input = page.locator(`[data-input-id="channel-input-${channelId}"]`);
+ await input.locator('[contenteditable="true"]').first().click();
const messageId = await message.getAttribute('data-message-id');
expect(messageId).toBeTruthy();
@@ -105,28 +107,3 @@ async function openSeededChannel(page: Page, channelId: string) {
timeout: 30_000,
});
}
-
-async function sendChannelMessage(
- page: Page,
- channelId: string,
- text: string
-): Promise<Locator> {
- const input = page.locator(`[data-input-id="channel-input-${channelId}"]`);
- const editable = input.locator('[contenteditable="true"]').first();
- await fillEditable(editable, text);
-
- const sendButton = input.locator('[data-input-action="send"]');
- await expect(sendButton).toBeEnabled({ timeout: 10_000 });
- await sendButton.click();
-
- const message = page
- .locator('[data-message]')
- .filter({ hasText: text })
- .last();
- await expect(message).toBeVisible({ timeout: 30_000 });
-
- // Keyboard selection starts from the channel input; clicking Send moved
- // focus to the button, so return it to the input first.
- await editable.click();
- return message;
-}
diff --git a/docs/STYLE_GUIDE.md b/docs/STYLE_GUIDE.md
index 6953abc709..4ed51b8de5 100644
--- a/docs/STYLE_GUIDE.md
+++ b/docs/STYLE_GUIDE.md
@@ -251,3 +251,29 @@ TypeScript · `[ui]` UI / UX conventions
- **FE-32** `[ui]` Prefer styling in the component (Tailwind on the markup). Reserve
`@utility` in `apps/web/src/index.css` for styles widely shared across many
components — not one-off or two-callsite layouts. (#6038 · also: apps/web/AGENTS.md)
+- **FE-33** `[arch]` Layered feature layout. A feature that adopts it (today:
+ `features/activity`) is split into `core/` (pure TS: types and functions, no
+ Solid, urql, generated GraphQL, or app modules), `queries/` (decode wire types
+ and build query factories that take the feature's context), `primitives/`
+ (reactive view models: Solid primitives, no JSX; each returns a view-state
+ union such as `loading | error | empty | ready` plus actions), `components/`
+ (props in, JSX out; no queries, primitives, or navigation), `views/` (compose
+ context, primitives, and components), `context/` (the injection seam), and
+ `tests/` (mocks shared by the feature's tests). Every ambient capability the
+ feature needs the same way on every surface (GraphQL client, viewer id, display
+ names, entity display, property definitions) is a field on one `Context` type
+ in `context/`. `useContext()` reads an optional Solid context and falls back to
+ the app wiring defined in the same file, so production mounts no provider;
+ tests mount `ContextProvider` with mocks. Keep the record to what the feature
+ must swap in tests; a value derivable from the environment (time zone) or
+ already shaped for one consumer does not belong in it. Behavior that varies
+ per surface (what a row click opens) is a callback prop from the host, so an
+ inert surface simply omits it. `primitives/` run under `createRoot` against a
+ mock client and `views/` render without `vi.mock`. The import graph is
+ one-way: `core` → `queries` → `primitives` → `views` and
+ `core` → `components` → `views`; `components` may import types from
+ `context/`. Feature flags gate mounting at the root and stay outside the
+ context. To adopt, add the feature's layer paths to `files` in each
+ `*-feature-*` rule. (enforced: ast-grep `ts-/tsx-feature-core-pure`,
+ `ts-/tsx-feature-components-presentational`, `ts-/tsx-feature-data-no-ui`,
+ `ts-/tsx-feature-layers-use-context`, warning)
diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.yml
new file mode 100644
index 0000000000..17d2484271
--- /dev/null
+++ b/rules/ast-grep/ts-feature-components-presentational.yml
@@ -0,0 +1,51 @@
+id: ts-feature-components-presentational
+language: typescript
+# Twin of tsx-feature-components-presentational — ast-grep rules are
+# single-language, and `tsx` only scans .ts files.
+severity: warning
+message: Feature components take resolved values and return JSX. Data, reactivity wiring, and navigation belong to primitives/ and views/.
+note: |-
+ Rule FE-33 in docs/STYLE_GUIDE.md. `components/` never imports
+ `queries/`, `primitives/`, `views/`, `@queries/*`, urql, or the split
+ navigation helpers. It renders what views hand it: domain values from
+ `core/`, resolved display (typed in `context/`), and event handlers. The
+ one sanctioned `queries/` import is `property-value`, which parses
+ untyped wire JSON for property-changed rows.
+files:
+ - apps/web/src/features/activity/components/**
+rule:
+ any:
+ - kind: string
+ regex: ^['"](@queries/|@urql|urql|@app/lib/urql|@core/util/useSplitNavigationHandler|(\.\./)+(primitives|views)/)
+ any:
+ - inside:
+ kind: import_statement
+ field: source
+ - inside:
+ kind: export_statement
+ field: source
+ - inside:
+ kind: arguments
+ inside:
+ kind: call_expression
+ has:
+ field: function
+ kind: import
+ - kind: string
+ regex: ^['"](\.\./)+queries/
+ not:
+ regex: property-value
+ any:
+ - inside:
+ kind: import_statement
+ field: source
+ - inside:
+ kind: export_statement
+ field: source
+ - inside:
+ kind: arguments
+ inside:
+ kind: call_expression
+ has:
+ field: function
+ kind: import
diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.yml
new file mode 100644
index 0000000000..b5d7922919
--- /dev/null
+++ b/rules/ast-grep/ts-feature-core-pure.yml
@@ -0,0 +1,33 @@
+id: ts-feature-core-pure
+language: typescript
+# Twin of tsx-feature-core-pure — ast-grep rules are single-language, and
+# `tsx` only scans .tsx files.
+severity: warning
+message: Feature core modules stay pure TypeScript — no Solid, urql, queries, generated GraphQL, app modules, or sibling layers.
+note: |-
+ Rule FE-33 in docs/STYLE_GUIDE.md. `core/` owns the feature's vocabulary
+ and the functions that describe, group, and summarize it. Wire types,
+ clients, reactivity, and UI stay outside so a schema rename or a
+ framework upgrade cannot churn core tests. Decode lives in `queries/`,
+ reactive view models in `primitives/`. The `dateBucket` import from
+ `soup/collection/date-buckets` (a pure date-fns module, not the soup barrel)
+ is the documented exception for feed labels that must match soup views.
+files:
+ - apps/web/src/features/activity/core/**
+rule:
+ kind: string
+ regex: ^['"](solid-js|@urql|urql|@app/lib/urql|@queries/|@service-storage/|@core/|@property/|@components/|@ui|@entity/|(\.\./)+(queries|primitives|components|views)/|(\.\./)+context/)
+ any:
+ - inside:
+ kind: import_statement
+ field: source
+ - inside:
+ kind: export_statement
+ field: source
+ - inside:
+ kind: arguments
+ inside:
+ kind: call_expression
+ has:
+ field: function
+ kind: import
diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.yml
new file mode 100644
index 0000000000..50aa9b2cac
--- /dev/null
+++ b/rules/ast-grep/ts-feature-data-no-ui.yml
@@ -0,0 +1,32 @@
+id: ts-feature-data-no-ui
+language: typescript
+# Twin of tsx-feature-data-no-ui — ast-grep rules are single-language, and
+# `tsx` only scans .tsx files.
+severity: warning
+message: Feature queries/ and primitives/ never import components, views, or UI primitives. They produce data and view-state; views render it.
+note: |-
+ Rule FE-33 in docs/STYLE_GUIDE.md. `queries/` decodes wire types and
+ builds query factories; `primitives/` turns query results into view-state
+ unions and actions with Solid primitives but no JSX. Both are tested
+ under `createRoot` against a mock client, which only stays possible
+ while they import nothing that renders.
+files:
+ - apps/web/src/features/activity/queries/**
+ - apps/web/src/features/activity/primitives/**
+rule:
+ kind: string
+ regex: ^['"](solid-js/web|@ui|@components/|(\.\./)+(components|views)/)
+ any:
+ - inside:
+ kind: import_statement
+ field: source
+ - inside:
+ kind: export_statement
+ field: source
+ - inside:
+ kind: arguments
+ inside:
+ kind: call_expression
+ has:
+ field: function
+ kind: import
diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.yml
new file mode 100644
index 0000000000..3eb84bcc06
--- /dev/null
+++ b/rules/ast-grep/ts-feature-layers-use-context.yml
@@ -0,0 +1,37 @@
+id: ts-feature-layers-use-context
+language: typescript
+# Twin of tsx-feature-layers-use-context — ast-grep rules are single-language,
+# and `tsx` only scans .tsx files.
+severity: warning
+message: Layered features reach the app only through context/. Add the capability to the feature's Context type and wire it in context/.
+note: |-
+ Rule FE-33 in docs/STYLE_GUIDE.md. Inside a layered feature, `queries/`,
+ `primitives/`, `components/`, and `views/` never import the app's singletons
+ or context hooks (GraphQL soup client, user context, display names,
+ entity display, openDocument, PostHog). Those arrive through the
+ feature's `Context` record so every layer runs against mocks in tests. Only
+ `context/` (the contract and its production wiring) at the
+ feature root touch them. Adopting features add their layer paths to
+ `files` in each ts-/tsx-feature-* rule.
+files:
+ - apps/web/src/features/activity/components/**
+ - apps/web/src/features/activity/queries/**
+ - apps/web/src/features/activity/primitives/**
+ - apps/web/src/features/activity/views/**
+rule:
+ kind: string
+ regex: ^['"](@service-storage/graphql-soup|@core/context/user|@core/user|@property/hooks|@property/editor/hooks|@core/component/LexicalMarkdown/component/core/BlockLink|@app/lib/analytics/posthog)
+ any:
+ - inside:
+ kind: import_statement
+ field: source
+ - inside:
+ kind: export_statement
+ field: source
+ - inside:
+ kind: arguments
+ inside:
+ kind: call_expression
+ has:
+ field: function
+ kind: import
diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.yml
new file mode 100644
index 0000000000..0177c28001
--- /dev/null
+++ b/rules/ast-grep/tsx-feature-components-presentational.yml
@@ -0,0 +1,51 @@
+id: tsx-feature-components-presentational
+language: tsx
+# Twin of ts-feature-components-presentational — ast-grep rules are
+# single-language, and `typescript` only scans .ts files.
+severity: warning
+message: Feature components take resolved values and return JSX. Data, reactivity wiring, and navigation belong to primitives/ and views/.
+note: |-
+ Rule FE-33 in docs/STYLE_GUIDE.md. `components/` never imports
+ `queries/`, `primitives/`, `views/`, `@queries/*`, urql, or the split
+ navigation helpers. It renders what views hand it: domain values from
+ `core/`, resolved display (typed in `context/`), and event handlers. The
+ one sanctioned `queries/` import is `property-value`, which parses
+ untyped wire JSON for property-changed rows.
+files:
+ - apps/web/src/features/activity/components/**
+rule:
+ any:
+ - kind: string
+ regex: ^['"](@queries/|@urql|urql|@app/lib/urql|@core/util/useSplitNavigationHandler|(\.\./)+(primitives|views)/)
+ any:
+ - inside:
+ kind: import_statement
+ field: source
+ - inside:
+ kind: export_statement
+ field: source
+ - inside:
+ kind: arguments
+ inside:
+ kind: call_expression
+ has:
+ field: function
+ kind: import
+ - kind: string
+ regex: ^['"](\.\./)+queries/
+ not:
+ regex: property-value
+ any:
+ - inside:
+ kind: import_statement
+ field: source
+ - inside:
+ kind: export_statement
+ field: source
+ - inside:
+ kind: arguments
+ inside:
+ kind: call_expression
+ has:
+ field: function
+ kind: import
diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.yml
new file mode 100644
index 0000000000..2937af47a2
--- /dev/null
+++ b/rules/ast-grep/tsx-feature-core-pure.yml
@@ -0,0 +1,33 @@
+id: tsx-feature-core-pure
+language: tsx
+# Twin of ts-feature-core-pure — ast-grep rules are single-language, and
+# `typescript` only scans .ts files.
+severity: warning
+message: Feature core modules stay pure TypeScript — no Solid, urql, queries, generated GraphQL, app modules, or sibling layers.
+note: |-
+ Rule FE-33 in docs/STYLE_GUIDE.md. `core/` owns the feature's vocabulary
+ and the functions that describe, group, and summarize it. Wire types,
+ clients, reactivity, and UI stay outside so a schema rename or a
+ framework upgrade cannot churn core tests. Decode lives in `queries/`,
+ reactive view models in `primitives/`. The `dateBucket` import from
+ `soup/collection/date-buckets` (a pure date-fns module, not the soup barrel)
+ is the documented exception for feed labels that must match soup views.
+files:
+ - apps/web/src/features/activity/core/**
+rule:
+ kind: string
+ regex: ^['"](solid-js|@urql|urql|@app/lib/urql|@queries/|@service-storage/|@core/|@property/|@components/|@ui|@entity/|(\.\./)+(queries|primitives|components|views)/|(\.\./)+context/)
+ any:
+ - inside:
+ kind: import_statement
+ field: source
+ - inside:
+ kind: export_statement
+ field: source
+ - inside:
+ kind: arguments
+ inside:
+ kind: call_expression
+ has:
+ field: function
+ kind: import
diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.yml
new file mode 100644
index 0000000000..fb9d0fbfab
--- /dev/null
+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml
@@ -0,0 +1,32 @@
+id: tsx-feature-data-no-ui
+language: tsx
+# Twin of ts-feature-data-no-ui — ast-grep rules are single-language, and
+# `typescript` only scans .ts files.
+severity: warning
+message: Feature queries/ and primitives/ never import components, views, or UI primitives. They produce data and view-state; views render it.
+note: |-
+ Rule FE-33 in docs/STYLE_GUIDE.md. `queries/` decodes wire types and
+ builds query factories; `primitives/` turns query results into view-state
+ unions and actions with Solid primitives but no JSX. Both are tested
+ under `createRoot` against a mock client, which only stays possible
+ while they import nothing that renders.
+files:
+ - apps/web/src/features/activity/queries/**
+ - apps/web/src/features/activity/primitives/**
+rule:
+ kind: string
+ regex: ^['"](solid-js/web|@ui|@components/|(\.\./)+(components|views)/)
+ any:
+ - inside:
+ kind: import_statement
+ field: source
+ - inside:
+ kind: export_statement
+ field: source
+ - inside:
+ kind: arguments
+ inside:
+ kind: call_expression
+ has:
+ field: function
+ kind: import
diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.yml
new file mode 100644
index 0000000000..8eec3ddccd
--- /dev/null
+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml
@@ -0,0 +1,37 @@
+id: tsx-feature-layers-use-context
+language: tsx
+# Twin of ts-feature-layers-use-context — ast-grep rules are single-language,
+# and `typescript` only scans .ts files.
+severity: warning
+message: Layered features reach the app only through context/. Add the capability to the feature's Context type and wire it in context/.
+note: |-
+ Rule FE-33 in docs/STYLE_GUIDE.md. Inside a layered feature, `queries/`,
+ `primitives/`, `components/`, and `views/` never import the app's singletons
+ or context hooks (GraphQL soup client, user context, display names,
+ entity display, openDocument, PostHog). Those arrive through the
+ feature's `Context` record so every layer runs against mocks in tests. Only
+ `context/` (the contract and its production wiring) at the
+ feature root touch them. Adopting features add their layer paths to
+ `files` in each ts-/tsx-feature-* rule.
+files:
+ - apps/web/src/features/activity/components/**
+ - apps/web/src/features/activity/queries/**
+ - apps/web/src/features/activity/primitives/**
+ - apps/web/src/features/activity/views/**
+rule:
+ kind: string
+ regex: ^['"](@service-storage/graphql-soup|@core/context/user|@core/user|@property/hooks|@property/editor/hooks|@core/component/LexicalMarkdown/component/core/BlockLink|@app/lib/analytics/posthog)
+ any:
+ - inside:
+ kind: import_statement
+ field: source
+ - inside:
+ kind: export_statement
+ field: source
+ - inside:
+ kind: arguments
+ inside:
+ kind: call_expression
+ has:
+ field: function
+ kind: import
diff --git a/tooling/seed_cli/seed/local_e2e/activity.sql b/tooling/seed_cli/seed/local_e2e/activity.sql
new file mode 100644
index 0000000000..dd7e1f9ee0
--- /dev/null
+++ b/tooling/seed_cli/seed/local_e2e/activity.sql
@@ -0,0 +1,24 @@
+INSERT INTO activity_events (
+ id,
+ actor_id,
+ subject_id,
+ action,
+ action_payload,
+ entity_type,
+ entity_id,
+ occurred_at
+)
+SELECT
+ ('00000000-0000-0000-0005-' || lpad(n::text, 12, '0'))::uuid,
+ CASE WHEN n = 1 THEN 'created' ELSE 'edited' END,
+ NULL,
+ CASE WHEN n = 1 THEN 'document' ELSE 'channel' END,
+ CASE
+ WHEN n = 1 THEN '00000000-0000-0000-0002-000000000001'
+ ELSE '00000000-0000-0000-0000-000000000001'
+ END,
+ TIMESTAMPTZ '2026-08-01 00:00:00+00' + ((n - 1) * INTERVAL '1 minute')
+FROM generate_series(1, 60) AS n
+ON CONFLICT (id) DO NOTHING
diff --git a/tooling/seed_cli/seed/local_e2e/manifest.json b/tooling/seed_cli/seed/local_e2e/manifest.json
index 014395da06..756e73c09c 100644
--- a/tooling/seed_cli/seed/local_e2e/manifest.json
+++ b/tooling/seed_cli/seed/local_e2e/manifest.json
@@ -29,6 +29,9 @@
}
}
},
+ "activity": {
+ "seededEventCount": 60
+ },
"navigation": {
"genericChannelMention": {
"sourceChannelId": "00000000-0000-0000-0000-000000000002",
diff --git a/tooling/seed_cli/seed/local_e2e/reset.sql b/tooling/seed_cli/seed/local_e2e/reset.sql
index ed66179fa5..01ba2c9332 100644
--- a/tooling/seed_cli/seed/local_e2e/reset.sql
+++ b/tooling/seed_cli/seed/local_e2e/reset.sql
@@ -1,3 +1,7 @@
+DELETE FROM activity_events
+WHERE id::text LIKE '00000000-0000-0000-0005-%'
+ OR subject_id = 'macro|[email protected]';
+
DELETE FROM notification
WHERE id::text LIKE '00000000-0000-0000-0004-%';
diff --git a/tooling/seed_cli/src/entity/scenario.rs b/tooling/seed_cli/src/entity/scenario.rs
index 437b565361..72fa9735cf 100644
--- a/tooling/seed_cli/src/entity/scenario.rs
+++ b/tooling/seed_cli/src/entity/scenario.rs
@@ -20,6 +20,7 @@ const LOCAL_E2E_RESET_SQL: &str = include_str!("../../seed/local_e2e/reset.sql")
const LOCAL_E2E_USERS_JSON: &str = include_str!("../../seed/local_e2e/users.json");
const LOCAL_E2E_CHANNEL_MESSAGES_SQL: &str =
include_str!("../../seed/local_e2e/channel_messages.sql");
+const LOCAL_E2E_ACTIVITY_SQL: &str = include_str!("../../seed/local_e2e/activity.sql");
#[derive(Debug, Deserialize)]
struct LocalE2eManifest {
@@ -567,6 +568,11 @@ async fn local_e2e_smoke(ctx: &SeedCliContext) -> anyhow::Result<()> {
.execute_sql_script(LOCAL_E2E_CHANNEL_MESSAGES_SQL)
.await?;
+ tracing::info!("seeding local e2e activity events");
+ ctx.db
+ .execute_sql_if_table_exists("public.activity_events", LOCAL_E2E_ACTIVITY_SQL)
+ .await?;
+
println!("Local e2e smoke seed data ready for {local_e2e_user_id}");
Ok(())
}