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(tasks): start agent sessions from task assignments (#7132)

Eric Hayes152f36428349
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index eec4751075..75e020fa75 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -306,6 +306,7 @@
"crates/cursor_api_key",
"crates/cursor_cloud_agents",
"crates/database_env_vars",
+ "crates/document_storage_service_client",
"crates/document_sub_type",
"crates/documents",
"crates/email",
@@ -432,6 +433,7 @@
"crates/cursor_api_key",
"crates/cursor_cloud_agents",
"crates/database_env_vars",
+ "crates/document_storage_service_client",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -839,6 +841,7 @@
"crates/contacts",
"crates/cowlike",
"crates/database_env_vars",
+ "crates/document_storage_service_client",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -920,6 +923,7 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/document_storage_service_client",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -2603,6 +2607,7 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/document_storage_service_client",
"crates/document_sub_type",
"crates/documents",
"crates/email",
@@ -3787,6 +3792,7 @@
"crates/crm",
"crates/database_env_vars",
"crates/dictation",
+ "crates/document_storage_service_client",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -10993,6 +10999,7 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/document_storage_service_client",
"crates/document_sub_type",
"crates/documents",
"crates/email",
diff --git a/Cargo.lock b/Cargo.lock
index 2f7d00fff1..c8cd901ed6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -420,6 +420,7 @@ dependencies = [
"cursor_api_key",
"cursor_cloud_agents",
"database_env_vars",
+ "document_storage_service_client",
"doppler-config",
"entity_access",
"entity_registry",
@@ -655,6 +656,8 @@ dependencies = [
"channel_sender",
"channels",
"chrono",
+ "document_storage_service_client",
+ "document_sub_type",
"entity_access",
"lexical_client",
"macro_event_broker",
@@ -665,11 +668,15 @@ dependencies = [
"mime",
"mockall",
"model_owner",
+ "models_properties",
+ "properties",
"serde",
"serde_json",
+ "sha2 0.10.9",
"sqlx",
"static_file",
"strum 0.27.2",
+ "system_properties",
"thiserror 2.0.18",
"tokio",
"tracing",
@@ -686,8 +693,10 @@ dependencies = [
"anyhow",
"bots",
"channels",
+ "connection_gateway_client",
"crm",
"database_env_vars",
+ "document_storage_service_client",
"entity_access",
"entity_registry",
"entity_registry_db_utils",
@@ -701,6 +710,7 @@ dependencies = [
"macro_service_urls",
"messages",
"rdkafka",
+ "rootcause",
"serde_json",
"sqlx",
"static_file",
diff --git a/apps/docs/AI/mcp/tools/set-entity-property.mdx b/apps/docs/AI/mcp/tools/set-entity-property.mdx
index 96d70ed8bb..edf000c5d7 100644
--- a/apps/docs/AI/mcp/tools/set-entity-property.mdx
+++ b/apps/docs/AI/mcp/tools/set-entity-property.mdx
@@ -1,6 +1,6 @@
---
title: SetEntityProperty
-description: "Set or update a property value on an entity. Tasks are targeted as entity_type='document'. Projects in the Tasks UI are entity_type='initiative'; entity_type='project' still means a folder. Initiatives share the Assignees, Status, Priority and Due Date definitions below and their clearing behavior. Project Status accepts only Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), and Completed (...0004); In Review and Canceled are task-only options. Provide the property_definition_id and exactly one value field matching the property's data type. For multi-select properties — including tags — prefer add_option_ids / remove_option_ids over option_ids: they add or remove just those options atomically, composing with concurrent edits. option_ids replaces the entire value, so a stale read can silently drop options someone else just added; only use it when the user asks to set the value to exactly a given list. To apply a tag, pass the tag set's property_definition_id and the tag's option id (both from ListTags) in add_option_ids; to remove a tag, use remove_option_ids. Tasks always have these system properties (use these property_definition_id values directly): - Assignees (00000001-0000-0000-0000-000000000001): entity type, multi-select. Use entity_refs with entity_type='user' and entity_id='macro|[email protected]'. - Status (00000001-0000-0000-0000-000000000002): select_string, single. Options: Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), In Review (...0003), Completed (...0004), Canceled (...0005). - Priority (00000001-0000-0000-0000-000000000003): select_string, single. Options: Low (...0001), Medium (...0002), High (...0003), Urgent (...0004). Option IDs: 00000001-0000-0000-0003-0000000000XX. - Due Date (00000001-0000-0000-0000-000000000004): date, single. Use date_value with ISO 8601. - Parent Task (00000001-0000-0000-0000-000000000005): entity, single. Use entity_ref with entity_type='task'. - Subtasks (00000001-0000-0000-0000-000000000006): entity, multi. Use entity_refs with entity_type='task'. - Story Points (00000001-0000-0000-0000-000000000009): number, single. Use number_value. CRM companies (entity_type='company', entity_id=the company UUID) always have these system properties: - Stage (00000001-0000-0000-0000-000000000010): select_string, single. Use option_id. Default options: Lead (00000001-0000-0000-0010-000000000001), Qualified (...0002), Demo (...0003), Trial (...0004), Negotiation (...0005), Customer (...0006), Churned (...0007). Teams can customize their stages, so prefer calling GetCompany or GetEntityProperties first to get the valid stage option ids. - Owner (00000001-0000-0000-0000-000000000011): entity, single. Use entity_ref with entity_type='user' and entity_id='macro|[email protected]'. - Revenue (00000001-0000-0000-0000-000000000012): number, single. Use number_value (dollars). Any member of the owning team can edit visible company properties; hidden records remain admin/owner-only. For non-system or custom properties, call GetEntityProperties first to discover property_definition_id values and options."
+description: "Set or update a property value on an entity. Tasks are targeted as entity_type='document'. Projects in the Tasks UI are entity_type='initiative'; entity_type='project' still means a folder. Initiatives share the Assignees, Status, Priority and Due Date definitions below and their clearing behavior. Project Status accepts only Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), and Completed (...0004); In Review and Canceled are task-only options. Provide the property_definition_id and exactly one value field matching the property's data type. For multi-select properties — including tags — prefer add_option_ids / remove_option_ids over option_ids: they add or remove just those options atomically, composing with concurrent edits. option_ids replaces the entire value, so a stale read can silently drop options someone else just added; only use it when the user asks to set the value to exactly a given list. To apply a tag, pass the tag set's property_definition_id and the tag's option id (both from ListTags) in add_option_ids; to remove a tag, use remove_option_ids. Tasks always have these system properties (use these property_definition_id values directly): - Assignees (00000001-0000-0000-0000-000000000001): entity type, multi-select. Use entity_refs with entity_type='user' and entity_id='macro|[email protected]' for people or 'bot|<agent UUID>' for agents. Adding an agent starts its session and replies in the task discussion. - Status (00000001-0000-0000-0000-000000000002): select_string, single. Options: Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), In Review (...0003), Completed (...0004), Canceled (...0005). - Priority (00000001-0000-0000-0000-000000000003): select_string, single. Options: Low (...0001), Medium (...0002), High (...0003), Urgent (...0004). Option IDs: 00000001-0000-0000-0003-0000000000XX. - Due Date (00000001-0000-0000-0000-000000000004): date, single. Use date_value with ISO 8601. - Parent Task (00000001-0000-0000-0000-000000000005): entity, single. Use entity_ref with entity_type='task'. - Subtasks (00000001-0000-0000-0000-000000000006): entity, multi. Use entity_refs with entity_type='task'. - Story Points (00000001-0000-0000-0000-000000000009): number, single. Use number_value. CRM companies (entity_type='company', entity_id=the company UUID) always have these system properties: - Stage (00000001-0000-0000-0000-000000000010): select_string, single. Use option_id. Default options: Lead (00000001-0000-0000-0010-000000000001), Qualified (...0002), Demo (...0003), Trial (...0004), Negotiation (...0005), Customer (...0006), Churned (...0007). Teams can customize their stages, so prefer calling GetCompany or GetEntityProperties first to get the valid stage option ids. - Owner (00000001-0000-0000-0000-000000000011): entity, single. Use entity_ref with entity_type='user' and entity_id='macro|[email protected]'. - Revenue (00000001-0000-0000-0000-000000000012): number, single. Use number_value (dollars). Any member of the owning team can edit visible company properties; hidden records remain admin/owner-only. For non-system or custom properties, call GetEntityProperties first to discover property_definition_id values and options."
---
# SetEntityProperty
@@ -10,7 +10,7 @@ Set or update a property value on an entity. Tasks are targeted as entity_type='
For multi-select properties — including tags — prefer add_option_ids / remove_option_ids over option_ids: they add or remove just those options atomically, composing with concurrent edits. option_ids replaces the entire value, so a stale read can silently drop options someone else just added; only use it when the user asks to set the value to exactly a given list. To apply a tag, pass the tag set's property_definition_id and the tag's option id (both from ListTags) in add_option_ids; to remove a tag, use remove_option_ids.
Tasks always have these system properties (use these property_definition_id values directly):
-- Assignees (00000001-0000-0000-0000-000000000001): entity type, multi-select. Use entity_refs with entity_type='user' and entity_id='macro|[email protected]'.
+- Assignees (00000001-0000-0000-0000-000000000001): entity type, multi-select. Use entity_refs with entity_type='user' and entity_id='macro|[email protected]' for people or 'bot|<agent UUID>' for agents. Adding an agent starts its session and replies in the task discussion.
- Status (00000001-0000-0000-0000-000000000002): select_string, single. Options: Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), In Review (...0003), Completed (...0004), Canceled (...0005).
- Priority (00000001-0000-0000-0000-000000000003): select_string, single. Options: Low (...0001), Medium (...0002), High (...0003), Urgent (...0004). Option IDs: 00000001-0000-0000-0003-0000000000XX.
- Due Date (00000001-0000-0000-0000-000000000004): date, single. Use date_value with ISO 8601.
diff --git a/apps/web/src/features/property/editors/popover/EntityEditor.test.tsx b/apps/web/src/features/property/editors/popover/EntityEditor.test.tsx
new file mode 100644
index 0000000000..1b2971a3ca
--- /dev/null
+++ b/apps/web/src/features/property/editors/popover/EntityEditor.test.tsx
@@ -0,0 +1,189 @@
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { createSignal, type ParentProps } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { SYSTEM_PROPERTY_IDS } from '../../constants';
+import {
+ PropertyRootContext,
+ type PropertyRootContextValue,
+} from '../../core/context';
+import type { EntityProperty } from '../../types';
+import { EntityEditor } from './EntityEditor';
+
+const agentId = 'bot|00000000-0000-0000-0000-000000000123';
+const userId = 'macro|[email protected]';
+
+vi.mock('@core/context/user', () => ({
+ useEmail: () => () => '[email protected]',
+ useUserId: () => () => 'macro|[email protected]',
+}));
+vi.mock('@core/user', () => ({
+ emailToId: (email: string) => `macro|${email}`,
+ useAugmentUserWithDmActivity: () => (user: unknown) => user,
+}));
+vi.mock('@core/user/util', () => ({
+ idToEmail: (id: string) => id,
+ idToDisplayName: (id: string) => id,
+}));
+vi.mock('@core/component/UserIcon', () => ({ UserIcon: () => <span /> }));
+vi.mock('@core/context/quickAccess', () => ({
+ useQuickAccess: () => ({
+ isLoading: () => false,
+ useList: () => ({
+ items: () => [
+ {
+ kind: 'user',
+ id: 'macro|[email protected]',
+ data: {
+ id: 'macro|[email protected]',
+ name: 'Alice',
+ email: '[email protected]',
+ },
+ },
+ ],
+ }),
+ }),
+}));
+vi.mock('@entity', () => ({
+ Entity: {},
+ isTaskEntity: () => false,
+ createEmailsInfiniteQuery: () => ({
+ data: [],
+ isLoading: false,
+ isPending: false,
+ }),
+}));
+vi.mock('@queries/soup/search', () => ({
+ useSearchSoupQuery: () => ({ status: 'pending', isFetching: false }),
+}));
+vi.mock('@queries/team/teams', () => ({
+ useCurrentTeamQuery: () => ({ data: null }),
+}));
+vi.mock('../../queries/agent-assignees', () => ({
+ useAgentAssignees: (enabled: () => boolean) => () =>
+ enabled()
+ ? [
+ {
+ id: 'bot|00000000-0000-0000-0000-000000000123',
+ name: 'Research assistant',
+ email: '@research',
+ },
+ ]
+ : [],
+}));
+vi.mock('../../utils', async () => ({
+ ...(await import('../../utils/typeGuards')),
+ useSearchInputFocus: () => undefined,
+}));
+vi.mock('../selectors/OptionCheckBox', () => ({
+ OptionCheckBox: (props: { checked: boolean }) => (
+ <input type="checkbox" checked={props.checked} readOnly />
+ ),
+}));
+vi.mock('./EditorPopover', () => ({
+ EditorPopover: (props: ParentProps<{ onClose: () => void }>) => (
+ <div role="dialog">
+ {props.children}
+ <button onClick={props.onClose}>Dismiss</button>
+ </div>
+ ),
+}));
+
+const property: EntityProperty = {
+ propertyId: 'assignees-property',
+ propertyDefinitionId: SYSTEM_PROPERTY_IDS.ASSIGNEES,
+ displayName: 'Assignees',
+ isMultiSelect: true,
+ specificEntityType: 'USER',
+ owner: { scope: 'system' },
+ createdAt: new Date(0),
+ updatedAt: new Date(0),
+ valueType: 'ENTITY',
+ value: [{ entity_id: userId, entity_type: 'USER' }],
+};
+
+function setup(existingTask: boolean, value = property) {
+ const onSave = vi.fn(async () => undefined);
+ const [editorOpen, setEditorOpen] = createSignal(true);
+ const context: PropertyRootContextValue = {
+ property: () => value,
+ canEdit: () => true,
+ editorOpen,
+ openEditor: () => setEditorOpen(true),
+ closeEditor: () => setEditorOpen(false),
+ onSave,
+ };
+ render(() => (
+ <PropertyRootContext.Provider value={context}>
+ <EntityEditor
+ selfFilter={
+ existingTask ? { entityType: 'TASK', blockId: 'task-id' } : undefined
+ }
+ />
+ </PropertyRootContext.Provider>
+ ));
+ return onSave;
+}
+
+afterEach(cleanup);
+
+describe('assigning an agent through task properties', () => {
+ it.each([false, true])(
+ 'saves the bot principal alongside the human assignee (existing task: %s)',
+ async (existingTask) => {
+ const onSave = setup(existingTask);
+ expect(screen.getByText('Alice')).toBeTruthy();
+ expect(screen.getByText('Agent')).toBeTruthy();
+ fireEvent.input(screen.getByPlaceholderText('Add assignees...'), {
+ target: { value: 'research' },
+ });
+ await waitFor(() => expect(screen.queryByText('Alice')).toBeNull());
+ fireEvent.click(screen.getByText('Research assistant'));
+ expect(onSave).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByText('Dismiss'));
+ await waitFor(() =>
+ expect(onSave).toHaveBeenCalledExactlyOnceWith(property, {
+ valueType: 'ENTITY',
+ refs: [
+ { entity_id: userId, entity_type: 'USER' },
+ { entity_id: agentId, entity_type: 'USER' },
+ ],
+ })
+ );
+ }
+ );
+
+ it('does not resave an unchanged assignment and can remove the agent', async () => {
+ const assigned: EntityProperty = {
+ ...property,
+ value: [{ entity_id: agentId, entity_type: 'USER' }],
+ };
+ const unchanged = setup(true, assigned);
+ fireEvent.click(screen.getByText('Dismiss'));
+ expect(unchanged).not.toHaveBeenCalled();
+ cleanup();
+ const onSave = setup(true, assigned);
+ fireEvent.click(screen.getByText('Research assistant'));
+ fireEvent.click(screen.getByText('Dismiss'));
+ await waitFor(() =>
+ expect(onSave).toHaveBeenCalledExactlyOnceWith(assigned, {
+ valueType: 'ENTITY',
+ refs: null,
+ })
+ );
+ });
+
+ it('keeps agents out of unrelated people properties', () => {
+ setup(false, {
+ ...property,
+ propertyDefinitionId: 'custom-people-property',
+ });
+ expect(screen.getByText('Alice')).toBeTruthy();
+ expect(screen.queryByText('Research assistant')).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/property/editors/popover/EntityEditor.tsx b/apps/web/src/features/property/editors/popover/EntityEditor.tsx
index 78947d7bd1..a3687fea22 100644
--- a/apps/web/src/features/property/editors/popover/EntityEditor.tsx
+++ b/apps/web/src/features/property/editors/popover/EntityEditor.tsx
@@ -10,6 +10,7 @@ import type { EntityReference } from '@service-properties/generated/schemas/enti
import type { EntityType } from '@service-properties/generated/schemas/entityType';
import { createSignal, Show, Suspense } from 'solid-js';
import { useProperty } from '../../core/context';
+import { useAgentAssignees } from '../../queries/agent-assignees';
import type { EntityProperty, PropertyApiValues } from '../../types';
import { isEntityProperty } from '../../utils';
import { PropertyEntitySelector } from '../selectors/PropertyEntitySelector';
@@ -45,6 +46,9 @@ function EntityEditorBody(props: EntityEditorProps) {
// team roster instead of the default quick-access people pool.
const isCompanyOwner =
property.propertyDefinitionId === SYSTEM_PROPERTY_IDS.COMPANY_OWNER;
+ const agents = useAgentAssignees(
+ () => property.propertyDefinitionId === SYSTEM_PROPERTY_IDS.ASSIGNEES
+ );
const teamQuery = useCurrentTeamQuery();
const teamMembers = (): IUser[] =>
(teamQuery.data?.members ?? []).map((member) => ({
@@ -100,6 +104,7 @@ function EntityEditorBody(props: EntityEditorProps) {
specificEntityType: property.specificEntityType,
selfFilter: props.selfFilter,
users: isCompanyOwner ? teamMembers : undefined,
+ additionalUsers: agents,
}}
selectedOptions={() => entityReferencesToIdSet(selectedRefs())}
setSelectedOptions={(newOptions, entityInfo) => {
diff --git a/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx b/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx
index 1e769546eb..36b065ae0a 100644
--- a/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx
+++ b/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx
@@ -1,4 +1,5 @@
import { UserIcon } from '@core/component/UserIcon';
+import { isBotPrincipalId } from '@core/constant/macroAgent';
import { useEmail, useUserId } from '@core/context/user';
import { emailToId, useAugmentUserWithDmActivity } from '@core/user';
import { createFreshSearch } from '@core/util/freshSort';
@@ -221,9 +222,15 @@ export function PropertyEntitySelector(props: EntityInputProps) {
// Convert quickAccess items to CombinedEntity
const items = quickAccessItems();
- const converted: CombinedEntity[] = [];
+ const additionalUsers =
+ specificEntityType === 'USER'
+ ? (props.config.additionalUsers?.() ?? [])
+ : [];
+ const converted: CombinedEntity[] = additionalUsers.map(userToEntity);
+ const additionalIds = new Set(additionalUsers.map((user) => user.id));
for (const item of items) {
+ if (additionalIds.has(item.id)) continue;
// Augment users with DM activity
if (item.kind === 'user') {
const augmentedUser = augmentUserWithDmActivity(item.data);
@@ -562,6 +569,11 @@ export function PropertyEntitySelector(props: EntityInputProps) {
size="sm"
isDeleted={false}
suppressClick={true}
+ photoUrl={
+ entity.kind === 'user'
+ ? entity.data.photoUrl
+ : undefined
+ }
/>
}
>
@@ -594,6 +606,11 @@ export function PropertyEntitySelector(props: EntityInputProps) {
/>
</Show>
</span>
+ <Show when={isBotPrincipalId(entity.id)}>
+ <span class="shrink-0 text-xs text-ink-muted">
+ Agent
+ </span>
+ </Show>
</div>
<Show
when={!props.config.isMultiSelect && isSelected()}
diff --git a/apps/web/src/features/property/editors/selectors/types.ts b/apps/web/src/features/property/editors/selectors/types.ts
index f3d6673cc1..9ea24fa0eb 100644
--- a/apps/web/src/features/property/editors/selectors/types.ts
+++ b/apps/web/src/features/property/editors/selectors/types.ts
@@ -21,6 +21,8 @@ export type EntitySelectorConfig = {
/** Explicit pool for USER pickers (e.g. company owner → team members);
* replaces the default quick-access people list. */
users?: Accessor<IUser[]>;
+ /** Additional principals offered alongside the default people pool. */
+ additionalUsers?: Accessor<IUser[]>;
/** When the query is a valid email that is not already in the pool,
* offer it as an "Add {email}" row (calendar guests, share sheets). */
allowCustomEmail?: boolean;
diff --git a/apps/web/src/features/property/extractors/PropertyText.tsx b/apps/web/src/features/property/extractors/PropertyText.tsx
index b9c0512a04..eb4f77b00f 100644
--- a/apps/web/src/features/property/extractors/PropertyText.tsx
+++ b/apps/web/src/features/property/extractors/PropertyText.tsx
@@ -1,6 +1,7 @@
-import { getDisplayNameParts, tryMacroId } from '@core/user';
+import { isBotPrincipalId } from '@core/constant/macroAgent';
import { cn } from '@ui';
import { type JSX, Show } from 'solid-js';
+import { usePropertyUserDisplay } from '../hooks/usePropertyUserDisplay';
import type { Property } from '../types';
import {
formatBoolean,
@@ -97,12 +98,7 @@ function UserPropertyText(props: {
fallback?: JSX.Element;
class?: string;
}) {
- const text = () => {
- const parts = getDisplayNameParts(tryMacroId(props.id), {
- emailFallback: 'local-part',
- });
- return parts.firstName || parts.fullName;
- };
+ const { shortName: text } = usePropertyUserDisplay(() => props.id);
return (
<Show when={text()} fallback={props.fallback ?? null}>
@@ -131,6 +127,9 @@ function extractText(property: Property): string {
const entities = getEntityValues(property);
if (entities.length === 0) return '';
if (property.specificEntityType === 'USER') {
+ if (entities.some((entity) => isBotPrincipalId(entity.entity_id))) {
+ return `${entities.length} assignees`;
+ }
return entities.length === 2 ? '2 people' : `${entities.length} people`;
}
return entities.length === 1 ? '1 item' : `${entities.length} items`;
diff --git a/apps/web/src/features/property/hooks/usePropertyEntityDisplay.test.tsx b/apps/web/src/features/property/hooks/usePropertyEntityDisplay.test.tsx
index cffa01af05..d503c00f7f 100644
--- a/apps/web/src/features/property/hooks/usePropertyEntityDisplay.test.tsx
+++ b/apps/web/src/features/property/hooks/usePropertyEntityDisplay.test.tsx
@@ -51,8 +51,12 @@ vi.mock('@core/context/channels', () => ({
}));
vi.mock('@core/user', () => ({
getDisplayName: () => '',
+ getDisplayNameParts: () => ({ fullName: '', firstName: '' }),
tryMacroId: () => undefined,
}));
+vi.mock('@queries/bots/profiles', () => ({
+ useBotProfile: () => ({ isPending: true }),
+}));
vi.mock('@queries/preview', () => ({
useItemPreview: () => {
fixture.previewMounts++;
diff --git a/apps/web/src/features/property/hooks/usePropertyEntityDisplay.tsx b/apps/web/src/features/property/hooks/usePropertyEntityDisplay.tsx
index af6b7d6c1b..c84b074cb2 100644
--- a/apps/web/src/features/property/hooks/usePropertyEntityDisplay.tsx
+++ b/apps/web/src/features/property/hooks/usePropertyEntityDisplay.tsx
@@ -6,7 +6,6 @@ import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { enableProjects } from '@core/constant/featureFlags';
import { useChannelName } from '@core/context/channels';
import { useUserId } from '@core/context/user';
-import { getDisplayName, tryMacroId } from '@core/user';
import ProjectIcon from '@phosphor/stack.svg';
import { isAccessiblePreviewItem, useItemPreview } from '@queries/preview';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
@@ -14,6 +13,7 @@ import { type Accessor, createMemo, type JSX, untrack } from 'solid-js';
import { match } from 'ts-pattern';
import { useProjectIdentityQuery } from '../../projects/queries/project-identity';
import { entityTypeToItemType } from '../utils';
+import { usePropertyUserDisplay } from './usePropertyUserDisplay';
const PREVIEWABLE_ENTITY_TYPES: EntityType[] = [
'DOCUMENT',
@@ -109,13 +109,9 @@ export function usePropertyEntityDisplay(
});
const channelName = () => channelNameSource()?.();
- const userNameWrapper = () => {
- const eType = entityType();
- if (eType === 'USER') {
- return () => getDisplayName(tryMacroId(entityId()));
- }
- };
- const userName = createMemo(() => userNameWrapper()?.() ?? '');
+ const user = usePropertyUserDisplay(() =>
+ entityType() === 'USER' ? entityId() : ''
+ );
const isLoading = createMemo(() => {
if (entityType() === 'INITIATIVE')
@@ -133,7 +129,7 @@ export function usePropertyEntityDisplay(
if (source.isPending) return 'Loading...';
return (!source.isError && source.data?.name) || 'Project unavailable';
})
- .with('USER', () => userName())
+ .with('USER', () => user.name())
.with('CHANNEL', () => channelName() || 'Channel')
.with('COMPANY', () => entityId())
.otherwise(() => {
@@ -152,7 +148,9 @@ export function usePropertyEntityDisplay(
(type) => type === 'INITIATIVE' && projectSource(),
() => <ProjectIcon class="size-4" />
)
- .with('USER', () => <UserIcon id={entityId()} size="sm" />)
+ .with('USER', () => (
+ <UserIcon id={entityId()} size="sm" photoUrl={user.photoUrl()} />
+ ))
.with('CHANNEL', () => <CoreEntityIcon targetType="channel" size="xs" />)
.with('TASK', () => <CoreEntityIcon targetType="task" size="xs" />)
.with('DOCUMENT', () => {
diff --git a/apps/web/src/features/property/hooks/usePropertyUserDisplay.test.tsx b/apps/web/src/features/property/hooks/usePropertyUserDisplay.test.tsx
new file mode 100644
index 0000000000..88402aff2e
--- /dev/null
+++ b/apps/web/src/features/property/hooks/usePropertyUserDisplay.test.tsx
@@ -0,0 +1,105 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import { storageServiceClient } from '@service-storage/client';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { err, ok } from 'neverthrow';
+import { createSignal } from 'solid-js';
+import { render } from 'solid-js/web';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@service-storage/client', () => ({
+ storageServiceClient: {
+ getBot: vi.fn(),
+ getBotOwnerProfiles: vi.fn(),
+ },
+}));
+vi.mock('@core/user', () => ({
+ getDisplayName: () => 'Alice Example',
+ tryMacroId: (id: string) => (id.startsWith('macro|') ? id : undefined),
+ getDisplayNameParts: () => ({
+ firstName: 'Alice',
+ fullName: 'Alice Example',
+ }),
+}));
+
+import { usePropertyUserDisplay } from './usePropertyUserDisplay';
+
+const BOT_ID = '0193fd84-36d7-7fe1-914e-6b9fdbb208c8';
+let queryClient: QueryClient;
+let dispose: (() => void) | undefined;
+
+function renderHook(factory: () => ReturnType<typeof usePropertyUserDisplay>) {
+ let display!: ReturnType<typeof usePropertyUserDisplay>;
+ dispose = render(
+ () => (
+ <QueryClientProvider client={queryClient}>
+ {(() => {
+ display = factory();
+ return null;
+ })()}
+ </QueryClientProvider>
+ ),
+ document.body
+ );
+ return display;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ vi.mocked(storageServiceClient.getBot).mockResolvedValue(
+ err([{ code: 'HTTP_ERROR', message: 'Forbidden' }])
+ );
+ vi.mocked(storageServiceClient.getBotOwnerProfiles).mockResolvedValue(
+ ok([
+ {
+ id: BOT_ID,
+ name: 'Research agent',
+ avatar_url: 'https://example.com/avatar.png',
+ },
+ ])
+ );
+});
+
+afterEach(() => {
+ dispose?.();
+ dispose = undefined;
+ queryClient.clear();
+});
+
+describe('property user identity', () => {
+ it('preserves human names without fetching a bot', () => {
+ const display = renderHook(() =>
+ usePropertyUserDisplay(() => 'macro|[email protected]')
+ );
+ expect(display.name()).toBe('Alice Example');
+ expect(display.shortName()).toBe('Alice');
+ expect(storageServiceClient.getBotOwnerProfiles).not.toHaveBeenCalled();
+ expect(storageServiceClient.getBot).not.toHaveBeenCalled();
+ });
+
+ it('resolves an assigned agent profile without permission to manage it', async () => {
+ const [id, setId] = createSignal(`bot|${BOT_ID}`);
+ const display = renderHook(() => usePropertyUserDisplay(id));
+
+ expect(display.name()).toBe('Agent');
+ expect(display.photoUrl()).toBeUndefined();
+ await vi.waitFor(() => {
+ expect(display.name()).toBe('Research agent');
+ });
+ expect(display.shortName()).toBe('Research agent');
+ expect(display.photoUrl()).toBe('https://example.com/avatar.png');
+ expect(storageServiceClient.getBotOwnerProfiles).toHaveBeenCalledWith({
+ ids: [BOT_ID],
+ });
+ expect(storageServiceClient.getBot).not.toHaveBeenCalled();
+
+ setId('macro|[email protected]');
+ expect(display.name()).toBe('Alice Example');
+ expect(display.photoUrl()).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/features/property/hooks/usePropertyUserDisplay.ts b/apps/web/src/features/property/hooks/usePropertyUserDisplay.ts
new file mode 100644
index 0000000000..2c1a3d590a
--- /dev/null
+++ b/apps/web/src/features/property/hooks/usePropertyUserDisplay.ts
@@ -0,0 +1,30 @@
+import { isBotPrincipalId } from '@core/constant/macroAgent';
+import { getDisplayName, getDisplayNameParts, tryMacroId } from '@core/user';
+import { firstPartyBotName } from '@queries/bots/first-party-bot-name';
+import { useBotProfile } from '@queries/bots/profiles';
+import { queryReadyGate } from '@queries/gate';
+import type { Accessor } from 'solid-js';
+
+/** Resolve user-property principals without treating bot IDs as email users. */
+export function usePropertyUserDisplay(id: Accessor<string>) {
+ const isAgent = () => isBotPrincipalId(id());
+ const botId = () => (isAgent() ? id().replace(/^bot\|/, '') : '');
+ const bot = useBotProfile(botId);
+ // Every data read is gated so property pills and hover cards never suspend
+ // their surrounding task while resolving an agent's profile.
+ const profile = () =>
+ isAgent() && queryReadyGate(bot) ? bot.data : undefined;
+ const userName = () =>
+ getDisplayNameParts(tryMacroId(id()), { emailFallback: 'local-part' });
+ const name = () =>
+ isAgent()
+ ? (profile()?.name ?? firstPartyBotName(id()) ?? 'Agent')
+ : getDisplayName(tryMacroId(id()));
+
+ return {
+ name,
+ shortName: () =>
+ isAgent() ? name() : userName().firstName || userName().fullName,
+ photoUrl: () => profile()?.avatarUrl,
+ };
+}
diff --git a/apps/web/src/features/property/queries/agent-assignees.test.ts b/apps/web/src/features/property/queries/agent-assignees.test.ts
new file mode 100644
index 0000000000..37378d1157
--- /dev/null
+++ b/apps/web/src/features/property/queries/agent-assignees.test.ts
@@ -0,0 +1,143 @@
+import { CLAUDE_BOT_PRINCIPAL_ID } from '@core/constant/claudeAgent';
+import { CODEX_BOT_PRINCIPAL_ID } from '@core/constant/codexAgent';
+import { CURSOR_BOT_PRINCIPAL_ID } from '@core/constant/cursorAgent';
+import { MACRO_AGENT_PRINCIPAL_ID } from '@core/constant/macroAgent';
+import { MACRO_CODER_PRINCIPAL_ID } from '@core/constant/macroCoder';
+import { MACRO_NEW_PRINCIPAL_ID } from '@core/constant/macroNew';
+import type { Agent } from '@service-storage/generated/schemas/agent';
+import type { Bot } from '@service-storage/generated/schemas/bot';
+import { createRoot } from 'solid-js';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const fixture = vi.hoisted(() => ({
+ agents: [] as Agent[],
+ bots: [] as Bot[],
+ pending: false,
+ agentRollout: false,
+ cursorRollout: false,
+}));
+
+vi.mock('@core/constant/featureFlags', () => ({
+ enableChatV3Agents: { key: 'enable-chat-v3-agents' },
+ enableCursorAgents: { key: 'enable-cursor-agents' },
+}));
+vi.mock('@app/lib/analytics/posthog', () => ({
+ useFeatureFlag: (flag: { key: string }) => () => ({
+ enabled:
+ flag.key === 'enable-chat-v3-agents'
+ ? fixture.agentRollout
+ : fixture.cursorRollout,
+ }),
+}));
+
+vi.mock('@queries/agents/agents', () => ({
+ useAgentsQuery: () => ({
+ get isPending() {
+ return fixture.pending;
+ },
+ get data() {
+ if (fixture.pending)
+ throw new Error('Pending agent data must not be read');
+ return fixture.agents;
+ },
+ }),
+}));
+vi.mock('@queries/bots/bots', () => ({
+ useBotsQuery: () => ({
+ isPending: false,
+ get data() {
+ return fixture.bots;
+ },
+ }),
+}));
+
+import { useAgentAssignees } from './agent-assignees';
+
+function agent(id: string, overrides: Partial<Bot> = {}): Agent {
+ return {
+ bot: {
+ id,
+ name: 'Research agent',
+ handle: 'research',
+ kind: 'owned',
+ has_agent: true,
+ created_at: '',
+ updated_at: '',
+ ...overrides,
+ },
+ harness: 'in-memory',
+ instructions: '',
+ default_model: '',
+ channel_ids: [],
+ channel_scope: 'all',
+ mcp: { scope: 'owner_connections' },
+ is_coding: false,
+ };
+}
+
+beforeEach(() => {
+ fixture.agents = [];
+ fixture.bots = [];
+ fixture.pending = false;
+ fixture.agentRollout = false;
+ fixture.cursorRollout = false;
+});
+
+describe('task agent assignees', () => {
+ it('offers owned and team agents as bot principals, excluding channel-only and non-agent bots', () => {
+ const owned = agent('owned', {
+ avatar_url: 'https://example.com/avatar.png',
+ });
+ const team = agent('team');
+ const channelOnly = agent('channel-only');
+ const inactive = agent('inactive', { has_agent: false });
+ const deleted = agent('deleted', { deleted_at: '2026-01-01' });
+ fixture.agents = [owned, team, channelOnly, inactive, deleted];
+ fixture.bots = [owned.bot, team.bot, inactive.bot, deleted.bot];
+ createRoot((dispose) => {
+ const users = useAgentAssignees(() => true);
+ expect(users().map(({ id }) => id)).toEqual([
+ CLAUDE_BOT_PRINCIPAL_ID,
+ CODEX_BOT_PRINCIPAL_ID,
+ 'bot|owned',
+ 'bot|team',
+ ]);
+ expect(users().find(({ id }) => id === 'bot|owned')).toEqual({
+ id: 'bot|owned',
+ name: 'Research agent',
+ email: '@research',
+ photoUrl: 'https://example.com/avatar.png',
+ });
+ dispose();
+ });
+ });
+
+ it('does not suspend people selection while agents are pending, or expose agents to other properties', () => {
+ fixture.pending = true;
+ createRoot((dispose) => {
+ expect(useAgentAssignees(() => true)().map(({ id }) => id)).toEqual([
+ CLAUDE_BOT_PRINCIPAL_ID,
+ CODEX_BOT_PRINCIPAL_ID,
+ ]);
+ expect(useAgentAssignees(() => false)()).toEqual([]);
+ dispose();
+ });
+ });
+
+ it('reuses system session-agent rollout and excludes classic Macro', () => {
+ fixture.agentRollout = true;
+ fixture.cursorRollout = true;
+ createRoot((dispose) => {
+ const ids = useAgentAssignees(() => true)().map(({ id }) => id);
+ expect(ids).toEqual([
+ MACRO_NEW_PRINCIPAL_ID,
+ CLAUDE_BOT_PRINCIPAL_ID,
+ CODEX_BOT_PRINCIPAL_ID,
+ CURSOR_BOT_PRINCIPAL_ID,
+ MACRO_CODER_PRINCIPAL_ID,
+ ]);
+ expect(ids).not.toContain(MACRO_AGENT_PRINCIPAL_ID);
+ dispose();
+ });
+ });
+});
diff --git a/apps/web/src/features/property/queries/agent-assignees.ts b/apps/web/src/features/property/queries/agent-assignees.ts
new file mode 100644
index 0000000000..9501064967
--- /dev/null
+++ b/apps/web/src/features/property/queries/agent-assignees.ts
@@ -0,0 +1,38 @@
+import { useAgentMentionUsers } from '@channel/use-agent-mention-users';
+import { isMacroAgentId } from '@core/constant/macroAgent';
+import type { IUser } from '@core/user';
+import { useAgentsQuery } from '@queries/agents/agents';
+import { useBotsQuery } from '@queries/bots/bots';
+import { queryReadyGate } from '@queries/gate';
+import type { Accessor } from 'solid-js';
+
+/** Agents use their canonical bot principal in the USER assignee property. */
+export function useAgentAssignees(
+ enabled: Accessor<boolean>
+): Accessor<IUser[]> {
+ const agents = useAgentsQuery(enabled);
+ // The agent list also includes agents visible through shared channels.
+ // The bot list is scoped to the caller's own and team bots, which are the
+ // principals they may invoke from a task outside those channels.
+ const bots = useBotsQuery(enabled);
+ const savedAgents = () => {
+ if (!enabled() || !queryReadyGate(agents) || !queryReadyGate(bots))
+ return [];
+ const availableIds = new Set(bots.data.map((bot) => bot.id));
+ return agents.data
+ .filter(
+ ({ bot }) =>
+ bot.has_agent && !bot.deleted_at && availableIds.has(bot.id)
+ )
+ .map(({ bot }) => ({
+ id: `bot|${bot.id}`,
+ name: bot.name,
+ email: `@${bot.handle}`,
+ photoUrl: bot.avatar_url ?? undefined,
+ }));
+ };
+ // Reuse the message composer's system-agent roster and rollout policy.
+ // Classic Macro replies inline without a session, so it cannot be assigned.
+ const available = useAgentMentionUsers(savedAgents, enabled);
+ return () => available().filter((agent) => !isMacroAgentId(agent.id));
+}
diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskGroupHeader.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskGroupHeader.tsx
index b0696b50b9..278f372bf4 100644
--- a/apps/web/src/features/tasks-view/components/task-list/TaskGroupHeader.tsx
+++ b/apps/web/src/features/tasks-view/components/task-list/TaskGroupHeader.tsx
@@ -1,5 +1,6 @@
import type { SoupGroupHeaderRow } from '@app/features/soup';
import { UserIcon } from '@core/component/UserIcon';
+import { isBotPrincipalId } from '@core/constant/macroAgent';
import { getDisplayName, tryMacroId } from '@core/user';
import { getPropertyOptionLabel } from '@entity';
import CaretRightIcon from '@phosphor/caret-right.svg';
@@ -7,6 +8,7 @@ import CircleDashedIcon from '@phosphor/circle-dashed.svg';
import FolderIcon from '@phosphor/folder-simple.svg';
import { PROPERTY_OPTION_IDS } from '@property';
import { PropertyValueIcon } from '@property/component/propertyValue';
+import { usePropertyUserDisplay } from '@property/hooks/usePropertyUserDisplay';
import { cn, Layer, Surface } from '@ui';
import { createMemo, Match, Show, Switch } from 'solid-js';
import type { TaskGroupBy } from '../../types';
@@ -34,6 +36,11 @@ export function TaskGroupHeader(props: {
onToggle: () => void;
onFocus: () => void;
}) {
+ const agent = usePropertyUserDisplay(() =>
+ props.groupBy === 'assignee' && isBotPrincipalId(props.row.groupId)
+ ? props.row.groupId
+ : ''
+ );
const label = createMemo(() => {
if (!props.row.groupId) return props.row.label || 'Not set';
@@ -42,6 +49,7 @@ export function TaskGroupHeader(props: {
}
if (props.groupBy === 'assignee') {
+ if (isBotPrincipalId(props.row.groupId)) return agent.name();
const assigneeId = tryMacroId(props.row.groupId);
if (!assigneeId) return props.row.label;
return (
diff --git a/apps/web/src/lib/queries/agents/agents.test.tsx b/apps/web/src/lib/queries/agents/agents.test.tsx
index 61cc670a74..3fa5765fd8 100644
--- a/apps/web/src/lib/queries/agents/agents.test.tsx
+++ b/apps/web/src/lib/queries/agents/agents.test.tsx
@@ -9,6 +9,7 @@ import { ok } from 'neverthrow';
import type { JSX } from 'solid-js';
import { render } from 'solid-js/web';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { botKeys, botProfileKeys } from '../bots/keys';
import { channelKeys } from '../channel/keys';
import { agentKeys } from './keys';
@@ -115,6 +116,12 @@ describe('agent channel-bot cache invalidation', () => {
expect(invalidateQueries).toHaveBeenCalledWith({
queryKey: channelKeys.channelBots('channel-other').queryKey,
});
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: botKeys.list.queryKey,
+ });
+ expect(
+ testQueryClient.getQueryData(botKeys.detail(created.bot.id).queryKey)
+ ).toEqual(created.bot);
});
it('invalidates old and new channel bot queries after editing', async () => {
@@ -122,6 +129,12 @@ describe('agent channel-bot cache invalidation', () => {
agent(['channel-old']),
]);
const updated = agent(['channel-new']);
+ const profileKey = botProfileKeys.detail(updated.bot.id).queryKey;
+ testQueryClient.setQueryData(profileKey, {
+ name: 'Previous name',
+ avatarUrl: undefined,
+ deleted: false,
+ });
vi.mocked(storageServiceClient.updateAgent).mockResolvedValue(ok(updated));
const invalidateQueries = vi.spyOn(testQueryClient, 'invalidateQueries');
const mutation = renderHook(() => useUpdateAgentMutation());
@@ -134,11 +147,24 @@ describe('agent channel-bot cache invalidation', () => {
expect(invalidateQueries).toHaveBeenCalledWith({
queryKey: channelKeys.channelBots('channel-new').queryKey,
});
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: botKeys.list.queryKey,
+ });
+ expect(
+ testQueryClient.getQueryData(botKeys.detail(updated.bot.id).queryKey)
+ ).toEqual(updated.bot);
+ expect(testQueryClient.getQueryState(profileKey)?.isInvalidated).toBe(true);
});
it('removes a deleted agent and invalidates its channel bot queries', async () => {
const existing = agent(['channel-old']);
testQueryClient.setQueryData(agentKeys.list.queryKey, [existing]);
+ const profileKey = botProfileKeys.detail(existing.bot.id).queryKey;
+ testQueryClient.setQueryData(profileKey, {
+ name: existing.bot.name,
+ avatarUrl: undefined,
+ deleted: false,
+ });
vi.mocked(storageServiceClient.deleteBot).mockResolvedValue(ok(undefined));
const invalidateQueries = vi.spyOn(testQueryClient, 'invalidateQueries');
const mutation = renderHook(() => useDeleteAgentMutation());
@@ -154,6 +180,7 @@ describe('agent channel-bot cache invalidation', () => {
expect(
testQueryClient.getQueryData<Agent[]>(agentKeys.list.queryKey)
).toEqual([]);
+ expect(testQueryClient.getQueryState(profileKey)?.isInvalidated).toBe(true);
expect(invalidateQueries).toHaveBeenCalledWith({
queryKey: channelKeys.channelBots('channel-old').queryKey,
});
diff --git a/apps/web/src/lib/queries/agents/agents.ts b/apps/web/src/lib/queries/agents/agents.ts
index da0ed6dead..7ac4b3a77b 100644
--- a/apps/web/src/lib/queries/agents/agents.ts
+++ b/apps/web/src/lib/queries/agents/agents.ts
@@ -1,5 +1,5 @@
import { throwOnErr } from '@core/util/result';
-import { botKeys } from '@queries/bots/keys';
+import { botKeys, botProfileKeys } from '@queries/bots/keys';
import { channelKeys } from '@queries/channel/keys';
import { queryClient } from '@queries/client';
import { storageServiceClient } from '@service-storage/client';
@@ -104,7 +104,14 @@ export function useCreateAgentMutation() {
agentKeys.list.queryKey,
(current = []) => [...current, agent]
);
- await invalidateAgentChannelBots(agent.channel_ids);
+ queryClient.setQueryData(
+ botKeys.detail(agent.bot.id).queryKey,
+ agent.bot
+ );
+ await Promise.all([
+ invalidateAgentChannelBots(agent.channel_ids),
+ queryClient.invalidateQueries({ queryKey: botKeys.list.queryKey }),
+ ]);
},
onError: (error) => console.error('failed to create agent', error),
}));
@@ -145,9 +152,19 @@ export function useUpdateAgentMutation() {
agent.bot.id === updated.bot.id ? updated : agent
)
);
- await invalidateAgentChannelBots([
- ...previousChannelIds,
- ...updated.channel_ids,
+ queryClient.setQueryData(
+ botKeys.detail(updated.bot.id).queryKey,
+ updated.bot
+ );
+ await Promise.all([
+ invalidateAgentChannelBots([
+ ...previousChannelIds,
+ ...updated.channel_ids,
+ ]),
+ queryClient.invalidateQueries({ queryKey: botKeys.list.queryKey }),
+ queryClient.invalidateQueries({
+ queryKey: botProfileKeys.detail(updated.bot.id).queryKey,
+ }),
]);
},
onError: (error) => console.error('failed to update agent', error),
@@ -179,6 +196,9 @@ export function useDeleteAgentMutation() {
await Promise.all([
queryClient.invalidateQueries({ queryKey: botKeys.list.queryKey }),
+ queryClient.invalidateQueries({
+ queryKey: botProfileKeys.detail(vars.agentId).queryKey,
+ }),
...[...new Set(vars.channelIds)].flatMap((channelId) => [
queryClient.invalidateQueries({
queryKey: channelKeys.channelBots(channelId).queryKey,
diff --git a/apps/web/src/lib/queries/bots/bots.ts b/apps/web/src/lib/queries/bots/bots.ts
index c10bedc209..56a9505f6e 100644
--- a/apps/web/src/lib/queries/bots/bots.ts
+++ b/apps/web/src/lib/queries/bots/bots.ts
@@ -39,8 +39,8 @@ export function botsQueryOptions() {
});
}
-export function useBotsQuery() {
- return useQuery(botsQueryOptions);
+export function useBotsQuery(enabled: () => boolean = () => true) {
+ return useQuery(() => ({ ...botsQueryOptions(), enabled: enabled() }));
}
export function useBotQuery(botId: () => string) {
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThread.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThread.ts
index 38f66df0f4..262c39e2cf 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThread.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThread.ts
@@ -22,6 +22,8 @@ message parents send this instead of `parent`. */
/** The mentioning message. */
messageId: string;
parent?: CreateSessionThreadParent;
+ /** Update the existing bot response reserved by a task assignment. */
+ reuseOriginMessage?: boolean;
/** Thread the session belongs to; defaults to the message itself, which
is how a top-level mention roots its own thread. */
threadId?: CreateSessionThreadThreadId;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
index 07293928a5..2d529594a7 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
@@ -2649,6 +2649,10 @@
}
]
},
+ "reuseOriginMessage": {
+ "type": "boolean",
+ "description": "Update the existing bot response reserved by a task assignment."
+ },
"threadId": {
"type": ["string", "null"],
"format": "uuid",
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.ts
index 0564c7210d..2db365c05b 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
@@ -6419,7 +6419,7 @@ export interface SendEmail {
* For multi-select properties — including tags — prefer add_option_ids / remove_option_ids over option_ids: they add or remove just those options atomically, composing with concurrent edits. option_ids replaces the entire value, so a stale read can silently drop options someone else just added; only use it when the user asks to set the value to exactly a given list. To apply a tag, pass the tag set's property_definition_id and the tag's option id (both from ListTags) in add_option_ids; to remove a tag, use remove_option_ids.
*
* Tasks always have these system properties (use these property_definition_id values directly):
- * - Assignees (00000001-0000-0000-0000-000000000001): entity type, multi-select. Use entity_refs with entity_type='user' and entity_id='macro|[email protected]'.
+ * - Assignees (00000001-0000-0000-0000-000000000001): entity type, multi-select. Use entity_refs with entity_type='user' and entity_id='macro|[email protected]' for people or 'bot|<agent UUID>' for agents. Adding an agent starts its session and replies in the task discussion.
* - Status (00000001-0000-0000-0000-000000000002): select_string, single. Options: Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), In Review (...0003), Completed (...0004), Canceled (...0005).
* - Priority (00000001-0000-0000-0000-000000000003): select_string, single. Options: Low (...0001), Medium (...0002), High (...0003), Urgent (...0004). Option IDs: 00000001-0000-0000-0003-0000000000XX.
* - Due Date (00000001-0000-0000-0000-000000000004): date, single. Use date_value with ISO 8601.
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index e55804bc2a..cb77e1684c 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -14,23 +14,8 @@ use bot_id::BotId;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use messages::domain::events::MessageEventAttachment;
-/// Where a mention happened.
-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
-pub struct MentionOrigin {
- /// Channel or document the mentioning message was posted in.
- pub parent: messages::domain::models::MessageParent,
- /// Thread the announcement replies into: the mention's thread root.
- pub thread_id: Uuid,
- /// The mentioning message itself.
- pub message_id: Uuid,
- /// Who asked. Owns the session and is credited for its messages.
- pub sender: MacroUserIdStr<'static>,
- /// The message text, verbatim; becomes the session's first prompt.
- pub content: String,
- /// Files attached to the message, as the prompt will refer to them.
- #[serde(default)]
- pub attachments: Vec<PromptAttachment>,
-}
+mod session_origin;
+pub use session_origin::{MentionOrigin, SessionOrigin, TaskAssignmentOrigin};
/// How a channel message's attached files are named to an agent.
///
@@ -91,7 +76,7 @@ impl StaticFileLinks {
}
}
-/// Open a new session for a mention.
+/// Open a new session for a mention or task assignment.
///
/// Only for managed sessions - the ones whose sandbox this deployment
/// provisions. External sessions are opened through
@@ -100,12 +85,12 @@ impl StaticFileLinks {
/// a plain create rather than a harness command.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OpenSession {
- /// The bot that was mentioned.
+ /// The bot selected by the triggering event.
pub bot_id: BotId,
/// Runtime configuration resolved for this bot when the trigger arrived.
pub runtime: AgentRuntimeConfig,
- /// The mention itself.
- pub origin: MentionOrigin,
+ /// The mention or assignment that requested the session.
+ pub origin: SessionOrigin,
}
/// How a bot's sessions get a runtime — the closed set of first-party
@@ -349,6 +334,9 @@ pub(crate) use agent_egress::domain::model::is_macro_staff;
/// answer back into.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct AnnounceOrigin {
+ /// Update the existing agent response instead of posting a reply.
+ #[serde(default)]
+ pub reuse_origin_message: bool,
/// Channel or document the prompt was posted in.
pub parent: messages::domain::models::MessageParent,
/// Thread the announcement replies into.
@@ -615,6 +603,8 @@ pub struct AnnouncePrompt {
/// Facts required to announce one prompt into its originating context.
#[derive(Debug, Clone)]
pub struct SessionAnnouncement {
+ /// Update the existing agent response instead of posting a reply.
+ pub reuse_origin_message: bool,
/// Agent session represented by the announcement.
pub session_id: AgentSessionId,
/// The bot the session runs for; the announcement posts as it.
diff --git a/crates/agent_harness/src/domain/model/session_origin.rs b/crates/agent_harness/src/domain/model/session_origin.rs
new file mode 100644
index 0000000000..fa3719db33
--- /dev/null
+++ b/crates/agent_harness/src/domain/model/session_origin.rs
@@ -0,0 +1,96 @@
+//! Distinct session origins for mentions and task assignments.
+
+use agent_runtime_protocol::domain::action::{AgentAction, PromptAttachment};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+
+use super::AnnounceOrigin;
+
+#[cfg(test)]
+mod test;
+
+/// Where a mention happened.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct MentionOrigin {
+ /// Channel or document the mentioning message was posted in.
+ pub parent: messages::domain::models::MessageParent,
+ /// Thread the announcement replies into: the mention's thread root.
+ pub thread_id: Uuid,
+ /// The mentioning message itself.
+ pub message_id: Uuid,
+ /// Who asked. Owns the session and is credited for its messages.
+ pub sender: MacroUserIdStr<'static>,
+ /// The message text, verbatim; becomes the session's first prompt.
+ pub content: String,
+ /// Files attached to the message, as the prompt will refer to them.
+ #[serde(default)]
+ pub attachments: Vec<PromptAttachment>,
+}
+
+/// A task assignment that starts a session without a user-authored mention.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct TaskAssignmentOrigin {
+ /// Task whose discussion receives the agent's response.
+ pub parent: messages::domain::models::MessageParent,
+ /// Reserved agent-authored response, also the discussion's root.
+ pub discussion_id: Uuid,
+ /// User who assigned the task and owns the session.
+ pub actor: MacroUserIdStr<'static>,
+ /// Task instructions supplied privately to the session.
+ pub prompt: String,
+}
+
+/// The event that opens a managed session.
+///
+/// Untagged serialization preserves the existing mention command shape.
+/// Assignments have distinct required fields and never deserialize as mentions.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(untagged)]
+pub enum SessionOrigin {
+ /// A user mentioned the agent in a message.
+ Mention(MentionOrigin),
+ /// A user assigned a task to the agent.
+ TaskAssignment(TaskAssignmentOrigin),
+}
+
+impl SessionOrigin {
+ pub(crate) fn actor(&self) -> &MacroUserIdStr<'static> {
+ match self {
+ Self::Mention(origin) => &origin.sender,
+ Self::TaskAssignment(origin) => &origin.actor,
+ }
+ }
+
+ pub(crate) fn kind(&self) -> &'static str {
+ match self {
+ Self::Mention(_) => "mention",
+ Self::TaskAssignment(_) => "task_assignment",
+ }
+ }
+
+ pub(crate) fn announcement(&self) -> AnnounceOrigin {
+ match self {
+ Self::Mention(origin) => AnnounceOrigin {
+ reuse_origin_message: false,
+ parent: origin.parent.clone(),
+ thread_id: origin.thread_id,
+ message_id: origin.message_id,
+ },
+ Self::TaskAssignment(origin) => AnnounceOrigin {
+ reuse_origin_message: true,
+ parent: origin.parent.clone(),
+ thread_id: origin.discussion_id,
+ message_id: origin.discussion_id,
+ },
+ }
+ }
+
+ pub(crate) fn into_action(self) -> AgentAction {
+ match self {
+ Self::Mention(origin) => {
+ AgentAction::prompt_with_attachments(origin.content, origin.attachments)
+ }
+ Self::TaskAssignment(origin) => AgentAction::prompt(origin.prompt),
+ }
+ }
+}
diff --git a/crates/agent_harness/src/domain/model/session_origin/test.rs b/crates/agent_harness/src/domain/model/session_origin/test.rs
new file mode 100644
index 0000000000..e57dc2d8d1
--- /dev/null
+++ b/crates/agent_harness/src/domain/model/session_origin/test.rs
@@ -0,0 +1,55 @@
+use super::*;
+use messages::domain::models::MessageParent;
+
+fn actor() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+#[test]
+fn existing_mention_commands_keep_their_wire_shape_and_reply_behavior() {
+ let mention = MentionOrigin {
+ parent: MessageParent::Channel(Uuid::from_u128(1)),
+ thread_id: Uuid::from_u128(2),
+ message_id: Uuid::from_u128(3),
+ sender: actor(),
+ content: "Please review this".to_owned(),
+ attachments: vec![PromptAttachment::new("https://example.com/file", "image")],
+ };
+ let wire = serde_json::to_value(&mention).unwrap();
+ let origin: SessionOrigin = serde_json::from_value(wire.clone()).unwrap();
+ assert!(matches!(origin, SessionOrigin::Mention(_)));
+ assert_eq!(serde_json::to_value(&origin).unwrap(), wire);
+ assert!(!origin.announcement().reuse_origin_message);
+ assert_eq!(origin.announcement().message_id, mention.message_id);
+ assert_eq!(origin.announcement().thread_id, mention.thread_id);
+ let AgentAction::Prompt(prompt) = origin.into_action() else {
+ panic!("a mention delivers a prompt");
+ };
+ assert_eq!(prompt.prompt, mention.content);
+ assert_eq!(prompt.attachments, mention.attachments);
+}
+
+#[test]
+fn assignments_remain_distinct_after_command_serialization() {
+ let origin = SessionOrigin::TaskAssignment(TaskAssignmentOrigin {
+ parent: MessageParent::parse("document", "task-1").unwrap(),
+ discussion_id: Uuid::from_u128(4),
+ actor: actor(),
+ prompt: "Private task brief".to_owned(),
+ });
+ let wire = serde_json::to_value(&origin).unwrap();
+ assert!(wire.get("content").is_none());
+ assert!(wire.get("sender").is_none());
+ let restored: SessionOrigin = serde_json::from_value(wire).unwrap();
+ assert!(matches!(restored, SessionOrigin::TaskAssignment(_)));
+ assert_eq!(restored.actor(), &actor());
+ assert_eq!(restored.kind(), "task_assignment");
+ let announcement = restored.announcement();
+ assert!(announcement.reuse_origin_message);
+ assert_eq!(announcement.message_id, Uuid::from_u128(4));
+ assert_eq!(announcement.thread_id, announcement.message_id);
+ let AgentAction::Prompt(prompt) = restored.into_action() else {
+ panic!("an assignment delivers its private brief");
+ };
+ assert_eq!(prompt.prompt, "Private task brief");
+}
diff --git a/crates/agent_harness/src/domain/queue/test.rs b/crates/agent_harness/src/domain/queue/test.rs
index 66f8a6682b..f019fbf66f 100644
--- a/crates/agent_harness/src/domain/queue/test.rs
+++ b/crates/agent_harness/src/domain/queue/test.rs
@@ -228,6 +228,7 @@ fn a_snapshot_round_trips_through_the_durable_shape() {
let session = AgentSessionId::TEST_A;
let mut entry = prompt_entry("keep me");
entry.announce = Some(AnnounceOrigin {
+ reuse_origin_message: false,
parent: messages::domain::models::MessageParent::Channel(Uuid::from_u128(0xf0)),
thread_id: Uuid::from_u128(0xf1),
message_id: Uuid::from_u128(0xf2),
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index cbd0d3e301..b282b7f9be 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -413,6 +413,7 @@ where
self.inner
.announcer
.announce(SessionAnnouncement {
+ reuse_origin_message: false,
session_id,
bot_id: session.bot_id,
is_coding: persona.is_coding,
diff --git a/crates/agent_harness/src/domain/service/deliver.rs b/crates/agent_harness/src/domain/service/deliver.rs
index 9fe1ddd92e..a73b603363 100644
--- a/crates/agent_harness/src/domain/service/deliver.rs
+++ b/crates/agent_harness/src/domain/service/deliver.rs
@@ -252,6 +252,7 @@ where
let persona = self.reply_persona(&session).await?;
Ok(Some(SessionAnnouncement {
+ reuse_origin_message: origin.reuse_origin_message,
session_id,
bot_id: session.bot_id,
is_coding: persona.is_coding,
diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rs
index 23e5ff7c4d..8c71915a9d 100644
--- a/crates/agent_harness/src/domain/service/open.rs
+++ b/crates/agent_harness/src/domain/service/open.rs
@@ -66,6 +66,7 @@ where
.authorize_origin(
&owner_user,
&AnnounceOrigin {
+ reuse_origin_message: thread.reuse_origin_message,
parent: thread.parent.clone(),
thread_id: thread.thread_id,
message_id: thread.message_id,
@@ -121,6 +122,7 @@ where
let announce = async {
let persona = self.inner.reply_persona(&session).await?;
let announcement = SessionAnnouncement {
+ reuse_origin_message: thread.reuse_origin_message,
session_id: session.id,
bot_id: request.bot_id,
is_coding: persona.is_coding,
@@ -412,10 +414,10 @@ where
#[tracing::instrument(err, skip(self, command), fields(
%session_id,
bot_id = %command.bot_id,
- message_id = %command.origin.message_id,
- parent = ?command.origin.parent,
- thread_id = %command.origin.thread_id,
- agent.trigger.kind = "mention",
+ message_id = tracing::field::Empty,
+ parent = tracing::field::Empty,
+ thread_id = tracing::field::Empty,
+ agent.trigger.kind = command.origin.kind(),
agent.session.id = tracing::field::Empty,
))]
pub(super) async fn open(
@@ -428,44 +430,38 @@ where
runtime,
origin,
} = command;
- tracing::Span::current().record("agent.session.id", tracing::field::display(session_id));
- // The mention was observed, but the sender's access is checked now:
- // a user removed from the parent since posting opens nothing.
+ let actor = origin.actor().clone();
+ let announcement = origin.announcement();
+ let span = tracing::Span::current();
+ span.record("agent.session.id", tracing::field::display(session_id));
+ span.record(
+ "message_id",
+ tracing::field::display(announcement.message_id),
+ );
+ span.record("parent", tracing::field::debug(&announcement.parent));
+ span.record("thread_id", tracing::field::display(announcement.thread_id));
+ // Recheck access after the triggering event: a user removed from the
+ // parent since mentioning or assigning the agent opens nothing.
self.prompt_context
- .authorize_origin(
- &origin.sender,
- &AnnounceOrigin {
- parent: origin.parent.clone(),
- thread_id: origin.thread_id,
- message_id: origin.message_id,
- },
- )
+ .authorize_origin(&actor, &announcement)
.await?;
// Asked before anything exists for the session: a row whose spawn is
// bound to fail would be marked disconnected and leave the thread
// with a chip that never answers. Declining is the bot's reply
// instead - what the mentioner has to connect, where to do it.
- if let Some(blocker) = self
- .containers
- .preflight(runtime.kind, &origin.sender)
- .await?
- {
+ if let Some(blocker) = self.containers.preflight(runtime.kind, &actor).await? {
tracing::info!(
bot_id = %bot_id,
- sender = %origin.sender,
+ sender = %actor,
?blocker,
- "declining a mention its sender is not set up for"
+ "declining a session its owner is not set up for"
);
self.announcer
.decline(DeclinedMention {
bot_id,
- origin: AnnounceOrigin {
- parent: origin.parent,
- thread_id: origin.thread_id,
- message_id: origin.message_id,
- },
- triggered_by: origin.sender,
+ origin: announcement,
+ triggered_by: actor,
blocker,
})
.await?;
@@ -473,7 +469,7 @@ where
}
let defaults = self.defaults.for_bot(bot_id);
- let sandbox_size = self.sessions.user_sandbox_size(&origin.sender).await?;
+ let sandbox_size = self.sessions.user_sandbox_size(&actor).await?;
// The same profile the create menu snapshots: a mention states nothing
// about how the runtime should work, so the bot's configured
// instructions are what it opens with, exactly as a dedicated session
@@ -488,7 +484,7 @@ where
// credentials, so there is nowhere else it could correctly come from.
let egress = self
.egress
- .provision(session_id, &origin.sender, &runtime.mcp_servers)
+ .provision(session_id, &actor, &runtime.mcp_servers)
.await?;
let session = self
@@ -496,10 +492,10 @@ where
.create_session(CreateAgentSessionParams {
repo_branch: None,
id: session_id,
- owner_id: Owner::User(origin.sender.clone()),
+ owner_id: Owner::User(actor.clone()),
bot_id,
- thread_id: Some(origin.thread_id),
- originating_message_id: Some(origin.message_id),
+ thread_id: Some(announcement.thread_id),
+ originating_message_id: Some(announcement.message_id),
model: runtime.model.clone(),
harness: runtime
.kind
@@ -518,7 +514,7 @@ where
// advertised, for as long as the session lives.
mcp_servers: runtime.mcp_servers.clone(),
egress_token_hash: Some(egress.session_token_hash),
- // This open came from the trigger pipeline seeing the mention.
+ // This open came from an observed trigger event.
})
.await?;
self.publish_opened(&session).await;
@@ -572,13 +568,9 @@ where
session_id,
DeliverAction {
id: AgentActionId::mint(),
- action: AgentAction::prompt_with_attachments(origin.content, origin.attachments),
- actor: Some(origin.sender),
- announce: Some(AnnounceOrigin {
- parent: origin.parent,
- thread_id: origin.thread_id,
- message_id: origin.message_id,
- }),
+ action: origin.into_action(),
+ actor: Some(actor),
+ announce: Some(announcement),
},
)
.await?;
diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rs
index 24e2f89ea1..7dfb4cc182 100644
--- a/crates/agent_harness/src/domain/service/queue.rs
+++ b/crates/agent_harness/src/domain/service/queue.rs
@@ -298,7 +298,7 @@ where
match &command {
HarnessCommand::Open(open)
if AgentKind::of(open.bot_id) == AgentKind::SandboxedCoder
- && !is_macro_staff(&open.origin.sender) =>
+ && !is_macro_staff(open.origin.actor()) =>
{
return Err(AgentSessionError::Forbidden.into());
}
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index cf9b229850..6e50e45463 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -48,7 +48,7 @@ use crate::domain::error::HarnessError;
use crate::domain::model::{
AgentKind, AgentRuntimeConfig, AnnounceOrigin, CommandOutcome, CommentAnchor, ContextMessage,
ContextThread, ConversationContext, DeclinedMention, DeliverAction, HarnessCommand,
- HarnessDefaults, MentionOrigin, OpenSession, SessionBlocker, SessionDefaults,
+ HarnessDefaults, MentionOrigin, OpenSession, SessionBlocker, SessionDefaults, SessionOrigin,
SessionRepository, SpawnContainer,
};
use crate::domain::ports::{
@@ -97,17 +97,31 @@ fn open_command() -> OpenSession {
instructions: String::new(),
mcp_servers: AgentMcpServers::OwnerConnections,
},
- origin: MentionOrigin {
+ origin: SessionOrigin::Mention(MentionOrigin {
parent: MessageParent::Channel(macro_uuid::generate_uuid_v7()),
thread_id,
message_id: thread_id,
sender: sender(),
content: "@claude fix the failing test".to_owned(),
attachments: vec![],
- },
+ }),
}
}
+fn mention_origin(command: &OpenSession) -> &MentionOrigin {
+ let SessionOrigin::Mention(origin) = &command.origin else {
+ panic!("expected a mention");
+ };
+ origin
+}
+
+fn mention_origin_mut(command: &mut OpenSession) -> &mut MentionOrigin {
+ let SessionOrigin::Mention(origin) = &mut command.origin else {
+ panic!("expected a mention");
+ };
+ origin
+}
+
/// A prompt arriving from a channel that is not the session's own, so it is
/// the announcing case.
fn forward_message(content: &str) -> DeliverAction {
@@ -117,6 +131,7 @@ fn forward_message(content: &str) -> DeliverAction {
AgentAction::prompt(content),
Some(staff_sender()),
Some(AnnounceOrigin {
+ reuse_origin_message: false,
parent: MessageParent::Channel(macro_uuid::Uuid::from_u128(0xf0)),
thread_id: macro_uuid::Uuid::from_u128(0xf1),
message_id: macro_uuid::Uuid::from_u128(0xf2),
@@ -624,8 +639,14 @@ async fn disconnected_session(
repo: &InMemoryAgentSessionRepo,
containers: &MockContainerManager,
) -> AgentSessionId {
- let OpenSession { origin, .. } = open_command();
- disconnected_session_owned_by(repo, containers, model_owner::Owner::User(origin.sender)).await
+ let command = open_command();
+ let origin = mention_origin(&command);
+ disconnected_session_owned_by(
+ repo,
+ containers,
+ model_owner::Owner::User(origin.sender.clone()),
+ )
+ .await
}
/// [`disconnected_session`] for an arbitrary owner: the in-memory repo stores
@@ -636,7 +657,8 @@ async fn disconnected_session_owned_by(
containers: &MockContainerManager,
owner: model_owner::Owner,
) -> AgentSessionId {
- let OpenSession { origin, .. } = open_command();
+ let command = open_command();
+ let origin = mention_origin(&command);
// The coder bot: resume-on-disconnect only exists for managed sessions.
let bot_id = bot_id::MACRO_CODER_BOT_ID;
let id = AgentSessionId::new();
@@ -681,7 +703,7 @@ async fn open_creates_announces_and_delivers_the_mention() {
let (service, repo, containers, announcer, _runtimes) = harness();
let command = open_command();
let id = AgentSessionId::new();
- let origin = command.origin.clone();
+ let origin = mention_origin(&command).clone();
let open = service.execute(id, HarnessCommand::Open(command));
let drive = async {
@@ -711,6 +733,7 @@ async fn open_creates_announces_and_delivers_the_mention() {
assert_eq!(session.harness, "opencode");
let announced = announcer.announced();
assert_eq!(announced.len(), 1);
+ assert!(!announced[0].reuse_origin_message);
assert_eq!(announced[0].origin_parent, origin.parent);
assert_eq!(announced[0].origin_thread_id, origin.thread_id);
assert_eq!(announced[0].triggered_by, origin.sender);
@@ -736,7 +759,7 @@ async fn claude_cloud_only_accepts_control_from_the_subscription_owner() {
let mut command = open_command();
command.runtime.kind = AgentKind::ClaudeCloud;
command.runtime.harness = "claude-cloud".into();
- let owner = command.origin.sender.clone();
+ let owner = command.origin.actor().clone();
let id = AgentSessionId::new();
let open = service.execute(id, HarnessCommand::Open(command));
let drive = async {
@@ -962,7 +985,7 @@ async fn open_sends_context_and_agent_instructions_in_the_first_prompt() {
);
let mut command = open_command();
command.runtime.instructions = "Diagnose first.".to_owned();
- let raw = command.origin.content.clone();
+ let raw = mention_origin(&command).content.clone();
let id = AgentSessionId::new();
let open = service.execute(id, HarnessCommand::Open(command));
@@ -1043,7 +1066,7 @@ async fn open_sends_the_comment_anchor_the_prompt_was_posted_on() {
composer.clone(),
);
let command = open_command();
- let raw = command.origin.content.clone();
+ let raw = mention_origin(&command).content.clone();
let id = AgentSessionId::new();
let open = service.execute(id, HarnessCommand::Open(command));
@@ -1102,7 +1125,7 @@ async fn a_mention_its_sender_is_not_set_up_for_is_declined_in_the_thread() {
command.bot_id = bot_id;
command.runtime.kind = kind;
command.runtime.harness = harness_slug.to_owned();
- let origin = command.origin.clone();
+ let origin = mention_origin(&command).clone();
let outcome = service
.execute(id, HarnessCommand::Open(command))
@@ -1119,6 +1142,7 @@ async fn a_mention_its_sender_is_not_set_up_for_is_declined_in_the_thread() {
[DeclinedMention {
bot_id,
origin: AnnounceOrigin {
+ reuse_origin_message: false,
parent: origin.parent,
thread_id: origin.thread_id,
message_id: origin.message_id,
@@ -1722,7 +1746,7 @@ async fn live_sandboxed_coder_session(
) -> ContainerMock {
let mut command = open_command();
command.bot_id = bot_id::MACRO_CODER_BOT_ID;
- command.origin.sender = staff_sender();
+ mention_origin_mut(&mut command).sender = staff_sender();
let open = service.execute(id, HarnessCommand::Open(command));
let drive = async {
loop {
@@ -3231,6 +3255,7 @@ async fn an_external_open_with_a_mention_announces_as_the_sessions_bot() {
let mut request = open_external_request("/srv/agent");
let bot = request.bot_id;
request.thread = Some(agent_session::domain::ports::SessionThread {
+ reuse_origin_message: false,
parent: MessageParent::Channel(macro_uuid::Uuid::from_u128(0xC1)),
thread_id: macro_uuid::Uuid::from_u128(0xC2),
message_id: macro_uuid::Uuid::from_u128(0xC2),
@@ -3276,6 +3301,7 @@ async fn an_external_prompt_announce_posts_into_the_observed_origin() {
crate::domain::model::AnnouncePrompt {
bot_id: bot,
origin: AnnounceOrigin {
+ reuse_origin_message: false,
parent: MessageParent::Channel(macro_uuid::Uuid::from_u128(0xAA)),
thread_id: macro_uuid::Uuid::from_u128(0xAB),
message_id: macro_uuid::Uuid::from_u128(0xAC),
@@ -3316,6 +3342,7 @@ async fn an_announce_whose_bot_does_not_own_the_session_is_dropped() {
crate::domain::model::AnnouncePrompt {
bot_id: BotId::new_from_uuid(macro_uuid::generate_uuid_v7()),
origin: AnnounceOrigin {
+ reuse_origin_message: false,
parent: MessageParent::Channel(macro_uuid::Uuid::from_u128(0xAA)),
thread_id: macro_uuid::Uuid::from_u128(0xAB),
message_id: macro_uuid::Uuid::from_u128(0xAC),
@@ -4323,7 +4350,7 @@ async fn codex_channel_mention_provisions_egress_without_advertising_mcp() {
servers: Vec::new(),
},
};
- command.origin.content = "@codex inspect the repository".into();
+ mention_origin_mut(&mut command).content = "@codex inspect the repository".into();
let id = AgentSessionId::new();
let open = service.execute(id, HarnessCommand::Open(command));
let drive = async {
diff --git a/crates/agent_harness/src/domain/service/test/chat_reply.rs b/crates/agent_harness/src/domain/service/test/chat_reply.rs
index dcdc7b4f8d..f8eddaaf01 100644
--- a/crates/agent_harness/src/domain/service/test/chat_reply.rs
+++ b/crates/agent_harness/src/domain/service/test/chat_reply.rs
@@ -4,7 +4,7 @@
//! is what the domain asked of it and when.
use super::*;
-use crate::domain::model::{ReplyOutcome, ResolvedReply};
+use crate::domain::model::{ReplyOutcome, ResolvedReply, TaskAssignmentOrigin};
use crate::domain::notifications::PlannedNotification;
/// A mention of a bot whose sessions the in-memory runtime serves.
@@ -15,6 +15,52 @@ fn chat_open_command() -> OpenSession {
command
}
+fn assignment_open_command() -> OpenSession {
+ let mut command = chat_open_command();
+ command.origin = SessionOrigin::TaskAssignment(TaskAssignmentOrigin {
+ parent: messages::domain::models::MessageParent::parse("document", "task-1").unwrap(),
+ discussion_id: macro_uuid::generate_uuid_v7(),
+ actor: sender(),
+ prompt: "Private assignment instructions".to_owned(),
+ });
+ command
+}
+
+#[tokio::test]
+async fn revoked_task_access_blocks_assignment_before_provisioning() {
+ let (service, repo, containers, announcer, _) = harness_with_edges(
+ PromptContextMock::unauthorized("task access revoked"),
+ PromptComposerMock::default(),
+ );
+ let id = AgentSessionId::new();
+ let result = service
+ .execute(id, HarnessCommand::Open(assignment_open_command()))
+ .await;
+ assert!(matches!(result, Err(HarnessError::PromptContext(_))));
+ assert!(repo.get(id).await.is_err());
+ assert_eq!(containers.spawned(), 0);
+ assert!(announcer.announced().is_empty());
+ assert!(service.inner.egress.provisioned().is_empty());
+}
+
+#[tokio::test]
+async fn task_assignment_keeps_the_coder_staff_gate() {
+ let (service, repo, containers, announcer, _) = harness();
+ let mut command = assignment_open_command();
+ command.bot_id = bot_id::MACRO_CODER_BOT_ID;
+ command.runtime.kind = AgentKind::SandboxedCoder;
+ let id = AgentSessionId::new();
+ assert!(
+ service
+ .execute(id, HarnessCommand::Open(command))
+ .await
+ .is_err()
+ );
+ assert!(repo.get(id).await.is_err());
+ assert_eq!(containers.spawned(), 0);
+ assert!(announcer.announced().is_empty());
+}
+
/// Open a chat session and leave its first turn running.
async fn chat_session_with_a_running_turn(
service: &TestHarness,
@@ -266,7 +312,7 @@ async fn a_persona_that_chose_to_chat_gets_a_reply_on_a_coding_runtime() {
let id = AgentSessionId::new();
let mut command = open_command();
command.bot_id = bot_id::MACRO_CODER_BOT_ID;
- command.origin.sender = staff_sender();
+ mention_origin_mut(&mut command).sender = staff_sender();
let container = session_with_a_running_turn(&service, &containers, id, command).await;
let agent = container.agent();
@@ -406,3 +452,29 @@ mod elicitation {
);
}
}
+
+#[tokio::test]
+async fn task_assignment_reuses_the_agent_root_and_delivers_its_private_prompt() {
+ let ((service, _, containers, announcer, _), turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let command = assignment_open_command();
+ let root_id = command.origin.announcement().message_id;
+ let container =
+ session_with_a_running_turn(&service, &containers, AgentSessionId::new(), command).await;
+ let announced = announcer.announced();
+ assert_eq!(announced.len(), 1);
+ assert!(announced[0].reuse_origin_message);
+ assert_eq!(announced[0].origin_message_id, root_id);
+ assert!(
+ announced[0]
+ .prompted_content
+ .contains("Private assignment instructions")
+ );
+ says(&container.agent(), "Task completed.");
+ container.agent().completes_prompt().await;
+ turns.lifecycle_published(4).await;
+ assert_eq!(
+ one_resolved(&announcer).outcome,
+ ReplyOutcome::Answered("Task completed.".to_owned())
+ );
+}
diff --git a/crates/agent_harness/src/domain/trigger_router.rs b/crates/agent_harness/src/domain/trigger_router.rs
index 1211cd9c4f..534368a44c 100644
--- a/crates/agent_harness/src/domain/trigger_router.rs
+++ b/crates/agent_harness/src/domain/trigger_router.rs
@@ -2,7 +2,7 @@
use agent_session::domain::model::AgentSessionId;
use agent_trigger::domain::broker_events::{
- AgentTriggerTopicEvent, OpeningMention, SessionMessage,
+ AgentTriggerTopicEvent, NewAgentSessionEvent, OpeningMention, SessionMessage,
};
use bot_id::BotId;
@@ -10,7 +10,7 @@ use agent_runtime_protocol::domain::action::AgentAction;
use super::model::{
AgentKind, AgentRuntimeConfig, AnnounceOrigin, AnnouncePrompt, DeliverAction, HarnessCommand,
- MentionOrigin, OpenSession, StaticFileLinks,
+ MentionOrigin, OpenSession, SessionOrigin, StaticFileLinks, TaskAssignmentOrigin,
};
/// What one trigger event asks this deployment to do.
@@ -57,6 +57,24 @@ pub fn route_agent_trigger(
links: &StaticFileLinks,
) -> Result<RoutedTrigger, Skipped> {
match event {
+ AgentTriggerTopicEvent::New(NewAgentSessionEvent::AssignedToTask(assigned)) => {
+ let Some(runtime) = runtime.filter(|runtime| runtime.kind.is_managed()) else {
+ return Err(Skipped::ForeignBot);
+ };
+ Ok(RoutedTrigger::Command(
+ AgentSessionId::new(),
+ HarnessCommand::Open(OpenSession {
+ bot_id: assigned.bot_id,
+ runtime,
+ origin: SessionOrigin::TaskAssignment(TaskAssignmentOrigin {
+ parent: assigned.parent,
+ discussion_id: assigned.discussion_id,
+ actor: assigned.actor,
+ prompt: assigned.prompt,
+ }),
+ }),
+ ))
+ }
AgentTriggerTopicEvent::New(event) => {
let Some(OpeningMention { bot_id, message }) = event.mention() else {
return Err(Skipped::Unrecognized);
@@ -74,7 +92,7 @@ pub fn route_agent_trigger(
HarnessCommand::Open(OpenSession {
bot_id,
runtime,
- origin: MentionOrigin {
+ origin: SessionOrigin::Mention(MentionOrigin {
parent: message.parent,
// A top-level mention roots its own thread; a mention
// inside a thread answers into that thread.
@@ -83,7 +101,7 @@ pub fn route_agent_trigger(
sender,
content: message.content,
attachments: links.prompt_attachments(&message.attachments),
- },
+ }),
}),
))
}
@@ -98,6 +116,7 @@ pub fn route_agent_trigger(
return Err(Skipped::Unrecognized);
};
let origin = AnnounceOrigin {
+ reuse_origin_message: false,
parent: message.parent,
thread_id: message.thread_id.unwrap_or(message.message_id),
message_id: message.message_id,
diff --git a/crates/agent_harness/src/inbound/kafka/test.rs b/crates/agent_harness/src/inbound/kafka/test.rs
index 8a6f4b4660..baa0f47d44 100644
--- a/crates/agent_harness/src/inbound/kafka/test.rs
+++ b/crates/agent_harness/src/inbound/kafka/test.rs
@@ -1,8 +1,9 @@
use agent_runtime_protocol::domain::action::AgentAction;
use agent_session::domain::model::{AgentMcpServers, AgentSessionId};
use agent_trigger::domain::broker_events::{
- AgentBotMentionedEvent, AgentMentionedEvent, AgentTriggerTopicEvent, ChannelEventMetadata,
- ExistingAgentSessionEvent, NewAgentSessionEvent, ThreadEventMetadata, ThreadMessageKind,
+ AgentAssignedToTaskEvent, AgentBotMentionedEvent, AgentMentionedEvent, AgentTriggerTopicEvent,
+ ChannelEventMetadata, ExistingAgentSessionEvent, NewAgentSessionEvent, ThreadEventMetadata,
+ ThreadMessageKind,
};
use bot_id::{BotId, MACRO_CODER_BOT_ID};
use channel_sender::ChannelSender;
@@ -15,10 +16,20 @@ use messages::domain::events::MessagePostedMetadata;
use messages::domain::models::MessageParent;
use super::*;
-use crate::domain::model::{AgentKind, AgentRuntimeConfig, HarnessCommand, StaticFileLinks};
+use crate::domain::model::{
+ AgentKind, AgentRuntimeConfig, HarnessCommand, MentionOrigin, OpenSession, SessionOrigin,
+ StaticFileLinks,
+};
use agent_runtime_protocol::domain::action::PromptAttachment;
use channels::domain::broker_events::ChannelEventAttachment;
+fn mention_origin(open: &OpenSession) -> &MentionOrigin {
+ let SessionOrigin::Mention(origin) = &open.origin else {
+ panic!("expected a mention origin");
+ };
+ origin
+}
+
fn runtime(kind: AgentKind) -> Option<AgentRuntimeConfig> {
Some(AgentRuntimeConfig {
kind,
@@ -115,11 +126,11 @@ fn a_mention_for_our_bot_opens_a_session() {
assert_eq!(open.runtime.kind, AgentKind::InMemory);
assert_eq!(open.runtime.model, "configured-model");
assert_eq!(open.runtime.instructions, "configured instructions");
- assert_eq!(open.origin.message_id, Uuid::from_u128(2));
+ assert_eq!(mention_origin(&open).message_id, Uuid::from_u128(2));
// A top-level mention roots its own thread.
- assert_eq!(open.origin.thread_id, Uuid::from_u128(2));
- assert_eq!(open.origin.sender, user());
- assert_eq!(open.origin.content, "@claude fix the tests");
+ assert_eq!(mention_origin(&open).thread_id, Uuid::from_u128(2));
+ assert_eq!(mention_origin(&open).sender, user());
+ assert_eq!(mention_origin(&open).content, "@claude fix the tests");
}
#[test]
@@ -140,7 +151,7 @@ fn a_threaded_mention_answers_into_its_thread() {
else {
panic!("a new-session event should open");
};
- assert_eq!(open.origin.thread_id, thread);
+ assert_eq!(mention_origin(&open).thread_id, thread);
}
#[test]
@@ -286,8 +297,8 @@ fn a_document_mention_opens_and_follows_up_on_its_document() {
else {
panic!("a new-session event should open");
};
- assert_eq!(open.origin.parent, document());
- assert_eq!(open.origin.thread_id, Uuid::from_u128(2));
+ assert_eq!(mention_origin(&open).parent, document());
+ assert_eq!(mention_origin(&open).thread_id, Uuid::from_u128(2));
let followed =
AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Thread(ThreadEventMetadata {
@@ -305,6 +316,92 @@ fn a_document_mention_opens_and_follows_up_on_its_document() {
assert_eq!(prompt.origin.parent, document());
}
+fn assigned_to_task() -> AgentTriggerTopicEvent {
+ AgentTriggerTopicEvent::New(NewAgentSessionEvent::AssignedToTask(
+ AgentAssignedToTaskEvent {
+ bot_id: BotId::TEST_A,
+ parent: document(),
+ discussion_id: Uuid::from_u128(2),
+ actor: user(),
+ prompt: "Complete the assigned task".to_owned(),
+ },
+ ))
+}
+
+#[test]
+fn assigning_a_managed_agent_opens_on_the_task_discussion() {
+ let event = assigned_to_task();
+ assert_eq!(agent_trigger_bot_id(&event), Some(BotId::TEST_A));
+ let RoutedTrigger::Command(_, HarnessCommand::Open(open)) =
+ route_agent_trigger(event, runtime(AgentKind::InMemory), &links())
+ .expect("a managed assignment opens a session")
+ else {
+ panic!("an assignment should open a session");
+ };
+ assert_eq!(open.bot_id, BotId::TEST_A);
+ let SessionOrigin::TaskAssignment(origin) = open.origin else {
+ panic!("an assignment must retain its own origin");
+ };
+ assert_eq!(origin.parent, document());
+ assert_eq!(origin.discussion_id, Uuid::from_u128(2));
+ assert_eq!(origin.actor, user());
+ assert_eq!(origin.prompt, "Complete the assigned task");
+}
+
+#[test]
+fn assigning_an_external_agent_leaves_session_creation_to_its_runtime() {
+ assert_eq!(
+ route_agent_trigger(assigned_to_task(), runtime(AgentKind::External), &links(),)
+ .unwrap_err(),
+ Skipped::ForeignBot,
+ );
+}
+
+#[test]
+fn task_discussion_followups_keep_the_managed_and_external_session_origin() {
+ let thread_id = Uuid::from_u128(7);
+ let message_id = Uuid::from_u128(8);
+ let followed =
+ AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Thread(ThreadEventMetadata {
+ bot_id: BotId::TEST_A,
+ session_id: AgentSessionId::TEST_A,
+ kind: ThreadMessageKind::MentionThread,
+ message: MessagePostedMetadata {
+ message_id,
+ thread_id: Some(thread_id),
+ root_id: thread_id,
+ content: "Include a regression test".to_owned(),
+ ..document_message(ChannelSender::new_from_user(user()))
+ },
+ }));
+ let RoutedTrigger::Command(session_id, HarnessCommand::Deliver(deliver)) =
+ route_agent_trigger(followed.clone(), runtime(AgentKind::InMemory), &links())
+ .expect("a managed follow-up delivers")
+ else {
+ panic!("a managed follow-up should deliver");
+ };
+ assert_eq!(session_id, AgentSessionId::TEST_A);
+ assert_eq!(
+ deliver.action,
+ AgentAction::prompt("Include a regression test")
+ );
+ let origin = deliver.announce.expect("a task follow-up announces");
+ assert_eq!(origin.parent, document());
+ assert_eq!(origin.thread_id, thread_id);
+ assert_eq!(origin.message_id, message_id);
+
+ let RoutedTrigger::Announce(session_id, prompt) =
+ route_agent_trigger(followed, runtime(AgentKind::External), &links())
+ .expect("an external follow-up announces")
+ else {
+ panic!("an external follow-up should announce");
+ };
+ assert_eq!(session_id, AgentSessionId::TEST_A);
+ assert_eq!(prompt.origin.parent, document());
+ assert_eq!(prompt.origin.thread_id, thread_id);
+ assert_eq!(prompt.origin.message_id, message_id);
+}
+
#[test]
fn any_user_can_follow_up_to_their_cursor_session() {
let user = MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id");
@@ -388,7 +485,7 @@ fn a_mention_with_attached_files_opens_with_them_as_prompt_attachments() {
panic!("a new-session event should open");
};
assert_eq!(
- open.origin.attachments,
+ mention_origin(&open).attachments,
vec![
PromptAttachment::new(
format!("https://static.example/file/{}", Uuid::from_u128(0x10)),
diff --git a/crates/agent_harness/src/outbound/channel_announcer.rs b/crates/agent_harness/src/outbound/channel_announcer.rs
index 12d04c8fb8..c22e70f0a7 100644
--- a/crates/agent_harness/src/outbound/channel_announcer.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer.rs
@@ -220,7 +220,9 @@ impl<Access: EntityAccessService> SessionAnnouncer for MessageAnnouncer<Access>
let content = if announcement.is_coding {
self.lexical
.compose_agent_announcement(
- &announcement_reply_target(&announcement),
+ (!announcement.reuse_origin_message)
+ .then(|| announcement_reply_target(&announcement))
+ .as_ref(),
&announcement_chip(&announcement),
)
.await
@@ -233,6 +235,23 @@ impl<Access: EntityAccessService> SessionAnnouncer for MessageAnnouncer<Access>
.await
}
.map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
+ if announcement.reuse_origin_message {
+ self.messages
+ .patch(
+ access,
+ announcement.origin_message_id,
+ MessagePatch {
+ content: Some(content),
+ notification_policy: PatchMessageNotificationPolicy::Default,
+ ..Default::default()
+ },
+ )
+ .await
+ .map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
+ return Ok(AnnouncedMessage {
+ message_id: announcement.origin_message_id,
+ });
+ }
let posted = self
.messages
.post(
@@ -319,6 +338,21 @@ impl<Access: EntityAccessService> SessionAnnouncer for MessageAnnouncer<Access>
.compose_agent_connection_prompt(&connection_prompt(declined.blocker))
.await
.map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
+ if declined.origin.reuse_origin_message {
+ self.messages
+ .patch(
+ access,
+ declined.origin.message_id,
+ MessagePatch {
+ content: Some(content),
+ notification_policy: PatchMessageNotificationPolicy::NotifyAsPostedMessage,
+ ..Default::default()
+ },
+ )
+ .await
+ .map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
+ return Ok(());
+ }
self.messages
.post(
access,
diff --git a/crates/agent_harness/src/outbound/channel_announcer/test.rs b/crates/agent_harness/src/outbound/channel_announcer/test.rs
index 8c580c2016..48e9d5b741 100644
--- a/crates/agent_harness/src/outbound/channel_announcer/test.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer/test.rs
@@ -6,6 +6,7 @@ use bot_id::BotId;
fn announcement() -> SessionAnnouncement {
SessionAnnouncement {
+ reuse_origin_message: false,
bot_id: BotId::TEST_A,
is_coding: true,
session_id: agent_session::domain::model::AgentSessionId::TEST_A,
diff --git a/crates/agent_harness/src/outbound/channel_prompt_context/test.rs b/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
index 34d7508154..865f6ddf3c 100644
--- a/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
+++ b/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
@@ -75,6 +75,7 @@ fn actor() -> MacroUserIdStr<'static> {
}
fn origin() -> AnnounceOrigin {
AnnounceOrigin {
+ reuse_origin_message: false,
parent: MessageParent::parse("document", "doc").unwrap(),
thread_id: Uuid::from_u128(1),
message_id: Uuid::from_u128(2),
@@ -373,6 +374,7 @@ async fn a_channel_thread_reply_is_about_its_thread_not_the_latest_message() {
20,
);
let origin = AnnounceOrigin {
+ reuse_origin_message: false,
parent: parent.clone(),
thread_id: calendar.id,
message_id: prompt.id,
@@ -474,6 +476,7 @@ async fn a_top_level_channel_prompt_replies_to_nothing_and_ends_the_channel() {
3,
);
let origin = AnnounceOrigin {
+ reuse_origin_message: false,
parent: parent.clone(),
thread_id: prompt.id,
message_id: prompt.id,
@@ -539,6 +542,7 @@ async fn a_quote_reply_carries_the_quoted_message_even_outside_the_window() {
30,
);
let origin = AnnounceOrigin {
+ reuse_origin_message: false,
parent: parent.clone(),
thread_id: prompt.id,
message_id: prompt.id,
@@ -598,6 +602,7 @@ async fn a_quote_from_another_conversation_travels_as_its_preview() {
30,
);
let origin = AnnounceOrigin {
+ reuse_origin_message: false,
parent: parent.clone(),
thread_id: prompt.id,
message_id: prompt.id,
@@ -674,6 +679,7 @@ async fn a_long_thread_keeps_its_root_and_the_messages_nearest_the_prompt() {
.collect();
let prompt = replies.last().unwrap().clone();
let origin = AnnounceOrigin {
+ reuse_origin_message: false,
parent: parent.clone(),
thread_id: root.id,
message_id: prompt.id,
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index 096b509d27..b921590f3a 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -242,6 +242,8 @@ pub async fn persona_for_owner<Bots: BotDirectory>(
/// where the bot can already post.
#[derive(Debug, Clone)]
pub struct SessionThread {
+ /// Update a reserved bot response for a task assignment.
+ pub reuse_origin_message: bool,
/// Channel or document the mentioning message was posted in.
pub parent: messages::domain::models::MessageParent,
/// Thread the session belongs to.
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index aa0fb84086..ab1e5dae45 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -1615,6 +1615,9 @@ pub struct CreateAgentSessionRequest {
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreateSessionThread {
+ /// Update the existing bot response reserved by a task assignment.
+ #[serde(default)]
+ pub reuse_origin_message: bool,
/// Entity the mentioning message was posted in.
#[serde(default)]
pub parent: Option<messages::domain::models::MessageParent>,
@@ -2100,6 +2103,7 @@ pub async fn create_agent_session_handler<
.map(messages::domain::models::MessageParent::Channel))
.ok_or(CreateSessionApiError::ThreadParentRequired)?;
Ok::<_, CreateSessionApiError>(SessionThread {
+ reuse_origin_message: thread.reuse_origin_message,
parent,
thread_id: thread.thread_id.unwrap_or(thread.message_id),
message_id: thread.message_id,
diff --git a/crates/agent_trigger/Cargo.toml b/crates/agent_trigger/Cargo.toml
index 24ace5c8bb..fbeb8955d8 100644
--- a/crates/agent_trigger/Cargo.toml
+++ b/crates/agent_trigger/Cargo.toml
@@ -9,7 +9,7 @@ version = "0.1.0"
# models_search → models_soup → notification → rdkafka, and the self-hosted
# daemon only needs domain events from this crate. Services that construct
# the adapters enable this; do not add it to coding_agent_worker.
-outbound = ["dep:agent", "dep:ai_usage", "dep:async-trait", "dep:lexical_client", "dep:sqlx", "dep:static_file", "channels/ports"]
+outbound = ["dep:agent", "dep:ai_usage", "dep:async-trait", "dep:document_storage_service_client", "dep:document_sub_type", "dep:lexical_client", "dep:sqlx", "dep:static_file", "channels/ports"]
[dependencies]
agent = { path = "../agent", optional = true }
@@ -17,6 +17,8 @@ agent_session = { path = "../agent_session", default-features = false }
ai_usage = { path = "../ai_usage", optional = true }
anyhow = { workspace = true }
bot_id = { path = "../bot_id" }
+document_storage_service_client = { path = "../document_storage_service_client", optional = true }
+document_sub_type = { path = "../document_sub_type", optional = true }
entity_access = { path = "../entity_access", default-features = false, features = ["ports"] }
bots = { path = "../bots", default-features = false, features = ["ports"] }
lexical_client = { path = "../lexical_client", optional = true }
@@ -32,6 +34,9 @@ macro_user_id = { path = "../macro_user_id" }
channel_sender = { path = "../channel_sender" }
macro_uuid = { path = "../macro_uuid" }
messages = { path = "../messages", features = ["broker", "ports"] }
+properties = { path = "../properties", default-features = false }
+models_properties = { path = "../models_properties" }
+system_properties = { path = "../system_properties" }
# Domain vocabulary: channel-parent trigger events keep the channel-only post
# shape, and the channel topic's `message_posted` can still feed the trigger.
channels = { path = "../channels", default-features = false }
@@ -39,6 +44,7 @@ serde = { workspace = true }
sqlx = { workspace = true, optional = true }
strum = { workspace = true }
serde_json = { workspace = true }
+sha2 = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
tokio = { workspace = true, features = ["rt", "time"] }
diff --git a/crates/agent_trigger/src/domain/broker_events.rs b/crates/agent_trigger/src/domain/broker_events.rs
index 4e0df90154..b51e3e7542 100644
--- a/crates/agent_trigger/src/domain/broker_events.rs
+++ b/crates/agent_trigger/src/domain/broker_events.rs
@@ -58,6 +58,21 @@ pub struct AgentMentionedEvent {
pub message: MessagePostedMetadata,
}
+/// A session opened when a task is assigned to an agent.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct AgentAssignedToTaskEvent {
+ /// The agent assigned to the task.
+ pub bot_id: BotId,
+ /// Task whose discussion receives the response.
+ pub parent: MessageParent,
+ /// The single bot-authored root to update with the session response.
+ pub discussion_id: Uuid,
+ /// User who assigned the task and owns the resulting session.
+ pub actor: macro_user_id::user_id::MacroUserIdStr<'static>,
+ /// Private startup prompt, never posted as a discussion message.
+ pub prompt: String,
+}
+
/// A session somebody asked for from Macro itself - the composer - rather
/// than by mentioning the bot. Nothing was posted anywhere, so there is no
/// thread to announce into and no message to quote.
@@ -85,23 +100,25 @@ pub enum NewAgentSessionEvent {
TopLevelMentioned(AgentBotMentionedEvent),
/// Opened by a bot mention on a message parent other than a channel.
Mentioned(AgentMentionedEvent),
+ /// Opened by assigning the agent to a task, with a discussion to answer in.
+ AssignedToTask(AgentAssignedToTaskEvent),
/// Asked for from the composer, with no mention behind it. Consumers that
/// only know mentions see no [`OpeningMention`] here and skip it.
Requested(AgentSessionRequestedEvent),
}
-/// The mention a new-session event carries, whichever parent it was on.
+/// The opening discussion message carried by a mention.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpeningMention {
- /// The bot that was mentioned.
+ /// The bot that should answer.
pub bot_id: BotId,
- /// The mentioning message, with its parent.
+ /// The opening message, with its parent.
pub message: MessagePostedMetadata,
}
impl NewAgentSessionEvent {
- /// The mention this event carries; `None` for a shape this build does
- /// not recognise, which a consumer skips rather than routes.
+ /// The user-authored message behind a mention. Assignments and composer
+ /// requests carry no user discussion message and return `None`.
#[must_use]
pub fn mention(&self) -> Option<OpeningMention> {
match self {
@@ -113,7 +130,7 @@ impl NewAgentSessionEvent {
bot_id: mentioned.bot_id,
message: mentioned.message.clone(),
}),
- Self::Requested(_) => None,
+ Self::AssignedToTask(_) | Self::Requested(_) => None,
}
}
@@ -122,7 +139,7 @@ impl NewAgentSessionEvent {
pub fn requested(&self) -> Option<&AgentSessionRequestedEvent> {
match self {
Self::Requested(requested) => Some(requested),
- Self::TopLevelMentioned(_) | Self::Mentioned(_) => None,
+ Self::TopLevelMentioned(_) | Self::Mentioned(_) | Self::AssignedToTask(_) => None,
}
}
}
@@ -231,6 +248,7 @@ impl AgentTriggerTopicEvent {
#[must_use]
pub fn bot_id(&self) -> Option<BotId> {
match self {
+ Self::New(NewAgentSessionEvent::AssignedToTask(assigned)) => Some(assigned.bot_id),
Self::New(event) => event
.mention()
.map(|mention| mention.bot_id)
@@ -386,6 +404,7 @@ impl AgentSessionMacroEvent {
let bot_id = match &event {
NewAgentSessionEvent::TopLevelMentioned(mentioned) => mentioned.bot_id,
NewAgentSessionEvent::Mentioned(mentioned) => mentioned.bot_id,
+ NewAgentSessionEvent::AssignedToTask(assigned) => assigned.bot_id,
NewAgentSessionEvent::Requested(requested) => requested.bot_id,
};
Self::new(bot_id, AgentTriggerTopicEvent::New(event))
diff --git a/crates/agent_trigger/src/domain/broker_events/test.rs b/crates/agent_trigger/src/domain/broker_events/test.rs
index 2d22732cf4..35f27f9d94 100644
--- a/crates/agent_trigger/src/domain/broker_events/test.rs
+++ b/crates/agent_trigger/src/domain/broker_events/test.rs
@@ -140,6 +140,34 @@ fn parent_aware_events_name_their_parent_and_are_new_variants() {
assert_eq!(value["metadata"]["source"], "mentioned");
}
+#[test]
+fn task_assignment_round_trips_and_opens_on_its_discussion() {
+ let message = MessagePostedMetadata {
+ content: "Complete the assigned task".to_owned(),
+ ..posted(document(), None)
+ };
+ let assigned = NewAgentSessionEvent::AssignedToTask(AgentAssignedToTaskEvent {
+ bot_id: BotId::TEST_A,
+ parent: message.parent.clone(),
+ discussion_id: message.message_id,
+ actor: message.sender.as_user().unwrap().clone(),
+ prompt: message.content.clone(),
+ });
+ let published = AgentSessionMacroEvent::new_session(assigned.clone());
+ assert_eq!(published.key(), BotId::TEST_A.to_string());
+ assert_eq!(published.event().event.bot_id(), Some(BotId::TEST_A));
+ assert!(assigned.requested().is_none());
+ assert!(assigned.mention().is_none());
+
+ let value = serde_json::to_value(&published.event().event).expect("serialize assignment");
+ assert_eq!(value["event_type"], "agent_trigger.new");
+ assert_eq!(value["metadata"]["source"], "assigned_to_task");
+ assert_eq!(value["metadata"]["parent"]["type"], "document");
+ let decoded: AgentTriggerTopicEvent =
+ serde_json::from_value(value).expect("deserialize assignment");
+ assert_eq!(decoded, published.event().event);
+}
+
/// Consumers read both shapes through one view: the channel shape converts
/// to a channel parent, the parent-aware shape passes through.
#[test]
diff --git a/crates/agent_trigger/src/domain/mod.rs b/crates/agent_trigger/src/domain/mod.rs
index 5e1e13131d..618ead0cea 100644
--- a/crates/agent_trigger/src/domain/mod.rs
+++ b/crates/agent_trigger/src/domain/mod.rs
@@ -2,5 +2,6 @@ pub mod broker_events;
pub mod processing;
pub mod service;
pub mod sources;
+pub mod task_assignment;
pub mod thread_window;
pub mod yield_event;
diff --git a/crates/agent_trigger/src/domain/processing.rs b/crates/agent_trigger/src/domain/processing.rs
index 6f2f14ee0b..21700ead01 100644
--- a/crates/agent_trigger/src/domain/processing.rs
+++ b/crates/agent_trigger/src/domain/processing.rs
@@ -40,6 +40,9 @@ pub trait ChannelTypeLookup: Send + Sync + 'static {
/// Failure while evaluating or publishing one message event.
#[derive(Debug, thiserror::Error)]
pub enum ProcessMessageEventError {
+ /// The assignment's discussion could not be read or created.
+ #[error("failed to open the task assignment discussion: {0}")]
+ Discussion(#[source] messages::domain::ports::MessageError),
/// Trigger evaluation could not read its session or bot context.
#[error(transparent)]
Evaluate(#[from] AgentSessionError),
diff --git a/crates/agent_trigger/src/domain/service.rs b/crates/agent_trigger/src/domain/service.rs
index b90e235d52..d25afc0e08 100644
--- a/crates/agent_trigger/src/domain/service.rs
+++ b/crates/agent_trigger/src/domain/service.rs
@@ -219,6 +219,16 @@ where
return Ok(false);
};
+ self.agent_is_available_for(&caller, &posted.parent, bot_id)
+ .await
+ }
+
+ async fn agent_is_available_for(
+ &self,
+ caller: &MacroUserIdStr<'static>,
+ parent: &MessageParent,
+ bot_id: BotId,
+ ) -> Result<bool> {
if let Some(agent) = self.bots.get_agent(bot_id).await? {
if !agent.bot.has_agent {
return Ok(false);
@@ -226,23 +236,23 @@ where
// Channel selection restricts channel placement. Discussion invocation
// requires ownership or team membership and is independently bounded
// by the invoking user's parent access at execution time.
- if posted.parent.is_discussion() {
- return self.owner_allows(&caller, agent.bot.owner.as_ref()).await;
+ if parent.is_discussion() {
+ return self.owner_allows(caller, agent.bot.owner.as_ref()).await;
}
- let MessageParent::Channel(channel_id) = posted.parent else {
+ let MessageParent::Channel(channel_id) = parent else {
unreachable!()
};
return match agent.channel_scope {
AgentChannelScope::All => match agent.bot.owner {
Some(BotOwner::User { user_id }) => Ok(user_id == caller.as_ref()),
Some(BotOwner::Team { team_id }) => {
- self.teams.user_has_team(caller, team_id).await
+ self.teams.user_has_team(caller.clone(), team_id).await
}
None => Ok(false),
},
AgentChannelScope::Selected => {
self.channels
- .bot_active_in_channel(channel_id, bot_id)
+ .bot_active_in_channel(*channel_id, bot_id)
.await
}
};
@@ -256,7 +266,7 @@ where
}
match bot.kind {
BotKind::System => Ok(true),
- BotKind::Owned => match &posted.parent {
+ BotKind::Owned => match parent {
MessageParent::Channel(channel_id) => {
self.channels
.bot_active_in_channel(*channel_id, bot_id)
@@ -266,12 +276,40 @@ where
| MessageParent::Initiative(_)
| MessageParent::CrmCompany(_)
| MessageParent::CrmContact(_) => {
- self.owner_allows(&caller, bot.owner.as_ref()).await
+ self.owner_allows(caller, bot.owner.as_ref()).await
}
},
}
}
+ /// Recheck task access and agent ownership before an assignment starts work.
+ pub async fn authorize_task_assignment(
+ &self,
+ caller: &MacroUserIdStr<'static>,
+ parent: &MessageParent,
+ root_id: Uuid,
+ bot_id: BotId,
+ ) -> Result<Option<AuthorizedInvocation>> {
+ if !matches!(parent, MessageParent::Document(_))
+ || !self.agent_is_available_for(caller, parent, bot_id).await?
+ {
+ return Ok(None);
+ }
+ self.history
+ .authorize_invocation(caller, parent, root_id)
+ .await
+ }
+
+ /// Whether this assignment's discussion already has a session for the agent.
+ pub async fn assignment_has_session(&self, root_id: Uuid, bot_id: BotId) -> Result<bool> {
+ Ok(matches!(
+ self.sessions
+ .find_for_thread(Some(root_id), Some(bot_id))
+ .await?,
+ ThreadSession::CreatedFromThread(_)
+ ))
+ }
+
async fn owner_allows(
&self,
caller: &MacroUserIdStr<'static>,
diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rs
index 6c28050a2c..d64cef576c 100644
--- a/crates/agent_trigger/src/domain/service/test.rs
+++ b/crates/agent_trigger/src/domain/service/test.rs
@@ -1,5 +1,7 @@
use super::*;
+mod task_assignment;
+
use agent_session::domain::error::AgentSessionError;
use agent_session::domain::model::{AgentSession, AgentSessionId, SessionStatus, ThreadSession};
use agent_session::domain::ports::MockAgentSessionRepo;
diff --git a/crates/agent_trigger/src/domain/service/test/task_assignment.rs b/crates/agent_trigger/src/domain/service/test/task_assignment.rs
new file mode 100644
index 0000000000..cabe69c83d
--- /dev/null
+++ b/crates/agent_trigger/src/domain/service/test/task_assignment.rs
@@ -0,0 +1,175 @@
+use super::*;
+
+fn task() -> MessageParent {
+ MessageParent::parse("document", "assigned-task").unwrap()
+}
+
+fn assignment_service(facts: impl Into<FactMocks>, history: MockThreadHistory) -> TestService {
+ let (replies, judge) = no_implicit();
+ service_reading(MockAgentSessionRepo::new(), facts, replies, judge, history)
+}
+
+fn allowed_history() -> MockThreadHistory {
+ let mut history = MockThreadHistory::new();
+ history
+ .expect_authorize_invocation()
+ .once()
+ .withf(|caller, parent, root| {
+ caller == &user() && parent == &task() && *root == Uuid::from_u128(3)
+ })
+ .returning(allow_invocation);
+ history
+}
+
+#[tokio::test]
+async fn owners_can_assign_their_agents_without_channel_participation() {
+ for scope in [AgentChannelScope::All, AgentChannelScope::Selected] {
+ let mut bots = MockAgentBotLookup::new();
+ bots.expect_get_agent()
+ .once()
+ .with(mockall::predicate::eq(BotId::TEST_A))
+ .return_once(move |id| {
+ Box::pin(async move {
+ let mut agent = private_agent(id);
+ agent.channel_scope = scope;
+ Ok(Some(agent))
+ })
+ });
+ let service = assignment_service(bots, allowed_history());
+
+ let invocation = service
+ .authorize_task_assignment(&user(), &task(), Uuid::from_u128(3), BotId::TEST_A)
+ .await
+ .unwrap()
+ .unwrap();
+
+ assert_eq!(invocation.root_id, Uuid::from_u128(3));
+ assert_eq!(invocation.access.entity().entity_id, "assigned-task");
+ }
+}
+
+#[tokio::test]
+async fn another_users_private_agent_cannot_be_assigned() {
+ let mut bots = MockAgentBotLookup::new();
+ bots.expect_get_agent()
+ .once()
+ .return_once(|id| Box::pin(async move { Ok(Some(private_agent(id))) }));
+ let service = assignment_service(bots, MockThreadHistory::new());
+
+ assert!(
+ service
+ .authorize_task_assignment(
+ &MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ &task(),
+ Uuid::from_u128(3),
+ BotId::TEST_A,
+ )
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
+
+#[tokio::test]
+async fn team_agents_require_current_team_membership() {
+ for member in [true, false] {
+ let team_id = Uuid::from_u128(99);
+ let mut facts = FactMocks::from(MockAgentBotLookup::new());
+ facts.bots.expect_get_agent().once().return_once(move |id| {
+ Box::pin(async move {
+ Ok(Some(agent_with(
+ id,
+ BotOwner::Team { team_id },
+ AgentChannelScope::Selected,
+ )))
+ })
+ });
+ facts
+ .teams
+ .expect_user_has_team()
+ .once()
+ .with(
+ mockall::predicate::eq(user()),
+ mockall::predicate::eq(team_id),
+ )
+ .return_once(move |_, _| Box::pin(async move { Ok(member) }));
+ let history = if member {
+ allowed_history()
+ } else {
+ MockThreadHistory::new()
+ };
+ let service = assignment_service(facts, history);
+
+ assert_eq!(
+ service
+ .authorize_task_assignment(&user(), &task(), Uuid::from_u128(3), BotId::TEST_A)
+ .await
+ .unwrap()
+ .is_some(),
+ member
+ );
+ }
+}
+
+#[tokio::test]
+async fn system_agents_can_be_assigned_without_membership_checks() {
+ let mut bots = MockAgentBotLookup::new();
+ bots.expect_get_agent()
+ .once()
+ .return_once(|_| Box::pin(async { Ok(None) }));
+ bots.expect_get_bot()
+ .once()
+ .return_once(|id| Box::pin(async move { Ok(Some(system_bot(id))) }));
+ let service = assignment_service(bots, allowed_history());
+
+ assert!(
+ service
+ .authorize_task_assignment(&user(), &task(), Uuid::from_u128(3), BotId::TEST_A)
+ .await
+ .unwrap()
+ .is_some()
+ );
+}
+
+#[tokio::test]
+async fn revoked_task_access_prevents_an_assignment_from_starting() {
+ let mut bots = MockAgentBotLookup::new();
+ bots.expect_get_agent()
+ .once()
+ .return_once(|id| Box::pin(async move { Ok(Some(private_agent(id))) }));
+ let mut history = MockThreadHistory::new();
+ history
+ .expect_authorize_invocation()
+ .once()
+ .withf(|caller, parent, root| {
+ caller == &user() && parent == &task() && *root == Uuid::from_u128(3)
+ })
+ .return_once(|_, _, _| Box::pin(async { Ok(None) }));
+ let service = assignment_service(bots, history);
+
+ assert!(
+ service
+ .authorize_task_assignment(&user(), &task(), Uuid::from_u128(3), BotId::TEST_A)
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
+
+#[tokio::test]
+async fn assignments_cannot_target_channels() {
+ let service = assignment_service(MockAgentBotLookup::new(), MockThreadHistory::new());
+
+ assert!(
+ service
+ .authorize_task_assignment(
+ &user(),
+ &MessageParent::Channel(Uuid::from_u128(1)),
+ Uuid::from_u128(3),
+ BotId::TEST_A,
+ )
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
diff --git a/crates/agent_trigger/src/domain/sources.rs b/crates/agent_trigger/src/domain/sources.rs
index 7b1b8c9614..3015dc78c5 100644
--- a/crates/agent_trigger/src/domain/sources.rs
+++ b/crates/agent_trigger/src/domain/sources.rs
@@ -9,16 +9,19 @@
//! until the producer retires it. Only one source is read at a time: every
//! channel post is published on both topics, so reading both would evaluate
//! every channel mention twice.
+//! Both configurations also read `macro.properties` for task assignments.
#[cfg(test)]
mod test;
use super::broker_events::posted_from_channel_event;
use super::processing::TriggerInput;
+use super::task_assignment::TaskAssignment;
use channels::domain::broker_events::{ChannelMacroEvent, ChannelTopicEvent};
use macro_event_broker::{MacroEvent as _, MacroEventCollection};
use macro_uuid::Uuid;
use messages::outbound::broker::{MessageMacroEvent, MessageTopicEvent};
+use properties::domain::events::{PropertyMacroEvent, PropertyTopicEvent};
use serde::Deserialize;
/// Which topic a trigger consumer subscribes to.
@@ -46,8 +49,8 @@ impl std::str::FromStr for TriggerEventSource {
}
}
-macro_event_broker::declare_topics!(MessageTriggerEvents: MessageMacroEvent);
-macro_event_broker::declare_topics!(ChannelTriggerEvents: ChannelMacroEvent);
+macro_event_broker::declare_topics!(MessageTriggerEvents: MessageMacroEvent, PropertyMacroEvent);
+macro_event_broker::declare_topics!(ChannelTriggerEvents: ChannelMacroEvent, PropertyMacroEvent);
/// A decoded broker record from one trigger source.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -59,6 +62,8 @@ pub struct DecodedTrigger {
/// The committed post, when the record was one; other facts on the topic
/// carry no trigger.
pub posted: Option<TriggerInput>,
+ /// Newly assigned agents, independent of the configured message source.
+ pub assignment: Option<TaskAssignment>,
}
/// A topic collection whose records may carry a committed post.
@@ -74,7 +79,10 @@ impl TriggerEvents for MessageTriggerEvents {
const SOURCE: TriggerEventSource = TriggerEventSource::Messages;
fn into_trigger(self) -> DecodedTrigger {
- let Self::MessageMacroEvent(event) = self;
+ let event = match self {
+ Self::MessageMacroEvent(event) => event,
+ Self::PropertyMacroEvent(event) => return property_trigger(event),
+ };
let envelope = event.event();
let (event_type, posted) = match &envelope.event {
MessageTopicEvent::Posted(posted) => (
@@ -94,6 +102,7 @@ impl TriggerEvents for MessageTriggerEvents {
event_id: envelope.event_id,
event_type,
posted,
+ assignment: None,
}
}
}
@@ -102,7 +111,10 @@ impl TriggerEvents for ChannelTriggerEvents {
const SOURCE: TriggerEventSource = TriggerEventSource::Channels;
fn into_trigger(self) -> DecodedTrigger {
- let Self::ChannelMacroEvent(event) = self;
+ let event = match self {
+ Self::ChannelMacroEvent(event) => event,
+ Self::PropertyMacroEvent(event) => return property_trigger(event),
+ };
let envelope = event.event();
let posted = match &envelope.event {
ChannelTopicEvent::MessagePosted(posted) => Some(TriggerInput {
@@ -115,10 +127,34 @@ impl TriggerEvents for ChannelTriggerEvents {
event_id: envelope.event_id,
event_type: channel_event_type(&envelope.event),
posted,
+ assignment: None,
}
}
}
+fn property_trigger(event: PropertyMacroEvent) -> DecodedTrigger {
+ let envelope = event.event();
+ let (event_type, assignment) = match &envelope.event {
+ PropertyTopicEvent::EntityPropertyUpdated(updated) => (
+ "entity_property.updated",
+ TaskAssignment::from_update(envelope.event_id, updated),
+ ),
+ PropertyTopicEvent::Created(_) => ("property.created", None),
+ PropertyTopicEvent::Deleted(_) => ("property.deleted", None),
+ PropertyTopicEvent::OptionCreated(_) => ("property_option.created", None),
+ PropertyTopicEvent::OptionUpdated(_) => ("property_option.updated", None),
+ PropertyTopicEvent::OptionDeleted(_) => ("property_option.deleted", None),
+ PropertyTopicEvent::EntityPropertyDeleted(_) => ("entity_property.deleted", None),
+ PropertyTopicEvent::EntityPropertiesCleared(_) => ("entity_properties.cleared", None),
+ };
+ DecodedTrigger {
+ event_id: envelope.event_id,
+ event_type,
+ posted: None,
+ assignment,
+ }
+}
+
/// The wire name of a channel topic event, as its serde tag spells it.
fn channel_event_type(event: &ChannelTopicEvent) -> &'static str {
match event {
diff --git a/crates/agent_trigger/src/domain/sources/test.rs b/crates/agent_trigger/src/domain/sources/test.rs
index 4ad14d61ee..f084f9a39a 100644
--- a/crates/agent_trigger/src/domain/sources/test.rs
+++ b/crates/agent_trigger/src/domain/sources/test.rs
@@ -159,9 +159,15 @@ fn the_message_source_carries_the_persisted_parent_through() {
}
#[test]
-fn each_source_reads_exactly_one_topic() {
- assert_eq!(MessageTriggerEvents::topics(), ["macro.messages"]);
- assert_eq!(ChannelTriggerEvents::topics(), ["macro.channels"]);
+fn each_source_reads_one_message_topic_and_properties() {
+ assert_eq!(
+ MessageTriggerEvents::topics(),
+ ["macro.messages", "macro.properties"]
+ );
+ assert_eq!(
+ ChannelTriggerEvents::topics(),
+ ["macro.channels", "macro.properties"]
+ );
assert_eq!(
"channels".parse::<TriggerEventSource>().unwrap(),
TriggerEventSource::Channels
diff --git a/crates/agent_trigger/src/domain/task_assignment.rs b/crates/agent_trigger/src/domain/task_assignment.rs
new file mode 100644
index 0000000000..e5bd3e5eeb
--- /dev/null
+++ b/crates/agent_trigger/src/domain/task_assignment.rs
@@ -0,0 +1,267 @@
+//! Start work for newly assigned agents in a task's discussion.
+
+use std::collections::HashSet;
+
+use agent_session::domain::error::Result as AgentResult;
+use agent_session::domain::ports::AgentSessionRepo;
+use bot_id::{BotId, BotIdStr};
+use macro_event_broker::MacroEventBroker;
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use messages::domain::{
+ api::MessageCommands,
+ models::{MessageAttribution, MessageParent, PostMessage, PostMessageNotificationPolicy},
+ service::MessageWrite,
+};
+use models_properties::{EntityType, service::property_value::PropertyValue};
+use properties::domain::events::EntityPropertyUpdatedMetadata;
+use system_properties::SystemPropertyKey;
+
+use super::{
+ broker_events::{AgentAssignedToTaskEvent, AgentSessionMacroEvent, NewAgentSessionEvent},
+ processing::ProcessMessageEventError,
+ service::{
+ AgentBotLookup, AgentTriggerService, ChannelParticipationLookup, ExplicitReplyExtractor,
+ ImplicitTriggerJudge, TeamMembershipLookup, ThreadHistory,
+ },
+};
+
+#[cfg(test)]
+mod test;
+
+/// Authorized task content supplied to every runtime, including those without tools.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TaskBrief {
+ /// Current task title.
+ pub title: String,
+ /// Current task description in Markdown.
+ pub markdown: String,
+}
+
+/// Reads the task through its owning service under a verified document capability.
+#[cfg_attr(test, mockall::automock)]
+pub trait TaskAssignmentContext: Send + Sync + 'static {
+ /// Missing or no-longer-task documents yield no work; read failures are retried.
+ fn task_brief(
+ &self,
+ access: entity_access::domain::models::EntityAccessReceipt<MessageWrite>,
+ ) -> impl Future<Output = AgentResult<Option<TaskBrief>>> + Send;
+}
+
+/// One committed assignment change, with only the newly assigned agents.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TaskAssignment {
+ /// The source event id identifies this assignment, including on replay.
+ pub event_id: Uuid,
+ /// Task document whose discussion receives the agent's replies.
+ pub parent: MessageParent,
+ /// User whose assignment starts the work.
+ pub actor: MacroUserIdStr<'static>,
+ /// Agents added by this change, in stable order.
+ pub bots: Vec<BotId>,
+}
+
+impl TaskAssignment {
+ /// Ignore other properties, human assignees, removals, and unchanged saves.
+ pub fn from_update(event_id: Uuid, updated: &EntityPropertyUpdatedMetadata) -> Option<Self> {
+ if updated.entity_type != EntityType::Task
+ || updated.property_definition_id != SystemPropertyKey::Assignees.uuid()
+ {
+ return None;
+ }
+ let previous = assigned_bots(updated.previous_value.as_ref());
+ let mut bots: Vec<_> = assigned_bots(updated.value.as_ref())
+ .difference(&previous)
+ .copied()
+ .collect();
+ bots.sort_by_key(ToString::to_string);
+ if bots.is_empty() {
+ return None;
+ }
+ Some(Self {
+ event_id,
+ parent: MessageParent::parse("document", &updated.entity_id).ok()?,
+ actor: updated
+ .actor_user_id
+ .clone()
+ .or_else(|| updated.on_behalf_of.clone())?,
+ bots,
+ })
+ }
+}
+
+fn assigned_bots(value: Option<&PropertyValue>) -> HashSet<BotId> {
+ let Some(PropertyValue::EntityRef(references)) = value else {
+ return HashSet::new();
+ };
+ references
+ .iter()
+ .filter(|reference| reference.entity_type == EntityType::User)
+ .filter_map(|reference| BotIdStr::parse_from_str(&reference.entity_id).ok())
+ .map(|id| id.bot_id())
+ .collect()
+}
+
+/// Open a real discussion before publishing a session trigger. The common
+/// harness then announces the session here and routes subsequent replies.
+pub async fn process_task_assignment<
+ Repo,
+ Bots,
+ Teams,
+ Channels,
+ Replies,
+ Judge,
+ History,
+ Broker,
+ Context,
+>(
+ trigger: &AgentTriggerService<Repo, Bots, Teams, Channels, Replies, Judge, History>,
+ publisher: &Broker,
+ messages: &dyn MessageCommands,
+ context: &Context,
+ assignment: &TaskAssignment,
+) -> Result<(), ProcessMessageEventError>
+where
+ Repo: AgentSessionRepo,
+ Bots: AgentBotLookup,
+ Teams: TeamMembershipLookup,
+ Channels: ChannelParticipationLookup,
+ Replies: ExplicitReplyExtractor,
+ Judge: ImplicitTriggerJudge,
+ History: ThreadHistory,
+ Broker: MacroEventBroker,
+ Context: TaskAssignmentContext,
+{
+ for &bot_id in &assignment.bots {
+ let Some(invocation) = trigger
+ .authorize_task_assignment(
+ &assignment.actor,
+ &assignment.parent,
+ assignment.event_id,
+ bot_id,
+ )
+ .await?
+ else {
+ continue;
+ };
+ let discussion_id = discussion_id(assignment.event_id, bot_id);
+ if trigger
+ .assignment_has_session(discussion_id, bot_id)
+ .await?
+ {
+ continue;
+ }
+ let Some(brief) = context.task_brief(invocation.access().clone()).await? else {
+ continue;
+ };
+ let Some(message) = assignment_discussion(
+ assignment,
+ bot_id,
+ discussion_id,
+ invocation.access().clone(),
+ messages,
+ )
+ .await?
+ else {
+ continue;
+ };
+ let event = AgentSessionMacroEvent::new_session(NewAgentSessionEvent::AssignedToTask(
+ AgentAssignedToTaskEvent {
+ bot_id,
+ parent: assignment.parent.clone(),
+ discussion_id: message.id,
+ actor: assignment.actor.clone(),
+ prompt: assignment_prompt(assignment, &brief),
+ },
+ ));
+ publisher
+ .send_event(&event)?
+ .await
+ .map_err(ProcessMessageEventError::PublishTask)??;
+ }
+ Ok(())
+}
+
+/// Derive one replay-stable UUIDv7 per assigned bot, retaining the event timestamp.
+/// The hashed random bits keep simultaneous agents in separate discussion threads.
+fn discussion_id(event_id: Uuid, bot_id: BotId) -> Uuid {
+ use sha2::{Digest, Sha256};
+ let hash = Sha256::new()
+ .chain_update(event_id.as_bytes())
+ .chain_update(bot_id.as_uuid().as_bytes())
+ .finalize();
+ let mut bytes = *event_id.as_bytes();
+ bytes[6..].copy_from_slice(&hash[..10]);
+ bytes[6] = (bytes[6] & 0x0f) | 0x70;
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
+ Uuid::from_bytes(bytes)
+}
+
+fn assignment_prompt(assignment: &TaskAssignment, brief: &TaskBrief) -> String {
+ // Keep the task ID available to agent runtimes in the private prompt. Escape tag delimiters in user-controlled titles.
+ let task_reference = serde_json::json!({
+ "documentId": assignment.parent.entity_id(),
+ "documentName": brief.title,
+ "blockName": "task",
+ "blockParams": {},
+ })
+ .to_string()
+ .replace('<', "\\u003c")
+ .replace('>', "\\u003e");
+ format!(
+ "{}\n\n<m-document-mention>{}</m-document-mention>\n\n{}",
+ include_str!("task_assignment/prompt.md").trim(),
+ task_reference,
+ brief.markdown,
+ )
+}
+
+async fn assignment_discussion(
+ assignment: &TaskAssignment,
+ bot_id: BotId,
+ discussion_id: Uuid,
+ access: entity_access::domain::models::EntityAccessReceipt<MessageWrite>,
+ commands: &dyn MessageCommands,
+) -> Result<Option<messages::domain::models::Message>, ProcessMessageEventError> {
+ use entity_access::domain::models::{BotReceiptScope, EntityAccessReceipt};
+ // Agent availability and the assigning user's capability were checked by
+ // authorize_task_assignment. The response spends that same capability.
+ let access = EntityAccessReceipt::try_new_bot(
+ bot_id.into(),
+ BotReceiptScope::User {
+ acting_user: assignment.actor.clone(),
+ },
+ access.entity().clone(),
+ *access.entity_permission(),
+ )
+ .map_err(|_| {
+ ProcessMessageEventError::Discussion(messages::domain::ports::MessageError::Forbidden)
+ })?;
+ let message = commands
+ .post_from_event(
+ access,
+ discussion_id,
+ PostMessage {
+ id: None,
+ attribution: MessageAttribution::ActingUser,
+ notification_policy: PostMessageNotificationPolicy::Silent,
+ content: "Working on this task…".to_owned(),
+ thread_id: None,
+ anchor: None,
+ mentions: Vec::new(),
+ attachments: Vec::new(),
+ nonce: None,
+ },
+ )
+ .await
+ .map_err(ProcessMessageEventError::Discussion)?;
+ // A replay must not resurrect a response the user deleted.
+ if message.deleted_at.is_some()
+ || message.parent != assignment.parent
+ || message.thread_id.is_some()
+ || message.sender_id.as_bot().map(|id| id.bot_id()) != Some(bot_id)
+ {
+ return Ok(None);
+ }
+ Ok(Some(message))
+}
diff --git a/crates/agent_trigger/src/domain/task_assignment/prompt.md b/crates/agent_trigger/src/domain/task_assignment/prompt.md
new file mode 100644
index 0000000000..bb7a8d1664
--- /dev/null
+++ b/crates/agent_trigger/src/domain/task_assignment/prompt.md
@@ -0,0 +1 @@
+You've been assigned the task below. Carry out the requested work and report your progress and results in this discussion. Ask here if you need clarification.
diff --git a/crates/agent_trigger/src/domain/task_assignment/test.rs b/crates/agent_trigger/src/domain/task_assignment/test.rs
new file mode 100644
index 0000000000..04eb74143d
--- /dev/null
+++ b/crates/agent_trigger/src/domain/task_assignment/test.rs
@@ -0,0 +1,392 @@
+use super::*;
+use crate::domain::sources::{ChannelTriggerEvents, MessageTriggerEvents, TriggerEvents};
+use chrono::Utc;
+use macro_event_broker::{Event, MacroEvent, MacroEventCollection};
+use messages::domain::ports::MessageError;
+use models_properties::EntityReference;
+use properties::domain::events::{PropertyMacroEvent, PropertyTopicEvent};
+
+fn brief() -> TaskBrief {
+ TaskBrief {
+ title: "Fix export".to_owned(),
+ markdown: "Include archived rows in CSV exports.".to_owned(),
+ }
+}
+
+fn value(ids: &[&str]) -> Option<PropertyValue> {
+ Some(PropertyValue::EntityRef(
+ ids.iter()
+ .map(|id| EntityReference::new(*id, EntityType::User))
+ .collect(),
+ ))
+}
+
+fn update() -> EntityPropertyUpdatedMetadata {
+ EntityPropertyUpdatedMetadata {
+ entity_property_id: Uuid::now_v7(),
+ entity_id: "task-1".to_owned(),
+ entity_type: EntityType::Task,
+ property_definition_id: SystemPropertyKey::Assignees.uuid(),
+ actor_user_id: Some(MacroUserIdStr::try_from_email("[email protected]").unwrap()),
+ actor: None,
+ on_behalf_of: None,
+ value: value(&["bot|00000000-0000-0000-0000-00000000b07a"]),
+ previous_value: None,
+ updated_at: Utc::now(),
+ }
+}
+
+#[test]
+fn creation_and_new_assignments_include_only_added_agents() {
+ let mut updated = update();
+ let event_id = Uuid::now_v7();
+ let assignment = TaskAssignment::from_update(event_id, &updated).unwrap();
+ assert_eq!(assignment.event_id, event_id);
+ assert_eq!(
+ assignment.parent,
+ MessageParent::parse("document", "task-1").unwrap()
+ );
+ assert_eq!(assignment.bots, vec![BotId::TEST_A]);
+
+ updated.previous_value = updated.value.clone();
+ updated.value = value(&[
+ "bot|00000000-0000-0000-0000-00000000b07a",
+ "bot|00000000-0000-0000-0000-00000000b07b",
+ "bot|00000000-0000-0000-0000-00000000b07b",
+ ]);
+ assert_eq!(
+ TaskAssignment::from_update(event_id, &updated)
+ .unwrap()
+ .bots,
+ vec![BotId::TEST_B]
+ );
+}
+
+#[test]
+fn unchanged_saves_removals_and_human_only_assignments_do_not_start_work() {
+ let mut updated = update();
+ updated.previous_value = updated.value.clone();
+ assert!(TaskAssignment::from_update(Uuid::now_v7(), &updated).is_none());
+ updated.value = None;
+ assert!(TaskAssignment::from_update(Uuid::now_v7(), &updated).is_none());
+ updated.value = value(&["macro|[email protected]", "bot|invalid"]);
+ assert!(TaskAssignment::from_update(Uuid::now_v7(), &updated).is_none());
+ updated.previous_value = None;
+ assert!(TaskAssignment::from_update(Uuid::now_v7(), &updated).is_none());
+}
+
+#[test]
+fn only_task_assignees_with_an_invoking_user_trigger() {
+ let mut updated = update();
+ updated.entity_type = EntityType::Document;
+ assert!(TaskAssignment::from_update(Uuid::now_v7(), &updated).is_none());
+ updated = update();
+ updated.property_definition_id = SystemPropertyKey::Status.uuid();
+ assert!(TaskAssignment::from_update(Uuid::now_v7(), &updated).is_none());
+ updated = update();
+ updated.actor_user_id = None;
+ assert!(TaskAssignment::from_update(Uuid::now_v7(), &updated).is_none());
+ updated.on_behalf_of = Some(MacroUserIdStr::try_from_email("[email protected]").unwrap());
+ assert_eq!(
+ TaskAssignment::from_update(Uuid::now_v7(), &updated)
+ .unwrap()
+ .actor,
+ updated.on_behalf_of.unwrap()
+ );
+}
+
+fn access(
+ assignment: &TaskAssignment,
+) -> entity_access::domain::models::EntityAccessReceipt<MessageWrite> {
+ use entity_access::domain::models::{
+ AccessLevel, Entity, EntityAccessReceipt, EntityPermission, EntityType,
+ };
+ EntityAccessReceipt::try_new_authenticated_user(
+ assignment.actor.clone(),
+ Entity {
+ entity_type: EntityType::Document,
+ entity_id: assignment.parent.entity_id(),
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit,
+ },
+ )
+ .unwrap()
+}
+
+fn discussion(assignment: &TaskAssignment) -> messages::domain::models::Message {
+ messages::domain::models::Message {
+ id: discussion_id(assignment.event_id, BotId::TEST_A),
+ parent: assignment.parent.clone(),
+ thread_id: None,
+ sender_id: channel_sender::ChannelSender::new_from_bot(BotId::TEST_A),
+ triggered_by: None,
+ bot_profile: None,
+ imported_author: None,
+ content: "Work on this task".to_owned(),
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ edited_at: None,
+ deleted_at: None,
+ attachments: Vec::new(),
+ reactions: Vec::new(),
+ mentions: Vec::new(),
+ }
+}
+
+#[tokio::test]
+async fn opens_one_bot_response_without_the_private_prompt() {
+ use messages::domain::api::MockMessageCommands;
+ let assignment = TaskAssignment::from_update(Uuid::now_v7(), &update()).unwrap();
+ let event_id = discussion_id(assignment.event_id, BotId::TEST_A);
+ let mut commands = MockMessageCommands::new();
+ let message = discussion(&assignment);
+ let expected = message.clone();
+ commands
+ .expect_post_from_event()
+ .once()
+ .withf(move |access, id, input| {
+ access.entity().entity_id == "task-1"
+ && *id == event_id
+ && input.id.is_none()
+ && input.thread_id.is_none()
+ && input.mentions.is_empty()
+ && input.content == "Working on this task…"
+ && access.get_authenticated_bot().unwrap().bot_id() == BotId::TEST_A
+ && input.notification_policy == PostMessageNotificationPolicy::Silent
+ })
+ .return_once(|_, _, _| Ok(message));
+ let posted = assignment_discussion(
+ &assignment,
+ BotId::TEST_A,
+ discussion_id(assignment.event_id, BotId::TEST_A),
+ access(&assignment),
+ &commands,
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(posted.id, expected.id);
+ assert_eq!(posted.parent, expected.parent);
+ assert_eq!(posted.sender_id, expected.sender_id);
+}
+
+#[tokio::test]
+async fn a_replayed_assignment_reuses_its_persisted_discussion() {
+ use messages::domain::api::MockMessageCommands;
+ let assignment = TaskAssignment::from_update(Uuid::now_v7(), &update()).unwrap();
+ let message = discussion(&assignment);
+ let mut commands = MockMessageCommands::new();
+ commands
+ .expect_post_from_event()
+ .once()
+ .return_once(|_, _, _| Ok(message));
+ let posted = assignment_discussion(
+ &assignment,
+ BotId::TEST_A,
+ discussion_id(assignment.event_id, BotId::TEST_A),
+ access(&assignment),
+ &commands,
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(posted.id, discussion_id(assignment.event_id, BotId::TEST_A));
+}
+
+#[tokio::test]
+async fn deleted_or_unrelated_discussions_cannot_start_a_session() {
+ use messages::domain::api::MockMessageCommands;
+ let assignment = TaskAssignment::from_update(Uuid::now_v7(), &update()).unwrap();
+ for variant in 0..4 {
+ let mut message = discussion(&assignment);
+ match variant {
+ 0 => message.deleted_at = Some(Utc::now()),
+ 1 => message.parent = MessageParent::parse("document", "other-task").unwrap(),
+ 2 => message.thread_id = Some(Uuid::now_v7()),
+ _ => {
+ message.sender_id = channel_sender::ChannelSender::new_from_user(
+ MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ )
+ }
+ }
+ let mut commands = MockMessageCommands::new();
+ commands
+ .expect_post_from_event()
+ .once()
+ .return_once(|_, _, _| Ok(message));
+ assert!(
+ assignment_discussion(
+ &assignment,
+ BotId::TEST_A,
+ discussion_id(assignment.event_id, BotId::TEST_A),
+ access(&assignment),
+ &commands
+ )
+ .await
+ .unwrap()
+ .is_none()
+ );
+ }
+}
+
+#[tokio::test]
+async fn a_discussion_failure_does_not_yield_an_opening_message() {
+ use messages::domain::api::MockMessageCommands;
+ let assignment = TaskAssignment::from_update(Uuid::now_v7(), &update()).unwrap();
+ let mut commands = MockMessageCommands::new();
+ commands
+ .expect_post_from_event()
+ .once()
+ .returning(|_, _, _| Err(MessageError::Forbidden));
+ assert!(matches!(
+ assignment_discussion(
+ &assignment,
+ BotId::TEST_A,
+ discussion_id(assignment.event_id, BotId::TEST_A),
+ access(&assignment),
+ &commands
+ )
+ .await,
+ Err(ProcessMessageEventError::Discussion(
+ MessageError::Forbidden
+ ))
+ ));
+}
+
+#[test]
+fn removing_then_reassigning_starts_a_new_assignment() {
+ let first = TaskAssignment::from_update(Uuid::now_v7(), &update()).unwrap();
+ let second = TaskAssignment::from_update(Uuid::now_v7(), &update()).unwrap();
+ assert_ne!(first.event_id, second.event_id);
+ assert_eq!(first.bots, second.bots);
+}
+
+#[test]
+fn both_message_sources_also_decode_task_assignments() {
+ let event_id = Uuid::now_v7();
+ let event = || {
+ PropertyMacroEvent::from_event(
+ "task-1".to_owned(),
+ Event::with_event_id(
+ event_id,
+ PropertyTopicEvent::EntityPropertyUpdated(update()),
+ ),
+ )
+ };
+ let message = MessageTriggerEvents::PropertyMacroEvent(event()).into_trigger();
+ let channel = ChannelTriggerEvents::PropertyMacroEvent(event()).into_trigger();
+ assert!(MessageTriggerEvents::topics().contains(&"macro.properties"));
+ assert!(ChannelTriggerEvents::topics().contains(&"macro.properties"));
+ assert_eq!(message, channel);
+ assert!(message.posted.is_none());
+ assert_eq!(message.assignment.unwrap().event_id, event_id);
+}
+
+#[derive(Default)]
+struct RecordedEvents(std::sync::Mutex<Vec<serde_json::Value>>);
+
+impl MacroEventBroker for RecordedEvents {
+ fn send_event<E: MacroEvent + ?Sized>(
+ &self,
+ event: &E,
+ ) -> Result<
+ tokio::task::JoinHandle<Result<(), macro_event_broker::EventBrokerError>>,
+ macro_event_broker::EventBrokerError,
+ > {
+ self.0
+ .lock()
+ .unwrap()
+ .push(serde_json::to_value(event.event())?);
+ Ok(tokio::spawn(async { Ok(()) }))
+ }
+}
+
+#[tokio::test]
+async fn authorized_assignment_publishes_the_task_brief_for_toolless_runtimes() {
+ use crate::domain::service::*;
+ use agent_session::domain::{model::ThreadSession, ports::MockAgentSessionRepo};
+ use messages::domain::api::MockMessageCommands;
+
+ let mut assignment = TaskAssignment::from_update(Uuid::now_v7(), &update()).unwrap();
+ assignment.bots = vec![bot_id::CODEX_BOT_ID];
+ let mut bots = MockAgentBotLookup::new();
+ bots.expect_get_agent()
+ .once()
+ .returning(|_| Box::pin(async { Ok(None) }));
+ bots.expect_get_bot().once().returning(|id| {
+ Box::pin(async move {
+ Ok(Some(bots::domain::models::Bot::system(
+ bot_id::system_bot(id).unwrap(),
+ )))
+ })
+ });
+ let mut history = MockThreadHistory::new();
+ let receipt = access(&assignment);
+ history
+ .expect_authorize_invocation()
+ .once()
+ .returning(move |_, _, root| {
+ let invocation = AuthorizedInvocation::new(receipt.clone(), root);
+ Box::pin(async { Ok(Some(invocation)) })
+ });
+ let mut sessions = MockAgentSessionRepo::new();
+ let event_id = discussion_id(assignment.event_id, bot_id::CODEX_BOT_ID);
+ sessions
+ .expect_find_for_thread()
+ .once()
+ .withf(move |root, bot| *root == Some(event_id) && *bot == Some(bot_id::CODEX_BOT_ID))
+ .returning(|_, _| Box::pin(async { Ok(ThreadSession::None) }));
+ let trigger = AgentTriggerService::new(
+ sessions,
+ bots,
+ MockTeamMembershipLookup::new(),
+ MockChannelParticipationLookup::new(),
+ MockExplicitReplyExtractor::new(),
+ MockImplicitTriggerJudge::new(),
+ history,
+ );
+ let mut context = MockTaskAssignmentContext::new();
+ context
+ .expect_task_brief()
+ .once()
+ .withf(|access| access.entity().entity_id == "task-1")
+ .returning(|_| Box::pin(async { Ok(Some(brief())) }));
+ let mut commands = MockMessageCommands::new();
+ let mut message = discussion(&assignment);
+ message.id = event_id;
+ message.sender_id = channel_sender::ChannelSender::new_from_bot(bot_id::CODEX_BOT_ID);
+ commands
+ .expect_post_from_event()
+ .once()
+ .return_once(move |_, _, input| {
+ message.content = input.content;
+ Ok(message)
+ });
+ let broker = RecordedEvents::default();
+ process_task_assignment(&trigger, &broker, &commands, &context, &assignment)
+ .await
+ .unwrap();
+ let events = broker.0.lock().unwrap();
+ assert_eq!(events.len(), 1);
+ let metadata = &events[0]["metadata"];
+ assert_eq!(metadata["source"], "assigned_to_task");
+ assert_eq!(metadata["bot_id"], bot_id::CODEX_BOT_ID.to_string());
+ let prompt = metadata["prompt"].as_str().unwrap();
+ assert!(prompt.contains("Fix export"));
+ assert!(prompt.contains("Include archived rows in CSV exports."));
+ assert!(prompt.contains(r#""documentId":"task-1""#));
+ assert_eq!(metadata["parent"]["type"], "document");
+}
+
+#[test]
+fn assignment_response_ids_are_stable_distinct_uuid_v7s() {
+ let event = Uuid::now_v7();
+ let root = discussion_id(event, BotId::TEST_A);
+ assert_eq!(root, discussion_id(event, BotId::TEST_A));
+ assert_ne!(root, discussion_id(event, BotId::TEST_B));
+ assert_ne!(root, discussion_id(Uuid::now_v7(), BotId::TEST_A));
+ assert_eq!(root.get_version_num(), 7);
+ assert_eq!(&root.as_bytes()[..6], &event.as_bytes()[..6]);
+}
diff --git a/crates/agent_trigger/src/outbound/dss_task_assignment_context.rs b/crates/agent_trigger/src/outbound/dss_task_assignment_context.rs
new file mode 100644
index 0000000000..1216cf04c0
--- /dev/null
+++ b/crates/agent_trigger/src/outbound/dss_task_assignment_context.rs
@@ -0,0 +1,63 @@
+//! Task briefs from the document service and its live Markdown renderer.
+
+use agent_session::domain::error::{AgentSessionError, Result};
+use document_storage_service_client::DocumentStorageServiceClient;
+use document_sub_type::DocumentSubType;
+use entity_access::domain::models::{EntityAccessReceipt, EntityType};
+use lexical_client::{LexicalClient, parse_markdown::MarkdownTarget};
+use messages::domain::service::MessageWrite;
+
+use crate::domain::task_assignment::{TaskAssignmentContext, TaskBrief};
+
+#[cfg(test)]
+mod test;
+
+/// Loads the current title and Markdown for an already-authorized task.
+pub struct DssTaskAssignmentContext {
+ documents: DocumentStorageServiceClient,
+ lexical: LexicalClient,
+}
+
+impl DssTaskAssignmentContext {
+ /// Compose the owning document service client and live Markdown renderer.
+ pub fn new(documents: DocumentStorageServiceClient, lexical: LexicalClient) -> Self {
+ Self { documents, lexical }
+ }
+}
+
+impl TaskAssignmentContext for DssTaskAssignmentContext {
+ async fn task_brief(
+ &self,
+ access: EntityAccessReceipt<MessageWrite>,
+ ) -> Result<Option<TaskBrief>> {
+ if access.entity().entity_type != EntityType::Document {
+ return Err(AgentSessionError::Forbidden);
+ }
+ let document_id = &access.entity().entity_id;
+ let Some(document) = self
+ .documents
+ .get_document_basic(document_id)
+ .await
+ .map_err(AgentSessionError::Unknown)?
+ else {
+ return Ok(None);
+ };
+ if document.document_id != *document_id {
+ return Err(AgentSessionError::Forbidden);
+ }
+ if document.deleted_at.is_some() || document.sub_type != Some(DocumentSubType::Task) {
+ return Ok(None);
+ }
+ // Extracted document text can lag a newly created or edited task. The
+ // renderer reads the live content and includes it in the opening brief.
+ let markdown = self
+ .lexical
+ .get_markdown(document_id, MarkdownTarget::External)
+ .await
+ .map_err(AgentSessionError::Unknown)?;
+ Ok(Some(TaskBrief {
+ title: document.document_name,
+ markdown,
+ }))
+ }
+}
diff --git a/crates/agent_trigger/src/outbound/dss_task_assignment_context/test.rs b/crates/agent_trigger/src/outbound/dss_task_assignment_context/test.rs
new file mode 100644
index 0000000000..fbea029151
--- /dev/null
+++ b/crates/agent_trigger/src/outbound/dss_task_assignment_context/test.rs
@@ -0,0 +1,123 @@
+use super::*;
+use entity_access::domain::models::{AccessLevel, Entity, EntityPermission};
+use macro_user_id::user_id::MacroUserIdStr;
+use serde_json::{Value, json};
+use std::io::{BufRead, BufReader, Write};
+use std::net::TcpListener;
+
+fn access() -> EntityAccessReceipt<MessageWrite> {
+ EntityAccessReceipt::try_new_authenticated_user(
+ MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ Entity {
+ entity_type: EntityType::Document,
+ entity_id: "task-1".to_owned(),
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit,
+ },
+ )
+ .unwrap()
+}
+
+fn task() -> Value {
+ json!({
+ "documentId": "task-1",
+ "documentName": "Fix the flaky test",
+ "owner": "macro|[email protected]",
+ "fileType": "md",
+ "subType": "task",
+ "deletedAt": null,
+ })
+}
+
+fn server(
+ responses: Vec<(&'static str, u16, Value)>,
+) -> (DssTaskAssignmentContext, std::thread::JoinHandle<()>) {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let address = listener.local_addr().unwrap();
+ let handle = std::thread::spawn(move || {
+ for (path, status, body) in responses {
+ let (mut stream, _) = listener.accept().unwrap();
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
+ let mut line = String::new();
+ reader.read_line(&mut line).unwrap();
+ assert_eq!(line.trim_end(), format!("GET {path} HTTP/1.1"));
+ loop {
+ line.clear();
+ reader.read_line(&mut line).unwrap();
+ if line == "\r\n" || line.is_empty() {
+ break;
+ }
+ }
+ let body = body.to_string();
+ write!(stream, "HTTP/1.1 {status} OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();
+ }
+ });
+ let url = format!("http://{address}");
+ (
+ DssTaskAssignmentContext::new(
+ DocumentStorageServiceClient::new("test-key".to_owned(), url.clone()),
+ LexicalClient::new("test-key".to_owned(), url),
+ ),
+ handle,
+ )
+}
+
+#[tokio::test]
+async fn a_task_brief_contains_the_title_and_current_markdown() {
+ let (context, server) = server(vec![
+ ("/internal/documents/task-1/basic", 200, task()),
+ (
+ "/markdown/task-1?target=external",
+ 200,
+ json!({"data": "Reproduce the race, then add a regression test."}),
+ ),
+ ]);
+ let brief = context.task_brief(access()).await.unwrap().unwrap();
+ assert_eq!(brief.title, "Fix the flaky test");
+ assert_eq!(
+ brief.markdown,
+ "Reproduce the race, then add a regression test."
+ );
+ server.join().unwrap();
+}
+
+#[tokio::test]
+async fn missing_deleted_and_non_task_documents_do_not_load_content() {
+ let mut deleted = task();
+ deleted["deletedAt"] = json!("2026-09-24T12:00:00Z");
+ let mut ordinary = task();
+ ordinary["subType"] = Value::Null;
+ for (status, metadata) in [(404, json!({})), (200, deleted), (200, ordinary)] {
+ let (context, server) =
+ server(vec![("/internal/documents/task-1/basic", status, metadata)]);
+ assert!(context.task_brief(access()).await.unwrap().is_none());
+ server.join().unwrap();
+ }
+}
+
+#[tokio::test]
+async fn a_response_for_a_different_document_cannot_supply_the_brief() {
+ let mut metadata = task();
+ metadata["documentId"] = json!("other-task");
+ let (context, server) = server(vec![("/internal/documents/task-1/basic", 200, metadata)]);
+ assert!(matches!(
+ context.task_brief(access()).await,
+ Err(AgentSessionError::Forbidden)
+ ));
+ server.join().unwrap();
+}
+
+#[tokio::test]
+async fn unavailable_live_content_is_retried_instead_of_starting_without_a_description() {
+ let (context, server) = server(vec![
+ ("/internal/documents/task-1/basic", 200, task()),
+ (
+ "/markdown/task-1?target=external",
+ 503,
+ json!({"error": "temporarily unavailable"}),
+ ),
+ ]);
+ assert!(context.task_brief(access()).await.is_err());
+ server.join().unwrap();
+}
diff --git a/crates/agent_trigger/src/outbound/mod.rs b/crates/agent_trigger/src/outbound/mod.rs
index 19ecaec7d5..87efbac504 100644
--- a/crates/agent_trigger/src/outbound/mod.rs
+++ b/crates/agent_trigger/src/outbound/mod.rs
@@ -2,6 +2,7 @@
mod bot_repo_agent_lookup;
mod channel_type_lookup;
+mod dss_task_assignment_context;
mod fast_model_judge;
mod image_caption;
mod lexical_explicit_reply_extractor;
@@ -9,6 +10,7 @@ mod message_thread_history;
pub use bot_repo_agent_lookup::BotRepoAgentLookup;
pub use channel_type_lookup::ChannelRepoTypeLookup;
+pub use dss_task_assignment_context::DssTaskAssignmentContext;
pub use fast_model_judge::FastModelTriggerJudge;
pub use image_caption::{ImageCaptioner, VisionImageCaptioner};
pub use lexical_explicit_reply_extractor::LexicalExplicitReplyExtractor;
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index 821665cc01..ff49b1cf26 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -215,10 +215,7 @@ pub async fn build_tool_service_context_from_env(
sync_service_url,
));
let email_ext_client = Arc::new(EmailServiceClientExternal::new(email_service_url.clone()));
- let lexical_client = LexicalClient::new(
- env.document_storage_service_auth_key.to_string(),
- lexical_service_url,
- );
+ let lexical_client = LexicalClient::new(env.internal_api_key.to_string(), lexical_service_url);
let frecency_storage = FrecencyPgStorage::new(pool.clone());
let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 0ea9b8db71..4dc9099de9 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -111,11 +111,11 @@ pub type ToolEmailService = EmailServiceImpl<
/// graceful shutdown by the hosting process.
pub type ToolEventBroker = MacroEventBrokerService<KafkaEventPublisher, TaskTracker>;
-/// Event broker used by bot tools across hosts that either do or do not have
+/// Event broker used by bot and property tools across hosts that either do or do not have
/// Kafka lifecycle publishing configured.
#[derive(Clone)]
pub enum ToolBotEventBroker {
- /// Publish bot lifecycle events through the shared Kafka broker.
+ /// Publish lifecycle events through the shared Kafka broker.
Real(ToolEventBroker),
/// Drop lifecycle events in hosts that do not configure Kafka.
NoOp(NoopMacroEventBroker),
@@ -462,6 +462,8 @@ pub fn build_crm_tool_context(pool: sqlx::PgPool) -> ToolCrmToolContext {
entity_access::outbound::PgAccessRepository::new(pool.clone()),
),
);
+ // This CRM-only context does not assign tasks. Task writes use the host's
+ // shared properties context, which carries its lifecycle event broker.
let properties = build_properties_service(pool.clone(), entity_access_service.clone());
CrmToolContext {
service: Arc::new(crm::domain::service::CrmServiceImpl::new(
diff --git a/crates/bots/src/inbound/channel_webhook_router/tests.rs b/crates/bots/src/inbound/channel_webhook_router/tests.rs
index cda2d0cffc..c0a56869af 100644
--- a/crates/bots/src/inbound/channel_webhook_router/tests.rs
+++ b/crates/bots/src/inbound/channel_webhook_router/tests.rs
@@ -500,6 +500,15 @@ impl TestChannelPoster {
#[async_trait::async_trait]
impl messages::domain::api::MessageCommands for TestChannelPoster {
+ async fn post_from_event(
+ &self,
+ _: EntityAccessReceipt<messages::domain::service::MessageWrite>,
+ _: Uuid,
+ _: messages::domain::models::PostMessage,
+ ) -> Result<messages::domain::models::Message, messages::domain::ports::MessageError> {
+ unimplemented!("channel webhooks do not post broker events")
+ }
+
async fn post(
&self,
access: EntityAccessReceipt<messages::domain::service::MessageWrite>,
diff --git a/crates/channels/src/inbound/toolset/test.rs b/crates/channels/src/inbound/toolset/test.rs
index 2e15f456e9..bac4610d14 100644
--- a/crates/channels/src/inbound/toolset/test.rs
+++ b/crates/channels/src/inbound/toolset/test.rs
@@ -48,6 +48,15 @@ struct RecordingMessages {
#[async_trait::async_trait]
impl messages::domain::api::MessageCommands for RecordingMessages {
+ async fn post_from_event(
+ &self,
+ _: EntityAccessReceipt<messages::domain::service::MessageWrite>,
+ _: Uuid,
+ _: messages::domain::models::PostMessage,
+ ) -> Result<messages::domain::models::Message, messages::domain::ports::MessageError> {
+ unimplemented!("channel tools do not post broker events")
+ }
+
async fn post(
&self,
access: EntityAccessReceipt<messages::domain::service::MessageWrite>,
diff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rs
index 35686df232..c4064e3f98 100644
--- a/crates/coding_agent_worker/src/dispatch.rs
+++ b/crates/coding_agent_worker/src/dispatch.rs
@@ -41,6 +41,7 @@ impl WorkExecutor for Dispatcher {
async fn execute(&self, work: TriggerWork) -> Result<(), DispatchError> {
match work {
TriggerWork::OpenAndPrompt {
+ reuse_origin_message,
bot,
sender,
parent,
@@ -65,6 +66,7 @@ impl WorkExecutor for Dispatcher {
repo_branch: None,
owner: Some(sender.as_ref().to_owned()),
thread: Some(CreateSessionThread {
+ reuse_origin_message,
// Keep `channel_id` populated for channel parents so a
// pre-parent harness, which ignores `parent` and reads
// `channel_id` as a required UUID, still deserializes
diff --git a/crates/coding_agent_worker/src/trigger.rs b/crates/coding_agent_worker/src/trigger.rs
index 6cf640239f..b408f527e0 100644
--- a/crates/coding_agent_worker/src/trigger.rs
+++ b/crates/coding_agent_worker/src/trigger.rs
@@ -28,6 +28,8 @@ pub enum TriggerWork {
/// Open a session for a mention, serve it, and forward the mention as
/// its first prompt.
OpenAndPrompt {
+ /// Update the bot response reserved by a task assignment.
+ reuse_origin_message: bool,
/// The mentioned agent the session runs for. One harness serves many
/// agents, so the daemon must name the bot when creating the session.
bot: BotId,
@@ -96,6 +98,17 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Ski
sender,
})
}
+ AgentTriggerTopicEvent::New(NewAgentSessionEvent::AssignedToTask(assigned)) => {
+ Ok(TriggerWork::OpenAndPrompt {
+ reuse_origin_message: true,
+ bot: assigned.bot_id,
+ sender: assigned.actor,
+ parent: assigned.parent,
+ thread_id: assigned.discussion_id,
+ message_id: assigned.discussion_id,
+ content: assigned.prompt,
+ })
+ }
AgentTriggerTopicEvent::New(event) => {
let Some(OpeningMention { bot_id, message }) = event.mention() else {
return Err(Skipped::Unrecognized);
@@ -106,6 +119,7 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Ski
.cloned()
.ok_or(Skipped::NotFromUser)?;
Ok(TriggerWork::OpenAndPrompt {
+ reuse_origin_message: false,
bot: bot_id,
sender,
parent: message.parent,
diff --git a/crates/coding_agent_worker/src/trigger/test.rs b/crates/coding_agent_worker/src/trigger/test.rs
index 9ac9099b5d..aad52a5ef9 100644
--- a/crates/coding_agent_worker/src/trigger/test.rs
+++ b/crates/coding_agent_worker/src/trigger/test.rs
@@ -1,7 +1,7 @@
use super::*;
use agent_trigger::domain::broker_events::{
- AgentBotMentionedEvent, AgentMentionedEvent, ChannelEventMetadata, ExistingAgentSessionEvent,
- NewAgentSessionEvent, ThreadEventMetadata, ThreadMessageKind,
+ AgentAssignedToTaskEvent, AgentBotMentionedEvent, AgentMentionedEvent, ChannelEventMetadata,
+ ExistingAgentSessionEvent, NewAgentSessionEvent, ThreadEventMetadata, ThreadMessageKind,
};
use channel_sender::ChannelSender;
use channels::domain::broker_events::ChannelMessagePostedMetadata;
@@ -84,6 +84,7 @@ fn document_triggers_become_work_on_the_document() {
assert_eq!(
trigger_to_work(opened).expect("a document mention is work"),
TriggerWork::OpenAndPrompt {
+ reuse_origin_message: false,
bot: bot_id::BotId::TEST_A,
sender: sender(),
parent: document(),
@@ -109,12 +110,38 @@ fn document_triggers_become_work_on_the_document() {
);
}
+#[test]
+fn a_task_assignment_opens_and_prompts_in_the_task_discussion() {
+ let event = AgentTriggerTopicEvent::New(NewAgentSessionEvent::AssignedToTask(
+ AgentAssignedToTaskEvent {
+ bot_id: BotId::TEST_A,
+ parent: document(),
+ discussion_id: Uuid::from_u128(2),
+ actor: sender(),
+ prompt: "Complete the assigned task".to_owned(),
+ },
+ ));
+ assert_eq!(
+ trigger_to_work(event).expect("a task assignment is work"),
+ TriggerWork::OpenAndPrompt {
+ reuse_origin_message: true,
+ bot: BotId::TEST_A,
+ sender: sender(),
+ parent: document(),
+ thread_id: Uuid::from_u128(2),
+ message_id: Uuid::from_u128(2),
+ content: "Complete the assigned task".to_owned(),
+ }
+ );
+}
+
#[test]
fn a_mention_becomes_open_and_prompt_rooting_its_own_thread() {
let work = trigger_to_work(mention("fix the test")).expect("a mention is work");
assert_eq!(
work,
TriggerWork::OpenAndPrompt {
+ reuse_origin_message: false,
bot: bot_id::BotId::TEST_A,
sender: sender(),
parent: messages::domain::models::MessageParent::Channel(Uuid::from_u128(1)),
diff --git a/crates/documents/src/domain/create.rs b/crates/documents/src/domain/create.rs
index d291de49d6..8e4f3e6d4a 100644
--- a/crates/documents/src/domain/create.rs
+++ b/crates/documents/src/domain/create.rs
@@ -632,6 +632,20 @@ where
.clone();
let finalize_result = async {
+ let initial_snapshot = self
+ .markdown_initializer
+ .initialize_existing_markdown(&document_id, &markdown)
+ .await?;
+
+ self.document_service
+ .set_document_content(
+ &document_id,
+ DocumentContent::ready(DocumentContentLocation::SyncService),
+ )
+ .await?;
+
+ // Assignments publish events that can start agents immediately.
+ // Make the task body readable before applying its properties.
if let Some((property_values, share_with_team, team_id)) = task {
self.document_service
.handle_task_properties(
@@ -649,18 +663,6 @@ where
.await?;
}
- let initial_snapshot = self
- .markdown_initializer
- .initialize_existing_markdown(&document_id, &markdown)
- .await?;
-
- self.document_service
- .set_document_content(
- &document_id,
- DocumentContent::ready(DocumentContentLocation::SyncService),
- )
- .await?;
-
Ok(initial_snapshot)
}
.await;
diff --git a/crates/documents/src/domain/create/test.rs b/crates/documents/src/domain/create/test.rs
index ffaf5265d3..d787a99b0b 100644
--- a/crates/documents/src/domain/create/test.rs
+++ b/crates/documents/src/domain/create/test.rs
@@ -1,4 +1,4 @@
-use std::sync::Mutex;
+use std::sync::{Arc, Mutex};
use bot_id::{BotId, NonSystemBotId};
use macro_user_id::user_id::MacroUserIdStr;
@@ -39,6 +39,8 @@ fn team_bot() -> CreationPrincipal {
struct FakeCreationService {
calls: Mutex<Vec<(CreationPrincipal, NewDocument)>>,
task_principals: Mutex<Vec<CreationPrincipal>>,
+ lifecycle: Arc<Mutex<Vec<&'static str>>>,
+ fail_content_update: bool,
}
impl DocumentCreationService for FakeCreationService {
@@ -49,6 +51,7 @@ impl DocumentCreationService for FakeCreationService {
_job_id: Option<String>,
) -> Result<CreateDocumentResponseData, DocumentError> {
let file_type = document.file_type.map(|kind| kind.to_string());
+ self.lifecycle.lock().unwrap().push("create");
self.calls
.lock()
.unwrap()
@@ -88,6 +91,7 @@ impl DocumentCreationService for FakeCreationService {
_request: &CreateTaskRequest,
) -> Result<(), DocumentError> {
self.task_principals.lock().unwrap().push(principal.clone());
+ self.lifecycle.lock().unwrap().push("properties");
Ok(())
}
@@ -100,11 +104,17 @@ impl DocumentCreationService for FakeCreationService {
_document_id: &str,
_content: DocumentContent,
) -> Result<(), DocumentError> {
+ self.lifecycle.lock().unwrap().push("content_ready");
+ if self.fail_content_update {
+ return Err(DocumentError::Internal(anyhow::anyhow!(
+ "content update failed"
+ )));
+ }
Ok(())
}
async fn cleanup_created_document(&self, _document_id: &str) {
- panic!("unexpected cleanup_created_document call")
+ self.lifecycle.lock().unwrap().push("cleanup");
}
}
@@ -120,6 +130,27 @@ impl MarkdownInitializationPort for FakeMarkdownInitializer {
}
}
+struct RecordingMarkdownInitializer {
+ lifecycle: Arc<Mutex<Vec<&'static str>>>,
+ fail: bool,
+}
+
+impl MarkdownInitializationPort for RecordingMarkdownInitializer {
+ async fn initialize_existing_markdown(
+ &self,
+ _document_id: &str,
+ _markdown: &str,
+ ) -> Result<Vec<u8>, DocumentError> {
+ self.lifecycle.lock().unwrap().push("initialize");
+ if self.fail {
+ return Err(DocumentError::Internal(anyhow::anyhow!(
+ "initialization failed"
+ )));
+ }
+ Ok(vec![1, 2, 3])
+ }
+}
+
struct FakeBytesUploader;
impl DocumentBytesUploadPort for FakeBytesUploader {
@@ -181,6 +212,73 @@ fn task_document(markdown: &str) -> NewMarkdownTextDocument {
}
}
+#[tokio::test]
+async fn task_assignments_are_applied_only_after_content_is_readable() {
+ let lifecycle = Arc::new(Mutex::new(Vec::new()));
+ let tracker = RecordingMentionTracker::default();
+ let creator = DocumentCreator::new(
+ FakeCreationService {
+ lifecycle: lifecycle.clone(),
+ ..Default::default()
+ },
+ RecordingMarkdownInitializer {
+ lifecycle: lifecycle.clone(),
+ fail: false,
+ },
+ FakeBytesUploader,
+ &tracker,
+ );
+
+ creator
+ .create_markdown_text(
+ &CreationPrincipal::User(owner()),
+ task_document("Do the assigned work"),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ *lifecycle.lock().unwrap(),
+ ["create", "initialize", "content_ready", "properties"]
+ );
+}
+
+#[tokio::test]
+async fn failed_task_content_never_applies_assignments() {
+ for fail_initialization in [true, false] {
+ let lifecycle = Arc::new(Mutex::new(Vec::new()));
+ let tracker = RecordingMentionTracker::default();
+ let creator = DocumentCreator::new(
+ FakeCreationService {
+ lifecycle: lifecycle.clone(),
+ fail_content_update: !fail_initialization,
+ ..Default::default()
+ },
+ RecordingMarkdownInitializer {
+ lifecycle: lifecycle.clone(),
+ fail: fail_initialization,
+ },
+ FakeBytesUploader,
+ &tracker,
+ );
+
+ assert!(
+ creator
+ .create_markdown_text(
+ &CreationPrincipal::User(owner()),
+ task_document("Do the assigned work")
+ )
+ .await
+ .is_err()
+ );
+
+ let lifecycle = lifecycle.lock().unwrap();
+ assert!(!lifecycle.contains(&"properties"));
+ assert_eq!(lifecycle.last(), Some(&"cleanup"));
+ assert!(tracker.calls().is_empty());
+ }
+}
+
fn creator(
tracker: &RecordingMentionTracker,
) -> DocumentCreator<
diff --git a/crates/documents/src/inbound/toolset/comment_test.rs b/crates/documents/src/inbound/toolset/comment_test.rs
index 47e9619cbf..589607a9c3 100644
--- a/crates/documents/src/inbound/toolset/comment_test.rs
+++ b/crates/documents/src/inbound/toolset/comment_test.rs
@@ -100,6 +100,15 @@ impl MessageReader for FakeMessages {
#[async_trait::async_trait]
impl MessageCommands for FakeMessages {
+ async fn post_from_event(
+ &self,
+ _: EntityAccessReceipt<MessageWrite>,
+ _: Uuid,
+ _: PostMessage,
+ ) -> Result<Message, MessageError> {
+ unimplemented!("comment tools do not post broker events")
+ }
+
async fn post(
&self,
access: EntityAccessReceipt<MessageWrite>,
diff --git a/crates/lexical_client/src/parse_markdown.rs b/crates/lexical_client/src/parse_markdown.rs
index ae111e3818..a0f1db3eee 100644
--- a/crates/lexical_client/src/parse_markdown.rs
+++ b/crates/lexical_client/src/parse_markdown.rs
@@ -171,7 +171,8 @@ pub struct AgentAnnouncementReplyTarget {
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct AgentAnnouncementRequest<'a> {
- reply_target: &'a AgentAnnouncementReplyTarget,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ reply_target: Option<&'a AgentAnnouncementReplyTarget>,
chip: &'a AgentAnnouncementChip,
}
@@ -621,7 +622,7 @@ impl LexicalClient {
#[tracing::instrument(skip(self, reply_target, chip), err)]
pub async fn compose_agent_announcement(
&self,
- reply_target: &AgentAnnouncementReplyTarget,
+ reply_target: Option<&AgentAnnouncementReplyTarget>,
chip: &AgentAnnouncementChip,
) -> Result<String> {
let url = format!("{}/agent-announcement", self.url);
diff --git a/crates/memory/src/context.rs b/crates/memory/src/context.rs
index a6cfd95cd5..fd78b78900 100644
--- a/crates/memory/src/context.rs
+++ b/crates/memory/src/context.rs
@@ -143,12 +143,11 @@ pub async fn build_tool_service_context(
)));
let properties_service =
ai_tools::build_properties_service(pool.clone(), entity_access_service.clone());
- let task_properties_service =
- ai_tools::build_task_properties_adapter(
- pool.clone(),
- properties_service.clone(),
- entity_access_service.clone(),
- );
+ let task_properties_service = ai_tools::build_task_properties_adapter(
+ pool.clone(),
+ properties_service.clone(),
+ entity_access_service.clone(),
+ );
let document_service = documents::domain::service::DocumentServiceImpl::new(
document_repo,
cloudfront_config,
@@ -233,7 +232,6 @@ pub async fn build_tool_service_context(
(*entity_access_service).clone(),
);
-
let skill_tool_context = ai_tools::build_skill_tool_context(
search_client.clone(),
soup_service.clone(),
diff --git a/crates/messages/src/domain/api.rs b/crates/messages/src/domain/api.rs
index 5d42470e0c..3fffe80740 100644
--- a/crates/messages/src/domain/api.rs
+++ b/crates/messages/src/domain/api.rs
@@ -56,6 +56,15 @@ pub trait MessageCommands: Send + Sync + 'static {
access: EntityAccessReceipt<MessageWrite>,
input: PostMessage,
) -> Result<Message, MessageError>;
+ /// Idempotently post a trusted server event, using its UUIDv7 as the message
+ /// id without a client clock-skew limit. Replays return the original message,
+ /// including tombstones, after checking its parent, author, and thread.
+ async fn post_from_event(
+ &self,
+ access: EntityAccessReceipt<MessageWrite>,
+ event_id: Uuid,
+ input: PostMessage,
+ ) -> Result<Message, MessageError>;
/// Apply partial body, mention, and attachment changes under the common policy.
async fn patch(
&self,
@@ -162,6 +171,14 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageCommands for Message
) -> Result<Message, MessageError> {
MessageService::post(self, access, input).await
}
+ async fn post_from_event(
+ &self,
+ access: EntityAccessReceipt<MessageWrite>,
+ event_id: Uuid,
+ input: PostMessage,
+ ) -> Result<Message, MessageError> {
+ MessageService::post_from_event(self, access, event_id, input).await
+ }
async fn patch(
&self,
access: EntityAccessReceipt<MessageWrite>,
@@ -260,6 +277,13 @@ mockall::mock! {
access: EntityAccessReceipt<MessageWrite>,
input: PostMessage,
) -> Result<Message, MessageError>;
+ /// Post or recover the message belonging to a trusted server event.
+ async fn post_from_event(
+ &self,
+ access: EntityAccessReceipt<MessageWrite>,
+ event_id: Uuid,
+ input: PostMessage,
+ ) -> Result<Message, MessageError>;
/// Apply partial body, mention, and attachment changes under the common policy.
async fn patch(&self, access: EntityAccessReceipt<MessageWrite>, id: Uuid, input: MessagePatch) -> Result<Message, MessageError>;
/// Tombstone a message, or delete the whole discussion when it is a root.
diff --git a/crates/messages/src/domain/service.rs b/crates/messages/src/domain/service.rs
index 9276a8fa6c..ba94997a0a 100644
--- a/crates/messages/src/domain/service.rs
+++ b/crates/messages/src/domain/service.rs
@@ -180,6 +180,49 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {
/// Post a root or reply with shared thread and anchor validation.
#[tracing::instrument(err, skip(self, access, input))]
pub async fn post(
+ &self,
+ access: EntityAccessReceipt<MessageWrite>,
+ input: PostMessage,
+ ) -> Result<Message, MessageError> {
+ if let Some(id) = input.id {
+ validate_client_id(id, chrono::Utc::now())?;
+ }
+ self.post_validated(access, input).await
+ }
+
+ /// Post a trusted server event once, including after long broker delays.
+ /// Replays return the stored message even if its discussion was deleted;
+ /// they never restore deleted content or publish another message event.
+ #[tracing::instrument(err, skip(self, access, input))]
+ pub async fn post_from_event(
+ &self,
+ access: EntityAccessReceipt<MessageWrite>,
+ event_id: Uuid,
+ mut input: PostMessage,
+ ) -> Result<Message, MessageError> {
+ validate_uuid_v7(event_id)?;
+ let parent = parent_from_receipt(&access)?;
+ let actor = actor_from_receipt(&access, &parent)?;
+ self.ensure_parent(&parent).await?;
+ let thread_id = input.thread_id;
+ if let Some(message) = self.repo.get(&parent, event_id).await? {
+ return validate_event_message(message, &parent, &actor, thread_id);
+ }
+ input.id = Some(event_id);
+ match self.post_validated(access, input).await {
+ Err(MessageError::Conflict) => {
+ let message = self
+ .repo
+ .get(&parent, event_id)
+ .await?
+ .ok_or(MessageError::Conflict)?;
+ validate_event_message(message, &parent, &actor, thread_id)
+ }
+ result => result,
+ }
+ }
+
+ async fn post_validated(
&self,
access: EntityAccessReceipt<MessageWrite>,
mut input: PostMessage,
@@ -792,9 +835,6 @@ fn validate_post(parent: &MessageParent, input: &PostMessage) -> Result<(), Mess
{
return Err(MessageError::Invalid("invalid PDF comment geometry"));
}
- if let Some(id) = input.id {
- validate_client_id(id, chrono::Utc::now())?;
- }
Ok(())
}
@@ -819,6 +859,28 @@ fn valid_spreadsheet_range(range: &str) -> bool {
})
}
+fn validate_event_message(
+ message: Message,
+ parent: &MessageParent,
+ actor: &ChannelSender<'static>,
+ thread_id: Option<Uuid>,
+) -> Result<Message, MessageError> {
+ if message.parent != *parent || message.sender_id != *actor || message.thread_id != thread_id {
+ return Err(MessageError::Conflict);
+ }
+ Ok(message)
+}
+
+fn validate_uuid_v7(id: Uuid) -> Result<chrono::DateTime<chrono::Utc>, MessageError> {
+ id.get_timestamp()
+ .filter(|_| id.get_version_num() == 7)
+ .and_then(|timestamp| {
+ let (seconds, nanos) = timestamp.to_unix();
+ chrono::DateTime::from_timestamp(i64::try_from(seconds).ok()?, nanos)
+ })
+ .ok_or(MessageError::Invalid("message id must be a UUIDv7"))
+}
+
/// How far a client-minted id's timestamp may drift from the server clock.
/// Ordering uses the server's `created_at`, so this only needs to catch forged
/// ids; it is wide so a device with a wrong clock can still post.
@@ -827,14 +889,7 @@ const CLIENT_ID_MAX_SKEW: chrono::TimeDelta = chrono::TimeDelta::days(1);
/// A client-minted id must be a UUIDv7 stamped near now, so its embedded time
/// stays roughly the message's creation time.
fn validate_client_id(id: Uuid, now: chrono::DateTime<chrono::Utc>) -> Result<(), MessageError> {
- let minted_at = id
- .get_timestamp()
- .filter(|_| id.get_version_num() == 7)
- .and_then(|timestamp| {
- let (seconds, nanos) = timestamp.to_unix();
- chrono::DateTime::from_timestamp(i64::try_from(seconds).ok()?, nanos)
- })
- .ok_or(MessageError::Invalid("message id must be a UUIDv7"))?;
+ let minted_at = validate_uuid_v7(id)?;
if (now - minted_at).abs() > CLIENT_ID_MAX_SKEW {
return Err(MessageError::Invalid(
"message id timestamp is too far from the server clock",
diff --git a/crates/messages/src/domain/service/test.rs b/crates/messages/src/domain/service/test.rs
index 3c25a12212..569ccefbce 100644
--- a/crates/messages/src/domain/service/test.rs
+++ b/crates/messages/src/domain/service/test.rs
@@ -3,6 +3,7 @@ use chrono::Utc;
use entity_access::domain::models::{AccessLevel, EntityAccessAuth};
use std::sync::{Arc, Mutex};
+mod event_posts;
mod initiative;
#[derive(Clone)]
@@ -16,6 +17,7 @@ struct Repo {
edits: Arc<Mutex<Vec<EditMessage>>>,
reaction_changed: bool,
file_type: Option<String>,
+ concurrent_create: bool,
}
impl Repo {
@@ -58,6 +60,9 @@ impl MessageRepository for Repo {
Ok(true)
}
async fn get(&self, parent: &MessageParent, id: Uuid) -> Result<Option<Message>, MessageError> {
+ if self.concurrent_create && self.creates.lock().unwrap().is_empty() {
+ return Ok(None);
+ }
let mut message = std::iter::once(&self.message)
.chain(&self.replies)
.find(|message| message.parent == *parent && message.id == id)
@@ -110,7 +115,12 @@ impl MessageRepository for Repo {
})
}
async fn create(&self, command: CreateMessage) -> Result<Message, MessageError> {
+ if command.input.id == Some(self.message.id) {
+ self.creates.lock().unwrap().push(command);
+ return Err(MessageError::Conflict);
+ }
let mut message = self.message.clone();
+ message.id = command.input.id.unwrap_or(message.id);
message.parent = command.parent.clone();
message.sender_id = command.actor.clone();
message.content = command.input.content.clone();
@@ -243,6 +253,7 @@ fn fixture() -> Repo {
edits: Arc::default(),
reaction_changed: true,
file_type: Some("md".into()),
+ concurrent_create: false,
}
}
diff --git a/crates/messages/src/domain/service/test/event_posts.rs b/crates/messages/src/domain/service/test/event_posts.rs
new file mode 100644
index 0000000000..51efb78de8
--- /dev/null
+++ b/crates/messages/src/domain/service/test/event_posts.rs
@@ -0,0 +1,161 @@
+use super::*;
+
+fn event_id() -> Uuid {
+ let created = Utc::now() - chrono::TimeDelta::days(30);
+ Uuid::new_v7(uuid::Timestamp::from_unix(
+ uuid::NoContext,
+ created.timestamp() as u64,
+ created.timestamp_subsec_nanos(),
+ ))
+}
+
+fn persisted_event() -> Repo {
+ let mut repo = fixture();
+ repo.message.id = event_id();
+ repo.state.root_id = repo.message.id;
+ repo
+}
+
+#[tokio::test]
+async fn a_delayed_server_event_posts_but_a_client_with_the_same_old_id_is_rejected() {
+ let repo = fixture();
+ let events = Events::default();
+ let service = MessageService::new(repo.clone(), events.clone());
+ let id = event_id();
+ let mut input = post_input();
+ input.id = Some(id);
+ assert!(matches!(
+ service
+ .post(
+ access("macro|[email protected]", "doc", AccessLevel::Comment),
+ input.clone()
+ )
+ .await,
+ Err(MessageError::Invalid(_)),
+ ));
+ let message = service
+ .post_from_event(
+ access("macro|[email protected]", "doc", AccessLevel::Comment),
+ id,
+ input,
+ )
+ .await
+ .unwrap();
+ assert_eq!(message.id, id);
+ assert_eq!(repo.creates.lock().unwrap().len(), 1);
+ assert_eq!(events.0.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn replay_preserves_edited_content_and_does_not_publish_again() {
+ let mut repo = persisted_event();
+ repo.message.content = "Edited after the original event".to_owned();
+ let events = Events::default();
+ let service = MessageService::new(repo.clone(), events.clone());
+ let message = service
+ .post_from_event(
+ access("macro|[email protected]", "doc", AccessLevel::Comment),
+ repo.message.id,
+ post_input(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(message.content, "Edited after the original event");
+ assert!(repo.creates.lock().unwrap().is_empty());
+ assert!(events.0.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn replay_returns_a_deleted_discussion_without_resurrecting_it() {
+ let repo = persisted_event();
+ repo.thread_deletes.lock().unwrap().push(repo.message.id);
+ let events = Events::default();
+ let service = MessageService::new(repo.clone(), events.clone());
+ let message = service
+ .post_from_event(
+ access("macro|[email protected]", "doc", AccessLevel::Comment),
+ repo.message.id,
+ post_input(),
+ )
+ .await
+ .unwrap();
+ assert!(message.deleted_at.is_some());
+ assert!(message.content.is_empty());
+ assert!(repo.creates.lock().unwrap().is_empty());
+ assert!(events.0.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn replay_cannot_reuse_another_author_parent_or_thread() {
+ let repo = persisted_event();
+ let events = Events::default();
+ let service = MessageService::new(repo.clone(), events.clone());
+ for (author, parent, thread_id) in [
+ ("macro|[email protected]", "doc", None),
+ ("macro|[email protected]", "other-doc", None),
+ ("macro|[email protected]", "doc", Some(Uuid::now_v7())),
+ ] {
+ let mut input = post_input();
+ input.thread_id = thread_id;
+ assert!(matches!(
+ service
+ .post_from_event(
+ access(author, parent, AccessLevel::Comment),
+ repo.message.id,
+ input
+ )
+ .await,
+ Err(MessageError::Conflict),
+ ));
+ }
+ assert!(events.0.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn concurrent_event_delivery_recovers_the_committed_message() {
+ let mut repo = persisted_event();
+ repo.concurrent_create = true;
+ let events = Events::default();
+ let service = MessageService::new(repo.clone(), events.clone());
+ let message = service
+ .post_from_event(
+ access("macro|[email protected]", "doc", AccessLevel::Comment),
+ repo.message.id,
+ post_input(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(message.id, repo.message.id);
+ assert_eq!(repo.creates.lock().unwrap().len(), 1);
+ assert!(events.0.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn trusted_event_posts_still_validate_ids_content_and_references() {
+ let repo = fixture();
+ let service = MessageService::new(repo.clone(), Events::default());
+ let mut empty = post_input();
+ empty.content.clear();
+ let mut inaccessible = post_input();
+ inaccessible.mentions = vec![SimpleMention {
+ entity_type: "document".to_owned(),
+ entity_id: "private-document".to_owned(),
+ }];
+ for (id, input) in [
+ (Uuid::new_v4(), post_input()),
+ (event_id(), empty),
+ (event_id(), inaccessible),
+ ] {
+ assert!(
+ service
+ .post_from_event(
+ access("macro|[email protected]", "doc", AccessLevel::Comment),
+ id,
+ input,
+ )
+ .await
+ .is_err()
+ );
+ }
+ assert!(repo.creates.lock().unwrap().is_empty());
+}
diff --git a/crates/properties/src/domain/service_impl/task_properties.rs b/crates/properties/src/domain/service_impl/task_properties.rs
index ff85216afa..a840afb192 100644
--- a/crates/properties/src/domain/service_impl/task_properties.rs
+++ b/crates/properties/src/domain/service_impl/task_properties.rs
@@ -1,7 +1,11 @@
//! Task-specific property handlers.
+#[cfg(test)]
+mod test;
+
use std::collections::HashSet;
+use bot_id::BotIdStr;
use entity_access::domain::models::EntityAccessAuth;
use macro_event_broker::MacroEventBroker;
use macro_user_id::cowlike::CowLike;
@@ -193,11 +197,25 @@ where
return Ok(());
};
- let assignee_ids = references
- .iter()
- .map(|r| MacroUserIdStr::parse_from_str(&r.entity_id))
- .collect::<Result<Vec<_>, _>>()
- .map_err(|e| PropertiesErr::Validation(e.to_string()))?;
+ let mut assignee_ids = Vec::new();
+ for reference in references {
+ if reference.entity_type != EntityType::User {
+ return Err(PropertiesErr::Validation(
+ "Assignees must reference users or agents".to_string(),
+ ));
+ }
+
+ // Agent identities share the User reference namespace. Their
+ // sessions run with the assigning user's access, so only humans
+ // receive direct task permissions and assignment notifications.
+ if BotIdStr::parse_from_str(&reference.entity_id).is_ok() {
+ continue;
+ }
+ assignee_ids.push(
+ MacroUserIdStr::parse_from_str(&reference.entity_id)
+ .map_err(|error| PropertiesErr::Validation(error.to_string()))?,
+ );
+ }
if assignee_ids.is_empty() {
return Ok(());
}
diff --git a/crates/properties/src/domain/service_impl/task_properties/test.rs b/crates/properties/src/domain/service_impl/task_properties/test.rs
new file mode 100644
index 0000000000..136f13c763
--- /dev/null
+++ b/crates/properties/src/domain/service_impl/task_properties/test.rs
@@ -0,0 +1,104 @@
+use super::*;
+use crate::domain::ports::{MockNotificationService, MockPermissionService, MockPropertiesRepo};
+use models_properties::EntityReference;
+
+fn assignment(references: Vec<EntityReference>) -> Option<SetPropertyValue> {
+ Some(SetPropertyValue::MultiEntityReference { references })
+}
+
+fn agent_reference() -> EntityReference {
+ EntityReference::new(
+ bot_id::CODEX_BOT_ID.into_storage_id().as_ref(),
+ EntityType::User,
+ )
+}
+
+#[tokio::test]
+async fn agents_do_not_require_human_permission_or_notification_services() {
+ let service = PropertiesServiceImpl::new(
+ MockPropertiesRepo::new(),
+ None::<MockPermissionService>,
+ None::<MockNotificationService>,
+ );
+
+ service
+ .handle_task_assignees_property(
+ &Uuid::from_u128(1).to_string(),
+ assignment(vec![agent_reference()]),
+ Some(&MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()),
+ )
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn mixed_assignments_grant_access_and_notify_only_humans() {
+ let task_id = Uuid::from_u128(1);
+ let assignee = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let assigner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_entity_property_value()
+ .times(1)
+ .returning(|_, _, _| Box::pin(async { Ok(None) }));
+
+ let mut permissions = MockPermissionService::new();
+ let expected_assignee = assignee.clone();
+ permissions
+ .expect_grant_permissions_to_task()
+ .times(1)
+ .withf(move |users, id| users == [expected_assignee.clone()] && id == task_id.to_string())
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+
+ let mut notifications = MockNotificationService::new();
+ let expected_assignee = assignee.clone();
+ let expected_assigner = assigner.clone();
+ notifications
+ .expect_send_task_assigned()
+ .times(1)
+ .withf(move |notification| {
+ notification.task_id == task_id
+ && notification.recipient_ids == [expected_assignee.clone()]
+ && notification.assigned_by == expected_assigner
+ })
+ .returning(|_| Box::pin(async { Ok(()) }));
+
+ let service = PropertiesServiceImpl::new(repo, Some(permissions), Some(notifications));
+ service
+ .handle_task_assignees_property(
+ &task_id.to_string(),
+ assignment(vec![
+ agent_reference(),
+ EntityReference::new(assignee.as_ref(), EntityType::User),
+ ]),
+ Some(&assigner),
+ )
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn malformed_agent_and_non_user_references_are_rejected_before_side_effects() {
+ for reference in [
+ EntityReference::new("bot|invalid", EntityType::User),
+ EntityReference::new(
+ bot_id::CODEX_BOT_ID.into_storage_id().as_ref(),
+ EntityType::Document,
+ ),
+ EntityReference::new("macro|[email protected]", EntityType::Document),
+ ] {
+ let service = PropertiesServiceImpl::new(
+ MockPropertiesRepo::new(),
+ Some(MockPermissionService::new()),
+ Some(MockNotificationService::new()),
+ );
+ let result = service
+ .handle_task_assignees_property(
+ &Uuid::from_u128(1).to_string(),
+ assignment(vec![reference]),
+ Some(&MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()),
+ )
+ .await;
+
+ assert!(matches!(result, Err(PropertiesErr::Validation(_))));
+ }
+}
diff --git a/crates/properties/src/inbound/toolset/set_entity_property.rs b/crates/properties/src/inbound/toolset/set_entity_property.rs
index 9504919a4d..9551f6e6e8 100644
--- a/crates/properties/src/inbound/toolset/set_entity_property.rs
+++ b/crates/properties/src/inbound/toolset/set_entity_property.rs
@@ -44,7 +44,7 @@ pub struct ToolEntityRef {
For multi-select properties — including tags — prefer add_option_ids / remove_option_ids over option_ids: they add or remove just those options atomically, composing with concurrent edits. option_ids replaces the entire value, so a stale read can silently drop options someone else just added; only use it when the user asks to set the value to exactly a given list. To apply a tag, pass the tag set's property_definition_id and the tag's option id (both from ListTags) in add_option_ids; to remove a tag, use remove_option_ids.
Tasks always have these system properties (use these property_definition_id values directly):
-- Assignees (00000001-0000-0000-0000-000000000001): entity type, multi-select. Use entity_refs with entity_type='user' and entity_id='macro|[email protected]'.
+- Assignees (00000001-0000-0000-0000-000000000001): entity type, multi-select. Use entity_refs with entity_type='user' and entity_id='macro|[email protected]' for people or 'bot|<agent UUID>' for agents. Adding an agent starts its session and replies in the task discussion.
- Status (00000001-0000-0000-0000-000000000002): select_string, single. Options: Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), In Review (...0003), Completed (...0004), Canceled (...0005).
- Priority (00000001-0000-0000-0000-000000000003): select_string, single. Options: Low (...0001), Medium (...0002), High (...0003), Urgent (...0004). Option IDs: 00000001-0000-0000-0003-0000000000XX.
- Due Date (00000001-0000-0000-0000-000000000004): date, single. Use date_value with ISO 8601.
diff --git a/crates/properties/src/outbound/entity_property_queries.rs b/crates/properties/src/outbound/entity_property_queries.rs
index 0cc6dfb238..2d087d6b8c 100644
--- a/crates/properties/src/outbound/entity_property_queries.rs
+++ b/crates/properties/src/outbound/entity_property_queries.rs
@@ -1,5 +1,8 @@
//! General entity property query helpers.
+#[cfg(test)]
+mod test;
+
use models_properties::service::{entity_property::EntityProperty, property_value::PropertyValue};
use models_properties::{EntityReference, EntityType};
use sqlx::{Pool, Postgres};
@@ -26,8 +29,8 @@ impl EntityPropertyMutationRow {
Some(value) if !value.is_null() => Some(serde_json::from_value(value)?),
Some(_) | None => None,
};
- // The pre-write value is display metadata; a row whose stored shape
- // no longer decodes must not fail the mutation that fixes it.
+ // The pre-write value supports display metadata and change triggers.
+ // Treat undecodable legacy values as absent so a mutation can fix them.
let previous_value = self
.previous
.filter(|value| !value.is_null())
@@ -51,8 +54,8 @@ impl EntityPropertyMutationRow {
/// Upsert an entity property value (insert or update).
/// If the property doesn't exist, it will be created and attached to the entity.
/// If it exists, the value will be updated. The returned snapshot carries the
-/// pre-write value (snapshotted by the CTE in the same statement) for
-/// activity's "changed X from A to B" transitions.
+/// pre-write value captured after serializing concurrent writes, so consumers
+/// can distinguish newly assigned agents from unchanged values.
pub async fn upsert_entity_property(
pool: &Pool<Postgres>,
entity_id: &str,
@@ -60,6 +63,52 @@ pub async fn upsert_entity_property(
property_definition_id: Uuid,
value: Option<PropertyValue>,
) -> anyhow::Result<EntityPropertyMutationSnapshot> {
+ let mut tx = pool.begin().await?;
+ let snapshot = upsert_entity_property_in_transaction(
+ &mut tx,
+ entity_id,
+ entity_type,
+ property_definition_id,
+ value,
+ )
+ .await?;
+ tx.commit().await?;
+ Ok(snapshot)
+}
+
+async fn upsert_entity_property_in_transaction(
+ tx: &mut sqlx::PgConnection,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ value: Option<PropertyValue>,
+) -> anyhow::Result<EntityPropertyMutationSnapshot> {
+ // Serialize first assignments even when no row exists to lock yet. Keep
+ // this separate from the UPSERT so its statement snapshot starts after
+ // the preceding writer commits, rather than before waiting for that row.
+ sqlx::query!(
+ r#"SELECT pg_advisory_xact_lock(hashtextextended($1, 0))"#,
+ format!("entity_property:{entity_type}:{entity_id}:{property_definition_id}"),
+ )
+ .execute(&mut *tx)
+ .await?;
+
+ // Other property operations use row locks rather than this advisory lock.
+ // Wait for those writers too before the UPSERT captures its previous value.
+ sqlx::query_scalar!(
+ r#"
+ SELECT values as "values: serde_json::Value"
+ FROM entity_properties
+ WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3
+ FOR UPDATE
+ "#,
+ entity_id,
+ entity_type as EntityType,
+ property_definition_id,
+ )
+ .fetch_optional(&mut *tx)
+ .await?;
+
let id = macro_uuid::generate_uuid_v7();
// Serialize PropertyValue to JSONB (or NULL if None)
@@ -70,9 +119,7 @@ pub async fn upsert_entity_property(
tracing::debug!(value_json = ?value_json, "upserting entity property");
- // Single UPSERT operation - handles both INSERT and UPDATE cases.
- // RETURNING yields the canonical assignment for both branches without a
- // second query; the CTE snapshots the pre-statement value.
+ // The locks above make this fresh statement snapshot authoritative.
let row = sqlx::query_as!(
EntityPropertyMutationRow,
r#"
@@ -102,7 +149,7 @@ pub async fn upsert_entity_property(
property_definition_id,
value_json
)
- .fetch_one(pool)
+ .fetch_one(&mut *tx)
.await?;
tracing::debug!("successfully upserted entity property");
diff --git a/crates/properties/src/outbound/entity_property_queries/test.rs b/crates/properties/src/outbound/entity_property_queries/test.rs
new file mode 100644
index 0000000000..5662d8092a
--- /dev/null
+++ b/crates/properties/src/outbound/entity_property_queries/test.rs
@@ -0,0 +1,132 @@
+use super::*;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use system_properties::SystemPropertyKey;
+
+fn assignment() -> PropertyValue {
+ PropertyValue::EntityRef(vec![EntityReference::new(
+ bot_id::CODEX_BOT_ID.into_storage_id().as_ref(),
+ EntityType::User,
+ )])
+}
+
+async fn wait_for_blocked_writer(pool: &Pool<Postgres>, blocker: i32) -> anyhow::Result<()> {
+ tokio::time::timeout(std::time::Duration::from_secs(10), async {
+ loop {
+ let waiting = sqlx::query_scalar!(
+ "SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE datname = current_database() AND $1 = ANY(pg_blocking_pids(pid))) AS \"exists!\"",
+ blocker,
+ )
+ .fetch_one(pool)
+ .await?;
+ if waiting {
+ return Ok::<_, sqlx::Error>(());
+ }
+ tokio::task::yield_now().await;
+ }
+ })
+ .await??;
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn concurrent_identical_assignments_report_only_one_new_assignment(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ for preattached in [false, true] {
+ let task_id = Uuid::now_v7().to_string();
+ if preattached {
+ upsert_entity_property(
+ &pool,
+ &task_id,
+ EntityType::Task,
+ SystemPropertyKey::ASSIGNEES_UUID,
+ None,
+ )
+ .await?;
+ }
+
+ let mut tx = pool.begin().await?;
+ let blocker = sqlx::query_scalar!("SELECT pg_backend_pid() AS \"pid!\"")
+ .fetch_one(&mut *tx)
+ .await?;
+ let first = upsert_entity_property_in_transaction(
+ &mut tx,
+ &task_id,
+ EntityType::Task,
+ SystemPropertyKey::ASSIGNEES_UUID,
+ Some(assignment()),
+ )
+ .await?;
+
+ let writer_pool = pool.clone();
+ let writer = tokio::spawn(async move {
+ upsert_entity_property(
+ &writer_pool,
+ &task_id,
+ EntityType::Task,
+ SystemPropertyKey::ASSIGNEES_UUID,
+ Some(assignment()),
+ )
+ .await
+ });
+ // The second request must already be waiting before the first commits:
+ // a pre-lock statement snapshot would still see the old empty value.
+ wait_for_blocked_writer(&pool, blocker).await?;
+ tx.commit().await?;
+ let second = writer.await??;
+
+ assert_eq!(first.previous_value, None, "preattached: {preattached}");
+ assert_eq!(second.previous_value, Some(assignment()));
+ assert_eq!(first.property.id, second.property.id);
+ assert_eq!(first.value, second.value);
+ }
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn assignment_snapshot_waits_for_writers_using_only_row_locks(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let task_id = Uuid::now_v7().to_string();
+ upsert_entity_property(
+ &pool,
+ &task_id,
+ EntityType::Task,
+ SystemPropertyKey::ASSIGNEES_UUID,
+ Some(assignment()),
+ )
+ .await?;
+
+ let mut tx = pool.begin().await?;
+ let blocker = sqlx::query_scalar!("SELECT pg_backend_pid() AS \"pid!\"")
+ .fetch_one(&mut *tx)
+ .await?;
+ // Deletion takes only PostgreSQL's row lock, and releases the assignment.
+ // The waiting assignment must observe that removal after it commits.
+ sqlx::query!(
+ "DELETE FROM entity_properties WHERE entity_id = $1 AND entity_type = $2",
+ task_id,
+ EntityType::Task as EntityType,
+ )
+ .execute(&mut *tx)
+ .await?;
+
+ let writer_pool = pool.clone();
+ let writer = tokio::spawn(async move {
+ upsert_entity_property(
+ &writer_pool,
+ &task_id,
+ EntityType::Task,
+ SystemPropertyKey::ASSIGNEES_UUID,
+ Some(assignment()),
+ )
+ .await
+ });
+ wait_for_blocked_writer(&pool, blocker).await?;
+ tx.commit().await?;
+ let reassigned = writer.await??;
+
+ assert_eq!(reassigned.previous_value, None);
+ assert_eq!(reassigned.value, Some(assignment()));
+ Ok(())
+}
diff --git a/crates/webhook/src/domain/ingestion.rs b/crates/webhook/src/domain/ingestion.rs
index cf13071378..ab08594fe7 100644
--- a/crates/webhook/src/domain/ingestion.rs
+++ b/crates/webhook/src/domain/ingestion.rs
@@ -439,6 +439,9 @@ pub(crate) fn normalized_agent_trigger_event(
use agent_trigger::domain::broker_events::AgentTriggerEventName;
let (bot_id, audience) = match &event.event {
+ AgentTriggerTopicEvent::New(
+ agent_trigger::domain::broker_events::NewAgentSessionEvent::AssignedToTask(assigned),
+ ) => Some((assigned.bot_id, TriggerAudience::parent(&assigned.parent))),
AgentTriggerTopicEvent::New(new) => match (new.mention(), new.requested()) {
(Some(mention), _) => Some((
mention.bot_id,
diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rs
index 43061f883d..e687563fb7 100644
--- a/crates/webhook/src/domain/ingestion/test.rs
+++ b/crates/webhook/src/domain/ingestion/test.rs
@@ -1443,6 +1443,86 @@ async fn a_document_trigger_is_gated_by_its_document() {
);
}
+fn agent_trigger_task_assignment_event() -> Event<AgentTriggerTopicEvent> {
+ use agent_trigger::domain::broker_events::{AgentAssignedToTaskEvent, NewAgentSessionEvent};
+
+ Event::new(AgentTriggerTopicEvent::New(
+ NewAgentSessionEvent::AssignedToTask(AgentAssignedToTaskEvent {
+ bot_id: bot_id::BotId::TEST_A,
+ parent: messages::domain::models::MessageParent::parse("document", DOCUMENT_ID)
+ .unwrap(),
+ discussion_id: uuid::Uuid::from_u128(2),
+ actor: user_id("macro|[email protected]"),
+ prompt: "Complete the assigned task".to_owned(),
+ }),
+ ))
+}
+
+#[tokio::test]
+async fn a_task_assignment_is_gated_by_the_task_and_delivered_under_the_bot() {
+ let access = MockAccessService::with_users(vec![user_id(PERSONAL_WORKSPACE_ID)]);
+ let repository = MockRepository::new(
+ vec![PERSONAL_WORKSPACE_ID.to_string()],
+ vec![webhook("wh_agent_feed", PERSONAL_WORKSPACE_ID)],
+ );
+ let enqueuer = MockEnqueuer::default();
+ let service = service(access.clone(), repository.clone(), enqueuer.clone());
+ let event = agent_trigger_task_assignment_event();
+
+ service
+ .ingest_agent_trigger_event(event.clone())
+ .await
+ .expect("task assignments are ingested");
+
+ assert_eq!(
+ lock(&access.calls).as_slice(),
+ &[(DOCUMENT_ID.to_owned(), EntityType::Document)],
+ );
+ let repository_state = lock(&repository.state);
+ assert_eq!(
+ repository_state.workspace_calls,
+ vec![vec![user_id(PERSONAL_WORKSPACE_ID)]],
+ );
+ assert_eq!(repository_state.match_calls.len(), 1);
+ assert_eq!(
+ repository_state.match_calls[0].entity_id,
+ bot_id::BotId::TEST_A.to_string(),
+ );
+ assert_eq!(
+ repository_state.match_calls[0].event_name,
+ "agent_trigger.new"
+ );
+ drop(repository_state);
+ let enqueuer_state = lock(&enqueuer.state);
+ assert_eq!(enqueuer_state.attempted_messages.len(), 1);
+ assert_eq!(
+ enqueuer_state.attempted_messages[0].event.broker_envelope,
+ serde_json::to_value(event).expect("serialize assignment envelope"),
+ );
+}
+
+#[tokio::test]
+async fn a_task_assignment_does_not_grant_the_assigner_access_to_the_trigger() {
+ let access = MockAccessService::with_users(vec![]);
+ let repository = MockRepository::new(vec![], vec![]);
+ let enqueuer = MockEnqueuer::default();
+ let service = service(access.clone(), repository.clone(), enqueuer.clone());
+
+ service
+ .ingest_agent_trigger_event(agent_trigger_task_assignment_event())
+ .await
+ .expect("an assignment without any readers is ingested");
+
+ assert_eq!(
+ lock(&access.calls).as_slice(),
+ &[(DOCUMENT_ID.to_owned(), EntityType::Document)],
+ );
+ let repository_state = lock(&repository.state);
+ assert_eq!(repository_state.workspace_calls, vec![vec![]]);
+ assert!(repository_state.match_calls[0].workspace_ids.is_empty());
+ assert!(lock(&enqueuer.state).attempted_messages.is_empty());
+}
+
/// An existing session does not grant a webhook access to a new message parent.
#[tokio::test]
async fn an_existing_session_trigger_is_gated_by_its_message_parent() {
diff --git a/docs/AGENT_GUIDE/tasks.md b/docs/AGENT_GUIDE/tasks.md
index ab39371a63..8ca1fc6051 100644
--- a/docs/AGENT_GUIDE/tasks.md
+++ b/docs/AGENT_GUIDE/tasks.md
@@ -262,6 +262,18 @@ including properties that do not have a value yet. Click a preview pill to edit
opening the task; the property picker keeps the preview open while you make a selection.
Users with view or comment access see the same pills read-only.
+The Assignees picker offers people and available agents together. Agent rows show
+their name and an `Agent` label; saved agents also show their `@handle`. Search by
+name or handle to find one. Built-in session agents follow the same availability
+as message mentions, alongside your own and team agents.
+Select an agent in the task composer, then create the task to start its session.
+For an existing task, add an agent to Assignees and dismiss the picker to save and
+start the session. Discussion gains one message from the assigned agent, which
+updates with its session or answer. The assignment instructions and task details
+are private startup context; no message is posted as you. People and agents
+can remain assigned together. Removing an agent and saving, then assigning it
+again starts a new session; saving an unchanged assignment does not restart it.
+
Selecting Status or Priority dismisses the picker immediately, without waiting
for the save request. With the GraphQL cache active, the pill updates
optimistically while the request is pending. To verify, delay `SetEntityProperty`
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index 0e902e3ba3..dfeeca37af 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -809,6 +809,10 @@ export type CreateSessionThread = {
*/
messageId: string;
parent?: null | MessageParent;
+ /**
+ * Update the existing bot response reserved by a task assignment.
+ */
+ reuseOriginMessage?: boolean;
/**
* Thread the session belongs to; defaults to the message itself, which
* is how a top-level mention roots its own thread.
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 07293928a5..2d529594a7 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -2649,6 +2649,10 @@
}
]
},
+ "reuseOriginMessage": {
+ "type": "boolean",
+ "description": "Update the existing bot response reserved by a task assignment."
+ },
"threadId": {
"type": ["string", "null"],
"format": "uuid",
diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.toml
index 7cbb5b3003..80e35fc8ae 100644
--- a/services/agent_harness_service/Cargo.toml
+++ b/services/agent_harness_service/Cargo.toml
@@ -60,6 +60,7 @@ macro_aws_config = { path = "../../crates/macro_aws_config", features = ["s3"] }
macro_event_broker = { path = "../../crates/macro_event_broker", features = ["outbound"] }
macro_queues = { path = "../../crates/macro_queues" }
lexical_client = { path = "../../crates/lexical_client" }
+document_storage_service_client = { path = "../../crates/document_storage_service_client" }
lexical_mention_extractor = { path = "../../crates/lexical_mention_extractor" }
macro_service_urls = { path = "../../crates/macro_service_urls" }
messages = { path = "../../crates/messages", features = ["broker", "delivery"] }
diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rs
index 3729ee2a5e..af35830e1c 100644
--- a/services/agent_harness_service/src/config.rs
+++ b/services/agent_harness_service/src/config.rs
@@ -154,6 +154,8 @@ pub struct Config {
pub inmem_harness_slug: String,
/// Key for internal service-to-service calls (the connection gateway).
pub internal_api_key: String,
+ /// Key required by document storage's internal endpoints.
+ pub document_storage_service_auth_key: String,
/// Port the control routes are served on.
#[macro_config_default(8101)]
pub port: u16,
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 4acb90f28a..65de43789c 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -820,7 +820,7 @@ async fn run() -> anyhow::Result<()> {
let prompt_mentions =
LexicalPromptMentions::new(lexical.clone(), PgSessionAccess::new(pool.clone()));
let prompt_context = MessagePromptContextAdapter::new(
- message_service,
+ message_service.clone(),
Arc::clone(&entity_access),
Arc::new(lexical.clone()),
);
@@ -1181,7 +1181,9 @@ async fn run() -> anyhow::Result<()> {
pool.clone(),
config.kafka_brokers.as_ref().to_owned(),
config.internal_api_key.clone(),
+ config.document_storage_service_auth_key.clone(),
config.agent_trigger_event_source,
+ message_service,
));
let egress_port = config.egress_port;
diff --git a/services/agent_harness_service/src/trigger.rs b/services/agent_harness_service/src/trigger.rs
index 67bd48ad62..3b0e9ad8a8 100644
--- a/services/agent_harness_service/src/trigger.rs
+++ b/services/agent_harness_service/src/trigger.rs
@@ -6,12 +6,14 @@ use agent_trigger::domain::service::AgentTriggerService;
use agent_trigger::domain::sources::{
ChannelTriggerEvents, MessageTriggerEvents, TriggerEventSource, TriggerEvents,
};
+use agent_trigger::domain::task_assignment::process_task_assignment;
use agent_trigger::outbound::{
- BotRepoAgentLookup, ChannelRepoTypeLookup, FastModelTriggerJudge,
+ BotRepoAgentLookup, ChannelRepoTypeLookup, DssTaskAssignmentContext, FastModelTriggerJudge,
LexicalExplicitReplyExtractor, MessageThreadHistory, VisionImageCaptioner,
};
use bots::outbound::pg_bots_repo::PgBotsRepo;
use channels::outbound::pg_channels_repo::PgChannelsRepo;
+use document_storage_service_client::DocumentStorageServiceClient;
use entity_registry::OwnerGrantPolicy;
use entity_registry_db_utils::OwnedEntityRegistrar;
use kafka_util::{GroupName, KafkaEventConsumer, consumer_span, record_span_error};
@@ -20,11 +22,13 @@ use macro_event_broker::{
KafkaConsumerAdapter, KafkaEventPublisher, MacroEventBrokerService, MacroEventCollection,
MacroEventConsumerService,
};
-use macro_service_urls::{LexicalServiceUrl, StaticFileServiceUrl};
+use macro_service_urls::{DocumentStorageServiceUrl, LexicalServiceUrl, StaticFileServiceUrl};
+use messages::domain::api::MessageServiceApi;
use messages::outbound::pg_message_repo::PgMessageRepository;
use rdkafka::consumer::CommitMode;
use rdkafka::message::{BorrowedMessage, Message as _};
use sqlx::PgPool;
+use std::sync::Arc;
use tokio::time::{Duration, sleep};
use tracing::Instrument as _;
@@ -69,14 +73,18 @@ pub async fn supervise(
pool: PgPool,
kafka_brokers: String,
internal_api_key: String,
+ document_storage_service_auth_key: String,
source: TriggerEventSource,
+ messages: Arc<dyn MessageServiceApi>,
) {
loop {
if let Err(error) = run(
pool.clone(),
kafka_brokers.clone(),
internal_api_key.clone(),
+ document_storage_service_auth_key.clone(),
source,
+ messages.clone(),
)
.await
{
@@ -90,9 +98,21 @@ async fn run(
pool: PgPool,
kafka_brokers: String,
internal_api_key: String,
+ document_storage_service_auth_key: String,
source: TriggerEventSource,
+ messages: Arc<dyn MessageServiceApi>,
) -> anyhow::Result<()> {
- let lexical = LexicalClient::new(internal_api_key, LexicalServiceUrl::new()?.to_string());
+ let lexical = LexicalClient::new(
+ internal_api_key.clone(),
+ LexicalServiceUrl::new()?.to_string(),
+ );
+ let task_context = DssTaskAssignmentContext::new(
+ DocumentStorageServiceClient::new(
+ document_storage_service_auth_key,
+ DocumentStorageServiceUrl::new()?.to_string(),
+ ),
+ lexical.clone(),
+ );
let recorder = ai_usage::pg_recorder(pool.clone());
let images = VisionImageCaptioner::new(
static_file::outbound::CdnStaticFileRepo::new(StaticFileServiceUrl::new()?.to_string()),
@@ -131,10 +151,26 @@ async fn run(
let consumer = KafkaConsumerAdapter::<AgentTriggerConsumerGroup, ()>::new(consumer);
match source {
TriggerEventSource::Messages => {
- consume::<MessageTriggerEvents>(consumer, &trigger, &publisher, &channel_types).await
+ consume::<MessageTriggerEvents>(
+ consumer,
+ &trigger,
+ &publisher,
+ &channel_types,
+ messages.as_ref(),
+ &task_context,
+ )
+ .await
}
TriggerEventSource::Channels => {
- consume::<ChannelTriggerEvents>(consumer, &trigger, &publisher, &channel_types).await
+ consume::<ChannelTriggerEvents>(
+ consumer,
+ &trigger,
+ &publisher,
+ &channel_types,
+ messages.as_ref(),
+ &task_context,
+ )
+ .await
}
}
}
@@ -145,6 +181,8 @@ async fn consume<Events: TriggerEvents>(
trigger: &Trigger,
publisher: &Publisher,
channel_types: &ChannelTypes,
+ messages: &dyn MessageServiceApi,
+ task_context: &DssTaskAssignmentContext,
) -> anyhow::Result<()> {
let consumer = consumer
.subscribe::<Events>()
@@ -191,6 +229,10 @@ async fn consume<Events: TriggerEvents>(
if let Some(posted) = &decoded.posted {
process_message_event(trigger, publisher, channel_types, posted).await?;
}
+ if let Some(assignment) = &decoded.assignment {
+ process_task_assignment(trigger, publisher, messages, task_context, assignment)
+ .await?;
+ }
commit_message(&consumer, kafka_message)?;
Ok(())
}
diff --git a/services/agent_trigger_service/Cargo.toml b/services/agent_trigger_service/Cargo.toml
index ebbdc327a9..1af577ba48 100644
--- a/services/agent_trigger_service/Cargo.toml
+++ b/services/agent_trigger_service/Cargo.toml
@@ -17,7 +17,9 @@ ai_usage = { path = "../../crates/ai_usage" }
anyhow = { workspace = true }
bots = { path = "../../crates/bots", default-features = false, features = ["outbound", "ports"] }
channels = { path = "../../crates/channels", default-features = false, features = ["outbound", "ports"] }
+connection_gateway_client = { path = "../../crates/connection_gateway_client" }
database_env_vars = { path = "../../crates/database_env_vars" }
+document_storage_service_client = { path = "../../crates/document_storage_service_client" }
entity_access = { path = "../../crates/entity_access" }
entity_registry = { path = "../../crates/entity_registry/entity_registry", default-features = false }
entity_registry_db_utils = { path = "../../crates/entity_registry/entity_registry_db_utils" }
@@ -28,8 +30,9 @@ macro_entrypoint = { path = "../../crates/macro_entrypoint" }
macro_env_var = { path = "../../crates/macro_env_var" }
macro_event_broker = { path = "../../crates/macro_event_broker", features = ["outbound"] }
macro_service_urls = { path = "../../crates/macro_service_urls" }
-messages = { path = "../../crates/messages", features = ["broker", "outbound"] }
+messages = { path = "../../crates/messages", features = ["broker", "delivery", "outbound"] }
rdkafka = { workspace = true }
+rootcause = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
static_file = { path = "../../crates/static_file" }
diff --git a/services/agent_trigger_service/src/config.rs b/services/agent_trigger_service/src/config.rs
index 9de1eeefed..dfd1a58c87 100644
--- a/services/agent_trigger_service/src/config.rs
+++ b/services/agent_trigger_service/src/config.rs
@@ -20,6 +20,8 @@ pub struct Config {
pub kafka_brokers: KafkaBrokers,
/// Key for internal service-to-service calls (the lexical service).
pub internal_api_key: String,
+ /// Key required by document storage's internal endpoints.
+ pub document_storage_service_auth_key: String,
/// Which committed-post topic feeds the trigger: `messages` (the default,
/// channel and document posts) or `channels` (the pre-parent channel
/// event, kept until its producer retires it). Never both: every channel
diff --git a/services/agent_trigger_service/src/main.rs b/services/agent_trigger_service/src/main.rs
index ba2f199e6b..5aca9b6fb6 100644
--- a/services/agent_trigger_service/src/main.rs
+++ b/services/agent_trigger_service/src/main.rs
@@ -10,14 +10,17 @@ use agent_session::outbound::postgres::PgAgentSessionRepo;
use agent_trigger::domain::processing::process_message_event;
use agent_trigger::domain::service::AgentTriggerService;
use agent_trigger::domain::sources::{ChannelTriggerEvents, MessageTriggerEvents, TriggerEvents};
+use agent_trigger::domain::task_assignment::process_task_assignment;
use agent_trigger::outbound::{
- BotRepoAgentLookup, ChannelRepoTypeLookup, FastModelTriggerJudge,
+ BotRepoAgentLookup, ChannelRepoTypeLookup, DssTaskAssignmentContext, FastModelTriggerJudge,
LexicalExplicitReplyExtractor, MessageThreadHistory, VisionImageCaptioner,
};
use anyhow::Context as _;
use bots::outbound::pg_bots_repo::PgBotsRepo;
use channels::outbound::pg_channels_repo::PgChannelsRepo;
use config::Config;
+use connection_gateway_client::client::ConnectionGatewayClient;
+use document_storage_service_client::DocumentStorageServiceClient;
use entity_registry::OwnerGrantPolicy;
use entity_registry_db_utils::OwnedEntityRegistrar;
use kafka_util::{GroupName, KafkaEventConsumer, consumer_span, record_span_error};
@@ -27,11 +30,15 @@ use macro_event_broker::{
KafkaConsumerAdapter, KafkaEventPublisher, MacroEventBrokerService, MacroEventCollection,
MacroEventConsumerService,
};
-use macro_service_urls::{LexicalServiceUrl, StaticFileServiceUrl};
+use macro_service_urls::{
+ ConnectionGatewayUrl, DocumentStorageServiceUrl, LexicalServiceUrl, StaticFileServiceUrl,
+};
+use messages::domain::api::MessageCommands;
use messages::outbound::pg_message_repo::PgMessageRepository;
use rdkafka::consumer::CommitMode;
use rdkafka::message::{BorrowedMessage, Message as _};
use sqlx::postgres::PgPoolOptions;
+use std::sync::Arc;
use tracing::Instrument as _;
struct AgentTriggerConsumerGroup;
@@ -60,6 +67,19 @@ type ChannelTypes = ChannelRepoTypeLookup<PgChannelsRepo>;
type TriggerKafkaAdapter<M> = KafkaConsumerAdapter<AgentTriggerConsumerGroup, M>;
type TriggerConsumer<M> = MacroEventConsumerService<M, TriggerKafkaAdapter<M>>;
+// This worker only posts silent assignment roots. Session replies and their
+// notifications are delivered by the harness's full message service.
+struct SilentAssignmentNotifications;
+
+impl messages::domain::delivery::DiscussionNotifier for SilentAssignmentNotifications {
+ async fn send(
+ &self,
+ _: messages::domain::delivery::DiscussionNotification<'_>,
+ ) -> Result<(), rootcause::Report> {
+ Ok(())
+ }
+}
+
fn commit_message<M: MacroEventCollection + 'static>(
consumer: &TriggerConsumer<M>,
message: &BorrowedMessage<'_>,
@@ -91,6 +111,13 @@ async fn run() -> anyhow::Result<()> {
config.internal_api_key.clone(),
LexicalServiceUrl::new()?.to_string(),
);
+ let task_context = DssTaskAssignmentContext::new(
+ DocumentStorageServiceClient::new(
+ config.document_storage_service_auth_key.clone(),
+ DocumentStorageServiceUrl::new()?.to_string(),
+ ),
+ lexical.clone(),
+ );
let recorder = ai_usage::pg_recorder(pool.clone());
let images = VisionImageCaptioner::new(
static_file::outbound::CdnStaticFileRepo::new(StaticFileServiceUrl::new()?.to_string()),
@@ -120,21 +147,60 @@ async fn run() -> anyhow::Result<()> {
),
),
);
- let channel_types = ChannelRepoTypeLookup::new(PgChannelsRepo::new(pool));
+ let channel_types = ChannelRepoTypeLookup::new(PgChannelsRepo::new(pool.clone()));
let publisher = MacroEventBrokerService::new(
KafkaEventPublisher::new(config.kafka_brokers.as_ref())?,
macro_event_broker::GlobalSpawner,
);
+ let discussion_delivery = messages::domain::delivery::DiscussionDelivery::new(
+ messages::outbound::pg_discussion_context::PgDiscussionContext(pool.clone()),
+ messages::outbound::entity_access_audience::EntityAccessMessageAudience(
+ entity_access::domain::service::EntityAccessServiceImpl::new(
+ entity_access::outbound::PgAccessRepository::new(pool.clone()),
+ ),
+ ),
+ messages::outbound::connection_gateway::ConnectionGatewayMessages(Arc::new(
+ ConnectionGatewayClient::new(
+ config.internal_api_key.clone(),
+ ConnectionGatewayUrl::new()?.to_string(),
+ ),
+ )),
+ SilentAssignmentNotifications,
+ );
+ let messages = messages::domain::service::MessageService::new(
+ PgMessageRepository::new(pool),
+ messages::domain::effects::MessageEffects::new(
+ messages::outbound::broker::BrokerMessagePublisher::new(publisher.clone()),
+ messages::domain::ports::NoMessageEventPublisher,
+ discussion_delivery,
+ ),
+ );
let consumer =
KafkaEventConsumer::<AgentTriggerConsumerGroup>::from_env(config.kafka_brokers.as_ref())?;
let consumer = KafkaConsumerAdapter::<AgentTriggerConsumerGroup, ()>::new(consumer);
match config.agent_trigger_event_source {
agent_trigger::domain::sources::TriggerEventSource::Messages => {
- consume::<MessageTriggerEvents>(consumer, &trigger, &publisher, &channel_types).await
+ consume::<MessageTriggerEvents>(
+ consumer,
+ &trigger,
+ &publisher,
+ &channel_types,
+ &messages,
+ &task_context,
+ )
+ .await
}
agent_trigger::domain::sources::TriggerEventSource::Channels => {
- consume::<ChannelTriggerEvents>(consumer, &trigger, &publisher, &channel_types).await
+ consume::<ChannelTriggerEvents>(
+ consumer,
+ &trigger,
+ &publisher,
+ &channel_types,
+ &messages,
+ &task_context,
+ )
+ .await
}
}
}
@@ -145,6 +211,8 @@ async fn consume<Events: TriggerEvents>(
trigger: &Trigger,
publisher: &Publisher,
channel_types: &ChannelTypes,
+ messages: &dyn MessageCommands,
+ task_context: &DssTaskAssignmentContext,
) -> anyhow::Result<()> {
let consumer = consumer
.subscribe::<Events>()
@@ -197,6 +265,9 @@ async fn consume<Events: TriggerEvents>(
if let Some(posted) = &decoded.posted {
process_message_event(trigger, publisher, channel_types, posted).await?;
}
+ if let Some(assignment) = &decoded.assignment {
+ process_task_assignment(trigger, publisher, messages, task_context, assignment).await?;
+ }
commit_message(&consumer, kafka_message)?;
Ok(())
}
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index e8c0f062eb..8cff205846 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -254,14 +254,6 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
entity_access::outbound::PgAccessRepository::new(pool.clone()),
),
);
- let properties_service =
- ai_tools::build_properties_service(pool.clone(), entity_access_service.clone());
- let task_properties_service = ai_tools::build_task_properties_adapter(
- pool.clone(),
- properties_service.clone(),
- entity_access_service.clone(),
- );
-
// Producer creation is lazy: nothing connects to Kafka unless an event
// is published, so a dummy broker address is safe for tests.
let macro_event_broker = macro_event_broker::MacroEventBrokerService::new(
@@ -269,6 +261,16 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
.expect("kafka producer config is valid"),
TaskTracker::new(),
);
+ let properties_service = ai_tools::build_properties_service_with_broker(
+ pool.clone(),
+ entity_access_service.clone(),
+ macro_event_broker.clone(),
+ );
+ let task_properties_service = ai_tools::build_task_properties_adapter(
+ pool.clone(),
+ properties_service.clone(),
+ entity_access_service.clone(),
+ );
let document_service = documents::domain::service::DocumentServiceImpl::new(
document_repo,
diff --git a/services/lexical-service/src/endpoints/agent-announcement.test.ts b/services/lexical-service/src/endpoints/agent-announcement.test.ts
index 5bcf8e889c..94ff583683 100644
--- a/services/lexical-service/src/endpoints/agent-announcement.test.ts
+++ b/services/lexical-service/src/endpoints/agent-announcement.test.ts
@@ -45,6 +45,15 @@ describe('agent announcements', () => {
if (!match?.[1]) throw new Error(`no reply target in ${markdown}`);
return readReplyTargetData(JSON.parse(match[1]));
};
+ it('announces an assignment as a chip without a user reply target', async () => {
+ const response = await request({ chip });
+ expect(response.status).toBe(200);
+ const { markdown } = await response.json<{ markdown: string }>();
+ expect(markdown).toBe(
+ `<m-magic-chip>${JSON.stringify(chip)}</m-magic-chip>`
+ );
+ expect(markdown).not.toContain('m-reply-target');
+ });
it('announces under the parent the reply lives in', async () => {
const parent = { type: 'document' as const, id: 'doc' };
const response = await request({
diff --git a/services/lexical-service/src/endpoints/agent-announcement.ts b/services/lexical-service/src/endpoints/agent-announcement.ts
index 40931bb489..4152a54252 100644
--- a/services/lexical-service/src/endpoints/agent-announcement.ts
+++ b/services/lexical-service/src/endpoints/agent-announcement.ts
@@ -35,7 +35,7 @@ const replyTargetRequest = z
);
const sessionAnnouncementRequest = z.object({
- replyTarget: replyTargetRequest,
+ replyTarget: replyTargetRequest.optional(),
chip: z.object({
agentSessionId: z.string(),
channelId: z.string().optional(),
@@ -130,15 +130,25 @@ export class AgentAnnouncementEndpoint extends OpenAPIRoute {
markdown: composeAgentChatReply({ sessionId, body: replyBody }),
});
}
- const { parent, channelId, ...target } = body.replyTarget;
- // Callers that predate message parents send only `channelId`; the
- // node itself references any parent the reply lives under.
- const replyParent: ReplyTargetParent | undefined =
- parent ?? (channelId ? { type: 'channel', id: channelId } : undefined);
+ const target = body.replyTarget;
+ // Assignments have no user-authored message to quote.
+ const replyParent: ReplyTargetParent | undefined = target
+ ? (target.parent ??
+ (target.channelId
+ ? { type: 'channel', id: target.channelId }
+ : undefined))
+ : undefined;
const markdown = composeAgentSessionAnnouncement({
- replyTarget: replyParent
- ? { ...target, parent: replyParent }
- : undefined,
+ replyTarget:
+ target && replyParent
+ ? {
+ parent: replyParent,
+ targetMessageId: target.targetMessageId,
+ targetThreadId: target.targetThreadId,
+ displayText: target.displayText,
+ senderId: target.senderId,
+ }
+ : undefined,
chip: body.chip,
});
return c.json({ markdown });