From c4093b911e11197d73175b2bf3f976c44ab4356d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 13:45:29 +0000 Subject: [PATCH 1/2] refactor(sales): Send Email and the activity actions add mail and timeline entries through the platform's doors Send Email hands its message to ctx.email.send and its timeline entry to ctx.activity.append; the fifteen generated activity actions add their entry through ctx.activity.append. No app action body writes an append-only object itself: the platform's writers stamp the sender or actor, the organization and the origin. Mail now goes out from the deployment's configured sender, with the rep named in the display name; the rep's address is the reply-to. An email's timeline entry carries the mail log id in its metadata (email_id) instead of a source, because the door reads a source in the caller's scope and a sales rep cannot read the mail log. The bodies no longer resolve the actor's display name themselves; the shared resolution block and its splice guard are gone, replaced by a guard that no shipped body addresses an append-only object and that every timeline writer uses the door. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibwzNRpkoiCFn1kQpUh --- ...ail-and-timeline-through-platform-doors.md | 14 ++ src/sales/actions/activity-actions.ts | 132 ++++-------- src/sales/actions/contact.actions.ts | 75 ++++--- test/freeze-guard-reference-cleanup.test.ts | 3 +- test/global-actions.test.ts | 127 +++-------- test/script-bodies.test.ts | 199 ++++++++---------- 6 files changed, 205 insertions(+), 345 deletions(-) create mode 100644 .changeset/mail-and-timeline-through-platform-doors.md diff --git a/.changeset/mail-and-timeline-through-platform-doors.md b/.changeset/mail-and-timeline-through-platform-doors.md new file mode 100644 index 000000000..1b1938307 --- /dev/null +++ b/.changeset/mail-and-timeline-through-platform-doors.md @@ -0,0 +1,14 @@ +--- +"hotcrm": patch +--- + +Clause-②: no +Metadata-protocol: none + +**Send Email and the activity actions hand their mail and timeline entries to the platform.** Send Email gives its message to the platform's mail service and adds its timeline entry through the platform's activity service. Log a Call, Log a Meeting and Schedule a Meeting add their timeline entry the same way. An app action no longer writes the mail log or the activity feed itself; the platform records who sent or logged it, under which organization, and which action added the entry. + +**What a user sees changes in one place.** An email sent with Send Email now goes out from the deployment's configured sender address, with the rep named in the sender's display name (the rep's name, then "via" and the organization's name), instead of from the rep's own address. Replies still reach the rep: the rep's address is the message's reply-to. + +The timeline entries look as before and name the rep by their display name. An email's entry no longer links to the mail log row, which a sales rep cannot open; it carries the message's id in its details. A logged call's or meeting's entry keeps the first 4,000 characters of its notes in its details; the event keeps all of them. + +Requires ObjectStack 18.4.0. diff --git a/src/sales/actions/activity-actions.ts b/src/sales/actions/activity-actions.ts index 6740fcb47..8117a84ca 100644 --- a/src/sales/actions/activity-actions.ts +++ b/src/sales/actions/activity-actions.ts @@ -30,11 +30,21 @@ import * as salesObjects from '../objects'; * other object a rep sells to, and an object-less one is unreachable * everywhere. * 2. **Shape.** Each of these actions inserts a real `crm_event`, real - * `crm_event_attendee` rows, and keeps the `sys_activity` row purely as the - * unified-timeline pointer (ADR-0052 `source_object` / `source_id`), the - * same way `send_email` points at its `sys_email`. ⛔ Never move that - * structure back into a `metadata` JSON blob: a blob is not data — no view - * filters it, no dataset groups by it, no report counts it. + * `crm_event_attendee` rows, and keeps the timeline entry purely as the + * unified-timeline pointer (ADR-0052 `source_object` / `source_id`) to that + * event. ⛔ Never move that structure back into a `metadata` JSON blob: a + * blob is not data — no view filters it, no dataset groups by it, no report + * counts it. + * + * # The timeline entry goes through the platform's door + * + * The entry is added with `ctx.activity.append` (capability `activity.append`), + * never a raw insert into `sys_activity`: the activity feed is an append-only + * object its platform service writes. The door stamps the actor (the acting + * user, with the platform's display name), the organization, the time and the + * origin, reads the record and the event in the caller's own scope, and holds + * the timeline's bounds (a 500-character summary, a 255-character label, + * 8,000 characters of metadata as JSON). * * # Live platform workaround * @@ -106,73 +116,6 @@ export const ACTIVITY_TARGETS: Record = { /** JS string literal, safely quoted for splicing into a body source. */ const lit = (value: string): string => JSON.stringify(value); -/** - * The acting user's display name, as action-body SOURCE TEXT. - * - * Shared verbatim by every body that writes `sys_activity.actor_name`: the - * activity family below and `send_email` in `contact.actions.ts`. - * - * # Why a string and not a function - * - * An action body is shipped BODY-ONLY and evaluated in a QuickJS sandbox with - * no module scope, so a shared helper called from a body is not a closure at - * runtime — it is a `ReferenceError` (`_line-item-price-fill.ts` states the - * same constraint for the shared line-item price fill). A string spliced at - * AUTHORING time, while Node builds the metadata, has no such problem: what - * reaches the sandbox is one self-contained body with this text inlined, - * exactly as if it had been typed there. `test/script-bodies.test.ts` runs - * the bodies through the real action door AND pins that every `actor_name` - * writer still contains this constant, so the call sites cannot drift into - * disagreeing. - * - * # Contract for a splice site - * - * Splice into a body that has already declared `userId` (`ctx.user?.id ?? null`) - * and whose action declares `api.read`. Afterwards `actorName` holds a - * non-blank display name — the id only as a last resort, never `null`. - */ -export const ACTOR_NAME_RESOLUTION_SOURCE = `// The acting user's DISPLAY name, for the sys_activity row (#673 / #678). - // - // PLATFORM WORKAROUND. \`ctx.user.name\` is not a display name on the - // dispatch path the Console uses: the REST action dispatcher builds the - // body's user as \`{ id: ec.userId, name: ec.userId, … }\` — the key is - // present and carries the raw id, so \`ctx.user?.name\` reads as a - // plausible string and silently wrote ids like - // "grDEyLoIgnunJ2M7Y2muLgcuQbDUT0s2" into \`sys_activity.actor_name\` - // (@objectstack/runtime 17.0.0-rc.2, dist/index.js:5397-5399). The MCP - // dispatcher does try a display name first - // (\`ec.userName ?? ec.userDisplayName ?? ec.userId\`, dist/index.js:1776) - // but nothing in the installed platform ever populates either field, so - // it falls back to the id too. - // - // So the name is resolved HERE, from \`sys_user.name\` (the column the - // platform itself treats as the profile display name), with the id kept - // as the last resort — an opaque id is bad, a blank actor is worse. - // A name that differs from the id is taken as already-resolved, which is - // what makes this one query and not a query per activity write. - // - // DELETE THIS once the platform delivers a display name on ctx.user.name - // for REST-dispatched action bodies: every splice site collapses back to - // \`actor_name: ctx.user?.name\` (objectstack-ai/objectstack#5372). - const ctxName = ctx.user?.name ? String(ctx.user.name).trim() : ''; - let actorName = ctxName && ctxName !== userId ? ctxName : ''; - if (!actorName && userId) { - try { - const found = await ctx.api.object('sys_user').find({ - where: { id: userId }, - fields: ['name'], - top: 1, - }); - const users = Array.isArray(found) ? found : (found?.records ?? []); - const resolved = users.length && users[0].name ? String(users[0].name).trim() : ''; - if (resolved) actorName = resolved; - } catch (e) { - // A denied or unavailable sys_user read must not fail the log — the - // interaction the rep just recorded matters more than its label. - } - } - if (!actorName) actorName = userId;`; - /** * The authored difference between one activity action and the next. * @@ -245,8 +188,6 @@ function activityAction(spec: ActivitySpec, objectName: string, nameField: strin const userId = ctx.user?.id ?? null; const nowIso = new Date().toISOString(); - ${ACTOR_NAME_RESOLUTION_SOURCE} - const subject = input.subject ? String(input.subject) : ${lit(spec.defaultSubject)}; const duration = input.duration ? Number(input.duration) : 0; const notes = input.notes ? String(input.notes) : ''; @@ -350,29 +291,34 @@ function activityAction(spec: ActivitySpec, objectName: string, nameField: strin if (row?.id) attendeeIds.push(row.id); } - // 3. the unified-timeline pointer. + // 3. the unified-timeline pointer, through the activity door. // \`metadata\` no longer carries the attendee list: it is a display hint // beside a real record now, not the record itself. ADR-0052 // source_object/source_id is the queryable drill to the crm_event row. + // The door stamps the actor and the origin; the summary and the label are + // held to the timeline's column bounds, and the notes in the hint to a + // share of its metadata bound (the full notes are the event's description). const summary = duration ? subject + ' (' + duration + ' min)' : subject; - const activity = await ctx.api.object('sys_activity').insert({ - type: EVENT_STATUS === 'held' ? 'completed' : 'scheduled', - summary: ${lit(spec.summaryPrefix)} + summary, - actor_id: userId, - actor_name: actorName, - object_name: OBJECT_NAME, - record_id: recordId, + let activity = null; + if (recordId) { + const entry = { + object: OBJECT_NAME, + recordId: String(recordId), + type: EVENT_STATUS === 'held' ? 'completed' : 'scheduled', + summary: (${lit(spec.summaryPrefix)} + summary).slice(0, 500), + metadata: { + kind: EVENT_TYPE, + duration_minutes: duration, + notes: notes.slice(0, 4000), + attendee_count: attendeeIds.length, + }, + }; // #514 item 2: the object's DECLARED nameField, not a hardcoded name. - record_label: record[NAME_FIELD] ?? null, - source_object: 'crm_event', - source_id: eventId, - metadata: JSON.stringify({ - kind: EVENT_TYPE, - duration_minutes: duration, - notes: notes, - attendee_count: attendeeIds.length, - }), - }); + const label = record[NAME_FIELD]; + if (label !== null && label !== undefined && label !== '') entry.recordLabel = String(label).slice(0, 255); + if (eventId) entry.source = { object: 'crm_event', id: String(eventId) }; + activity = await ctx.activity.append(entry); + } // 4. SLA first-response stamp — NOT here. #575 B2 originally stamped // \`crm_case.first_response_date\` from this body, which meant the metric @@ -389,7 +335,7 @@ function activityAction(spec: ActivitySpec, objectName: string, nameField: strin return { eventId: eventId, activityId: activity?.id ?? null, attendeeIds: attendeeIds }; `, - capabilities: ['api.read', 'api.write'], + capabilities: ['api.write', 'activity.append'], timeoutMs: 5000, }, locations: ['record_header', 'list_item', 'record_related'], diff --git a/src/sales/actions/contact.actions.ts b/src/sales/actions/contact.actions.ts index d5c5bc0e8..17bbf5e7c 100644 --- a/src/sales/actions/contact.actions.ts +++ b/src/sales/actions/contact.actions.ts @@ -2,7 +2,6 @@ import type { Action } from '@objectstack/spec/ui'; import { P } from '@objectstack/spec'; -import { ACTOR_NAME_RESOLUTION_SOURCE } from './activity-actions'; /** * Mark Contact as Primary. @@ -121,8 +120,24 @@ export const AddContactToCampaignAction: Action = { /** * Send Email to Contact. * - * Modal-typed action: collects subject + body, then logs an `activity` - * record via the metadata body. Runs sandboxed under `api.write`. + * Script action: collects subject + body, hands the message to the platform's + * mail door and adds the send to the contact's activity timeline. + * + * Both writes go through the platform's doors, never a raw insert into the + * ledgers: `ctx.email.send` (capability `email.send`) for the message and + * `ctx.activity.append` (capability `activity.append`) for the timeline entry. + * The mail log (`sys_email`) and the activity feed (`sys_activity`) are + * append-only objects their platform services write; the doors stamp what the + * platform says about the write: the sender is the deployment's configured + * address, with the rep named in its display name, the message is recorded as + * sent by the rep under the rep's organization, and the entry's actor and + * origin are the platform's. `replyTo` is the rep's own address, so a reply + * still reaches the rep. + * + * The timeline entry names the contact and carries the mail log row's id in + * its `metadata` (`email_id`), not as its `source`: the door reads a `source` + * in the caller's scope, and a sales rep cannot read the mail log, so an entry + * pointing there would be refused after the message had already gone. */ export const SendEmailAction: Action = { name: 'send_email', @@ -145,40 +160,32 @@ export const SendEmailAction: Action = { const record = ctx.record ?? {}; const recipientId = ctx.recordId ?? record.id ?? null; const to = record.email ? String(record.email) : ''; - const from = ctx.user?.email ?? 'noreply@hotcrm.local'; - const userId = ctx.user?.id ?? null; + const replyTo = ctx.user?.email ? String(ctx.user.email) : ''; const subject = input.subject ? String(input.subject) : ('Email to ' + to); const body = input.body ? String(input.body) : ''; - const email = await ctx.api.object('sys_email').insert({ - from_address: from, - to_addresses: to, - subject, - body_text: body, - status: 'queued', - related_object: 'crm_contact', - related_id: recipientId, - sent_by: userId, - }); - - ${ACTOR_NAME_RESOLUTION_SOURCE} + const message = { to, subject, text: body }; + if (replyTo) message.replyTo = replyTo; + if (recipientId) message.related = { object: 'crm_contact', id: String(recipientId) }; + const email = await ctx.email.send(message); // Surface the email on the contact's unified activity timeline // (the audit writer only logs generic CRUD; this is the semantic event). - const activity = await ctx.api.object('sys_activity').insert({ - type: 'completed', - summary: 'Email: ' + subject, - actor_id: userId, - actor_name: actorName, - object_name: 'crm_contact', - record_id: recipientId, - record_label: record.full_name ?? record.name ?? to, - // ADR-0052 ActivityPointer: structured pointer to the rich source entity - // (the sys_email row) so the timeline renders a "View source →" drill to - // the full email — the queryable replacement for stashing the id in metadata. - source_object: 'sys_email', - source_id: email?.id ?? null, - metadata: JSON.stringify({ kind: 'email', to, subject }), - }); + // The door stamps the actor (the rep, with the platform's display name) + // and the origin; the summary and the label are held to the timeline's + // column bounds (500 and 255 characters). + let activity = null; + if (recipientId) { + const label = record.full_name ?? record.name ?? to; + const entry = { + object: 'crm_contact', + recordId: String(recipientId), + type: 'completed', + summary: ('Email: ' + subject).slice(0, 500), + metadata: { kind: 'email', to, subject, email_id: email?.id ?? null }, + }; + if (label) entry.recordLabel = String(label).slice(0, 255); + activity = await ctx.activity.append(entry); + } // #592 scope item 3: every activity writer bumps interaction recency. // An email is an interaction but NOT a calendar slot, so it writes no // \`crm_event\` — which means it cannot ride the event hook's bubble and @@ -206,7 +213,7 @@ export const SendEmailAction: Action = { } return { emailId: email?.id, activityId: activity?.id }; `, - capabilities: ['api.read', 'api.write'], + capabilities: ['api.write', 'email.send', 'activity.append'], timeoutMs: 5000, }, locations: ['record_header', 'list_item'], @@ -215,7 +222,7 @@ export const SendEmailAction: Action = { { name: 'subject', label: 'Subject', type: 'text', required: true }, { name: 'body', label: 'Body', type: 'textarea', required: true }, ], - // "queued", not "sent": the body inserts the `sys_email` row with + // "queued", not "sent": the mail door writes the `sys_email` row with // `status: 'queued'` and delivery happens after the action returns (#2246). successMessage: 'Email queued to this contact.', refreshAfter: false, diff --git a/test/freeze-guard-reference-cleanup.test.ts b/test/freeze-guard-reference-cleanup.test.ts index 853682864..461332574 100644 --- a/test/freeze-guard-reference-cleanup.test.ts +++ b/test/freeze-guard-reference-cleanup.test.ts @@ -827,8 +827,7 @@ describe.each(GUARDS)('$label yields to the cleanup shape and nothing else', (gu * one that cannot be lowered), so it cannot call an imported helper — a * shared module-scope predicate would be `undefined` at runtime in the shipped * artifact. Sharing by copy is only as good as a guard against drift, so this - * pins the copies against each other, the same way the actions' shared - * `actor_name` block is pinned. + * pins the copies against each other. */ describe('the reference-cleanup predicate is one block in three places', () => { const CANONICAL = [ diff --git a/test/global-actions.test.ts b/test/global-actions.test.ts index 9a25f1311..62ade0c02 100644 --- a/test/global-actions.test.ts +++ b/test/global-actions.test.ts @@ -128,46 +128,6 @@ async function run(objectName: string, kind: string, opts: { input?: AnyRec; as? return { result, event: event!, attendees, activity: activity!, who }; } -/** - * Watch — and optionally fault — the reads the action BODY makes, on the real - * engine. Everything the route does before the body (resolving the caller, - * loading the subject record under their scope) happens before that subject - * load returns, so only engine reads issued after it are the body's. Measured - * on 17.7.0: a `log_call` makes exactly one such `sys_user` read, at system - * context, before its first write. - */ -async function watchBodyReads( - objectName: string, - body: () => Promise, - fault?: (object: string) => (() => Promise) | undefined, -) { - const ql = verify.kernel.getService('objectql'); - const realFind = ql.find.bind(ql); - const realFindOne = ql.findOne.bind(ql); - let subjectLoaded = false; - const bodyReads: string[] = []; - const findOne = vi.spyOn(ql, 'findOne').mockImplementation((async (object: string, ...rest: unknown[]) => { - const row = await realFindOne(object, ...rest); - if (object === objectName) subjectLoaded = true; - return row; - }) as never); - const find = vi.spyOn(ql, 'find').mockImplementation((async (object: string, ...rest: unknown[]) => { - if (subjectLoaded) { - bodyReads.push(object); - const injected = fault?.(object); - if (injected) return injected(); - } - return realFind(object, ...rest); - }) as never); - try { - const out = await body(); - return { out, bodyReads }; - } finally { - find.mockRestore(); - findOne.mockRestore(); - } -} - // ────────────────────────────────────── the family exists, per object ── describe('a rep can log an interaction on everything they sell to (#509 / #592)', () => { @@ -438,26 +398,16 @@ describe('activity actions stamp a real record_label (#514 item 2)', () => { }); }); -// ──────────────────── actor_name is a name, not a raw user id (#673) ── +// ──────────── the timeline entry goes through the platform door (#673) ── /** - * The timeline used to render a 32-character id where the actor's name belongs. - * - * The cause is upstream and worth stating precisely, because the guards below - * only make sense against it: `@objectstack/runtime`'s REST action dispatcher — - * the path the Console uses — builds the body's user as - * `{ id: ec.userId, name: ec.userId, … }` (17.0.0-rc.2, `dist/index.js:5397`), - * so `ctx.user?.name` is PRESENT and is the id. Not absent, not null: a - * plausible-looking string that no `??` could catch. (The MCP dispatcher at - * `dist/index.js:1776` prefers `ec.userName ?? ec.userDisplayName`, but nothing - * in the platform populates either, so it lands on the id as well.) - * - * Which is exactly why a guard written against a hand-built user - * (`{ id, name: 'Ada Lovelace' }`) stayed green through the whole bug: that is - * a shape the REST dispatcher never produces. These run through the REAL - * dispatcher (`actions.run`), which on 17.7.0 still hands the body the id as - * the name — measured: the body issues its `sys_user` read on every action — - * and assert on the resolved value. + * The timeline used to render a 32-character id where the actor's name belongs + * (#673): the action dispatcher hands a body the user's id as its name, and the + * bodies wrote `actor_name` themselves. They no longer write it. Each body + * hands its entry to `ctx.activity.append`, and the platform's writer stamps + * the actor, the platform's display name for them, the organization and the + * entry's origin. These run through the REAL dispatcher (`actions.run`) as the + * people who use the actions, and assert on what the door stored. */ /** @@ -468,8 +418,8 @@ describe('activity actions stamp a real record_label (#514 item 2)', () => { const inputFor = (kind: string): AnyRec => kind === 'schedule_meeting' ? { subject: 'Quarterly sync', start_date: '2026-09-01', start_time: '09:00' } : {}; -describe('sys_activity.actor_name is a human-readable name (#673)', () => { - it('resolves the display name for every activity action on every target', async () => { +describe('the activity actions add their entry through the platform door (#673)', () => { + it('names the actor and the action on every entry, for every action on every target', async () => { for (const objectName of TARGETS) { for (const kind of KINDS) { const { activity, who } = await run(objectName, kind, { input: inputFor(kind) }); @@ -479,50 +429,22 @@ describe('sys_activity.actor_name is a human-readable name (#673)', () => { // The regression itself, stated as its own assertion: whatever else // changes, the timeline must never render the opaque id again. expect(activity.actor_name, where).not.toBe(who.id); + // The door stamps where the entry came from: this action. + expect(activity.origin, where).toMatch(new RegExp(`/action:${kind}$`)); } } }); - it('reads sys_user once — and only because the dispatcher delivered no name', async () => { - // The lookup is a workaround, and it has to disappear on its own the day - // the platform starts honouring `ctx.user.name`: the body believes a - // delivered display name as-is. On 17.7.0 the real dispatcher still - // delivers the id, so the body reads `sys_user` exactly once per action — - // the day this reads 0 with the name still right, the dispatcher has been - // fixed upstream and the workaround can go. - const { out, bodyReads } = await watchBodyReads('crm_account', () => run('crm_account', 'log_call')); - expect(bodyReads.filter((o) => o === 'sys_user'), 'the body did not read sys_user once').toHaveLength(1); - expect((out as Awaited>).activity.actor_name).toBe('Ada Lovelace'); - }); - - it('falls back to the id rather than writing a blank actor', async () => { - // No `sys_user` row for the caller — a deleted user, or a read the caller's - // context is not allowed to satisfy. An opaque id is bad; an activity whose - // actor is `null` is worse, because it is not attributable at all. The empty - // read is injected into the real engine, for the body's read only. - const { out } = await watchBodyReads( - 'crm_case', - () => run('crm_case', 'log_meeting'), - (object) => (object === 'sys_user' ? async () => [] : undefined), - ); - const { activity } = out as Awaited>; - expect(activity.actor_name).toBe(agent.id); - expect(activity.actor_name).not.toBeNull(); - }); - - it('never fails the log when the sys_user read throws', async () => { - const { out } = await watchBodyReads( - 'crm_contact', - () => run('crm_contact', 'log_call'), - (object) => (object === 'sys_user' - ? async () => { throw new Error('FORBIDDEN: no read access to sys_user'); } - : undefined), - ); - const { result, activity } = out as Awaited>; - // The interaction the rep just recorded outranks the label on it. - expect(result.eventId).toBeTruthy(); - expect(result.activityId).toBeTruthy(); - expect(activity.actor_name).toBe(rep.id); + it('resolves no actor in the body', () => { + // The door owns the actor, so a body that still resolved one would be a + // second, divergent answer to "who did this". + for (const objectName of TARGETS) { + for (const kind of KINDS) { + const body = action(objectName, kind).body; + expect(body.capabilities, `${objectName}:${kind}`).toContain('activity.append'); + expect(String(body.source), `${objectName}:${kind}`).not.toMatch(/actor_name|object\('sys_user'\)/); + } + } }); }); @@ -598,10 +520,13 @@ describe('the activity actions stay twins (#514 item 15)', () => { // stamps, `timestamp`); those differ between any two rows and say nothing // about the twins. const shape = (row: AnyRec) => { - const { summary, metadata, source_id, id, created_at, updated_at, timestamp, ...rest } = row; + const { summary, metadata, source_id, id, created_at, updated_at, timestamp, origin, ...rest } = row; return rest; }; expect(shape(meeting.activity)).toEqual(shape(call.activity)); + // The origin the door stamps names each twin's own action, under one package. + expect(call.activity.origin).toMatch(/\/action:log_call$/); + expect(meeting.activity.origin).toBe(call.activity.origin.replace(/log_call$/, 'log_meeting')); expect(call.activity.summary).toBe('Quarterly sync (30 min)'); expect(meeting.activity.summary).toBe('Meeting: Quarterly sync (30 min)'); diff --git a/test/script-bodies.test.ts b/test/script-bodies.test.ts index 9db5699f4..d9dc29438 100644 --- a/test/script-bodies.test.ts +++ b/test/script-bodies.test.ts @@ -4,7 +4,6 @@ import { describe, it, expect, beforeAll, vi } from 'vitest'; import { extractHookBody } from '@objectstack/cli/hook-body'; import type { VerifyStack } from '@objectstack/verify'; import stack, { hookNamed } from './helpers/composed-stack'; -import { ACTOR_NAME_RESOLUTION_SOURCE } from '../src/sales/actions/activity-actions'; import { createLineItemPriceFill } from '../src/revenue/objects/_line-item-price-fill'; import { hotcrmStack, signUpPerson, recordEngineWrites, today, type Person, @@ -256,7 +255,7 @@ describe('what the record actions write', () => { expect((await stored('crm_contact', contact.id)).is_primary).toBe(true); }); - it('send_email writes the email and its timeline pointer', async () => { + it('send_email hands the message to the mail door and its entry to the timeline door', async () => { const engine = recordEngineWrites(verify); let result: AnyRec; try { @@ -267,16 +266,16 @@ describe('what the record actions write', () => { const email = await stored('sys_email', result!.emailId); const activity = await stored('sys_activity', result!.activityId); expect(email.to_addresses).toBe('ada@example.com'); - // The body hands the mail over QUEUED; delivering it is the email service's + // The door hands the mail over QUEUED; delivering it is the email service's // job, and with the platform's service mounted it may already have moved // the row on (the dev transport sends at once). // // The recorder's window is time, not cause. The messaging dispatcher sends // an earlier write's notification emails on its own loop, so another - // writer's `sys_email` insert can land in the window ahead of the body's + // writer's `sys_email` insert can land in the window ahead of the door's // (#2175, measured: the `contact_welcome` email for a contact created // earlier in this file). The insert read here is the one the engine - // answered with the id the body returned, never the window's first. + // answered with the id the body got back, never the window's first. const answered = await Promise.all( engine.of('sys_email', 'insert').map(async (write) => ({ write, answer: await write.settled })), ); @@ -285,137 +284,107 @@ describe('what the record actions write', () => { const handedOver = own[0]!.write; expect((handedOver.args[1] as AnyRec).status).toBe('queued'); expect(['queued', 'sent']).toContain(email.status); - expect(activity.source_object).toBe('sys_email'); - // The pointer is the id the engine answered the body's `sys_email` insert - // with (the row read above), which the body only holds once that first - // await has resolved, so this also proves the body's two awaits really - // sequenced across the VM boundary. - expect(activity.source_id).toBe(email.id); + + // What the mail door says about the message, not the body: the rep is its + // sender of record, it goes out from the deployment's configured address + // with the rep named in the display name, and a reply reaches the rep. + expect(email.sent_by).toBe(rep.id); + expect(email.from_address).toContain('Ada Lovelace'); + expect(email.from_address).not.toContain('rep@script-bodies.test'); + expect(email.reply_to).toBe('rep@script-bodies.test'); + expect(email.related_object).toBe('crm_contact'); + expect(email.related_id).toBe(record.crm_contact!.id); + + // The timeline entry names the contact and carries the mail log row's id in + // its metadata. It has no `source`: the timeline door reads a source in the + // caller's scope, and a sales rep cannot read the mail log. `email_id` is + // not one of the metadata keys the door reserves for the platform (it + // refuses those), so the entry it wrote is the measurement. + expect(activity.object_name).toBe('crm_contact'); + expect(activity.record_id).toBe(record.crm_contact!.id); + expect(activity.source_object).toBeNull(); + expect(activity.source_id).toBeNull(); + // The id is the one the engine answered the door's `sys_email` insert with + // (the row read above), which the body only holds once that first await + // has resolved, so this also proves the body's two awaits really sequenced + // across the VM boundary. + expect(JSON.parse(activity.metadata)).toEqual({ + kind: 'email', to: 'ada@example.com', subject: 'Hello', email_id: email.id, + }); + expect(activity.type).toBe('completed'); + expect(activity.summary).toBe('Email: Hello'); + // The door stamps where the entry came from: this action. + expect(activity.origin).toMatch(/\/action:send_email$/); expect(activity.record_label).toBe(record.crm_contact!.full_name); expect(activity.record_label).toBe('Ada Lovelace'); expect(result!).toEqual({ emailId: email.id, activityId: activity.id }); }); }); -// ─────────────── send_email's actor is a name, not a raw user id (#678) ── - -/** - * The twin of #673, on the same `sys_activity.actor_name` column. - * - * `send_email` stamped `actor_name: ctx.user?.name ?? null`, and on the - * dispatch path the Console uses that key is not a display name: the REST - * action dispatcher builds the body's user as `{ id: ec.userId, name: ec.userId, - * … }`, so the key is PRESENT and carries the id. These run through the REAL - * dispatcher, which on 17.7.0 still does that (measured: the body issues its - * `sys_user` read on every send), and the fault cases inject into the real - * engine — for the body's reads only, which are the reads issued after the - * route has loaded the subject record. - */ -async function watchBodyReads( - objectName: string, - body: () => Promise, - fault?: (object: string) => (() => Promise) | undefined, -) { - const ql = verify.kernel.getService('objectql'); - const realFind = ql.find.bind(ql); - const realFindOne = ql.findOne.bind(ql); - let subjectLoaded = false; - const bodyReads: string[] = []; - const findOne = vi.spyOn(ql, 'findOne').mockImplementation((async (object: string, ...rest: unknown[]) => { - const row = await realFindOne(object, ...rest); - if (object === objectName) subjectLoaded = true; - return row; - }) as never); - const find = vi.spyOn(ql, 'find').mockImplementation((async (object: string, ...rest: unknown[]) => { - if (subjectLoaded) { - bodyReads.push(object); - const injected = fault?.(object); - if (injected) return injected(); - } - return realFind(object, ...rest); - }) as never); - try { - return { result: await body(), bodyReads }; - } finally { - find.mockRestore(); - findOne.mockRestore(); - } -} +// ───────────────── send_email's entry, as the platform writes it and the rep reads it ── const sendEmail = () => runAction('crm_contact:send_email', { params: { subject: 'Hello', body: 'Body text' } }); -describe('send_email writes a human-readable sys_activity.actor_name (#678)', () => { - it('resolves the display name from sys_user instead of stamping the id', async () => { +/** The contact's newest timeline entries, read the way the record page reads them, as `who`. */ +async function contactTimeline(who: Person): Promise { + const res = await verify.apiAs(who.token, 'POST', `/data/crm_contact/${record.crm_contact!.id}/page`, { + activity: { top: 50 }, + }); + expect(res.status, 'the record page refused the timeline read').toBe(200); + const body = (await res.json()) as AnyRec; + return (body.data?.activity?.records ?? []) as AnyRec[]; +} + +describe('send_email adds its entry through the platform door', () => { + it('names the rep by the platform display name, not the raw user id', async () => { + // #678 was this column carrying the rep's 32-character id. The door now + // stamps the actor and the platform's display name; the body writes neither. const result = await sendEmail(); const activity = await stored('sys_activity', result.activityId); expect(activity.actor_id).toBe(rep.id); expect(activity.actor_name).toBe('Ada Lovelace'); - // The regression itself, as its own assertion: whatever else changes, the - // contact timeline must never render the opaque id again. expect(activity.actor_name).not.toBe(rep.id); }); - it('reads sys_user once — and only because the dispatcher delivered no name', async () => { - // A dispatcher that DOES deliver a display name is believed as-is: the - // lookup is a workaround and has to retire itself the day the platform - // starts honouring `ctx.user.name` (objectstack-ai/objectstack#5372). On - // 17.7.0 it does not, so the body reads `sys_user` exactly once — the day - // this reads 0 with the name still right, the platform has been fixed. - const { result, bodyReads } = await watchBodyReads('crm_contact', sendEmail); - expect(bodyReads.filter((o) => o === 'sys_user')).toHaveLength(1); - expect((await stored('sys_activity', result.activityId)).actor_name).toBe('Ada Lovelace'); - }); - - it('falls back to the id rather than writing a blank actor', async () => { - // No `sys_user` row for the sender — a deleted user, or a read this context - // is not allowed to satisfy. An opaque id is bad; an activity whose actor is - // `null` is worse, because it is not attributable at all. - const { result } = await watchBodyReads('crm_contact', sendEmail, (o) => (o === 'sys_user' ? async () => [] : undefined)); - const activity = await stored('sys_activity', result.activityId); - expect(activity.actor_name).toBe(rep.id); - expect(activity.actor_name).not.toBeNull(); - }); - - it('never fails the send when the sys_user read throws', async () => { - const { result } = await watchBodyReads('crm_contact', sendEmail, (o) => (o === 'sys_user' - ? async () => { throw new Error('FORBIDDEN: no read access to sys_user'); } - : undefined)); - // The email the rep just sent outranks the label on its timeline row. - expect(result.emailId).toBeTruthy(); - expect(result.activityId).toBeTruthy(); - expect((await stored('sys_activity', result.activityId)).actor_name).toBe(rep.id); + it("is on the contact's timeline when the rep reads it", async () => { + // Measured as the rep, not as an administrator: the entry carries no + // `source` because the rep cannot read the mail log, and the rep still has + // to see the email on the contact. + const result = await sendEmail(); + const entry = (await contactTimeline(rep)).find((row) => row.id === result.activityId); + expect(entry, "the rep does not see the email on the contact's timeline").toBeDefined(); + expect(entry!.summary).toBe('Email: Hello'); + const meta = typeof entry!.metadata === 'string' ? JSON.parse(entry!.metadata) : entry!.metadata; + expect(meta.email_id).toBe(result.emailId); }); /** - * The anti-drift guard: the resolution is shared as body SOURCE TEXT - * (`ACTOR_NAME_RESOLUTION_SOURCE`), spliced into every writer at authoring - * time, because a body runs body-only inside QuickJS and cannot call an - * imported helper. + * The anti-drift guard. The mail log and the activity feed are append-only + * ledgers that their platform services write; a body hands a message to + * `ctx.email.send` and a timeline entry to `ctx.activity.append`, and never + * inserts into a ledger itself. */ - it('every actor_name writer splices the SAME resolution block', () => { - const writers = stackActions.filter((a) => String(a.body?.source ?? '').includes('actor_name:')); + it('no shipped body writes an append-only object, and the timeline writers use the door', () => { + const appendOnly = verify.metadata.objects() + .filter((o) => (o as AnyRec).managedBy === 'append-only') + .map((o) => o.name); + // Vacuity floor: the two ledgers this file is about are in the set. + expect(appendOnly).toEqual(expect.arrayContaining(['sys_activity', 'sys_email'])); + + const writesLedger = (source: string) => + appendOnly.some((name) => new RegExp(`object\\(\\s*['"\`]${name}['"\`]\\s*\\)`).test(source)); + const direct = SCRIPT_ACTIONS.filter((a) => writesLedger(String(a.body.source))).map(keyOf); + expect(direct, 'these bodies address an append-only object directly').toEqual([]); + + const timelineWriters = SCRIPT_ACTIONS.filter((a) => String(a.body.source).includes('ctx.activity.append(')).map(keyOf); // `send_email` plus the fifteen generated activity bodies. - expect(writers.map(keyOf).sort()).toContain('crm_contact:send_email'); - expect(writers.length).toBeGreaterThan(1); - - const divergent = writers - .filter((a) => !String(a.body.source).includes(ACTOR_NAME_RESOLUTION_SOURCE)) - .map(keyOf); - expect( - divergent, - 'these bodies write sys_activity.actor_name without the shared resolution ' + - `block — a second copy is a second thing to forget (#673 / #678):\n ${divergent.join('\n ')}`, - ).toEqual([]); - - // And nobody stamps the raw `ctx.user.name` beside it. Comment lines are - // excluded on purpose: the shared block QUOTES that expression in its own - // retirement note. - const raw = writers.filter((a) => - String(a.body.source) - .split('\n') - .some((line) => !line.trim().startsWith('//') && /actor_name:\s*ctx\.user/.test(line)), - ); - expect(raw.map(keyOf), 'actor_name is being stamped from ctx.user again').toEqual([]); + expect(timelineWriters).toContain('crm_contact:send_email'); + expect(timelineWriters).toHaveLength(16); + for (const a of SCRIPT_ACTIONS.filter((x) => timelineWriters.includes(keyOf(x)))) { + expect(a.body.capabilities, keyOf(a)).toContain('activity.append'); + // The door stamps the actor; no body resolves or writes one. + expect(String(a.body.source), keyOf(a)).not.toMatch(/actor_name|sys_user'\)/); + } }); }); From 238251d4aa0f9e79bbc112e8710928ca1db840a6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 15:17:12 +0000 Subject: [PATCH 2/2] docs(guides): Send Email says where its mail goes out from and what its timeline entry carries The mail goes out from the deployment's configured sender address with the rep's name in the display name, and a reply comes back to the rep. The contact's timeline entry carries the message id in its details instead of linking to the mail log row. English, Simplified and Traditional Chinese. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibwzNRpkoiCFn1kQpUh --- content/docs/guides/email-and-calendar.mdx | 4 ++-- content/docs/guides/email-and-calendar.zh-Hans.mdx | 4 ++-- content/docs/guides/email-and-calendar.zh-Hant.mdx | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/content/docs/guides/email-and-calendar.mdx b/content/docs/guides/email-and-calendar.mdx index 98c8793ba..d09379fa6 100644 --- a/content/docs/guides/email-and-calendar.mdx +++ b/content/docs/guides/email-and-calendar.mdx @@ -21,8 +21,8 @@ HotCRM turns customer conversations into **records you can query**: an email you **Send Email** is registered on the **contact** record, and it is hidden on a contact with *Email Opt Out* ticked. Opportunities and cases carry the three activity actions below, not this one. 1. The action asks for a **Subject** and a **Body**. The recipient is the contact's own email address; there is no template picker and no merge-field expansion. -2. On submit an email row is written with status **Queued**, sent from your user's email address and linked back to the contact under *Related Object*. -3. The contact's **Activity** timeline gains an entry — `Email: ` — that points at that email row, so the drill-through opens the message rather than a summary string. +2. On submit the platform's mail service writes an email row with status **Queued**. The message goes out from your deployment's configured sender address, with your name in the sender's display name, and a reply comes back to your own address. The row is linked back to the contact under *Related Object* and records you as its sender. +3. The contact's **Activity** timeline gains an entry under your name — `Email: `. The entry carries the message's id in its details; it does not link to the email row, which a sales rep cannot open. 4. The contact's **Last Contacted Date**, and the parent account's **Last Activity Date**, are stamped. An email is an interaction, even though it is not a calendar slot, so it refreshes the same recency clock a held meeting does — see [Meetings & Calls](/docs/sales/meetings-and-calls). Delivery belongs to the platform's email service, which owns the states the row moves through: **Queued → Sent**, or **Failed** with the transport's error message and an attempt count. Whether the message leaves the building depends on the transport your deployment configures — with no provider configured the platform falls back to a log-only transport, which records the message and sends nothing. diff --git a/content/docs/guides/email-and-calendar.zh-Hans.mdx b/content/docs/guides/email-and-calendar.zh-Hans.mdx index e7e3c2b71..a51dc6b29 100644 --- a/content/docs/guides/email-and-calendar.zh-Hans.mdx +++ b/content/docs/guides/email-and-calendar.zh-Hans.mdx @@ -21,8 +21,8 @@ HotCRM 把客户沟通变成**可查询的记录**:你从联系人发出的一 **发送邮件** 注册在**联系人**记录上,并且对勾选了*拒绝邮件*的联系人隐藏。商机与工单上带的是下文那三个活动操作,而不是这一个。 1. 该操作只要求填写**主题**与**正文**。收件人就是该联系人自己的邮件地址;没有模板选择器,也没有合并字段展开。 -2. 提交后会写入一条状态为 **已排队** 的邮件行,发件人是你的用户邮箱地址,并在*关联对象*下链接回该联系人。 -3. 联系人的**活动**时间线会新增一条条目——`Email: <主题>`——它指向那条邮件行,因此下钻打开的是邮件本身,而不是一句摘要文本。 +2. 提交后,平台邮件服务会写入一条状态为 **已排队** 的邮件行。邮件从你的部署所配置的发件地址发出,发件人显示名中带有你的名字;客户的回复会回到你自己的邮箱。这条记录在*关联对象*下链接回该联系人,并记下你是发件人。 +3. 联系人的**活动**时间线会新增一条以你署名的条目——`Email: <主题>`。条目在详情里记下这封邮件的 id;它不链接到那条邮件行,因为销售代表打不开它。 4. 联系人的**最近联系日期**、以及其上级客户的**最近活动日期**会被打上时间戳。邮件虽然不是一个日历时段,但它是一次互动,因此它刷新的是与"已举行的会议"同一个时点时钟——参见[会议与通话](/zh-Hans/docs/sales/meetings-and-calls)。 投递本身属于平台邮件服务,它掌管这条记录会经过的状态:**已排队 → 已发送**,或者**失败**并附上传输层的错误信息与尝试次数。邮件是否真的发得出去,取决于你的部署配置了什么传输方式——若未配置任何提供方,平台会回落到只记日志的传输方式:消息被记录下来,但什么也不会发出。 diff --git a/content/docs/guides/email-and-calendar.zh-Hant.mdx b/content/docs/guides/email-and-calendar.zh-Hant.mdx index f7f93a4f9..84f8cd75c 100644 --- a/content/docs/guides/email-and-calendar.zh-Hant.mdx +++ b/content/docs/guides/email-and-calendar.zh-Hant.mdx @@ -23,8 +23,8 @@ HotCRM 把客戶溝通變成**可查詢的記錄**:你從聯絡人寄出的一 **傳送郵件** 註冊在**聯絡人**記錄上,並且對勾選了*拒絕郵件*的聯絡人隱藏。商機與工單上帶的是下文那三個活動操作,而不是這一個。 1. 該操作只要求填寫**主旨**與**內文**。收件人就是該聯絡人自己的郵件地址;沒有範本選擇器,也沒有合併欄位展開。 -2. 送出後會寫入一筆狀態為 **已排隊** 的郵件列,寄件人是你的使用者信箱地址,並在*關聯物件*下連結回該聯絡人。 -3. 聯絡人的**活動**時間軸會新增一條條目——`Email: <主旨>`——它指向那筆郵件列,因此下鑽打開的是郵件本身,而不是一句摘要文字。 +2. 送出後,平台郵件服務會寫入一筆狀態為 **已排隊** 的郵件列。郵件從你的部署所設定的寄件地址寄出,寄件人顯示名稱中帶有你的名字;客戶的回覆會回到你自己的信箱。這筆記錄在*關聯物件*下連結回該聯絡人,並記下你是寄件人。 +3. 聯絡人的**活動**時間軸會新增一條以你署名的條目——`Email: <主旨>`。條目在詳細資訊裡記下這封郵件的 id;它不連結到那筆郵件列,因為業務代表打不開它。 4. 聯絡人的**最近聯絡日期**、以及其上層客戶的**最近活動日期**會被打上時間戳記。郵件雖然不是一個行事曆時段,但它是一次互動,因此它刷新的是與「已舉行的會議」同一個時點時鐘——參見[會議與通話](/zh-Hant/docs/sales/meetings-and-calls)。 投遞本身屬於平台郵件服務,它掌管這筆記錄會經過的狀態:**已排隊 → 已寄出**,或者**失敗**並附上傳輸層的錯誤訊息與嘗試次數。郵件是否真的寄得出去,取決於你的部署設定了什麼傳輸方式——若未設定任何供應商,平台會回落到只記錄日誌的傳輸方式:訊息被記下來,但什麼也不會寄出。