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.

fix(calls): surface call records in ListEntities (#5124)

gbirmane0a6388384bd
diff --git a/apps/web/scripts/generate-dcs-tools.ts b/apps/web/scripts/generate-dcs-tools.ts
index fe437ab806..a7ad98ff6f 100644
--- a/apps/web/scripts/generate-dcs-tools.ts
+++ b/apps/web/scripts/generate-dcs-tools.ts
@@ -85,8 +85,40 @@ async function loadFrontendSchemas(): Promise<FrontendSchemas> {
return parsed;
}
+// json-schema-to-zod drops both `.optional()` and `.default()` for an optional
+// property whose schema is `anyOf: [<multi-literal oneOf>, null]` with a
+// `default` (e.g. an `Option<Enum>` field). The result is a required key the
+// model legitimately omits, so `deserializeToolCall` fails and the whole tool
+// card is hidden. The `default` is meaningless for parse-to-render, so strip it
+// from every optional (non-required) property; the field then renders as
+// `.optional()`.
+function stripOptionalDefaults(node: unknown): void {
+ if (Array.isArray(node)) {
+ for (const child of node) stripOptionalDefaults(child);
+ return;
+ }
+ if (!node || typeof node !== 'object') return;
+ const obj = node as Record<string, unknown>;
+ const properties = obj.properties;
+ if (properties && typeof properties === 'object') {
+ const required = new Set(Array.isArray(obj.required) ? obj.required : []);
+ for (const [key, propSchema] of Object.entries(properties)) {
+ if (
+ !required.has(key) &&
+ propSchema &&
+ typeof propSchema === 'object' &&
+ 'default' in propSchema
+ ) {
+ delete (propSchema as Record<string, unknown>).default;
+ }
+ }
+ }
+ for (const value of Object.values(obj)) stripOptionalDefaults(value);
+}
+
async function generateSchemasFile(schema: FrontendSchemas) {
const resolved = await $RefParser.dereference(structuredClone(schema));
+ stripOptionalDefaults(resolved);
const defs = (resolved as { $defs: Record<string, JsonObject> }).$defs;
const seen = new Set<string>();
const content: string[] = [];
diff --git a/apps/web/src/features/next-soup/soup-view/soup-entity-context-menu.tsx b/apps/web/src/features/next-soup/soup-view/soup-entity-context-menu.tsx
index 4f22e7a0c2..2f52f7d779 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-entity-context-menu.tsx
+++ b/apps/web/src/features/next-soup/soup-view/soup-entity-context-menu.tsx
@@ -31,6 +31,7 @@ function tagEntityType(entity: EntityData): EntityType | undefined {
.with({ type: 'email' }, () => EntityType.THREAD)
.with({ type: 'project' }, () => EntityType.PROJECT)
.with({ type: 'chat' }, () => EntityType.CHAT)
+ .with({ type: 'call' }, () => EntityType.CALL_RECORD)
.otherwise(() => undefined);
}
diff --git a/apps/web/src/lib/core/component/AI/component/tool/ListCallRecords.tsx b/apps/web/src/lib/core/component/AI/component/tool/ListCallRecords.tsx
deleted file mode 100644
index bb4d3ca2cb..0000000000
--- a/apps/web/src/lib/core/component/AI/component/tool/ListCallRecords.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import PhoneList from '@phosphor-icons/core/regular/phone-list.svg';
-import { BaseTool } from './BaseTool';
-import { createToolRenderer } from './ToolRenderer';
-
-const handler = createToolRenderer({
- name: 'ListCallRecords',
- render: (ctx) => (
- <BaseTool type="call" icon={PhoneList} renderContext={ctx.renderContext}>
- List call records
- {ctx.tool.data.channelId ? (
- <>
- {' '}
- in <span class="text-ink">channel {ctx.tool.data.channelId}</span>
- </>
- ) : null}
- </BaseTool>
- ),
-});
-
-export const listCallRecordsHandler = handler;
diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
index c4b65d86d4..a05cd228bb 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
@@ -18,7 +18,6 @@ import {
deleteImportEntityHandler,
listImportEntitiesHandler,
} from './ImportTools';
-import { listCallRecordsHandler } from './ListCallRecords';
import { listEntitiesHandler } from './ListEntities';
import { listInboxesHandler } from './ListInboxes';
import { listLabelsHandler } from './ListLabels';
@@ -70,7 +69,6 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
GetCompany: getCompanyHandler,
GetEntityProperties: getEntityPropertiesHandler,
ListCompanies: listCompaniesHandler,
- ListCallRecords: listCallRecordsHandler,
ListImportEntities: listImportEntitiesHandler,
ListEntities: listEntitiesHandler,
ListInboxes: listInboxesHandler,
diff --git a/apps/web/src/lib/queries/properties/entity.ts b/apps/web/src/lib/queries/properties/entity.ts
index a1753c5038..13257c3eea 100644
--- a/apps/web/src/lib/queries/properties/entity.ts
+++ b/apps/web/src/lib/queries/properties/entity.ts
@@ -119,11 +119,11 @@ function optimisticUpdateSoupEntityProperties(
}[]
): SoupTransaction | undefined {
const current = getSoupEntityById(entityId);
- // channel / call / foreign entities are property-less.
+ // channel / foreign entity / channel thread rows are property-less; call
+ // records carry properties (tags) and are handled like documents.
if (
!current ||
current.tag === 'channel' ||
- current.tag === 'call' ||
current.tag === 'foreignEntity' ||
current.tag === 'channelThread' ||
!current.data.properties
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/normalizer.ts b/apps/web/src/lib/queries/soup/normalized-cache/normalizer.ts
index f21d9616f8..34bae70c45 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/normalizer.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/normalizer.ts
@@ -28,6 +28,9 @@ export const getNormalizationObjectKey = (
const channel = data?.channel as Record<string, unknown> | undefined;
return channel?.id ? soupNormKey(channel.id as string) : undefined;
}
+ if (obj.tag === 'call') {
+ return data?.callId ? soupNormKey(data.callId as string) : undefined;
+ }
return data?.id ? soupNormKey(data.id as string) : undefined;
}
return undefined;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index 6303711186..8eddc421b9 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -72,7 +72,7 @@ export const BashCodeExecutionResponse = z.object({
});
export const BulkSetEntityPropertyOptions = z.object({
- add_option_ids: z.union([z.array(z.string().uuid()), z.null()]).default(null),
+ add_option_ids: z.union([z.array(z.string().uuid()), z.null()]).optional(),
entities: z.array(
z.object({
entity_id: z.string(),
@@ -89,9 +89,7 @@ export const BulkSetEntityPropertyOptions = z.object({
})
),
property_definition_id: z.string().uuid(),
- remove_option_ids: z
- .union([z.array(z.string().uuid()), z.null()])
- .default(null),
+ remove_option_ids: z.union([z.array(z.string().uuid()), z.null()]).optional(),
});
export const BulkSetEntityPropertyOptionsResponse = z.object({
@@ -118,8 +116,8 @@ export const ContentSearch = z.object({
'call_records',
])
)
- .default([]),
- inbox: z.union([z.string(), z.null()]).default(null),
+ .optional(),
+ inbox: z.union([z.string(), z.null()]).optional(),
matchType: z
.intersection(
z.any().superRefine((x, ctx) => {
@@ -149,28 +147,30 @@ export const ContentSearch = z.object({
z.array(
z.object({
label: z.string(),
- scope: z.union([
- z.any().superRefine((x, ctx) => {
- const schemas = [z.literal('personal'), z.literal('team')];
- const errors = schemas.reduce<z.ZodError[]>(
- (errors, schema) =>
- ((result) =>
- result.error ? [...errors, result.error] : errors)(
- schema.safeParse(x)
- ),
- []
- );
- if (schemas.length - errors.length !== 1) {
- ctx.addIssue({
- path: ctx.path,
- code: 'invalid_union',
- unionErrors: errors,
- message: 'Invalid input: Should pass single schema',
- });
- }
- }),
- z.null(),
- ]),
+ scope: z
+ .union([
+ z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('personal'), z.literal('team')];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error ? [...errors, result.error] : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ z.null(),
+ ])
+ .optional(),
})
),
z.null(),
@@ -646,7 +646,7 @@ export const CreateDocument = z.object({
documentName: z.string(),
fileContent: z.string(),
fileExtension: z.string(),
- isTask: z.boolean().default(false),
+ isTask: z.boolean().optional(),
});
export const CreateDocumentResponse = z.object({
@@ -654,7 +654,7 @@ export const CreateDocumentResponse = z.object({
});
export const CreateImportEntity = z.object({
- entityId: z.union([z.string(), z.null()]).default(null),
+ entityId: z.union([z.string(), z.null()]).optional(),
foreignId: z.string(),
metadata: z.any(),
source: z.any().superRefine((x, ctx) => {
@@ -910,7 +910,7 @@ export const EditTag = z.object({
])
.optional(),
id: z.string().uuid(),
- label: z.union([z.string(), z.null()]).default(null),
+ label: z.union([z.string(), z.null()]).optional(),
property_definition_id: z.string().uuid(),
});
@@ -1028,7 +1028,7 @@ export const GetEntityPropertiesResponse = z.object({
});
export const GetThread = z.object({
- limit: z.union([z.number().int(), z.null()]).default(null),
+ limit: z.union([z.number().int(), z.null()]).optional(),
threadId: z.string().uuid(),
});
@@ -1069,41 +1069,12 @@ export const GetThreadResponse = z.object({
threadId: z.string().uuid(),
});
-export const ListCallRecords = z.object({
- attended: z.union([z.boolean(), z.null()]).optional(),
- channelId: z.union([z.string().uuid(), z.null()]).optional(),
- status: z
- .union([z.enum(['ATTENDED', 'MISSED', 'UNATTENDED']), z.null()])
- .optional(),
-});
-
-export const ListCallRecordsResponse = z.object({
- records: z.array(
- z.object({
- callId: z.string().uuid(),
- channelId: z.string().uuid(),
- channelName: z.union([z.string(), z.null()]).optional(),
- createdBy: z.string(),
- durationMs: z.union([z.number().int(), z.null()]).optional(),
- endedAt: z
- .union([z.string().datetime({ offset: true }), z.null()])
- .optional(),
- isActive: z.boolean(),
- participants: z.array(z.string()),
- startedAt: z.string().datetime({ offset: true }),
- status: z
- .union([z.enum(['ATTENDED', 'MISSED', 'UNATTENDED']), z.null()])
- .optional(),
- })
- ),
-});
-
export const ListCompanies = z.object({
- include_hidden: z.union([z.boolean(), z.null()]).default(null),
- limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).default(null),
- owner_user_id: z.union([z.string(), z.null()]).default(null),
- search: z.union([z.string(), z.null()]).default(null),
- stage: z.union([z.string(), z.null()]).default(null),
+ include_hidden: z.union([z.boolean(), z.null()]).optional(),
+ limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).optional(),
+ owner_user_id: z.union([z.string(), z.null()]).optional(),
+ search: z.union([z.string(), z.null()]).optional(),
+ stage: z.union([z.string(), z.null()]).optional(),
});
export const ListCompaniesResponse = z.object({
@@ -1128,16 +1099,16 @@ export const ListCompaniesResponse = z.object({
});
export const ListEntities = z.object({
- callf: z.any().default(null),
- cf: z.any().default(null),
- chanf: z.any().default(null),
- cthf: z.any().default(null),
- df: z.any().default(null),
- ef: z.any().default(null),
+ callf: z.any().optional(),
+ cf: z.any().optional(),
+ chanf: z.any().optional(),
+ cthf: z.any().optional(),
+ df: z.any().optional(),
+ ef: z.any().optional(),
emailPreset: z.union([z.literal('signal'), z.null()]).optional(),
- emailView: z.union([z.string(), z.null()]).default(null),
- fef: z.any().default(null),
- inbox: z.union([z.string(), z.null()]).default(null),
+ emailView: z.union([z.string(), z.null()]).optional(),
+ fef: z.any().optional(),
+ inbox: z.union([z.string(), z.null()]).optional(),
includeTypes: z
.union([
z.array(
@@ -1172,9 +1143,9 @@ export const ListEntities = z.object({
z.null(),
])
.optional(),
- limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).default(null),
- pf: z.any().default(null),
- propf: z.any().default(null),
+ limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).optional(),
+ pf: z.any().optional(),
+ propf: z.any().optional(),
sortBy: z
.any()
.superRefine((x, ctx) => {
@@ -1205,28 +1176,30 @@ export const ListEntities = z.object({
z.array(
z.object({
label: z.string(),
- scope: z.union([
- z.any().superRefine((x, ctx) => {
- const schemas = [z.literal('personal'), z.literal('team')];
- const errors = schemas.reduce<z.ZodError[]>(
- (errors, schema) =>
- ((result) =>
- result.error ? [...errors, result.error] : errors)(
- schema.safeParse(x)
- ),
- []
- );
- if (schemas.length - errors.length !== 1) {
- ctx.addIssue({
- path: ctx.path,
- code: 'invalid_union',
- unionErrors: errors,
- message: 'Invalid input: Should pass single schema',
- });
- }
- }),
- z.null(),
- ]),
+ scope: z
+ .union([
+ z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('personal'), z.literal('team')];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error ? [...errors, result.error] : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ z.null(),
+ ])
+ .optional(),
})
),
z.null(),
@@ -1487,7 +1460,7 @@ export const ListImportEntities = z.object({
}),
z.null(),
])
- .default(null),
+ .optional(),
status: z
.union([
z.any().superRefine((x, ctx) => {
@@ -1515,7 +1488,7 @@ export const ListImportEntities = z.object({
}),
z.null(),
])
- .default(null),
+ .optional(),
});
export const ListImportEntitiesResponse = z.object({
@@ -1590,8 +1563,8 @@ export const ListInboxesResponse = z.object({
});
export const ListLabels = z.object({
- inbox: z.union([z.string(), z.null()]).default(null),
- thread_id: z.union([z.string().uuid(), z.null()]).default(null),
+ inbox: z.union([z.string(), z.null()]).optional(),
+ thread_id: z.union([z.string().uuid(), z.null()]).optional(),
});
export const ListLabelsResponse = z.object({
@@ -1602,7 +1575,7 @@ export const ListLabelsResponse = z.object({
});
export const ListNotifications = z.object({
- done: z.union([z.boolean(), z.null()]).default(null),
+ done: z.union([z.boolean(), z.null()]).optional(),
entities: z
.union([
z.array(
@@ -1623,7 +1596,7 @@ export const ListNotifications = z.object({
),
z.null(),
])
- .default(null),
+ .optional(),
includeTypes: z
.union([
z.array(
@@ -1641,9 +1614,9 @@ export const ListNotifications = z.object({
),
z.null(),
])
- .default(null),
- limit: z.union([z.number().int().gte(0), z.null()]).default(null),
- seen: z.union([z.boolean(), z.null()]).default(null),
+ .optional(),
+ limit: z.union([z.number().int().gte(0), z.null()]).optional(),
+ seen: z.union([z.boolean(), z.null()]).optional(),
});
export const ListNotificationsResponse = z.object({
@@ -1739,8 +1712,8 @@ export const NameSearch = z.object({
'call_records',
])
)
- .default([]),
- inbox: z.union([z.string(), z.null()]).default(null),
+ .optional(),
+ inbox: z.union([z.string(), z.null()]).optional(),
matchType: z
.intersection(
z.any().superRefine((x, ctx) => {
@@ -1770,28 +1743,30 @@ export const NameSearch = z.object({
z.array(
z.object({
label: z.string(),
- scope: z.union([
- z.any().superRefine((x, ctx) => {
- const schemas = [z.literal('personal'), z.literal('team')];
- const errors = schemas.reduce<z.ZodError[]>(
- (errors, schema) =>
- ((result) =>
- result.error ? [...errors, result.error] : errors)(
- schema.safeParse(x)
- ),
- []
- );
- if (schemas.length - errors.length !== 1) {
- ctx.addIssue({
- path: ctx.path,
- code: 'invalid_union',
- unionErrors: errors,
- message: 'Invalid input: Should pass single schema',
- });
- }
- }),
- z.null(),
- ]),
+ scope: z
+ .union([
+ z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('personal'), z.literal('team')];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error ? [...errors, result.error] : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ z.null(),
+ ])
+ .optional(),
})
),
z.null(),
@@ -1841,21 +1816,19 @@ export const ReadCallRecordResponse = z.object({
export const ReadChannelMessageContext = z.object({
channelAfter: z
.union([z.number().int().gte(0).lte(65535), z.null()])
- .default(null),
+ .optional(),
channelBefore: z
.union([z.number().int().gte(0).lte(65535), z.null()])
- .default(null),
+ .optional(),
channelId: z.string().uuid(),
- maxCharsPerMessage: z
- .union([z.number().int().gte(0), z.null()])
- .default(null),
+ maxCharsPerMessage: z.union([z.number().int().gte(0), z.null()]).optional(),
messageId: z.string().uuid(),
threadAfter: z
.union([z.number().int().gte(0).lte(65535), z.null()])
- .default(null),
+ .optional(),
threadBefore: z
.union([z.number().int().gte(0).lte(65535), z.null()])
- .default(null),
+ .optional(),
});
export const ReadChannelMessageContextResponse = z.object({
@@ -2271,19 +2244,15 @@ export const ReadChannelMessageContextResponse = z.object({
export const ReadChannelMessages = z.object({
channelId: z.string().uuid(),
- cursor: z.union([z.string(), z.null()]).default(null),
- direction: z.union([z.enum(['older', 'newer']), z.null()]).default(null),
- from: z
- .union([z.string().datetime({ offset: true }), z.null()])
- .default(null),
- includeThreadPreviews: z.union([z.boolean(), z.null()]).default(null),
- limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).default(null),
- maxCharsPerMessage: z
- .union([z.number().int().gte(0), z.null()])
- .default(null),
- messageId: z.union([z.string().uuid(), z.null()]).default(null),
- messageIds: z.array(z.string().uuid()).default([]),
- to: z.union([z.string().datetime({ offset: true }), z.null()]).default(null),
+ cursor: z.union([z.string(), z.null()]).optional(),
+ direction: z.union([z.enum(['older', 'newer']), z.null()]).optional(),
+ from: z.union([z.string().datetime({ offset: true }), z.null()]).optional(),
+ includeThreadPreviews: z.union([z.boolean(), z.null()]).optional(),
+ limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).optional(),
+ maxCharsPerMessage: z.union([z.number().int().gte(0), z.null()]).optional(),
+ messageId: z.union([z.string().uuid(), z.null()]).optional(),
+ messageIds: z.array(z.string().uuid()).optional(),
+ to: z.union([z.string().datetime({ offset: true }), z.null()]).optional(),
windowType: z.enum([
'latest',
'timeRange',
@@ -2415,19 +2384,17 @@ export const ReadChannelMessagesResponse = z.object({
});
export const ReadChannelThread = z.object({
- after: z.union([z.number().int().gte(0).lte(65535), z.null()]).default(null),
- before: z.union([z.number().int().gte(0).lte(65535), z.null()]).default(null),
+ after: z.union([z.number().int().gte(0).lte(65535), z.null()]).optional(),
+ before: z.union([z.number().int().gte(0).lte(65535), z.null()]).optional(),
channelId: z.string().uuid(),
- includeChannelContext: z.union([z.boolean(), z.null()]).default(null),
- limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).default(null),
- maxCharsPerMessage: z
- .union([z.number().int().gte(0), z.null()])
- .default(null),
+ includeChannelContext: z.union([z.boolean(), z.null()]).optional(),
+ limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).optional(),
+ maxCharsPerMessage: z.union([z.number().int().gte(0), z.null()]).optional(),
messageId: z.string().uuid(),
- replyId: z.union([z.string().uuid(), z.null()]).default(null),
+ replyId: z.union([z.string().uuid(), z.null()]).optional(),
windowType: z
.union([z.enum(['allIfSmall', 'latest', 'aroundReply']), z.null()])
- .default(null),
+ .optional(),
});
export const ReadChannelThreadResponse = z.object({
@@ -2922,7 +2889,7 @@ export const SendEmail = z.object({
.array(
z.object({
email: z.string(),
- name: z.union([z.string(), z.null()]).default(null),
+ name: z.union([z.string(), z.null()]).optional(),
})
)
.optional(),
@@ -2931,17 +2898,17 @@ export const SendEmail = z.object({
.array(
z.object({
email: z.string(),
- name: z.union([z.string(), z.null()]).default(null),
+ name: z.union([z.string(), z.null()]).optional(),
})
)
.optional(),
- includeSignature: z.union([z.boolean(), z.null()]).default(null),
- replyingToId: z.union([z.string().uuid(), z.null()]).default(null),
+ includeSignature: z.union([z.boolean(), z.null()]).optional(),
+ replyingToId: z.union([z.string().uuid(), z.null()]).optional(),
subject: z.string(),
to: z.array(
z.object({
email: z.string(),
- name: z.union([z.string(), z.null()]).default(null),
+ name: z.union([z.string(), z.null()]).optional(),
})
),
});
@@ -3006,11 +2973,11 @@ export const UserToolResponse = z.any().superRefine((x, ctx) => {
});
export const SetEntityProperty = z.object({
- add_option_ids: z.union([z.array(z.string().uuid()), z.null()]).default(null),
- boolean_value: z.union([z.boolean(), z.null()]).default(null),
+ add_option_ids: z.union([z.array(z.string().uuid()), z.null()]).optional(),
+ boolean_value: z.union([z.boolean(), z.null()]).optional(),
date_value: z
.union([z.string().datetime({ offset: true }), z.null()])
- .default(null),
+ .optional(),
entity_id: z.string(),
entity_ref: z
.union([
@@ -3062,16 +3029,14 @@ export const SetEntityProperty = z.object({
'user',
'company',
]),
- link_url: z.union([z.string(), z.null()]).default(null),
- link_urls: z.union([z.array(z.string()), z.null()]).default(null),
- number_value: z.union([z.number(), z.null()]).default(null),
- option_id: z.union([z.string().uuid(), z.null()]).default(null),
- option_ids: z.union([z.array(z.string().uuid()), z.null()]).default(null),
+ link_url: z.union([z.string(), z.null()]).optional(),
+ link_urls: z.union([z.array(z.string()), z.null()]).optional(),
+ number_value: z.union([z.number(), z.null()]).optional(),
+ option_id: z.union([z.string().uuid(), z.null()]).optional(),
+ option_ids: z.union([z.array(z.string().uuid()), z.null()]).optional(),
property_definition_id: z.string().uuid(),
- remove_option_ids: z
- .union([z.array(z.string().uuid()), z.null()])
- .default(null),
- string_value: z.union([z.string(), z.null()]).default(null),
+ remove_option_ids: z.union([z.array(z.string().uuid()), z.null()]).optional(),
+ string_value: z.union([z.string(), z.null()]).optional(),
});
export const SetEntityPropertyResponse = z.object({
@@ -3336,7 +3301,7 @@ export const ReadThread = z.object({
ids: z.array(z.string()),
messagesSince: z
.union([z.string().datetime({ offset: true }), z.null()])
- .default(null),
+ .optional(),
});
export const ReadResponse = z.object({
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
index ee871b2870..073ca70483 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
@@ -49,10 +49,6 @@ type ToolParserMap = {
response: types.GetEntityPropertiesResponse;
};
GetThread: { call: types.GetThread; response: types.GetThreadResponse };
- ListCallRecords: {
- call: types.ListCallRecords;
- response: types.ListCallRecordsResponse;
- };
ListCompanies: {
call: types.ListCompanies;
response: types.ListCompaniesResponse;
@@ -185,10 +181,6 @@ const toolParserMap = {
response: schemas.GetEntityPropertiesResponse,
},
GetThread: { call: schemas.GetThread, response: schemas.GetThreadResponse },
- ListCallRecords: {
- call: schemas.ListCallRecords,
- response: schemas.ListCallRecordsResponse,
- },
ListCompanies: {
call: schemas.ListCompanies,
response: schemas.ListCompaniesResponse,
@@ -341,10 +333,6 @@ type ToolDataMap = {
response: types.GetEntityPropertiesResponse;
};
GetThread: { call: types.GetThread; response: types.GetThreadResponse };
- ListCallRecords: {
- call: types.ListCallRecords;
- response: types.ListCallRecordsResponse;
- };
ListCompanies: {
call: types.ListCompanies;
response: types.ListCompaniesResponse;
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 b36822a07b..43a2904531 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
@@ -54,11 +54,6 @@ export type ToolPropertyTargetEntityType =
* Serializes as `ATTENDED`, `MISSED`, or `UNATTENDED`.
*/
export type CallStatus = 'ATTENDED' | 'MISSED' | 'UNATTENDED';
-/**
- * Schema-only mirror of [`CallStatus`] without variant docs, keeping AI tool
- * schemas as a simple enum instead of `oneOf`.
- */
-export type ToolCallStatus = 'ATTENDED' | 'MISSED' | 'UNATTENDED';
/**
* Type of channel timeline window to read.
*/
@@ -739,52 +734,6 @@ export interface SearchHighlight {
*/
user_id?: string | null;
}
-/**
- * A call-record summary. Intentionally omits the transcript — use
- * [`super::read_call_record::ReadCallRecord`] to fetch it.
- */
-export interface CallRecordSummary {
- /**
- * The call's unique identifier.
- */
- callId: string;
- /**
- * The channel the call belongs to.
- */
- channelId: string;
- /**
- * The channel's display name, if resolvable.
- */
- channelName?: string | null;
- /**
- * The user who created the call.
- */
- createdBy: string;
- /**
- * Call duration in milliseconds. Absent if the call is still active.
- */
- durationMs?: number | null;
- /**
- * When the call ended. Absent if the call is still active.
- */
- endedAt?: string | null;
- /**
- * True if the call is currently active.
- */
- isActive: boolean;
- /**
- * IDs of users who participated in the call.
- */
- participants: string[];
- /**
- * When the call started.
- */
- startedAt: string;
- /**
- * The caller's viewer-relative status for this call.
- */
- status?: ToolCallStatus | null;
-}
/**
* A single channel-message content hit in the unified search response.
* One item per matching message, timestamped by the message itself, so the
@@ -2000,32 +1949,6 @@ export interface ToolContact {
*/
name?: string | null;
}
-/**
- * List recent call records the user can access, ordered by start time descending. Status is relative to the caller. Transcripts are NOT included — call ReadCallRecord with a specific callId to fetch a transcript.
- */
-export interface ListCallRecords {
- /**
- * Deprecated compatibility filter. true = only calls the user attended; false = only calls the user did not attend; omit to include both. Ignored when status is provided.
- */
- attended?: boolean | null;
- /**
- * Optional channel id. When provided, only calls from that channel are returned.
- */
- channelId?: string | null;
- /**
- * Optional viewer-relative status filter. ATTENDED = calls the user joined; MISSED = calls the user did not join while they are in the channel; UNATTENDED = calls the user did not join while they are not in the channel. Prefer this over the deprecated attended filter.
- */
- status?: ToolCallStatus | null;
-}
-/**
- * Response for [`ListCallRecords`].
- */
-export interface ListCallRecordsResponse {
- /**
- * Call records ordered by start time descending.
- */
- records: CallRecordSummary[];
-}
/**
* List the CRM companies tracked by the authenticated user's team, sorted by most recent interaction. Each row includes the company id, name, domains, last interaction time, and its pipeline Stage / Owner / Revenue properties when set. Use the filters to narrow results: `search` for name/domain text, `stage` for pipeline stage, `owner_user_id` for companies owned by a user. Use GetCompany for one company's full details (contacts + all properties), and SetEntityProperty with entity_type=company to move stages or update owner/revenue/custom properties.
*/
@@ -2607,7 +2530,7 @@ export interface ProjectSearchResult {
score?: number | null;
}
/**
- * Retrieve the transcript for a specific call record. Use ListCallRecords first to find the callId. Only the transcript is returned — other metadata (participants, duration, etc.) is already available from ListCallRecords. In transcript segments, speakerId is the associated user/track, not guaranteed speaker identity; use diarizedSpeakerId to distinguish actual voices, and treat different diarizedSpeakerIds as potentially different speakers even if speakerId is the caller/"you".
+ * Retrieve the transcript for a specific call record. Use ListEntities with includeTypes: ["call"] first to find the callId. Only the transcript is returned — other metadata (participants, duration, etc.) is already available from ListEntities. In transcript segments, speakerId is the associated user/track, not guaranteed speaker identity; use diarizedSpeakerId to distinguish actual voices, and treat different diarizedSpeakerIds as potentially different speakers even if speakerId is the caller/"you".
*/
export interface ReadCallRecord {
/**
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index f45fe82285..7c20a9f48f 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -216,7 +216,9 @@ pub async fn build_tool_service_context_from_env(
frecency_service,
ReadonlyEmailPreviewAdapter(email_service),
channels_service,
- call::domain::ports::NoOpCallRecordQueryService,
+ call::domain::service::CallRecordQueryServiceImpl::new(
+ call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
+ ),
crm::domain::service::NoOpCrmService,
foreign_entity_service,
));
@@ -317,12 +319,8 @@ pub async fn build_tool_service_context_from_env(
None::<call::outbound::s3_recording_storage::S3RecordingStorage>,
String::new(),
);
- let call_query_service = call::domain::service::CallRecordQueryServiceImpl::new(
- call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
- );
let call_tool_context = call::inbound::toolset::CallToolContext::new(
call_service,
- call_query_service,
(*entity_access_service).clone(),
);
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index e5a0f8bc6f..0880228775 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -546,7 +546,7 @@ pub type ToolSoupService = SoupImpl<
ToolFrecencyService,
email::domain::ports::ReadonlyEmailPreviewAdapter<ToolEmailService>,
ToolCommsService,
- call::domain::ports::NoOpCallRecordQueryService,
+ ToolCallRecordQueryService,
crm::domain::service::NoOpCrmService,
ToolForeignEntityService,
>;
@@ -641,8 +641,7 @@ pub type ToolCallService = CallServiceImpl<
pub type ToolCallRecordQueryService = CallRecordQueryServiceImpl<PgCallRepo>;
/// Type alias for the call tool context
-pub type ToolCallToolContext =
- CallToolContext<ToolCallService, ToolCallRecordQueryService, ToolEntityAccessService>;
+pub type ToolCallToolContext = CallToolContext<ToolCallService, ToolEntityAccessService>;
/// Type alias for the notification reader service used by AI tools.
pub type ToolNotificationService = notification::domain::service::NotificationReaderService<
diff --git a/crates/call/src/inbound/toolset/list_call_records.rs b/crates/call/src/inbound/toolset/list_call_records.rs
deleted file mode 100644
index 1a0dde75ba..0000000000
--- a/crates/call/src/inbound/toolset/list_call_records.rs
+++ /dev/null
@@ -1,183 +0,0 @@
-//! ListCallRecords tool for listing the caller's recent call records.
-
-use std::sync::Arc;
-
-use crate::domain::{
- models::GetCallRecordsRequest,
- ports::{CallRecordQueryService, CallService},
-};
-use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
-use async_trait::async_trait;
-use chrono::{DateTime, Utc};
-use entity_access::domain::ports::EntityAccessService;
-use filter_ast::Expr;
-use item_filters::{
- CallStatus,
- ast::{LiteralTree, call::CallLiteral},
-};
-use models_pagination::{Query, SimpleSortMethod};
-use schemars::JsonSchema;
-use serde::{Deserialize, Serialize};
-use uuid::Uuid;
-
-use super::CallToolContext;
-
-/// Maximum call records returned by a single [`ListCallRecords`] invocation.
-const LIST_LIMIT: u32 = 50;
-
-/// Schema-only mirror of [`CallStatus`] without variant docs, keeping AI tool
-/// schemas as a simple enum instead of `oneOf`.
-#[allow(dead_code)]
-#[derive(Debug, Serialize, Deserialize, JsonSchema)]
-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
-enum ToolCallStatus {
- Attended,
- Missed,
- Unattended,
-}
-
-/// A call-record summary. Intentionally omits the transcript — use
-/// [`super::read_call_record::ReadCallRecord`] to fetch it.
-#[derive(Debug, Serialize, JsonSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct CallRecordSummary {
- /// The call's unique identifier.
- pub call_id: Uuid,
- /// The channel the call belongs to.
- pub channel_id: Uuid,
- /// The channel's display name, if resolvable.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub channel_name: Option<String>,
- /// The user who created the call.
- pub created_by: String,
- /// When the call started.
- pub started_at: DateTime<Utc>,
- /// When the call ended. Absent if the call is still active.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub ended_at: Option<DateTime<Utc>>,
- /// Call duration in milliseconds. Absent if the call is still active.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub duration_ms: Option<i64>,
- /// The caller's viewer-relative status for this call.
- #[schemars(with = "Option<ToolCallStatus>")]
- #[serde(skip_serializing_if = "Option::is_none")]
- pub status: Option<CallStatus>,
- /// IDs of users who participated in the call.
- pub participants: Vec<String>,
- /// True if the call is currently active.
- pub is_active: bool,
-}
-
-/// Response for [`ListCallRecords`].
-#[derive(Debug, Serialize, JsonSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct ListCallRecordsResponse {
- /// Call records ordered by start time descending.
- pub records: Vec<CallRecordSummary>,
-}
-
-/// Tool: list the caller's recent call records (transcripts excluded).
-#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]
-#[serde(rename_all = "camelCase")]
-#[schemars(
- title = "ListCallRecords",
- description = "List recent call records the user can access, ordered by start time descending. Status is relative to the caller. Transcripts are NOT included — call ReadCallRecord with a specific callId to fetch a transcript."
-)]
-pub struct ListCallRecords {
- /// Only include calls in this channel.
- #[schemars(
- description = "Optional channel id. When provided, only calls from that channel are returned."
- )]
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub channel_id: Option<Uuid>,
-
- /// Only include calls with this viewer-relative status for the caller.
- #[schemars(
- with = "Option<ToolCallStatus>",
- description = "Optional viewer-relative status filter. ATTENDED = calls the user joined; MISSED = calls the user did not join while they are in the channel; UNATTENDED = calls the user did not join while they are not in the channel. Prefer this over the deprecated attended filter."
- )]
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub status: Option<CallStatus>,
-
- /// Deprecated compatibility filter for calls the caller attended (or did not attend).
- #[schemars(
- description = "Deprecated compatibility filter. true = only calls the user attended; false = only calls the user did not attend; omit to include both. Ignored when status is provided."
- )]
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub attended: Option<bool>,
-}
-
-#[async_trait]
-impl<CSvc, QSvc, ESvc> AsyncTool<CallToolContext<CSvc, QSvc, ESvc>> for ListCallRecords
-where
- CSvc: CallService,
- QSvc: CallRecordQueryService,
- ESvc: EntityAccessService,
-{
- type Output = ListCallRecordsResponse;
-
- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
- async fn call(
- &self,
- service_context: ServiceContext<CallToolContext<CSvc, QSvc, ESvc>>,
- request_context: RequestContext,
- ) -> ToolResult<Self::Output> {
- tracing::info!(params=?self, "List call records");
-
- let filter = build_filter(self.channel_id, self.status, self.attended);
-
- let req = GetCallRecordsRequest {
- user_id: request_context.user_id.clone(),
- limit: LIST_LIMIT,
- query: Query::Sort(SimpleSortMethod::CreatedAt, filter),
- };
-
- let records = service_context
- .query_service
- .get_user_call_records(req)
- .await
- .map_err(|e| ToolCallError {
- description: "unable to list call records".to_string(),
- internal_error: e.into(),
- })?;
-
- let records = records
- .into_iter()
- .map(|r| CallRecordSummary {
- call_id: r.call_id,
- channel_id: r.channel_id,
- channel_name: r.channel_name,
- created_by: r.created_by,
- started_at: r.started_at,
- ended_at: r.ended_at,
- duration_ms: r.duration_ms,
- status: r.status,
- participants: r.participants.into_iter().map(|p| p.user_id).collect(),
- is_active: r.is_active,
- })
- .collect();
-
- Ok(ListCallRecordsResponse { records })
- }
-}
-
-pub(super) fn build_filter(
- channel_id: Option<Uuid>,
- status: Option<CallStatus>,
- attended: Option<bool>,
-) -> LiteralTree<CallLiteral> {
- let mut parts = Vec::new();
- if let Some(id) = channel_id {
- parts.push(Expr::Literal(CallLiteral::ChannelId(id)));
- }
- if let Some(status) = status {
- parts.push(Expr::Literal(CallLiteral::Status(status)));
- } else if let Some(attended) = attended {
- parts.push(Expr::Literal(CallLiteral::Attended(attended)));
- }
-
- let mut iter = parts.into_iter();
- let first = iter.next()?;
- let combined = iter.fold(first, Expr::and);
- Some(Arc::new(combined))
-}
diff --git a/crates/call/src/inbound/toolset/mod.rs b/crates/call/src/inbound/toolset/mod.rs
index c2506c9fbb..85bfe6ecdc 100644
--- a/crates/call/src/inbound/toolset/mod.rs
+++ b/crates/call/src/inbound/toolset/mod.rs
@@ -1,73 +1,61 @@
//! Toolset inbound adapter for calls.
-mod list_call_records;
mod read_call_record;
#[cfg(test)]
mod test;
-use crate::domain::ports::{CallRecordQueryService, CallService};
+use crate::domain::ports::CallService;
use ai_toolset::AsyncToolCollection;
use entity_access::domain::ports::EntityAccessService;
use std::sync::Arc;
-use list_call_records::ListCallRecords;
use read_call_record::ReadCallRecord;
/// Service context for call AI tools.
-pub struct CallToolContext<CSvc, QSvc, ESvc>
+pub struct CallToolContext<CSvc, ESvc>
where
CSvc: CallService,
- QSvc: CallRecordQueryService,
ESvc: EntityAccessService,
{
/// The call service — used to read a single call record with access checks.
pub service: Arc<CSvc>,
- /// The read-only query service — used to list the caller's call records.
- pub query_service: Arc<QSvc>,
/// The entity access service — used to generate access receipts.
pub entity_access_service: Arc<ESvc>,
}
-impl<CSvc, QSvc, ESvc> Clone for CallToolContext<CSvc, QSvc, ESvc>
+impl<CSvc, ESvc> Clone for CallToolContext<CSvc, ESvc>
where
CSvc: CallService,
- QSvc: CallRecordQueryService,
ESvc: EntityAccessService,
{
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
- query_service: self.query_service.clone(),
entity_access_service: self.entity_access_service.clone(),
}
}
}
-impl<CSvc, QSvc, ESvc> CallToolContext<CSvc, QSvc, ESvc>
+impl<CSvc, ESvc> CallToolContext<CSvc, ESvc>
where
CSvc: CallService,
- QSvc: CallRecordQueryService,
ESvc: EntityAccessService,
{
/// Create a new call tool context.
- pub fn new(service: CSvc, query_service: QSvc, entity_access_service: ESvc) -> Self {
+ pub fn new(service: CSvc, entity_access_service: ESvc) -> Self {
Self {
service: Arc::new(service),
- query_service: Arc::new(query_service),
entity_access_service: Arc::new(entity_access_service),
}
}
}
/// Create a call toolset.
-pub fn call_toolset<CSvc, QSvc, ESvc>() -> AsyncToolCollection<CallToolContext<CSvc, QSvc, ESvc>>
+pub fn call_toolset<CSvc, ESvc>() -> AsyncToolCollection<CallToolContext<CSvc, ESvc>>
where
CSvc: CallService,
- QSvc: CallRecordQueryService,
ESvc: EntityAccessService,
{
- AsyncToolCollection::new()
- .add_tool::<ListCallRecords, CallToolContext<CSvc, QSvc, ESvc>>()
- .add_tool::<ReadCallRecord, CallToolContext<CSvc, QSvc, ESvc>>()
+ AsyncToolCollection::new().add_tool::<ReadCallRecord, CallToolContext<CSvc, ESvc>>()
}
diff --git a/crates/call/src/inbound/toolset/read_call_record.rs b/crates/call/src/inbound/toolset/read_call_record.rs
index e09cfbf902..2181d379dd 100644
--- a/crates/call/src/inbound/toolset/read_call_record.rs
+++ b/crates/call/src/inbound/toolset/read_call_record.rs
@@ -1,6 +1,6 @@
//! ReadCallRecord tool for fetching a single call's transcript.
-use crate::domain::ports::{CallRecordQueryService, CallService};
+use crate::domain::ports::CallService;
use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
@@ -68,7 +68,7 @@ pub struct ReadCallRecordResponse {
#[serde(rename_all = "camelCase")]
#[schemars(
title = "ReadCallRecord",
- description = "Retrieve the transcript for a specific call record. Use ListCallRecords first to find the callId. Only the transcript is returned — other metadata (participants, duration, etc.) is already available from ListCallRecords. In transcript segments, speakerId is the associated user/track, not guaranteed speaker identity; use diarizedSpeakerId to distinguish actual voices, and treat different diarizedSpeakerIds as potentially different speakers even if speakerId is the caller/\"you\"."
+ description = "Retrieve the transcript for a specific call record. Use ListEntities with includeTypes: [\"call\"] first to find the callId. Only the transcript is returned — other metadata (participants, duration, etc.) is already available from ListEntities. In transcript segments, speakerId is the associated user/track, not guaranteed speaker identity; use diarizedSpeakerId to distinguish actual voices, and treat different diarizedSpeakerIds as potentially different speakers even if speakerId is the caller/\"you\"."
)]
pub struct ReadCallRecord {
#[schemars(description = "The id of the call whose transcript you want to retrieve.")]
@@ -76,10 +76,9 @@ pub struct ReadCallRecord {
}
#[async_trait]
-impl<CSvc, QSvc, ESvc> AsyncTool<CallToolContext<CSvc, QSvc, ESvc>> for ReadCallRecord
+impl<CSvc, ESvc> AsyncTool<CallToolContext<CSvc, ESvc>> for ReadCallRecord
where
CSvc: CallService,
- QSvc: CallRecordQueryService,
ESvc: EntityAccessService,
{
type Output = ReadCallRecordResponse;
@@ -87,7 +86,7 @@ where
#[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, call_id=?self.call_id), err)]
async fn call(
&self,
- service_context: ServiceContext<CallToolContext<CSvc, QSvc, ESvc>>,
+ service_context: ServiceContext<CallToolContext<CSvc, ESvc>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
tracing::info!(params=?self, "Read call record");
diff --git a/crates/call/src/inbound/toolset/test.rs b/crates/call/src/inbound/toolset/test.rs
index df26791a98..148ed91630 100644
--- a/crates/call/src/inbound/toolset/test.rs
+++ b/crates/call/src/inbound/toolset/test.rs
@@ -1,71 +1,5 @@
-use super::list_call_records::{ListCallRecords, build_filter};
use super::read_call_record::ReadCallRecord;
use ai_toolset::schema::generate_validated_input_schema;
-use filter_ast::Expr;
-use item_filters::{CallStatus, ast::call::CallLiteral};
-use serde_json::Value;
-
-#[test]
-fn test_list_call_records_schema_validation() {
- let result = generate_validated_input_schema::<ListCallRecords>();
- assert!(result.is_ok(), "{:?}", result);
-
- let validated = result.unwrap();
- assert_eq!(
- validated.name, "ListCallRecords",
- "Tool name should match the schemars title"
- );
- assert!(
- validated.description.contains("List"),
- "Description should contain expected text"
- );
-
- let schema_json =
- serde_json::to_value(&validated.schema).expect("schema should serialize to JSON");
- let status_schema = schema_property(&schema_json, "status");
- let status_values = find_enum_values(status_schema)
- .expect("status schema should include supported enum values");
- assert_eq!(
- status_values,
- vec![
- "ATTENDED".to_string(),
- "MISSED".to_string(),
- "UNATTENDED".to_string(),
- ]
- );
-
- let attended_schema = schema_property(&schema_json, "attended");
- let attended_description = attended_schema
- .get("description")
- .and_then(Value::as_str)
- .expect("attended schema should include a description");
- assert!(
- attended_description.contains("Deprecated"),
- "attended should remain documented as deprecated compatibility"
- );
-}
-
-#[test]
-fn test_list_call_records_status_filter_preferred_over_attended() {
- let filter = build_filter(None, Some(CallStatus::Missed), Some(true));
- let expr = filter.expect("status should produce a filter");
-
- assert!(matches!(
- expr.as_ref(),
- Expr::Literal(CallLiteral::Status(CallStatus::Missed))
- ));
-}
-
-#[test]
-fn test_list_call_records_attended_filter_still_supported() {
- let filter = build_filter(None, None, Some(false));
- let expr = filter.expect("attended should produce a filter");
-
- assert!(matches!(
- expr.as_ref(),
- Expr::Literal(CallLiteral::Attended(false))
- ));
-}
#[test]
fn test_read_call_record_schema_validation() {
@@ -82,32 +16,3 @@ fn test_read_call_record_schema_validation() {
"Description should contain expected text"
);
}
-
-fn schema_property<'a>(schema: &'a Value, property: &str) -> &'a Value {
- schema
- .get("properties")
- .and_then(Value::as_object)
- .and_then(|properties| properties.get(property))
- .unwrap_or_else(|| panic!("schema should include `{property}` property"))
-}
-
-fn find_enum_values(schema: &Value) -> Option<Vec<String>> {
- if let Some(values) = schema.get("enum").and_then(Value::as_array) {
- return Some(
- values
- .iter()
- .filter_map(|value| value.as_str().map(str::to_owned))
- .collect(),
- );
- }
-
- for key in ["anyOf", "allOf"] {
- if let Some(values) = schema.get(key).and_then(Value::as_array) {
- if let Some(enum_values) = values.iter().find_map(find_enum_values) {
- return Some(enum_values);
- }
- }
- }
-
- None
-}
diff --git a/crates/memory/src/context.rs b/crates/memory/src/context.rs
index 5c1e7620a2..e9bb150ccc 100644
--- a/crates/memory/src/context.rs
+++ b/crates/memory/src/context.rs
@@ -104,7 +104,9 @@ pub async fn build_tool_service_context(
frecency_service,
ReadonlyEmailPreviewAdapter(email_service),
channels_service,
- call::domain::ports::NoOpCallRecordQueryService,
+ call::domain::service::CallRecordQueryServiceImpl::new(
+ call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
+ ),
crm::domain::service::NoOpCrmService,
foreign_entity_service,
));
@@ -190,12 +192,8 @@ pub async fn build_tool_service_context(
None::<call::outbound::s3_recording_storage::S3RecordingStorage>,
String::new(),
);
- let call_query_service = call::domain::service::CallRecordQueryServiceImpl::new(
- call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
- );
let call_tool_context = call::inbound::toolset::CallToolContext::new(
call_service,
- call_query_service,
(*entity_access_service).clone(),
);
diff --git a/crates/soup/src/domain/service/tests.rs b/crates/soup/src/domain/service/tests.rs
index 9abda60f64..3d605858bb 100644
--- a/crates/soup/src/domain/service/tests.rs
+++ b/crates/soup/src/domain/service/tests.rs
@@ -172,6 +172,67 @@ impl CallRecordQueryService for NoopCallRecordQueryService {
}
}
+#[derive(Clone)]
+struct RecordingCallRecordQueryService {
+ records: Vec<call::domain::models::CallRecord>,
+ calls: Arc<Mutex<u32>>,
+}
+
+impl RecordingCallRecordQueryService {
+ fn new(records: Vec<call::domain::models::CallRecord>) -> Self {
+ Self {
+ records,
+ calls: Arc::new(Mutex::new(0)),
+ }
+ }
+
+ fn calls(&self) -> u32 {
+ *self.calls.lock().unwrap()
+ }
+}
+
+impl CallRecordQueryService for RecordingCallRecordQueryService {
+ async fn get_user_call_records(
+ &self,
+ _req: call::domain::models::GetCallRecordsRequest,
+ ) -> Result<Vec<call::domain::models::CallRecord>, call::domain::models::CallError> {
+ *self.calls.lock().unwrap() += 1;
+ Ok(self.records.clone())
+ }
+}
+
+fn call_record(
+ call_id: Uuid,
+ channel_id: Uuid,
+ created_by: &str,
+ started_at: DateTime<Utc>,
+) -> call::domain::models::CallRecord {
+ call::domain::models::CallRecord {
+ call_id,
+ channel_id,
+ room_name: String::new(),
+ created_by: created_by.to_string(),
+ started_at,
+ ended_at: None,
+ duration_ms: None,
+ egress_id: None,
+ recording_started_at: None,
+ recording_key: None,
+ preview_key: None,
+ recording_url: None,
+ recording_preview_url: None,
+ channel_name: None,
+ custom_name: None,
+ summary: None,
+ share_with_team: false,
+ is_active: true,
+ status: None,
+ user_access_level: None,
+ participants: Vec::new(),
+ transcript: Vec::new(),
+ }
+}
+
fn foreign_entity_id_from_receipt(
receipt: EntityAccessReceipt<ViewAccessLevel>,
) -> Result<Uuid, ForeignEntityError> {
@@ -592,6 +653,64 @@ async fn simple_soup_includes_channel_threads() {
);
}
+#[tokio::test]
+async fn simple_soup_includes_call_records() {
+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let call_id = Uuid::from_u128(0xca11);
+ let channel_id = Uuid::from_u128(0xc4a2);
+ let call_query_service = RecordingCallRecordQueryService::new(vec![call_record(
+ call_id,
+ channel_id,
+ user.as_ref(),
+ DateTime::default() + Days::new(2),
+ )]);
+
+ let mut soup_mock = MockSoupRepo::new();
+ soup_mock
+ .expect_unexpanded_generic_cursor_soup()
+ .times(1)
+ .returning(|_params| Box::pin(async move { Ok(Vec::new()) }));
+
+ let page = SoupImpl::new(
+ soup_mock,
+ FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),
+ NoopEmailPreviewService,
+ NoopCommsService,
+ call_query_service.clone(),
+ NoOpCrmService,
+ NoopForeignEntityService,
+ )
+ .get_user_soup(
+ SoupRequest {
+ email_preview_view: PreviewView::StandardLabel(
+ email::domain::models::PreviewViewStandardLabel::Inbox,
+ ),
+ link_ids: vec![],
+ soup_type: SoupType::UnExpanded,
+ limit: 20,
+ cursor: SoupQuery::new_sort_simple(
+ SimpleSortMethod::UpdatedAt,
+ EntityFilters::default(),
+ ),
+ user: user.clone(),
+ },
+ None,
+ )
+ .await
+ .unwrap()
+ .unwrap_left();
+
+ assert_eq!(call_query_service.calls(), 1);
+ assert_eq!(page.items.len(), 1);
+ assert_matches!(
+ &page.items[0],
+ SoupItem::Call(call) => {
+ assert_eq!(call.call_id, call_id);
+ assert_eq!(call.channel_id, channel_id);
+ }
+ );
+}
+
#[tokio::test]
async fn simple_soup_uses_channel_thread_filters_without_touching_channel_filters() {
let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index 218ac32ff2..a8add69638 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -188,7 +188,9 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
frecency_service,
ReadonlyEmailPreviewAdapter(email_service),
channels_service,
- call::domain::ports::NoOpCallRecordQueryService,
+ call::domain::service::CallRecordQueryServiceImpl::new(
+ call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
+ ),
crm::domain::service::NoOpCrmService,
foreign_entity_service,
));
@@ -321,12 +323,8 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
None::<call::outbound::s3_recording_storage::S3RecordingStorage>,
String::new(),
);
- let call_query_service = call::domain::service::CallRecordQueryServiceImpl::new(
- call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
- );
let call_tool_context = call::inbound::toolset::CallToolContext::new(
call_service,
- call_query_service,
(*entity_access_service).clone(),
);
diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rs
index 188c453df0..e128e264d1 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -256,7 +256,7 @@ async fn main() -> anyhow::Result<()> {
frecency_service,
ReadonlyEmailPreviewAdapter(email_service),
channels_service,
- call::domain::ports::NoOpCallRecordQueryService,
+ CallRecordQueryServiceImpl::new(PgCallRepo::new(db.clone())),
crm::domain::service::NoOpCrmService,
foreign_entity_service,
));
@@ -398,12 +398,7 @@ async fn main() -> anyhow::Result<()> {
None::<S3RecordingStorage>,
String::new(),
);
- let call_query_service = CallRecordQueryServiceImpl::new(PgCallRepo::new(db.clone()));
- let call_tool_context = CallToolContext::new(
- call_service,
- call_query_service,
- (*entity_access_service).clone(),
- );
+ let call_tool_context = CallToolContext::new(call_service, (*entity_access_service).clone());
tracing::info!("initialized call tool context");
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index f9d4996496..96ae574eda 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -171,7 +171,9 @@ async fn build_tool_context(
frecency_service,
ReadonlyEmailPreviewAdapter(email_service),
channels_service,
- call::domain::ports::NoOpCallRecordQueryService,
+ call::domain::service::CallRecordQueryServiceImpl::new(
+ call::outbound::pg_call_repo::PgCallRepo::new(db.clone()),
+ ),
crm::domain::service::NoOpCrmService,
foreign_entity_service,
));
@@ -280,12 +282,8 @@ async fn build_tool_context(
None::<call::outbound::s3_recording_storage::S3RecordingStorage>,
String::new(),
);
- let call_query_service = call::domain::service::CallRecordQueryServiceImpl::new(
- call::outbound::pg_call_repo::PgCallRepo::new(db.clone()),
- );
let call_tool_context = call::inbound::toolset::CallToolContext::new(
call_service,
- call_query_service,
EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone())),
);