Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(activity): ai activity tools (#5714)
teo561c2c2c9aae
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 8396daf1f0..f4789bdca7 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -3,6 +3,7 @@"closures": {"activity": ["crates/activity",+ "crates/ai_toolset","crates/bot_id","crates/channel_sender","crates/cowlike",@@ -3393,6 +3394,7 @@],"graphql_activity": ["crates/activity",+ "crates/ai_toolset","crates/bot_id","crates/channel_sender","crates/cowlike",diff --git a/.sqlx/query-fc09ef8fa86f4f1a53b37a2811a9ac608dfb92074a4d3bcbd8fb4953ebda4e1c.json b/.sqlx/query-fc09ef8fa86f4f1a53b37a2811a9ac608dfb92074a4d3bcbd8fb4953ebda4e1c.jsonnew file mode 100644index 0000000000..66e316f1b9--- /dev/null+++ b/.sqlx/query-fc09ef8fa86f4f1a53b37a2811a9ac608dfb92074a4d3bcbd8fb4953ebda4e1c.json@@ -0,0 +1,67 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, actor_id, action, action_payload,\n subject_id, entity_type, entity_id, occurred_at\n FROM activity_events\n WHERE subject_id = $1\n AND occurred_at >= $2\n AND occurred_at < $3\n ORDER BY occurred_at DESC, id DESC\n LIMIT $4\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "actor_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "action",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "action_payload",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 4,+ "name": "subject_id",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "entity_id",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "occurred_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Int8"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "fc09ef8fa86f4f1a53b37a2811a9ac608dfb92074a4d3bcbd8fb4953ebda4e1c"+}diff --git a/Cargo.lock b/Cargo.lockindex 1187091f2d..57f29e9342 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -12,6 +12,8 @@ checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3"name = "activity"version = "0.1.0"dependencies = [+ "ai_toolset",+ "async-trait","channel_sender","chrono","kafka_util",@@ -22,6 +24,7 @@ dependencies = ["rdkafka","readonly","rootcause",+ "schemars 1.2.1","serde","serde_json","sqlx",diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdxindex f2365b8c46..825dd8f2be 100644--- a/apps/docs/AI/mcp/tools/index.mdx+++ b/apps/docs/AI/mcp/tools/index.mdx@@ -46,6 +46,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [MarkNotificationsSeen](/AI/mcp/tools/mark-notifications-seen)- [MoveToProject](/AI/mcp/tools/move-to-project)- [NameSearch](/AI/mcp/tools/name-search)+- [ReadActivity](/AI/mcp/tools/read-activity)- [ReadCallRecord](/AI/mcp/tools/read-call-record)- [ReadChannelMessageContext](/AI/mcp/tools/read-channel-message-context)- [ReadChannelMessages](/AI/mcp/tools/read-channel-messages)diff --git a/apps/docs/AI/mcp/tools/read-activity.mdx b/apps/docs/AI/mcp/tools/read-activity.mdxnew file mode 100644index 0000000000..08f64e15e3--- /dev/null+++ b/apps/docs/AI/mcp/tools/read-activity.mdx@@ -0,0 +1,15 @@+---+title: ReadActivity+description: "Read actions attributed to the authenticated user within a time range, newest first. Use this for questions about what the user did, including actions an agent performed on their behalf. Property changes include propertyName/propertyType plus fromLabels/toLabels for resolved select and tag values; use those human-readable fields in the answer and never expose property or option ids. Do not use this for organization-wide updates or everything that happened to entities the user can access; use ListEntities for those. Returns at most 100 activities and reports when the result was truncated."+---++# ReadActivity++Read actions attributed to the authenticated user within a time range, newest first. Use this for questions about what the user did, including actions an agent performed on their behalf. Property changes include propertyName/propertyType plus fromLabels/toLabels for resolved select and tag values; use those human-readable fields in the answer and never expose property or option ids. Do not use this for organization-wide updates or everything that happened to entities the user can access; use ListEntities for those. Returns at most 100 activities and reports when the result was truncated.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `from` | string | Yes | Inclusive start of the range as an RFC 3339 timestamp. |+| `to` | string | Yes | Exclusive end of the range as an RFC 3339 timestamp. Must be after from. |diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.jsonindex 70a4b95ed4..8132d31b47 100644--- a/apps/docs/config/tool-pages.json+++ b/apps/docs/config/tool-pages.json@@ -37,6 +37,7 @@"AI/mcp/tools/mark-notifications-seen","AI/mcp/tools/move-to-project","AI/mcp/tools/name-search",+ "AI/mcp/tools/read-activity","AI/mcp/tools/read-call-record","AI/mcp/tools/read-channel-message-context","AI/mcp/tools/read-channel-messages",diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex 83978423e9..d39cd7d87e 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -106,6 +106,7 @@"AI/mcp/tools/mark-notifications-seen","AI/mcp/tools/move-to-project","AI/mcp/tools/name-search",+ "AI/mcp/tools/read-activity","AI/mcp/tools/read-call-record","AI/mcp/tools/read-channel-message-context","AI/mcp/tools/read-channel-messages",diff --git a/apps/web/src/features/activity/action-phrase.tsx b/apps/web/src/features/activity/action-phrase.tsxindex 4805872b30..f04bbea37e 100644--- a/apps/web/src/features/activity/action-phrase.tsx+++ b/apps/web/src/features/activity/action-phrase.tsx@@ -3,18 +3,31 @@ import { Show } from 'solid-js';import { actionAsPropertyChange, describeAction } from './describe-action';import { PropertyChangeText } from './property-change';+function capitalize(value: string): string {+ return value.length === 0 ? value : value[0].toUpperCase() + value.slice(1);+}+/*** The verb half of an activity row: property changes render their resolved* transition ("changed Status from … to …"), everything else the plain verb* phrase.*/-export function ActionPhrase(props: { event: ActivityEvent }) {+export function ActionPhrase(props: {+ event: ActivityEvent;+ capitalize?: boolean;+}) {return (<Showwhen={actionAsPropertyChange(props.event.action)}- fallback={describeAction(props.event.action)}+ fallback={+ props.capitalize+ ? capitalize(describeAction(props.event.action))+ : describeAction(props.event.action)+ }>- {(change) => <PropertyChangeText action={change()} />}+ {(change) => (+ <PropertyChangeText action={change()} capitalize={props.capitalize} />+ )}</Show>);}diff --git a/apps/web/src/features/activity/activity-timeline-row.tsx b/apps/web/src/features/activity/activity-timeline-row.tsxnew file mode 100644index 0000000000..ed5093a4d4--- /dev/null+++ b/apps/web/src/features/activity/activity-timeline-row.tsx@@ -0,0 +1,162 @@+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/my-activity-view.tsx b/apps/web/src/features/activity/my-activity-view.tsxindex d2f2989cee..97f2f86c52 100644--- a/apps/web/src/features/activity/my-activity-view.tsx+++ b/apps/web/src/features/activity/my-activity-view.tsx@@ -1,48 +1,12 @@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 { openDocument } from '@core/component/LexicalMarkdown/component/core/BlockLink';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';-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 { createMyActivityQuery } from '@queries/activity/graphql/feed';-import type { EntityType } from '@service-properties/generated/schemas/entityType';-import type { GraphqlEntityType } from '@service-storage/graphql/generated/graphql';import { Button } from '@ui';import { type Component, createMemo, For, 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. Only types the resolver- * can actually name are mapped — calls, calendar events, and companies have- * no preview/name source there and would render as a stuck "Loading…" or a- * raw id, so they (like teams and static files) return undefined and the row- * shows without an entity reference.- */-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);-}+import { ActivityTimelineRow } from './activity-timeline-row';type FeedGroup = { key: string; label: string; events: ActivityEvent[] };@@ -82,7 +46,7 @@ export function MyActivityView() {</p>}>- <FeedGroups groups={groups()} row={SentenceTimelineRow} />+ <FeedGroups groups={groups()} row={ActivityTimelineRow} /><Show when={feed.hasNextPage}><div class="flex justify-center py-2"><Button@@ -118,99 +82,3 @@ function FeedGroups(props: {</For>);}--function Timestamp(props: { event: ActivityEvent }) {- return (- <span class="ml-auto shrink-0 text-right font-medium text-ink-extra-muted text-xs">- {formatRelativeTimestamp(new Date(props.event.occurredAt), {- condensed: true,- })}- </span>- );-}--/**- * "<actor> <action> on <entity>": the glyph rail with a full sentence —- * actor in medium weight, verb muted, the natural connector per action- * kind, and the entity as a real mention.- */-function SentenceTimelineRow(props: { event: ActivityEvent }) {- const entityType = () => displayEntityType(props.event.entityType);-- 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}>- <span class="shrink-0 font-medium">- <ActorName actorId={props.event.actorId} />- </span>- <span class="min-w-0 truncate text-ink-muted">- <ActionPhrase event={props.event} />- </span>- <Timestamp event={props.event} />- </div>- }- >- {(type) => <EntityRow event={props.event} entityType={type()} />}- </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';--/**- * A feed row that names its entity. Resolves the entity's display once and- * shares it between the row-wide click-to-open (shift-click for a new split,- * same target as the inline mention) and the mention itself. Rows whose- * entity isn't linkable (inaccessible, unmapped type) stay inert.- */-function EntityRow(props: { event: ActivityEvent; entityType: EntityType }) {- const parts = () => describeActionForEntity(props.event.action);- const display = usePropertyEntityDisplay(- () => props.event.entityId,- () => props.entityType- );- const navHandlers = useSplitNavigationHandler<HTMLDivElement>((e) => {- const block = display.blockOrFileType();- if (!block) return;- openDocument(block, props.event.entityId, display.linkParams(), e.shiftKey);- });-- return (- <div {...navHandlers} class={ROW_BODY_CLASS}>- <span class="shrink-0 font-medium">- <ActorName actorId={props.event.actorId} />- </span>- <span class="min-w-0 text-ink-muted">- <Show- when={actionAsPropertyChange(props.event.action)}- fallback={parts().verb}- >- {(change) => <PropertyChangeText action={change()} />}- </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/property-change.tsx b/apps/web/src/features/activity/property-change.tsxindex 081ce00279..fcce3ba89d 100644--- a/apps/web/src/features/activity/property-change.tsx+++ b/apps/web/src/features/activity/property-change.tsx@@ -23,7 +23,10 @@ type PropertyChangedAction = Extract<* wording. `from` is rendered only when the source event carried it (most* producers don't yet).*/-export function PropertyChangeText(props: { action: PropertyChangedAction }) {+export function PropertyChangeText(props: {+ action: PropertyChangedAction;+ capitalize?: boolean;+}) {const definitions = useAllProperties();const definition = () =>definitions().find((def) => def.id === props.action.property);@@ -38,7 +41,15 @@ export function PropertyChangeText(props: { action: PropertyChangedAction }) {return (<span class="inline-flex min-w-0 flex-wrap items-center gap-x-1 gap-y-0.5">- <span class="shrink-0">{cleared() ? 'cleared' : 'changed'}</span>+ <span class="shrink-0">+ {cleared()+ ? props.capitalize+ ? 'Cleared'+ : 'cleared'+ : props.capitalize+ ? 'Changed'+ : 'changed'}+ </span><span class="shrink-0 font-medium text-ink">{name()}</span><Show when={hasFrom()}><span class="shrink-0">from</span>diff --git a/apps/web/src/features/dynamic-ui/toolSchema.ts b/apps/web/src/features/dynamic-ui/toolSchema.tsindex 4a76ef2269..bca717c6d0 100644--- a/apps/web/src/features/dynamic-ui/toolSchema.ts+++ b/apps/web/src/features/dynamic-ui/toolSchema.ts@@ -22,6 +22,7 @@ export function displayResultsInstructions(): string {'# displayResults','`displayResults` renders a rich, interactive view (lists, timelines, channel messages) directly in the chat. PREFER it over a plain-text answer whenever your response is largely about the user\'s workspace data — summaries of tasks/docs/activity, lists of entities, anything you would otherwise format as a markdown table or a long bulleted list. You do NOT need the user to ask for a "dashboard" or a "view": proactively call `displayResults` whenever it presents the information more clearly than text would.','Typical triggers — call it even though the user never said "dashboard": "what did I get done this week?", "what\'s <teammate> working on?", "show me my open tasks", "summarize this project", "what happened in <channel>?". When in doubt and the answer is mostly workspace entities or metrics, render a view.',+ '`ReadActivity` is the exception: it already renders its complete, entity-resolved response as a rich user-facing activity timeline. After calling `ReadActivity`, do NOT call `displayResults` to restate or summarize those events. Add at most one short textual takeaway.','When you DO render a view, keep any accompanying chat text short (a one-line lead-in at most) — the view IS the answer; do not also restate it in prose.','Its `view` argument MUST be a JSON object matching this JSON Schema (a `title` plus an ordered `widgets` array; layout is flexbox via the `container` widget):','```json',diff --git a/apps/web/src/lib/core/component/AI/component/message/AssistantMessageParts.test.tsx b/apps/web/src/lib/core/component/AI/component/message/AssistantMessageParts.test.tsxindex 05283d092d..b504642a7c 100644--- a/apps/web/src/lib/core/component/AI/component/message/AssistantMessageParts.test.tsx+++ b/apps/web/src/lib/core/component/AI/component/message/AssistantMessageParts.test.tsx@@ -96,7 +96,12 @@ vi.mock('@core/component/AI/component/tool/handler', async () => {const solid = await vi.importActual<typeof import('solid-js')>('solid-js');return {- RenderTool: (props: { tool_id: string; isComplete: boolean }) => {+ RenderTool: (props: {+ tool_id: string;+ isComplete: boolean;+ name: string;+ renderContext: { renderContext: { grouped?: boolean } };+ }) => {solid.onMount(() => {lifecycle.toolMounts.set(props.tool_id,@@ -110,7 +115,12 @@ vi.mock('@core/component/AI/component/tool/handler', async () => {);});return (- <div data-complete={String(props.isComplete)} data-testid="tool">+ <div+ data-complete={String(props.isComplete)}+ data-grouped={String(props.renderContext.renderContext.grouped)}+ data-name={props.name}+ data-testid="tool"+ >{props.tool_id}</div>);@@ -360,6 +370,84 @@ describe('AssistantMessageParts streaming identity', () => {expect(rendered.getByTestId('markdown').textContent).toBe('Interim answer');});+ it('shows the native activity result and suppresses a redundant dashboard', () => {+ const parts: AssistantMessagePart[] = [+ { thinking: 'Read the activity', type: 'thinking' },+ {+ id: 'activity-tool',+ json: {+ from: '2026-08-12T21:57:00Z',+ to: '2026-08-19T21:57:00Z',+ },+ name: 'ReadActivity',+ type: 'toolCall',+ },+ {+ id: 'activity-tool',+ json: { activities: [], truncated: false },+ name: 'ReadActivity',+ type: 'toolCallResponseJson',+ },+ { text: "Here's your activity:", type: 'text' },+ {+ id: 'dashboard-tool',+ json: {+ view: {+ widgets: [{ events: [], type: 'timeline' }],+ },+ },+ name: 'DisplayResults',+ type: 'toolCall',+ },+ {+ id: 'dashboard-tool',+ json: { message: 'View displayed' },+ name: 'DisplayResults',+ type: 'toolCallResponseJson',+ },+ {+ id: 'other-dashboard-tool',+ json: {+ view: {+ widgets: [+ {+ source: { entities: [], kind: 'items' },+ type: 'list',+ },+ ],+ },+ },+ name: 'DisplayResults',+ type: 'toolCall',+ },+ {+ id: 'other-dashboard-tool',+ json: { message: 'View displayed' },+ name: 'DisplayResults',+ type: 'toolCallResponseJson',+ },+ ];+ const rendered = render(() => (+ <AssistantMessageParts+ parts={parts}+ message={{+ attachments: [],+ content: parts,+ id: 'message-1',+ role: 'assistant',+ }}+ isStreaming={false}+ />+ ));++ const tools = rendered.getAllByTestId('tool');+ expect(tools).toHaveLength(2);+ expect(tools[0].dataset.name).toBe('ReadActivity');+ expect(tools[0].dataset.grouped).toBe('false');+ expect(rendered.queryByText('dashboard-tool')).toBeNull();+ expect(rendered.getByText('other-dashboard-tool')).toBeTruthy();+ });+it('previews only the latest activity group while streaming', async () => {let append!: (item: ChatStream) => void;let disposeStream!: () => void;diff --git a/apps/web/src/lib/core/component/AI/component/message/AssistantMessageParts.tsx b/apps/web/src/lib/core/component/AI/component/message/AssistantMessageParts.tsxindex ac30be3f5f..518767b553 100644--- a/apps/web/src/lib/core/component/AI/component/message/AssistantMessageParts.tsx+++ b/apps/web/src/lib/core/component/AI/component/message/AssistantMessageParts.tsx@@ -71,9 +71,48 @@ type RenderItem =const STANDALONE_TOOLS: ReadonlySet<string> = new Set(['CreateCalendarEvent','DisplayResults',+ 'ReadActivity','SendEmail',]);+function asObject(value: unknown): Record<string, unknown> | undefined {+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {+ return undefined;+ }+ return value as Record<string, unknown>;+}++function hasTimelineWidget(value: unknown): boolean {+ const widget = asObject(value);+ if (!widget) return false;+ if (widget.type === 'timeline') return true;+ if (widget.type !== 'container' || !Array.isArray(widget.children)) {+ return false;+ }+ return widget.children.some(hasTimelineWidget);+}++function isActivityPresentationWidget(value: unknown): boolean {+ const widget = asObject(value);+ if (!widget) return false;+ if (widget.type === 'timeline' || widget.type === 'md') return true;+ if (widget.type !== 'container' || !Array.isArray(widget.children)) {+ return false;+ }+ return widget.children.every(isActivityPresentationWidget);+}++function isRedundantActivityDashboard(part: AssistantMessagePart): boolean {+ if (part.type !== 'toolCall' || part.name !== 'DisplayResults') return false;+ const view = asObject(asObject(part.json)?.view);+ const widgets = view?.widgets;+ return (+ Array.isArray(widgets) &&+ widgets.some(hasTimelineWidget) &&+ widgets.every(isActivityPresentationWidget)+ );+}+export function AssistantMessageParts(props: {parts: AssistantMessagePart[];message: ChatMessageWithAttachments;@@ -95,6 +134,12 @@ export function AssistantMessageParts(props: {completedToolIds,(id: string, completed) => completed.has(id));+ const hasNativeActivityResult = createMemo(() =>+ props.parts.some(+ (part) =>+ part.type === 'toolCallResponseJson' && part.name === 'ReadActivity'+ )+ );const responseById = createMemo(() => {const responseMap = new Map<@@ -116,6 +161,7 @@ export function AssistantMessageParts(props: {(part) =>part.type !== 'toolCallResponseJson' &&part.type !== 'toolCallErr' &&+ !(hasNativeActivityResult() && isRedundantActivityDashboard(part)) &&(part.type !== 'thinking' || part.thinking.trim().length > 0));});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.tsxnew file mode 100644index 0000000000..261ac9da2c--- /dev/null+++ b/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.test.tsx@@ -0,0 +1,144 @@+/**+ * @vitest-environment jsdom+ */++import type { PropertyDefinitionDomain } from '@property/types';+import type { NamedTool } from '@service-cognition/generated/tools/tool';+import { cleanup, render, screen } from '@solidjs/testing-library';+import type { Component } from 'solid-js';+import { Dynamic } from 'solid-js/web';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { readActivityHandler } from './ReadActivity';++const STATUS_PROPERTY_ID = 'property-status';+const COMPLETED_OPTION_ID = 'option-completed';++const definitions = [+ {+ id: STATUS_PROPERTY_ID,+ displayName: 'Status',+ options: [+ {+ id: COMPLETED_OPTION_ID,+ value: { type: 'string', value: 'Completed' },+ color: 'rgb(16, 185, 129)',+ },+ ],+ } as unknown as PropertyDefinitionDomain,+];++vi.mock('@property/editor/hooks/useAllProperties', () => ({+ useAllProperties: () => () => definitions,+}));++vi.mock('@core/component/LexicalMarkdown/component/core/BlockLink', () => ({+ openDocument: vi.fn(),+}));++vi.mock(+ '@core/component/LexicalMarkdown/component/core/StaticMarkdown',+ () => ({+ StaticMarkdownContext: (props: { children: unknown }) => props.children,+ StaticMarkdown: () => null,+ })+);++vi.mock('@property/hooks', () => ({+ usePropertyEntityDisplay: () => ({+ name: () => 'Launch plan',+ icon: () => null,+ isLoading: () => false,+ blockOrFileType: () => null,+ linkParams: () => undefined,+ }),+}));++function renderTool(+ activities: NamedTool<'ReadActivity', 'response'>['data']['activities']+) {+ const tool: NamedTool<'ReadActivity', 'call'> = {+ id: 'tool-1',+ name: 'ReadActivity',+ data: {+ from: '2026-08-18T17:30:00Z',+ to: '2026-08-19T17:30:00Z',+ },+ };+ const response: NamedTool<'ReadActivity', 'response'> = {+ id: 'tool-1',+ name: 'ReadActivity',+ data: { activities, truncated: false },+ };++ 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 }}+ />+ ));+}++afterEach(cleanup);++describe('ReadActivity renderer', () => {+ it('reuses activity property and entity display resolution', async () => {+ const { container } = renderTool([+ {+ actorId: 'macro|[email protected]',+ entityType: 'document',+ entityId: 'document-raw-id',+ action: {+ type: 'propertyChanged',+ property: STATUS_PROPERTY_ID,+ to: {+ type: 'SelectOption',+ value: [COMPLETED_OPTION_ID],+ },+ },+ occurredAt: '2026-08-19T17:30:00Z',+ },+ ]);++ const toggle = screen.getByRole('button', { name: /1 activity/i });+ expect(toggle.getAttribute('aria-expanded')).toBe('true');++ expect(container.textContent).toContain('Changed');+ expect(container.textContent).toContain('Status');+ expect(container.textContent).toContain('Completed');+ expect(container.textContent).toContain('Launch plan');+ expect(container.textContent).not.toContain(STATUS_PROPERTY_ID);+ expect(container.textContent).not.toContain(COMPLETED_OPTION_ID);+ expect(container.textContent).not.toContain('document-raw-id');+ });++ it('renders an unsupported entity type without leaking the raw id', () => {+ const { container } = renderTool([+ {+ actorId: 'macro|[email protected]',+ entityType: 'agent_session',+ entityId: 'agent-session-raw-id',+ action: { type: 'created' },+ occurredAt: '2026-08-19T17:30:00Z',+ },+ ]);++ expect(screen.getByRole('button', { name: /1 activity/i })).toBeTruthy();+ expect(container.textContent).toContain('Created');+ expect(container.textContent).not.toContain('agent-session-raw-id');+ });++ it('reports an empty range without an expand control', () => {+ renderTool([]);++ expect(screen.getByText('No Results')).toBeTruthy();+ expect(screen.queryByRole('button', { name: /activity/i })).toBeNull();+ });+});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.tsxnew file mode 100644index 0000000000..030553d358--- /dev/null+++ b/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.tsx@@ -0,0 +1,164 @@+import { ActivityTimelineRow } from '@app/features/activity/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';+import { Tool } from './Tool';+import { createToolRenderer } from './ToolRenderer';++type Activity = NamedTool<+ 'ReadActivity',+ '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 activityAction(action: Activity['action']): ActivityEvent['action'] {+ return match(action)+ .with({ type: 'created' }, () => ({+ __typename: 'GraphqlActivityCreated' as const,+ }))+ .with({ type: 'edited' }, () => ({+ __typename: 'GraphqlActivityEdited' as const,+ }))+ .with({ type: 'opened' }, () => ({+ __typename: 'GraphqlActivityOpened' as const,+ }))+ .with({ type: 'deleted' }, () => ({+ __typename: 'GraphqlActivityDeleted' as const,+ }))+ .with({ type: 'messaged' }, () => ({+ __typename: 'GraphqlActivityMessaged' as const,+ }))+ .with({ type: 'sent' }, () => ({+ __typename: 'GraphqlActivitySent' as const,+ }))+ .with({ type: 'propertyChanged' }, ({ property, from, to }) => ({+ __typename: 'GraphqlActivityPropertyChanged' as const,+ property,+ from,+ to,+ }))+ .with({ type: 'participantAdded' }, ({ participant }) => ({+ __typename: 'GraphqlActivityParticipantAdded' as const,+ participant,+ }))+ .with({ type: 'participantRemoved' }, ({ participant }) => ({+ __typename: 'GraphqlActivityParticipantRemoved' as const,+ participant,+ }))+ .with({ type: 'callStarted' }, ({ callId }) => ({+ __typename: 'GraphqlActivityCallStarted' as const,+ callId,+ }))+ .with({ type: 'unknown' }, ({ tag, payload }) => ({+ __typename: 'GraphqlActivityUnknownAction' 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',+ entityId: activity.entityId,+ action: activityAction(activity.action),+ occurredAt: activity.occurredAt,+ };+}++function formatRangeTimestamp(value: string): string {+ return new Date(value).toLocaleString(undefined, {+ dateStyle: 'medium',+ timeStyle: 'short',+ });+}++const handler = createToolRenderer({+ name: 'ReadActivity',+ render: (ctx) => {+ const [isExpanded, setIsExpanded] = createSignal(+ ctx.renderContext.grouped !== true+ );+ const activities = () => ctx.response?.data.activities ?? [];+ const events = createMemo(() => activities().map(activityEvent));+ const hasResults = () => activities().length > 0;+ const statusText = () => {+ if (!ctx.response) return undefined;+ const count = activities().length;+ if (count === 0) return 'No Results';+ if (ctx.response.data.truncated) return `${count}+ activities`;+ if (count === 1) return '1 activity';+ return `${count} activities`;+ };++ return (+ <BaseTool+ icon={ClockCounterClockwise}+ renderContext={ctx.renderContext}+ type="call"+ response={+ hasResults() && isExpanded() ? (+ <StaticMarkdownContext>+ <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} />+ )}+ </For>+ </div>+ </StaticMarkdownContext>+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">+ <span class="min-w-0 truncate">+ Read activity from{' '}+ <span class="text-ink">+ {formatRangeTimestamp(ctx.tool.data.from)}+ </span>{' '}+ to{' '}+ <span class="text-ink">+ {formatRangeTimestamp(ctx.tool.data.to)}+ </span>+ </span>+ <Tool.ResultToggle+ expanded={isExpanded()}+ onToggle={() => setIsExpanded((expanded) => !expanded)}+ showToggle={hasResults()}+ status={statusText()}+ />+ </div>+ </BaseTool>+ );+ },+});++export const readActivityHandler = handler;diff --git a/apps/web/src/lib/core/component/AI/component/tool/Tool.tsx b/apps/web/src/lib/core/component/AI/component/tool/Tool.tsxindex bd4565db2e..23c6c81d77 100644--- a/apps/web/src/lib/core/component/AI/component/tool/Tool.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/Tool.tsx@@ -106,6 +106,7 @@ function ResultToggle(props: ToolResultToggleProps) {variant="ghost"size="sm"noTouchResize+ aria-expanded={props.expanded}class="shrink-0 whitespace-nowrap px-1 text-ink-extra-muted hover:text-ink-muted"onClick={(event) => {event.preventDefault();diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsxindex efd8f0ecf2..f4452ce3cd 100644--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx@@ -44,6 +44,7 @@ import {getEntityPropertiesHandler,setEntityPropertyHandler,} from './Properties';+import { readActivityHandler } from './ReadActivity';import { readCallRecordHandler } from './ReadCallRecord';import {readChannelMessageContextHandler,@@ -119,6 +120,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {EditTag: editTagHandler,GetThread: getThreadHandler,NameSearch: nameSearchHandler,+ ReadActivity: readActivityHandler,ReadCallRecord: readCallRecordHandler,ReadChannelMessageContext: readChannelMessageContextHandler,ReadChannelMessages: readChannelMessagesHandler,diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex dbec80e627..a52100f10b 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -2335,6 +2335,72 @@ export const NameSearch = z.object({.optional(),});+export const ReadActivity = z.object({+ from: z.string().datetime({ offset: true }),+ to: z.string().datetime({ offset: true }),+});++export const ReadActivityResponse = z.object({+ activities: z.array(+ z.object({+ actorId: z.string(),+ entityType: z.string(),+ entityId: z.string(),+ action: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.object({ type: z.literal('created') }),+ z.object({ type: z.literal('edited') }),+ z.object({ type: z.literal('opened') }),+ z.object({ type: z.literal('deleted') }),+ z.object({ type: z.literal('messaged') }),+ z.object({ type: z.literal('sent') }),+ z.object({+ property: z.string(),+ propertyName: z.union([z.string(), z.null()]).optional(),+ propertyType: z.union([z.string(), z.null()]).optional(),+ from: z.any().optional(),+ fromLabels: z.union([z.array(z.string()), z.null()]).optional(),+ to: z.any().optional(),+ toLabels: z.union([z.array(z.string()), z.null()]).optional(),+ type: z.literal('propertyChanged'),+ }),+ z.object({+ participant: z.string(),+ type: z.literal('participantAdded'),+ }),+ z.object({+ participant: z.string(),+ type: z.literal('participantRemoved'),+ }),+ z.object({ callId: z.string(), type: z.literal('callStarted') }),+ z.object({+ tag: z.string(),+ payload: z.any().optional(),+ type: z.literal('unknown'),+ }),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ occurredAt: z.string().datetime({ offset: true }),+ })+ ),+ truncated: z.boolean(),+});+export const ReadCallRecord = z.object({ callId: z.string().uuid() });export const ReadCallRecordResponse = z.object({diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.tsindex c2cb315b5e..c40abb61a5 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts@@ -120,6 +120,10 @@ type ToolParserMap = {response: types.MoveToProjectResponse;};NameSearch: { call: types.NameSearch; response: types.SearchToolResponse };+ ReadActivity: {+ call: types.ReadActivity;+ response: types.ReadActivityResponse;+ };ReadCallRecord: {call: types.ReadCallRecord;response: types.ReadCallRecordResponse;@@ -318,6 +322,10 @@ const toolParserMap = {call: schemas.NameSearch,response: schemas.SearchToolResponse,},+ ReadActivity: {+ call: schemas.ReadActivity,+ response: schemas.ReadActivityResponse,+ },ReadCallRecord: {call: schemas.ReadCallRecord,response: schemas.ReadCallRecordResponse,@@ -518,6 +526,10 @@ type ToolDataMap = {response: types.MoveToProjectResponse;};NameSearch: { call: types.NameSearch; response: types.SearchToolResponse };+ ReadActivity: {+ call: types.ReadActivity;+ response: types.ReadActivityResponse;+ };ReadCallRecord: {call: types.ReadCallRecord;response: types.ReadCallRecordResponse;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex c6c6c499c4..72c4cf7431 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -449,6 +449,98 @@ export type NotificationEntityType =* The kind of entity to move.*/export type MoveableEntityType = 'document' | 'chat' | 'email' | 'project';+/**+ * One activity action returned to the AI.+ */+export type ToolActivityAction =+ | {+ type: 'created';+ }+ | {+ type: 'edited';+ }+ | {+ type: 'opened';+ }+ | {+ type: 'deleted';+ }+ | {+ type: 'messaged';+ }+ | {+ type: 'sent';+ }+ | {+ /**+ * The property definition id.+ */+ property: string;+ /**+ * The property definition's human-readable display name, when it is+ * still visible to the caller.+ */+ propertyName?: string | null;+ /**+ * The property's canonical data type, including `tag` for tag sets.+ */+ propertyType?: string | null;+ /**+ * The previous value, when known.+ */+ from?: {+ [k: string]: unknown;+ };+ /**+ * Previous select/tag option ids resolved to display labels.+ */+ fromLabels?: string[] | null;+ /**+ * The new value, or `None` when cleared.+ */+ to?: {+ [k: string]: unknown;+ };+ /**+ * New select/tag option ids resolved to display labels.+ */+ toLabels?: string[] | null;+ type: 'propertyChanged';+ }+ | {+ /**+ * The added principal.+ */+ participant: string;+ type: 'participantAdded';+ }+ | {+ /**+ * The removed principal.+ */+ participant: string;+ type: 'participantRemoved';+ }+ | {+ /**+ * The started call's id.+ */+ callId: string;+ type: 'callStarted';+ }+ | {+ /**+ * The stored action tag.+ */+ tag: string;+ /**+ * The stored payload, verbatim.+ */+ payload?: {+ [k: string]: unknown;+ };+ type: 'unknown';+ };/*** Position of a channel message.*/@@ -3187,6 +3279,54 @@ export interface NameSearch {tags?: TagFilter[] | null;tagsMatch?: TagMatch;}+/**+ * Read actions attributed to the authenticated user within a time range, newest first. Use this for questions about what the user did, including actions an agent performed on their behalf. Property changes include propertyName/propertyType plus fromLabels/toLabels for resolved select and tag values; use those human-readable fields in the answer and never expose property or option ids. Do not use this for organization-wide updates or everything that happened to entities the user can access; use ListEntities for those. Returns at most 100 activities and reports when the result was truncated.+ */+export interface ReadActivity {+ /**+ * Inclusive start of the range as an RFC 3339 timestamp.+ */+ from: string;+ /**+ * Exclusive end of the range as an RFC 3339 timestamp. Must be after from.+ */+ to: string;+}+/**+ * Response from [`ReadActivity`].+ */+export interface ReadActivityResponse {+ /**+ * Matching activity events, newest first.+ */+ activities: ToolActivityEvent[];+ /**+ * Whether more than 100 events matched the requested range.+ */+ truncated: boolean;+}+/**+ * One activity event returned by [`ReadActivity`].+ */+export interface ToolActivityEvent {+ /**+ * The principal that mechanically performed the action.+ */+ actorId: string;+ /**+ * The kind of entity acted on.+ */+ entityType: string;+ /**+ * The entity acted on.+ */+ entityId: string;+ action: ToolActivityAction;+ /**+ * When the action occurred.+ */+ occurredAt: string;+}/*** Retrieve the transcript for a specific call record. Use ListEntities with includeTypes: ["call"] first to find the callId. Only the transcript is returned — other metadata (participants, duration, etc.) is already available from ListEntities. In transcript segments, speakerId is the associated user/track, not guaranteed speaker identity; use diarizedSpeakerId to distinguish actual voices, and treat different diarizedSpeakerIds as potentially different speakers even if speakerId is the caller/"you".*/diff --git a/crates/activity/Cargo.toml b/crates/activity/Cargo.tomlindex 27092997de..74f2d29f81 100644--- a/crates/activity/Cargo.toml+++ b/crates/activity/Cargo.toml@@ -5,6 +5,7 @@ publish = falseversion = "0.1.0"[features]+ai_tools = ["dep:ai_toolset", "dep:async-trait", "dep:schemars", "dep:tracing"]consumer = ["dep:kafka_util","dep:macro_event_broker",@@ -18,6 +19,8 @@ default = ["consumer", "outbound"]outbound = ["dep:sqlx", "dep:tracing"][dependencies]+ai_toolset = { path = "../ai_toolset", optional = true }+async-trait = { workspace = true, optional = true }channel_sender = { path = "../channel_sender" }chrono = { workspace = true }kafka_util = { path = "../kafka_util", optional = true }@@ -27,6 +30,7 @@ model-entity = { path = "../model-entity" }rdkafka = { workspace = true, optional = true }readonly = { workspace = true }rootcause = { workspace = true, optional = true }+schemars = { workspace = true, optional = true }serde = { workspace = true }serde_json = { workspace = true }sqlx = { workspace = true, features = ["json"], optional = true }diff --git a/crates/activity/src/domain/mod.rs b/crates/activity/src/domain/mod.rsindex 0cd0a237ec..fc203e14b9 100644--- a/crates/activity/src/domain/mod.rs+++ b/crates/activity/src/domain/mod.rs@@ -2,3 +2,5 @@pub mod models;pub mod ports;+#[cfg(feature = "ai_tools")]+pub mod service;diff --git a/crates/activity/src/domain/ports.rs b/crates/activity/src/domain/ports.rsindex 08d06abe27..3e33066808 100644--- a/crates/activity/src/domain/ports.rs+++ b/crates/activity/src/domain/ports.rs@@ -9,6 +9,35 @@ use uuid::Uuid;use super::models::{Activity, ActivityRecord};+/// Human-readable metadata for a property referenced by an activity event.+#[cfg(feature = "ai_tools")]+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ActivityPropertyMetadata {+ /// The property definition's display name.+ pub display_name: String,+ /// The canonical property data type (for example `tag` or `select_string`).+ pub data_type: String,+ /// Select-option ids mapped to their human-readable labels.+ pub option_labels: HashMap<String, String>,+}++/// Resolves user-visible metadata referenced by stored activity payloads.+///+/// Implementations enforce the viewer's property-definition visibility and+/// return only metadata the viewer may read. Resolution is best-effort: an+/// unavailable secondary service returns an empty map so the primary activity+/// read can still succeed.+#[cfg(feature = "ai_tools")]+#[async_trait::async_trait]+pub trait ActivityMetadataResolver: Send + Sync + 'static {+ /// Resolve the requested property definition ids for `viewer`.+ async fn resolve_properties(+ &self,+ viewer: ¯o_user_id::user_id::MacroUserIdStr<'_>,+ property_ids: &[String],+ ) -> HashMap<String, ActivityPropertyMetadata>;+}+/// Activity rows grouped per requested entity, newest first within each.pub type EntityActivityMap = HashMap<(EntityType, String), Vec<ActivityRecord>>;@@ -24,6 +53,15 @@ pub struct ActivityFeedPage {pub next: Option<(DateTime<Utc>, Uuid)>,}+/// A bounded time-range read of one subject's activity.+#[derive(Debug, Clone, PartialEq)]+pub struct ActivityRange {+ /// Decoded rows in the requested range, newest first.+ pub records: Vec<ActivityRecord>,+ /// Whether more matching raw rows existed beyond the requested limit.+ pub truncated: bool,+}+/// Persists activities.pub trait ActivityRepo {/// The adapter's error type.@@ -73,4 +111,15 @@ pub trait ActivityReads {keys: &[(EntityType, String)],per_entity_limit: u32,) -> impl Future<Output = Result<EntityActivityMap, Self::Err>> + Send;++ /// The subject's activity in the half-open interval `[from, to)`, newest+ /// first, capped at `limit`. `truncated` reports whether more matching raw+ /// rows exist, so callers can disclose that the bounded result is partial.+ fn subject_activity_range(+ &self,+ subject_id: &str,+ from: DateTime<Utc>,+ to: DateTime<Utc>,+ limit: NonZeroU32,+ ) -> impl Future<Output = Result<ActivityRange, Self::Err>> + Send;}diff --git a/crates/activity/src/domain/service.rs b/crates/activity/src/domain/service.rsnew file mode 100644index 0000000000..b2a8c6d8cb--- /dev/null+++ b/crates/activity/src/domain/service.rs@@ -0,0 +1,122 @@+//! Activity read use cases.++#[cfg(test)]+mod test;++use std::{+ collections::{HashMap, HashSet},+ num::NonZeroU32,+ sync::Arc,+};++use chrono::{DateTime, Utc};+use macro_user_id::user_id::MacroUserIdStr;++use super::{+ models::{Action, RecordedAction},+ ports::{ActivityMetadataResolver, ActivityPropertyMetadata, ActivityRange, ActivityReads},+};++/// A bounded activity read plus display metadata for referenced properties.+#[derive(Debug, Clone, PartialEq)]+pub struct ResolvedActivityRange {+ /// The underlying activity result.+ pub activity: ActivityRange,+ /// Visible property metadata keyed by property definition id.+ pub properties: HashMap<String, ActivityPropertyMetadata>,+}++/// No-op resolver used by activity consumers that do not provide presentation+/// metadata, including isolated domain and inbound tests.+#[derive(Debug, Clone, Copy, Default)]+pub struct NoopActivityMetadataResolver;++#[async_trait::async_trait]+impl ActivityMetadataResolver for NoopActivityMetadataResolver {+ async fn resolve_properties(+ &self,+ _viewer: &MacroUserIdStr<'_>,+ _property_ids: &[String],+ ) -> HashMap<String, ActivityPropertyMetadata> {+ HashMap::new()+ }+}++/// Orchestrates activity reads and best-effort display metadata resolution.+pub struct ActivityReadService<R>+where+ R: ActivityReads,+{+ reads: Arc<R>,+ metadata: Arc<dyn ActivityMetadataResolver>,+}++impl<R> Clone for ActivityReadService<R>+where+ R: ActivityReads,+{+ fn clone(&self) -> Self {+ Self {+ reads: Arc::clone(&self.reads),+ metadata: Arc::clone(&self.metadata),+ }+ }+}++impl<R> ActivityReadService<R>+where+ R: ActivityReads,+{+ /// Create a read service without optional display metadata resolution.+ pub fn new(reads: R) -> Self {+ Self {+ reads: Arc::new(reads),+ metadata: Arc::new(NoopActivityMetadataResolver),+ }+ }++ /// Attach the viewer-scoped metadata resolver used by presentation reads.+ pub fn with_metadata_resolver(self, metadata: impl ActivityMetadataResolver) -> Self {+ Self {+ reads: self.reads,+ metadata: Arc::new(metadata),+ }+ }++ /// Read the caller's bounded activity and resolve distinct properties in+ /// one viewer-scoped metadata request.+ pub async fn subject_activity_range(+ &self,+ subject_id: &MacroUserIdStr<'_>,+ from: DateTime<Utc>,+ to: DateTime<Utc>,+ limit: NonZeroU32,+ ) -> Result<ResolvedActivityRange, R::Err> {+ let activity = self+ .reads+ .subject_activity_range(subject_id.as_ref(), from, to, limit)+ .await?;++ let property_ids: Vec<String> = activity+ .records+ .iter()+ .filter_map(|record| match &record.action {+ RecordedAction::Known(Action::PropertyChanged(change)) => {+ Some(change.property.clone())+ }+ _ => None,+ })+ .collect::<HashSet<_>>()+ .into_iter()+ .collect();+ let properties = self+ .metadata+ .resolve_properties(subject_id, &property_ids)+ .await;++ Ok(ResolvedActivityRange {+ activity,+ properties,+ })+ }+}diff --git a/crates/activity/src/domain/service/test.rs b/crates/activity/src/domain/service/test.rsnew file mode 100644index 0000000000..423c3260d4--- /dev/null+++ b/crates/activity/src/domain/service/test.rs@@ -0,0 +1,140 @@+use std::{+ collections::HashMap,+ convert::Infallible,+ num::NonZeroU32,+ sync::{Arc, Mutex},+};++use chrono::{DateTime, Utc};+use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++use super::*;+use crate::domain::{+ models::{Action, ActivityRecord, Actor, PropertyChange, RecordedAction},+ ports::{ActivityFeedPage, ActivityRange, EntityActivityMap},+};++#[derive(Clone)]+struct FakeReads {+ range: ActivityRange,+}++impl ActivityReads for FakeReads {+ type Err = Infallible;++ async fn subject_feed(+ &self,+ _subject_id: &str,+ _cursor: Option<(DateTime<Utc>, Uuid)>,+ _limit: NonZeroU32,+ ) -> Result<ActivityFeedPage, Self::Err> {+ unreachable!()+ }++ async fn entity_activity(+ &self,+ _keys: &[(crate::EntityType, String)],+ _per_entity_limit: u32,+ ) -> Result<EntityActivityMap, Self::Err> {+ unreachable!()+ }++ async fn subject_activity_range(+ &self,+ _subject_id: &str,+ _from: DateTime<Utc>,+ _to: DateTime<Utc>,+ _limit: NonZeroU32,+ ) -> Result<ActivityRange, Self::Err> {+ Ok(self.range.clone())+ }+}++#[derive(Clone)]+struct RecordingMetadata {+ requests: Arc<Mutex<Vec<Vec<String>>>>,+}++#[async_trait::async_trait]+impl ActivityMetadataResolver for RecordingMetadata {+ async fn resolve_properties(+ &self,+ _viewer: &MacroUserIdStr<'_>,+ property_ids: &[String],+ ) -> HashMap<String, ActivityPropertyMetadata> {+ self.requests.lock().unwrap().push(property_ids.to_vec());+ property_ids+ .iter()+ .map(|id| {+ (+ id.clone(),+ ActivityPropertyMetadata {+ display_name: "Status".to_string(),+ data_type: "select_string".to_string(),+ option_labels: HashMap::new(),+ },+ )+ })+ .collect()+ }+}++fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()+}++fn time(value: &str) -> DateTime<Utc> {+ DateTime::parse_from_rfc3339(value)+ .unwrap()+ .with_timezone(&Utc)+}++fn property_record(id: u128) -> ActivityRecord {+ ActivityRecord {+ id: Uuid::from_u128(id),+ actor: Actor::new_from_user(user()),+ subject_id: user().to_string(),+ entity_type: crate::EntityType::Document,+ entity_id: format!("doc-{id}"),+ action: RecordedAction::Known(Action::PropertyChanged(PropertyChange {+ property: "property-status".to_string(),+ from: None,+ to: None,+ })),+ occurred_at: time("2026-08-19T17:30:00Z"),+ }+}++#[tokio::test]+async fn resolves_each_referenced_property_once() {+ let requests = Arc::new(Mutex::new(Vec::new()));+ let service = ActivityReadService::new(FakeReads {+ range: ActivityRange {+ records: vec![property_record(1), property_record(2)],+ truncated: false,+ },+ })+ .with_metadata_resolver(RecordingMetadata {+ requests: Arc::clone(&requests),+ });++ let resolved = service+ .subject_activity_range(+ &user(),+ time("2026-08-19T16:00:00Z"),+ time("2026-08-19T18:00:00Z"),+ NonZeroU32::new(100).unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(+ resolved.properties["property-status"].display_name,+ "Status"+ );+ assert_eq!(+ requests.lock().unwrap().as_slice(),+ &[vec!["property-status".to_string()]]+ );+}diff --git a/crates/activity/src/inbound/mod.rs b/crates/activity/src/inbound/mod.rsindex 0bd24635fe..8033d105e6 100644--- a/crates/activity/src/inbound/mod.rs+++ b/crates/activity/src/inbound/mod.rs@@ -1,3 +1,6 @@//! Inbound adapters.+#[cfg(feature = "consumer")]pub mod kafka_consumer;+#[cfg(feature = "ai_tools")]+pub mod toolset;diff --git a/crates/activity/src/inbound/toolset/context.rs b/crates/activity/src/inbound/toolset/context.rsnew file mode 100644index 0000000000..49eeb3481f--- /dev/null+++ b/crates/activity/src/inbound/toolset/context.rs@@ -0,0 +1,59 @@+use std::sync::Arc;++use ai_toolset::AsyncToolCollection;++use super::ReadActivity;+use crate::domain::{ports::ActivityReads, service::ActivityReadService};++/// Service context for activity AI tools.+pub struct ActivityToolContext<R>+where+ R: ActivityReads,+{+ /// Domain service used to query activity and resolve display metadata.+ pub service: Arc<ActivityReadService<R>>,+}++impl<R> Clone for ActivityToolContext<R>+where+ R: ActivityReads,+{+ fn clone(&self) -> Self {+ Self {+ service: Arc::clone(&self.service),+ }+ }+}++impl<R> ActivityToolContext<R>+where+ R: ActivityReads,+{+ /// Create an activity tool context over `reads`.+ pub fn new(reads: R) -> Self {+ Self {+ service: Arc::new(ActivityReadService::new(reads)),+ }+ }++ /// Attach the viewer-scoped display metadata resolver.+ pub fn with_metadata_resolver(+ self,+ metadata: impl crate::domain::ports::ActivityMetadataResolver,+ ) -> Self {+ let service = Arc::try_unwrap(self.service)+ .unwrap_or_else(|service| (*service).clone())+ .with_metadata_resolver(metadata);+ Self {+ service: Arc::new(service),+ }+ }+}++/// Create the activity AI toolset.+pub fn activity_toolset<R>() -> AsyncToolCollection<ActivityToolContext<R>>+where+ R: ActivityReads + Send + Sync + 'static,+{+ AsyncToolCollection::new().add_tool::<ReadActivity, ActivityToolContext<R>>()+}diff --git a/crates/activity/src/inbound/toolset/mod.rs b/crates/activity/src/inbound/toolset/mod.rsnew file mode 100644index 0000000000..db3d78a8c6--- /dev/null+++ b/crates/activity/src/inbound/toolset/mod.rs@@ -0,0 +1,12 @@+//! AI tools for reading the authenticated user's activity.++mod context;+mod read_activity;++#[cfg(test)]+mod test;++pub use context::{ActivityToolContext, activity_toolset};+pub use read_activity::{+ ReadActivity, ReadActivityResponse, ToolActivityAction, ToolActivityEvent,+};diff --git a/crates/activity/src/inbound/toolset/read_activity.rs b/crates/activity/src/inbound/toolset/read_activity.rsnew file mode 100644index 0000000000..3f272650af--- /dev/null+++ b/crates/activity/src/inbound/toolset/read_activity.rs@@ -0,0 +1,264 @@+use std::{collections::HashMap, num::NonZeroU32};++use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,+ ToolResult,+};+use async_trait::async_trait;+use chrono::{DateTime, Utc};+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use serde_json::Value;++use super::ActivityToolContext;+use crate::domain::{+ models::{Action, ActivityRecord, RecordedAction},+ ports::{ActivityPropertyMetadata, ActivityReads},+};++const MAX_ACTIVITY_RESULTS: u32 = 100;++/// Tool: read the authenticated user's own activity in a time range.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "ReadActivity",+ description = "Read actions attributed to the authenticated user within a time range, newest first. Use this for questions about what the user did, including actions an agent performed on their behalf. Property changes include propertyName/propertyType plus fromLabels/toLabels for resolved select and tag values; use those human-readable fields in the answer and never expose property or option ids. Do not use this for organization-wide updates or everything that happened to entities the user can access; use ListEntities for those. Returns at most 100 activities and reports when the result was truncated."+)]+pub struct ReadActivity {+ /// Inclusive start of the time range.+ #[schemars(description = "Inclusive start of the range as an RFC 3339 timestamp.")]+ pub from: DateTime<Utc>,+ /// Exclusive end of the time range.+ #[schemars(+ description = "Exclusive end of the range as an RFC 3339 timestamp. Must be after from."+ )]+ pub to: DateTime<Utc>,+}++impl ToolAnnotated for ReadActivity {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Read activity");+}++/// One activity action returned to the AI.+#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]+#[serde(+ tag = "type",+ rename_all = "camelCase",+ rename_all_fields = "camelCase"+)]+pub enum ToolActivityAction {+ /// The entity was created.+ Created,+ /// The entity's content or metadata was edited.+ Edited,+ /// The entity was opened.+ Opened,+ /// The entity was soft-deleted.+ Deleted,+ /// A message was sent in the entity.+ Messaged,+ /// An email message was sent on the thread.+ Sent,+ /// A property value changed on the entity.+ PropertyChanged {+ /// The property definition id.+ property: String,+ /// The property definition's human-readable display name, when it is+ /// still visible to the caller.+ #[serde(skip_serializing_if = "Option::is_none")]+ property_name: Option<String>,+ /// The property's canonical data type, including `tag` for tag sets.+ #[serde(skip_serializing_if = "Option::is_none")]+ property_type: Option<String>,+ /// The previous value, when known.+ from: Option<Value>,+ /// Previous select/tag option ids resolved to display labels.+ #[serde(skip_serializing_if = "Option::is_none")]+ from_labels: Option<Vec<String>>,+ /// The new value, or `None` when cleared.+ to: Option<Value>,+ /// New select/tag option ids resolved to display labels.+ #[serde(skip_serializing_if = "Option::is_none")]+ to_labels: Option<Vec<String>>,+ },+ /// A principal was added to the entity.+ ParticipantAdded {+ /// The added principal.+ participant: String,+ },+ /// A principal was removed from the entity.+ ParticipantRemoved {+ /// The removed principal.+ participant: String,+ },+ /// A call was started in the entity.+ CallStarted {+ /// The started call's id.+ call_id: String,+ },+ /// An action outside this deployment's vocabulary.+ Unknown {+ /// The stored action tag.+ tag: String,+ /// The stored payload, verbatim.+ payload: Option<Value>,+ },+}++impl ToolActivityAction {+ fn from_recorded(+ action: RecordedAction,+ properties: &HashMap<String, ActivityPropertyMetadata>,+ ) -> Self {+ match action {+ RecordedAction::Known(Action::Created) => Self::Created,+ RecordedAction::Known(Action::Edited) => Self::Edited,+ RecordedAction::Known(Action::Opened) => Self::Opened,+ RecordedAction::Known(Action::Deleted) => Self::Deleted,+ RecordedAction::Known(Action::Messaged) => Self::Messaged,+ RecordedAction::Known(Action::Sent) => Self::Sent,+ RecordedAction::Known(Action::PropertyChanged(change)) => {+ let metadata = properties.get(&change.property);+ let from_labels = option_labels(change.from.as_ref(), metadata);+ let to_labels = option_labels(change.to.as_ref(), metadata);+ Self::PropertyChanged {+ property: change.property,+ property_name: metadata.map(|property| property.display_name.clone()),+ property_type: metadata.map(|property| property.data_type.clone()),+ from: change.from,+ from_labels,+ to: change.to,+ to_labels,+ }+ }+ RecordedAction::Known(Action::ParticipantAdded(change)) => Self::ParticipantAdded {+ participant: change.participant.as_ref().to_owned(),+ },+ RecordedAction::Known(Action::ParticipantRemoved(change)) => Self::ParticipantRemoved {+ participant: change.participant.as_ref().to_owned(),+ },+ RecordedAction::Known(Action::CallStarted(start)) => Self::CallStarted {+ call_id: start.call_id,+ },+ RecordedAction::Unknown { tag, payload } => Self::Unknown { tag, payload },+ }+ }+}++fn option_labels(+ value: Option<&Value>,+ metadata: Option<&ActivityPropertyMetadata>,+) -> Option<Vec<String>> {+ let value = value?;+ let metadata = metadata?;+ if value.get("type").and_then(Value::as_str) != Some("SelectOption") {+ return None;+ }+ let labels: Vec<String> = value+ .get("value")?+ .as_array()?+ .iter()+ .filter_map(Value::as_str)+ .filter_map(|id| metadata.option_labels.get(id).cloned())+ .collect();+ (!labels.is_empty()).then_some(labels)+}++/// One activity event returned by [`ReadActivity`].+#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolActivityEvent {+ /// The principal that mechanically performed the action.+ pub actor_id: String,+ /// The kind of entity acted on.+ pub entity_type: String,+ /// The entity acted on.+ pub entity_id: String,+ /// What the principal did.+ pub action: ToolActivityAction,+ /// When the action occurred.+ pub occurred_at: DateTime<Utc>,+}++impl ToolActivityEvent {+ fn from_record(+ record: ActivityRecord,+ properties: &HashMap<String, ActivityPropertyMetadata>,+ ) -> Self {+ Self {+ actor_id: record.actor.as_ref().to_owned(),+ entity_type: record.entity_type.as_ref().to_owned(),+ entity_id: record.entity_id,+ action: ToolActivityAction::from_recorded(record.action, properties),+ occurred_at: record.occurred_at,+ }+ }+}++/// Response from [`ReadActivity`].+#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ReadActivityResponse {+ /// Matching activity events, newest first.+ pub activities: Vec<ToolActivityEvent>,+ /// Whether more than 100 events matched the requested range.+ pub truncated: bool,+}++#[async_trait]+impl<R> AsyncTool<ActivityToolContext<R>> for ReadActivity+where+ R: ActivityReads + Send + Sync + 'static,+{+ type Output = ReadActivityResponse;++ #[tracing::instrument(+ skip_all,+ fields(from = ?self.from, to = ?self.to),+ err+ )]+ async fn call(+ &self,+ service_context: ServiceContext<ActivityToolContext<R>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ if self.from >= self.to {+ return Err(ToolCallError {+ description: "activity range `from` must be before `to`".to_string(),+ internal_error: std::io::Error::new(+ std::io::ErrorKind::InvalidInput,+ "invalid activity time range",+ )+ .into(),+ });+ }++ let range = service_context+ .service+ .subject_activity_range(+ &request_context.user_id,+ self.from,+ self.to,+ NonZeroU32::new(MAX_ACTIVITY_RESULTS).expect("activity result limit is non-zero"),+ )+ .await+ .map_err(|error| ToolCallError {+ description: "unable to read activity for the requested time range".to_string(),+ internal_error: error.into(),+ })?;++ let crate::domain::service::ResolvedActivityRange {+ activity,+ properties,+ } = range;+ Ok(ReadActivityResponse {+ activities: activity+ .records+ .into_iter()+ .map(|record| ToolActivityEvent::from_record(record, &properties))+ .collect(),+ truncated: activity.truncated,+ })+ }+}diff --git a/crates/activity/src/inbound/toolset/test.rs b/crates/activity/src/inbound/toolset/test.rsnew file mode 100644index 0000000000..3e47160eb7--- /dev/null+++ b/crates/activity/src/inbound/toolset/test.rs@@ -0,0 +1,261 @@+use std::{+ collections::HashMap,+ fmt,+ num::NonZeroU32,+ sync::{Arc, Mutex},+};++use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, schema::generate_validated_input_schema,+};+use chrono::{DateTime, Utc};+use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++use super::*;+use crate::domain::{+ models::{Action, ActivityRecord, Actor, PropertyChange, RecordedAction},+ ports::{+ ActivityFeedPage, ActivityMetadataResolver, ActivityPropertyMetadata, ActivityRange,+ ActivityReads, EntityActivityMap,+ },+};++#[derive(Debug)]+struct FakeReadError;++impl fmt::Display for FakeReadError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "fake activity read error")+ }+}++impl std::error::Error for FakeReadError {}++#[derive(Debug, Clone, PartialEq)]+struct RangeQuery {+ subject_id: String,+ from: DateTime<Utc>,+ to: DateTime<Utc>,+ limit: NonZeroU32,+}++#[derive(Clone)]+struct FakeReads {+ queries: Arc<Mutex<Vec<RangeQuery>>>,+ range: ActivityRange,+}++impl FakeReads {+ fn new(range: ActivityRange) -> Self {+ Self {+ queries: Arc::new(Mutex::new(Vec::new())),+ range,+ }+ }+}++impl ActivityReads for FakeReads {+ type Err = FakeReadError;++ async fn subject_feed(+ &self,+ _subject_id: &str,+ _cursor: Option<(DateTime<Utc>, Uuid)>,+ _limit: NonZeroU32,+ ) -> Result<ActivityFeedPage, Self::Err> {+ Ok(ActivityFeedPage {+ records: Vec::new(),+ next: None,+ })+ }++ async fn entity_activity(+ &self,+ _keys: &[(crate::EntityType, String)],+ _per_entity_limit: u32,+ ) -> Result<EntityActivityMap, Self::Err> {+ Ok(HashMap::new())+ }++ async fn subject_activity_range(+ &self,+ subject_id: &str,+ from: DateTime<Utc>,+ to: DateTime<Utc>,+ limit: NonZeroU32,+ ) -> Result<ActivityRange, Self::Err> {+ self.queries.lock().unwrap().push(RangeQuery {+ subject_id: subject_id.to_string(),+ from,+ to,+ limit,+ });+ Ok(self.range.clone())+ }+}++fn time(value: &str) -> DateTime<Utc> {+ DateTime::parse_from_rfc3339(value)+ .unwrap()+ .with_timezone(&Utc)+}++fn user(value: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(value.to_string()).expect("valid user id")+}++fn record() -> ActivityRecord {+ ActivityRecord {+ id: Uuid::from_u128(1),+ actor: Actor::new_from_user(user("macro|[email protected]")),+ subject_id: "macro|[email protected]".to_string(),+ entity_type: crate::EntityType::Document,+ entity_id: "doc-1".to_string(),+ action: RecordedAction::Known(Action::Edited),+ occurred_at: time("2026-08-17T13:00:00Z"),+ }+}++#[derive(Clone, Copy)]+struct FakeMetadata;++#[async_trait::async_trait]+impl ActivityMetadataResolver for FakeMetadata {+ async fn resolve_properties(+ &self,+ _viewer: &MacroUserIdStr<'_>,+ property_ids: &[String],+ ) -> HashMap<String, ActivityPropertyMetadata> {+ property_ids+ .iter()+ .map(|id| {+ (+ id.clone(),+ ActivityPropertyMetadata {+ display_name: "Status".to_string(),+ data_type: "select_string".to_string(),+ option_labels: HashMap::from([(+ "00000000-0000-0000-0000-000000000001".to_string(),+ "Completed".to_string(),+ )]),+ },+ )+ })+ .collect()+ }+}++#[test]+fn read_activity_schema_is_valid() {+ let validated = generate_validated_input_schema::<ReadActivity>().unwrap();+ assert_eq!(validated.name, "ReadActivity");+ assert!(validated.description.contains("authenticated user"));+}++#[tokio::test]+async fn reads_only_the_authenticated_users_activity_with_a_fixed_cap() {+ let from = time("2026-08-17T12:00:00Z");+ let to = time("2026-08-17T14:00:00Z");+ let reads = FakeReads::new(ActivityRange {+ records: vec![record()],+ truncated: true,+ });+ let queries = Arc::clone(&reads.queries);+ let tool = ReadActivity { from, to };++ let response = tool+ .call(+ ServiceContext(ActivityToolContext::new(reads)),+ RequestContext::new(user("macro|[email protected]")),+ )+ .await+ .unwrap();++ assert_eq!(+ queries.lock().unwrap().as_slice(),+ &[RangeQuery {+ subject_id: "macro|[email protected]".to_string(),+ from,+ to,+ limit: NonZeroU32::new(100).unwrap(),+ }]+ );+ assert!(response.truncated);+ assert_eq!(response.activities.len(), 1);+ assert_eq!(response.activities[0].actor_id, "macro|[email protected]");+ assert_eq!(response.activities[0].entity_type, "document");+ assert_eq!(response.activities[0].entity_id, "doc-1");+ assert_eq!(response.activities[0].action, ToolActivityAction::Edited);+}++#[tokio::test]+async fn rejects_an_empty_or_reversed_range_before_reading() {+ let at = time("2026-08-17T12:00:00Z");+ let reads = FakeReads::new(ActivityRange {+ records: Vec::new(),+ truncated: false,+ });+ let queries = Arc::clone(&reads.queries);+ let tool = ReadActivity { from: at, to: at };++ let error = tool+ .call(+ ServiceContext(ActivityToolContext::new(reads)),+ RequestContext::new(user("macro|[email protected]")),+ )+ .await+ .unwrap_err();++ assert_eq!(+ error.description,+ "activity range `from` must be before `to`"+ );+ assert!(queries.lock().unwrap().is_empty());+}++#[tokio::test]+async fn resolves_property_and_option_names_for_the_model() {+ let property = "00000000-0000-0000-0000-000000000002";+ let option = "00000000-0000-0000-0000-000000000001";+ let mut record = record();+ record.action = RecordedAction::Known(Action::PropertyChanged(PropertyChange {+ property: property.to_string(),+ from: None,+ to: Some(serde_json::json!({+ "type": "SelectOption",+ "value": [option],+ })),+ }));+ let reads = FakeReads::new(ActivityRange {+ records: vec![record],+ truncated: false,+ });++ let response = ReadActivity {+ from: time("2026-08-17T12:00:00Z"),+ to: time("2026-08-17T14:00:00Z"),+ }+ .call(+ ServiceContext(ActivityToolContext::new(reads).with_metadata_resolver(FakeMetadata)),+ RequestContext::new(user("macro|[email protected]")),+ )+ .await+ .unwrap();++ assert_eq!(+ response.activities[0].action,+ ToolActivityAction::PropertyChanged {+ property: property.to_string(),+ property_name: Some("Status".to_string()),+ property_type: Some("select_string".to_string()),+ from: None,+ from_labels: None,+ to: Some(serde_json::json!({+ "type": "SelectOption",+ "value": [option],+ })),+ to_labels: Some(vec!["Completed".to_string()]),+ }+ );+}diff --git a/crates/activity/src/lib.rs b/crates/activity/src/lib.rsindex 436cac306e..69731373b9 100644--- a/crates/activity/src/lib.rs+++ b/crates/activity/src/lib.rs@@ -20,7 +20,7 @@//! consumer); both on by default. The models are always available.pub mod domain;-#[cfg(feature = "consumer")]+#[cfg(any(feature = "ai_tools", feature = "consumer"))]pub mod inbound;#[cfg(feature = "outbound")]pub mod outbound;@@ -30,4 +30,9 @@ pub use domain::models::{CallStart, CommonAction, DomainActivity, EntityType, Ingest, ParticipantChange, PropertyChange,RecordedAction, VIEW_ACTION_TAGS, activity_id, event_time,};-pub use domain::ports::{ActivityFeedPage, ActivityReads, EntityActivityMap};+pub use domain::ports::{ActivityFeedPage, ActivityRange, ActivityReads, EntityActivityMap};+#[cfg(feature = "ai_tools")]+pub use domain::{+ ports::{ActivityMetadataResolver, ActivityPropertyMetadata},+ service::{ActivityReadService, NoopActivityMetadataResolver, ResolvedActivityRange},+};diff --git a/crates/activity/src/outbound/pg_activity_repo.rs b/crates/activity/src/outbound/pg_activity_repo.rsindex 048d482821..6f6da9ff68 100644--- a/crates/activity/src/outbound/pg_activity_repo.rs+++ b/crates/activity/src/outbound/pg_activity_repo.rs@@ -14,7 +14,7 @@ use uuid::Uuid;use crate::domain::{models::{ActionDecodeError, Activity, ActivityRecord, Actor, RecordedAction},- ports::{ActivityFeedPage, ActivityReads, ActivityRepo, EntityActivityMap},+ ports::{ActivityFeedPage, ActivityRange, ActivityReads, ActivityRepo, EntityActivityMap},};/// Writes activities to MacroDB.@@ -290,4 +290,41 @@ impl ActivityReads for PgActivityRepo {}Ok(by_entity)}++ async fn subject_activity_range(+ &self,+ subject_id: &str,+ from: DateTime<Utc>,+ to: DateTime<Utc>,+ limit: NonZeroU32,+ ) -> Result<ActivityRange, Self::Err> {+ let limit = limit.get();+ let fetch = i64::from(limit) + 1;+ let mut rows = sqlx::query_as!(+ StoredRow,+ r#"+ SELECT id, actor_id, action, action_payload,+ subject_id, entity_type, entity_id, occurred_at+ FROM activity_events+ WHERE subject_id = $1+ AND occurred_at >= $2+ AND occurred_at < $3+ ORDER BY occurred_at DESC, id DESC+ LIMIT $4+ "#,+ subject_id,+ from,+ to,+ fetch,+ )+ .fetch_all(&self.pool)+ .await?;++ let truncated = rows.len() > limit as usize;+ rows.truncate(limit as usize);+ Ok(ActivityRange {+ records: rows.into_iter().filter_map(StoredRow::decode).collect(),+ truncated,+ })+ }}diff --git a/crates/activity/src/outbound/pg_activity_repo/test.rs b/crates/activity/src/outbound/pg_activity_repo/test.rsindex 9bc8012ab1..2688d4e1a4 100644--- a/crates/activity/src/outbound/pg_activity_repo/test.rs+++ b/crates/activity/src/outbound/pg_activity_repo/test.rs@@ -209,6 +209,86 @@ async fn subject_feed_breaks_timestamp_ties_by_id(pool: PgPool) {assert_eq!(fetched_ids, expected_ids);}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn subject_activity_range_filters_half_open_interval_and_subject(pool: PgPool) {+ let repo = PgActivityRepo::new(pool.clone());+ let from = base_time();+ let to = from + chrono::Duration::seconds(3);+ repo.insert_activities(&[+ seed_at(+ 60,+ CommonAction::Edited,+ "before",+ from - chrono::Duration::seconds(1),+ ),+ seed_at(61, CommonAction::Created, "at-from", from),+ seed_at(+ 62,+ CommonAction::Opened,+ "inside",+ from + chrono::Duration::seconds(2),+ ),+ seed_at(63, CommonAction::Deleted, "at-to", to),+ Activity::common(+ Uuid::from_u128(64),+ 0,+ Actor::new_from_user(user("macro|[email protected]")),+ None,+ model_entity::EntityType::Document,+ "other-subject",+ CommonAction::Edited,+ from + chrono::Duration::seconds(1),+ ),+ ])+ .await+ .unwrap();++ let range = repo+ .subject_activity_range("macro|[email protected]", from, to, nz(10))+ .await+ .unwrap();++ let entity_ids: Vec<&str> = range+ .records+ .iter()+ .map(|record| record.entity_id.as_str())+ .collect();+ assert_eq!(entity_ids, vec!["inside", "at-from"]);+ assert!(!range.truncated);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn subject_activity_range_reports_truncation(pool: PgPool) {+ let repo = PgActivityRepo::new(pool.clone());+ let from = base_time();+ let activities: Vec<Activity> = (0..3u32)+ .map(|i| {+ seed_at(+ u128::from(70 + i),+ CommonAction::Edited,+ &format!("doc-{i}"),+ from + chrono::Duration::seconds(i64::from(i)),+ )+ })+ .collect();+ repo.insert_activities(&activities).await.unwrap();++ let range = repo+ .subject_activity_range(+ "macro|[email protected]",+ from,+ from + chrono::Duration::seconds(10),+ nz(2),+ )+ .await+ .unwrap();++ assert_eq!(range.records.len(), 2);+ assert_eq!(range.records[0].entity_id, "doc-2");+ assert_eq!(range.records[1].entity_id, "doc-1");+ assert!(range.truncated);+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn entity_activity_batches_with_a_per_entity_limit(pool: PgPool) {let repo = PgActivityRepo::new(pool.clone());diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.tomlindex 5b86a812b6..bd84b9cfb5 100644--- a/crates/ai_tools/Cargo.toml+++ b/crates/ai_tools/Cargo.toml@@ -8,13 +8,13 @@ version = "0.1.0"test-support = [][dependencies]+activity = { path = "../activity", default-features = false, features = ["ai_tools", "outbound"] }agent = { path = "../agent" }ai_usage = { path = "../ai_usage" }anthropic = { path = "../anthropic", features = ["toolset"] }attachment = { path = "../attachment" }non_empty = { path = "../non_empty" }ai_toolset = { path = "../ai_toolset" }-activity = { path = "../activity", default-features = false }anyhow.workspace = truebot_id = { path = "../bot_id" }async-trait.workspace = truediff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rsindex a0d180496e..5351a69d6d 100644--- a/crates/ai_tools/src/build_context.rs+++ b/crates/ai_tools/src/build_context.rs@@ -307,7 +307,7 @@ pub async fn build_tool_service_context_from_env();let properties_tool_context = crate::tool_context::build_properties_tool_context(- properties_service,+ properties_service.clone(),entity_access_service.clone(),);@@ -399,6 +399,11 @@ pub async fn build_tool_service_context_from_env(email_service_client: email_ext_client,soup_service,email_service: email_service_for_tools,+ activity_tool_context: crate::tool_context::build_activity_tool_context(+ pool.clone(),+ properties_service,+ entity_access_service.clone(),+ ),document_tool_context,properties_tool_context,email_tool_context,diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rsindex 234057c475..8f02dedc66 100644--- a/crates/ai_tools/src/lib.rs+++ b/crates/ai_tools/src/lib.rs@@ -1,5 +1,6 @@#![recursion_limit = "256"]+use activity::inbound::toolset::activity_toolset;use ai_toolset::AsyncToolCollection;use ai_toolset::schema::{FrontendSchemas, ToolSchemaGenerator, frontend_schemas_builder};@@ -49,18 +50,19 @@ pub use tool_context::no_op_schedule_context;pub use tool_context::{ChannelSideEffectClients, NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress,NoOpNotificationService, NoOpScheduleContext, NoOpSnsEndpointManager, NoOpTaskProperties,- RequestContext, TaskPropertiesAdapter, ToolCalendarMutationService, ToolCalendarReadService,- ToolCalendarToolContext, ToolCallRecordQueryService, ToolCallService, ToolCallToolContext,- ToolChannelEventDispatcher, ToolChannelMessagesService, ToolChannelToolContext,- ToolChatService, ToolChatToolContext, ToolCommsService, ToolCrmService, ToolCrmToolContext,- ToolDocumentService, ToolDocumentToolContext, ToolEmailService, ToolEmailToolContext,- ToolEntityAccessManagementService, ToolEntityAccessService, ToolEntityCreator,- ToolForeignEntityService, ToolFrecencyService, ToolImportService, ToolImportToolContext,- ToolMcpSelector, ToolNotificationQueue, ToolNotificationService, ToolNotificationToolContext,- ToolPipedreamConnection, ToolProjectService, ToolProjectToolContext, ToolPropertiesService,- ToolPropertiesToolContext, ToolRemindersService, ToolRemindersToolContext, ToolServiceContext,- ToolSkillService, ToolSkillToolContext, ToolSoupService, ToolSystemPropertiesService,- ToolTeamService, ToolTeamToolContext, ToolUserEmailService, build_calendar_tool_context,+ RequestContext, TaskPropertiesAdapter, ToolActivityToolContext, ToolCalendarMutationService,+ ToolCalendarReadService, ToolCalendarToolContext, ToolCallRecordQueryService, ToolCallService,+ ToolCallToolContext, ToolChannelEventDispatcher, ToolChannelMessagesService,+ ToolChannelToolContext, ToolChatService, ToolChatToolContext, ToolCommsService, ToolCrmService,+ ToolCrmToolContext, ToolDocumentService, ToolDocumentToolContext, ToolEmailService,+ ToolEmailToolContext, ToolEntityAccessManagementService, ToolEntityAccessService,+ ToolEntityCreator, ToolForeignEntityService, ToolFrecencyService, ToolImportService,+ ToolImportToolContext, ToolMcpSelector, ToolNotificationQueue, ToolNotificationService,+ ToolNotificationToolContext, ToolPipedreamConnection, ToolProjectService,+ ToolProjectToolContext, ToolPropertiesService, ToolPropertiesToolContext, ToolRemindersService,+ ToolRemindersToolContext, ToolServiceContext, ToolSkillService, ToolSkillToolContext,+ ToolSoupService, ToolSystemPropertiesService, ToolTeamService, ToolTeamToolContext,+ ToolUserEmailService, build_activity_tool_context, build_calendar_tool_context,build_channel_tool_context_with_dispatcher, build_channel_tool_context_with_side_effects,build_channel_tool_context_without_side_effects, build_crm_tool_context,build_project_tool_context, build_properties_service, build_properties_tool_context,@@ -90,6 +92,7 @@ pub(crate) fn subagent_toolset() -> AiToolSet {.add_toolset(search_toolset()).add_tool::<SelfKnowledge, ToolServiceContext>().add_tool::<ListEntities, SoupToolContext<ToolSoupService, ToolEmailService>>()+ .add_subtoolset::<ToolActivityToolContext>(activity_toolset()).add_subtoolset::<ToolDocumentToolContext>(document_toolset()).add_subtoolset::<ToolProjectToolContext>(project_toolset()).add_subtoolset::<ToolPropertiesToolContext>(properties_toolset())diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex c4ed1f5bee..a9da48bcd9 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -52,6 +52,9 @@ use system_properties::{use teams::{inbound::toolset::TeamToolContext, outbound::team_repo::TeamRepositoryImpl};use tokio_util::task::TaskTracker;+mod activity_metadata;++use activity_metadata::ToolActivityMetadataResolver;pub use ai_toolset::RequestContext;/// Type alias for the frecency service implementation@@ -1184,6 +1187,24 @@ pub type ToolImportService = import::domain::service::ImportServiceImpl</// with a wired one after constructing the import service.pub type ToolImportToolContext = import::inbound::toolset::ImportToolContext<ToolImportService>;+pub type ToolActivityToolContext = activity::inbound::toolset::ActivityToolContext<+ activity::outbound::pg_activity_repo::PgActivityRepo,+>;++pub fn build_activity_tool_context(+ pool: sqlx::PgPool,+ properties: Arc<ToolPropertiesService>,+ entity_access_service: Arc<ToolEntityAccessService>,+) -> ToolActivityToolContext {+ activity::inbound::toolset::ActivityToolContext::new(+ activity::outbound::pg_activity_repo::PgActivityRepo::new(pool),+ )+ .with_metadata_resolver(ToolActivityMetadataResolver::new(+ properties,+ entity_access_service,+ ))+}+#[derive(Clone, Default)]pub struct NoOpScheduleContext;@@ -1200,6 +1221,7 @@ pub struct ToolServiceContext {pub email_service_client: Arc<email_service_client::EmailServiceClientExternal>,pub soup_service: Arc<ToolSoupService>,pub email_service: Arc<ToolEmailService>,+ pub activity_tool_context: ToolActivityToolContext,pub document_tool_context: ToolDocumentToolContext,pub properties_tool_context: ToolPropertiesToolContext,pub email_tool_context: ToolEmailToolContext,diff --git a/crates/ai_tools/src/tool_context/activity_metadata.rs b/crates/ai_tools/src/tool_context/activity_metadata.rsnew file mode 100644index 0000000000..6ce9f0b015--- /dev/null+++ b/crates/ai_tools/src/tool_context/activity_metadata.rs@@ -0,0 +1,130 @@+use std::sync::Arc;++use entity_access::domain::ports::EntityAccessService as _;+use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;+use models_properties::DataType;+use models_properties::service::property_option::PropertyOptionValue;++use super::{ToolEntityAccessService, ToolPropertiesService};++#[derive(Clone)]+pub struct ToolActivityMetadataResolver {+ properties: Arc<ToolPropertiesService>,+ entity_access_service: Arc<ToolEntityAccessService>,+}++impl ToolActivityMetadataResolver {+ pub(super) fn new(+ properties: Arc<ToolPropertiesService>,+ entity_access_service: Arc<ToolEntityAccessService>,+ ) -> Self {+ Self {+ properties,+ entity_access_service,+ }+ }+}++#[async_trait::async_trait]+impl activity::ActivityMetadataResolver for ToolActivityMetadataResolver {+ async fn resolve_properties(+ &self,+ viewer: &MacroUserIdStr<'_>,+ property_ids: &[String],+ ) -> std::collections::HashMap<String, activity::ActivityPropertyMetadata> {+ use entity_access::domain::models::{+ Entity, EntityAccessReceipt, EntityPermission, EntityType,+ };+ use properties::domain::service::PropertiesService as _;++ if property_ids.is_empty() {+ return std::collections::HashMap::new();+ }++ let team = match self.entity_access_service.get_user_team(viewer).await {+ Ok(Some(team_info)) => {+ let viewer = viewer.copied().into_owned();+ match EntityAccessReceipt::try_new_authenticated_user(+ viewer,+ Entity {+ entity_id: team_info.team_id.to_string(),+ entity_type: EntityType::Team,+ },+ EntityPermission::TeamRole {+ role: team_info.role,+ },+ ) {+ Ok(receipt) => Some(receipt),+ Err(error) => {+ tracing::warn!(error=?error, "failed to mint activity metadata team receipt");+ return std::collections::HashMap::new();+ }+ }+ }+ Ok(None) => None,+ Err(error) => {+ tracing::warn!(error=?error, "failed to resolve activity metadata team");+ return std::collections::HashMap::new();+ }+ };++ let definitions = match self+ .properties+ .list_property_definitions_with_options(team.as_ref(), Some(viewer), true, None)+ .await+ {+ Ok(definitions) => definitions,+ Err(error) => {+ tracing::warn!(error=?error, "failed to resolve activity property metadata");+ return std::collections::HashMap::new();+ }+ };+ let requested: std::collections::HashSet<&str> =+ property_ids.iter().map(String::as_str).collect();++ definitions+ .into_iter()+ .filter_map(|definition| {+ let id = definition.definition.id.to_string();+ if !requested.contains(id.as_str()) {+ return None;+ }+ let data_type = property_data_type_name(definition.definition.data_type);+ let option_labels = definition+ .property_options+ .into_iter()+ .map(|option| {+ let label = match option.value {+ PropertyOptionValue::String(value) => value,+ PropertyOptionValue::Number(value) => value.to_string(),+ };+ (option.id.to_string(), label)+ })+ .collect();+ Some((+ id,+ activity::ActivityPropertyMetadata {+ display_name: definition.definition.display_name,+ data_type: data_type.to_string(),+ option_labels,+ },+ ))+ })+ .collect()+ }+}++fn property_data_type_name(data_type: DataType) -> &'static str {+ match data_type {+ DataType::Boolean => "boolean",+ DataType::Date => "date",+ DataType::Number => "number",+ DataType::String => "string",+ DataType::SelectNumber => "select_number",+ DataType::SelectString => "select_string",+ DataType::Tag => "tag",+ DataType::Entity => "entity",+ DataType::Link => "link",+ }+}diff --git a/crates/memory/src/context.rs b/crates/memory/src/context.rsindex 28ad51d369..1f4c7a1542 100644--- a/crates/memory/src/context.rs+++ b/crates/memory/src/context.rs@@ -164,7 +164,10 @@ pub async fn build_tool_service_context();// Properties tool context- let properties_tool_context = ai_tools::build_properties_tool_context(properties_service, entity_access_service.clone());+ let properties_tool_context = ai_tools::build_properties_tool_context(+ properties_service.clone(),+ entity_access_service.clone(),+ );// Email tool contextlet email_tool_context = email::inbound::toolset::EmailToolContext::new(@@ -233,6 +236,11 @@ pub async fn build_tool_service_context(email_service_client: email_ext_client,soup_service,email_service: email_service_for_tools,+ activity_tool_context: ai_tools::build_activity_tool_context(+ pool.clone(),+ properties_service,+ entity_access_service.clone(),+ ),document_tool_context,properties_tool_context,email_tool_context,diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rsindex fd6bb7b273..0110b90f39 100644--- a/services/document_cognition_service/src/api/context/test.rs+++ b/services/document_cognition_service/src/api/context/test.rs@@ -358,6 +358,11 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Aremail_service_client: email_service_client_external.clone(),soup_service: soup_service.clone(),email_service: email_service_for_tools.clone(),+ activity_tool_context: ai_tools::build_activity_tool_context(+ pool.clone(),+ properties_service.clone(),+ entity_access_service.clone(),+ ),document_tool_context: document_tool_context.clone(),properties_tool_context: properties_tool_context.clone(),email_tool_context: email_tool_context.clone(),diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rsindex 814ecfc060..06196e1ca1 100644--- a/services/document_cognition_service/src/main.rs+++ b/services/document_cognition_service/src/main.rs@@ -371,8 +371,10 @@ async fn main() -> anyhow::Result<()> {let search_service_client = Arc::new(search_service_client);- let properties_tool_context =- ai_tools::build_properties_tool_context(properties_service, entity_access_service.clone());+ let properties_tool_context = ai_tools::build_properties_tool_context(+ properties_service.clone(),+ entity_access_service.clone(),+ );tracing::info!("initialized properties tool context");@@ -566,6 +568,11 @@ async fn main() -> anyhow::Result<()> {email_service_client: email_service_client_external.clone(),soup_service: soup_service.clone(),email_service: email_service_for_tools.clone(),+ activity_tool_context: ai_tools::build_activity_tool_context(+ db.clone(),+ properties_service,+ entity_access_service.clone(),+ ),document_tool_context: document_tool_context.clone(),properties_tool_context: properties_tool_context.clone(),email_tool_context: email_tool_context.clone(),diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rsindex 7de0ccd084..64d7fa8a13 100644--- a/services/mcp_service/src/context.rs+++ b/services/mcp_service/src/context.rs@@ -273,8 +273,10 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<Toconfig.document_permission_jwt.to_string(),);- let properties_tool_context =- ai_tools::build_properties_tool_context(properties_service, entity_access_service.clone());+ let properties_tool_context = ai_tools::build_properties_tool_context(+ properties_service.clone(),+ entity_access_service.clone(),+ );let user_email_service = Arc::new(EmailServiceImpl::new(@@ -372,6 +374,11 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<Tosearch_service_client: search_service_client.clone(),soup_service,email_service: email_service_for_tools,+ activity_tool_context: ai_tools::build_activity_tool_context(+ db.clone(),+ properties_service,+ entity_access_service.clone(),+ ),document_tool_context,properties_tool_context,email_tool_context,