From 2fcd010d24f72d1082a852ee7f2efcea41473fa1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 23:50:18 +0000 Subject: [PATCH 01/14] wip(plugin-approvals): approval steps write sys_activity entries, read-gated by request visibility Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg3KqwSpt61Y8ovKK7 --- ...al-activity-feed-35723.integration.test.ts | 272 ++++++++++++++++ .../src/approval-activity-feed.ts | 301 ++++++++++++++++++ .../plugin-approvals/src/approvals-plugin.ts | 8 + 3 files changed, 581 insertions(+) create mode 100644 packages/plugins/plugin-approvals/src/approval-activity-feed-35723.integration.test.ts create mode 100644 packages/plugins/plugin-approvals/src/approval-activity-feed.ts diff --git a/packages/plugins/plugin-approvals/src/approval-activity-feed-35723.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-activity-feed-35723.integration.test.ts new file mode 100644 index 00000000000..e814fcad2b3 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-activity-feed-35723.integration.test.ts @@ -0,0 +1,272 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35723] Approval steps reach the record's activity stream, and only the + * users who can read the record's approvals read them. + * + * - one `sys_activity` entry per approval step (submitted, approved, + * rejected, recalled) about the record the request governs, in the shape the + * console reads as the `approval` feed kind: `type: 'system'`, + * `metadata.kind: 'approval'`, `source_object: 'sys_approval_request'`; + * - no entry for a step the stream does not show (a thread comment); + * - on the generic data door, as the record page reads its stream (the record + * named by `object_name` + `record_id`): a participant reads the entries, a + * reader of the record who participates in nothing reads none — while every + * other entry about the record stays served to both, and the stream's count + * agrees with its rows — and an object that opts into the record-reader tier + * serves the same reader its entries. + * + * ## The rig + * + * The sibling read-gate suites' (`record-reader-opt-in.integration.test.ts`): a + * real ObjectQL engine over better-sqlite3, the real + * `ApprovalsServicePlugin.start()`, so the producer and the gate are bound as in + * a deployment, and the real data-door normalizer. Two stand-ins: RECORD + * READABILITY (one middleware per business object scopes a caller to its own + * records), and `sys_activity`'s definition, which is plugin-audit's — this + * package does not depend on it, so the suite declares the columns the stream + * reads. plugin-audit's own parent-record gate is not mounted: what is under + * test is the narrowing this package adds on top of it. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import type { ApprovalService } from './approval-service.js'; +import { ApprovalsServicePlugin } from './approvals-plugin.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const PKG = 'approvals-activity-feed-35723-test'; +const READ_OPS = new Set(['find', 'findOne', 'count', 'aggregate']); +const SYSTEM = { isSystem: true, positions: [], permissions: [] } as any; +const asUser = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; + +const SUBMITTER = 'u_submitter'; +const APPROVER = 'u_approver'; +/** Reads every record and participates in nothing. */ +const READER = 'u_reader'; + +/** Declares nothing: the record-reader tier stays off. */ +const SHEET = 'memo_sheet'; +/** Opts into the record-reader tier in its own `enable` block. */ +const OPEN_SHEET = 'exam_sheet'; + +const text = (name: string) => ({ name, label: name, type: 'text' as const }); + +function sheet(name: string, enable?: Record) { + return { + name, + label: name, + fields: { id: { ...text('id'), primaryKey: true }, title: text('title') }, + ...(enable ? { enable } : {}), + }; +} + +/** `sys_user`: the columns the entry's actor snapshot reads. */ +const sysUser = { + name: 'sys_user', + label: 'User', + nameField: 'name', + fields: { id: { ...text('id'), primaryKey: true }, name: text('name'), image: text('image'), email: text('email') }, +}; + +/** `sys_activity`, the stand-in (see the header): the columns the stream reads. */ +const sysActivity = { + name: 'sys_activity', + label: 'Activity Feed', + fields: { + id: { ...text('id'), primaryKey: true }, + timestamp: { name: 'timestamp', label: 'Timestamp', type: 'datetime' as const }, + type: text('type'), + summary: text('summary'), + actor_id: text('actor_id'), + actor_name: text('actor_name'), + actor_avatar_url: text('actor_avatar_url'), + object_name: text('object_name'), + record_id: text('record_id'), + source_object: text('source_object'), + source_id: text('source_id'), + metadata: { name: 'metadata', label: 'Metadata', type: 'textarea' as const }, + }, +}; + +const nodeConfig = { approvers: [{ type: 'user' as const, value: APPROVER }], behavior: 'first_response' as const }; + +interface Rig { + engine: ObjectQL; + svc: ApprovalService; + protocol: any; +} + +let current: ObjectQL | undefined; + +afterEach(async () => { + try { await current?.destroy(); } catch { /* noop */ } + current = undefined; +}); + +function guardReads(engine: ObjectQL, object: string): void { + engine.registerMiddleware(async (op: any, next: () => Promise) => { + const ctx = op.context; + if (READ_OPS.has(op.operation) && ctx && !ctx.isSystem && op.ast) { + const scope = { id: { $like: `${object}_%` } }; + op.ast.where = op.ast.where ? { $and: [op.ast.where, scope] } : scope; + } + return next(); + }, { object }); +} + +async function boot(): Promise { + const engine = new ObjectQL(); + current = engine; + engine.registerDriver(new SqlDriver({ + client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true, + }), true); + await engine.init(); + for (const def of [ + sheet(SHEET), sheet(OPEN_SHEET, { approvalsVisibleToReaders: true }), sysUser, sysActivity, + SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, + ]) { + engine.registry.registerObject(def as any, PKG, PKG); + } + await engine.syncSchemas(); + await installDefaultOrganization(engine); + for (const object of [SHEET, OPEN_SHEET]) guardReads(engine, object); + for (const [id, name] of [[SUBMITTER, 'Sam Submitter'], [APPROVER, 'Ada Approver'], [READER, 'Rae Reader']]) { + await engine.insert('sys_user', { id, name, image: `https://img.example/${id}.png` }, { context: SYSTEM } as any); + } + + const services: Record = { objectql: engine }; + const ctx: any = { + getService: (name: string) => { + if (!(name in services)) throw new Error(`[Kernel] Service '${name}' not found`); + return services[name]; + }, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + hook: () => {}, + logger: { info: () => {}, debug: () => {}, warn: () => {}, error: () => {} }, + }; + await new ApprovalsServicePlugin().start(ctx); + const svc = services.approvals as ApprovalService; + svc.attachAutomation({ + resume: async () => ({ status: 'completed' }), + cancelRun: async () => undefined, + getRun: async (runId: string) => ({ id: runId, status: 'paused' }), + getFlow: async () => ({ name: 'memo_review', nodes: [{ id: 'review', type: 'approval' }], edges: [] }), + } as any); + return { engine, svc, protocol: new ObjectStackProtocolImplementation(engine as any) }; +} + +async function open(rig: Rig, object: string, recordId: string): Promise { + await rig.engine.insert(object, { id: recordId, title: recordId }, { context: SYSTEM } as any); + const row: any = await rig.svc.openNodeRequest({ + object, recordId, runId: `run_${recordId}`, nodeId: 'review', flowName: 'memo_review', + config: nodeConfig as any, submitterId: SUBMITTER, record: { id: recordId, title: recordId }, + }, asUser(SUBMITTER)); + return String(row.id); +} + +/** Every `sys_activity` row about `recordId`, as the system reads them, oldest first. */ +async function entriesOf(rig: Rig, recordId: string): Promise { + const rows = (await rig.engine.find('sys_activity', { + where: { record_id: recordId }, context: SYSTEM, + } as any)) as any[]; + return rows.sort((a, b) => String(a.timestamp).localeCompare(String(b.timestamp)) || 0); +} + +/** The record page's stream read on the data door: its rows' summaries and its count. */ +async function streamOf(rig: Rig, caller: any, object: string, recordId: string) { + const res = await rig.protocol.findData({ + object: 'sys_activity', + query: { object_name: object, record_id: recordId, $count: true }, + context: caller, + }); + const records = (res.records as any[]); + return { + approval: records.filter((r) => r.source_object === 'sys_approval_request').map((r) => r.summary).sort(), + other: records.filter((r) => r.source_object !== 'sys_approval_request').map((r) => r.summary).sort(), + total: res.total, + }; +} + +const kindOf = (row: any) => JSON.parse(row.metadata); + +describe('approval steps on the record activity stream (#35723)', () => { + it('writes one approval entry per step — submitted, approved, rejected, recalled — about the governed record', async () => { + const rig = await boot(); + const approved = await open(rig, SHEET, `${SHEET}_approved`); + await rig.svc.comment(approved, { actorId: APPROVER, comment: 'looking' }, asUser(APPROVER)); + await rig.svc.decideNode(approved, { decision: 'approve', actorId: APPROVER }, asUser(APPROVER)); + const rejected = await open(rig, SHEET, `${SHEET}_rejected`); + await rig.svc.decideNode(rejected, { decision: 'reject', actorId: APPROVER, comment: 'no budget' }, asUser(APPROVER)); + const recalled = await open(rig, SHEET, `${SHEET}_recalled`); + await rig.svc.recall(recalled, { actorId: SUBMITTER } as any, asUser(SUBMITTER)); + + const cases: Array<[string, string, Array<[string, string]>]> = [ + [`${SHEET}_approved`, approved, [['submit', SUBMITTER], ['approve', APPROVER]]], + [`${SHEET}_rejected`, rejected, [['submit', SUBMITTER], ['reject', APPROVER]]], + [`${SHEET}_recalled`, recalled, [['submit', SUBMITTER], ['recall', SUBMITTER]]], + ]; + for (const [recordId, requestId, steps] of cases) { + const entries = await entriesOf(rig, recordId); + // One per step; the thread comment on the first request wrote none. + expect(entries.map((e) => [kindOf(e).action, e.actor_id]), recordId).toEqual(steps); + for (const entry of entries) { + expect(entry).toMatchObject({ + type: 'system', + object_name: SHEET, + record_id: recordId, + source_object: 'sys_approval_request', + source_id: requestId, + }); + expect(kindOf(entry).kind).toBe('approval'); + // No decision comment rides on the one line. + expect(entry.metadata).not.toContain('no budget'); + expect(entry.summary).not.toContain('no budget'); + } + } + const [submitted, approvedEntry] = await entriesOf(rig, `${SHEET}_approved`); + expect(submitted).toMatchObject({ + summary: 'Submitted for approval', + actor_name: 'Sam Submitter', + actor_avatar_url: `https://img.example/${SUBMITTER}.png`, + }); + expect(approvedEntry.summary).toMatch(/^Approved/); + expect(approvedEntry.actor_name).toBe('Ada Approver'); + }); + + it('serves the entries to a participant, none to a reader without approval access, and keeps every other entry', async () => { + const rig = await boot(); + const recordId = `${SHEET}_a`; + await open(rig, SHEET, recordId); + await rig.engine.insert('sys_activity', { + id: 'act_created', type: 'created', summary: 'Created memo', timestamp: '2026-01-01T00:00:00.000Z', + object_name: SHEET, record_id: recordId, + }, { context: SYSTEM } as any); + + const participant = await streamOf(rig, asUser(SUBMITTER), SHEET, recordId); + expect(participant).toEqual({ approval: ['Submitted for approval'], other: ['Created memo'], total: 2 }); + + // The same record, read by a user who can open it but is served none of its approvals. + expect(await rig.svc.listRequests({ object: SHEET, recordId }, asUser(READER))).toEqual([]); + const reader = await streamOf(rig, asUser(READER), SHEET, recordId); + expect(reader).toEqual({ approval: [], other: ['Created memo'], total: 1 }); + + // The system's own reads are never narrowed. + expect((await entriesOf(rig, recordId)).length).toBe(2); + }); + + it('serves a reader the entries of a record whose object opts into the record-reader tier', async () => { + const rig = await boot(); + const recordId = `${OPEN_SHEET}_a`; + await open(rig, OPEN_SHEET, recordId); + expect((await rig.svc.listRequests({ object: OPEN_SHEET, recordId }, asUser(READER))).length).toBe(1); + const reader = await streamOf(rig, asUser(READER), OPEN_SHEET, recordId); + expect(reader).toEqual({ approval: ['Submitted for approval'], other: [], total: 1 }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-activity-feed.ts b/packages/plugins/plugin-approvals/src/approval-activity-feed.ts new file mode 100644 index 00000000000..818b26747e2 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-activity-feed.ts @@ -0,0 +1,301 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35723] Approval steps on the record's activity stream. + * + * The record page's 动态 stream draws `sys_activity` rows. Until this module + * nothing wrote one for an approval, so a record under approval showed no + * approval in its activity: the stream's one-line approval entry (the + * `approval` feed kind, with 「看审批」 opening the record's approvals) was + * reachable only from items a host supplied by hand. + * + * ## The producer + * + * {@link bindApprovalActivityFeed}: an `afterInsert` hook on the decision log, + * `sys_approval_action`. Every approval step already lands there, one row per + * step, written by `ApprovalService` with the record it governs copied onto + * the row (`object_name` + `record_id`, the request's pointer pair). For each + * row of a kind in {@link APPROVAL_ACTIVITY_STEPS} — `submit`, `approve`, + * `reject`, `recall` — the hook appends one `sys_activity` row about that + * record. Reading the decision log rather than calling in from each decision + * method keeps `approval-service.ts` untouched, and a step the service learns + * to record in a new place reaches the stream with no second call site. + * + * The row is shaped as ADR-0052 §5 says a domain event rides the ActivityPointer + * model, so no published vocabulary moves: + * + * - `type` stays domain-NEUTRAL: `system`, a built-in value only the platform + * may write (`SYS_ACTIVITY_PLATFORM_TYPES`; the app activity door refuses + * it), so an app cannot write a row that reads as an approval step; + * - the domain kind rides in `metadata.kind` ({@link APPROVAL_ACTIVITY_KIND}), + * with the step's action kind and step label beside it; + * - `source_object` / `source_id` point at the request + * (`sys_approval_request`), the entity the entry drills to. + * + * The console reads exactly that triple as the `approval` feed kind + * (`recordActivityFeed.ts` in `@object-ui/plugin-detail`, which restates the + * three values because it cannot depend on this server plugin). + * + * The row carries no decision comment and no snapshot value: it is the one + * line the stream draws, and the request's detail stays on the approvals tab. + * + * ## Who reads it + * + * The card's rule: an approval entry is read by the same users who can read + * the record's approvals. `sys_activity`'s own gate (plugin-audit's + * parent-record gate) keeps a row whenever its record is readable, which here + * would switch the record-reader tier on for every object, against its default + * OFF (`request-read-gate.ts` says why that gate is not this one). + * + * {@link bindApprovalActivityReadGate} therefore narrows `sys_activity` reads + * once more, for the approval rows alone: a row whose `source_object` is + * `sys_approval_request` is kept only when its `source_id` is a request the + * approvals door would serve the caller. ⛔ Nothing here decides who may see a + * request: the answer is the approvals service's own + * ({@link RequestVisibilitySource}, the same source the generic door's gates on + * the request tables read), and a read that names the record (`object_name` + + * `record_id` both pinned, as the record page reads its stream) is asked with + * that record, so an object that opted into the record-reader tier serves its + * readers there too. Every other row passes untouched; plugin-audit's gate + * still applies on top, so a reader must also be able to read the record. + * + * Added as a conjunct of `ast.where` on `find`, `findOne`, `count` and + * `aggregate`, so the record page's `timeline` count and its rows agree. Fails + * CLOSED for the approval rows only: when the source cannot answer, the read + * keeps every other row and no approval row. + * + * ## What stays as it was + * + * A deployment without plugin-audit has no `sys_activity`; the hook then writes + * nothing. A failed append never fails the approval step: the decision log row + * is the record of the step, and the activity row a projection of it. The + * failure is logged at `error` once, with what is lost and the fix. + * `sys_activity` keeps its own lifecycle (entries are reaped after 14 days); + * the approvals tab keeps the full history. + */ + +import { createFieldPresenceProbe } from '@objectstack/metadata-core'; +import type { ApprovalActionKind } from '@objectstack/spec/contracts'; +import { pinnedEquality } from './payload-predicate-guard.js'; +import { APPROVAL_REQUEST_OBJECT, type MiddlewareEngine } from './payload-redaction-middleware.js'; +import { REQUEST_READ_OPS, type RequestVisibilitySource } from './request-read-gate.js'; + +/** The activity stream's table (plugin-audit's). */ +export const ACTIVITY_OBJECT = 'sys_activity'; + +/** The decision log the producer reads. */ +export const APPROVAL_ACTION_OBJECT = 'sys_approval_action'; + +/** `sys_activity.type` of an approval entry: domain-neutral and platform-only (ADR-0052 §5). */ +export const APPROVAL_ACTIVITY_TYPE = 'system'; + +/** `metadata.kind` of an approval entry: the domain kind (ADR-0052 §5). */ +export const APPROVAL_ACTIVITY_KIND = 'approval'; + +/** `sys_activity.source_object` of an approval entry: the request it drills to. */ +export const APPROVAL_ACTIVITY_SOURCE_OBJECT = APPROVAL_REQUEST_OBJECT; + +/** The hook package the producer binds under, so a second `start()` replaces it. */ +export const APPROVAL_ACTIVITY_HOOK_PACKAGE = 'plugin-approvals:activity'; + +/** + * The approval steps the stream shows, each with the one-line summary its + * entry is written with. A kind not listed (a reminder, a reassignment, a + * thread comment, …) writes no entry. + */ +export const APPROVAL_ACTIVITY_STEPS: Readonly>> = Object.freeze({ + submit: 'Submitted for approval', + approve: 'Approved', + reject: 'Rejected', + recall: 'Recalled the approval request', +}); + +/** `sys_activity.summary` holds at most this many characters. */ +const SUMMARY_MAX = 500; + +type Logger = { + warn?: (msg: string, meta?: Record) => void; + error?: (msg: string, meta?: Record) => void; +}; + +/** The engine slice the producer needs. */ +export interface ApprovalActivityEngine { + registerHook(event: string, handler: (ctx: any) => unknown, options?: Record): void; + unregisterHooksByPackage?(packageId: string): number; + insert(object: string, data: Record, options?: Record): Promise; + find(object: string, options?: Record): Promise; + getSchema?(object: string): unknown; +} + +const text = (value: unknown): string | null => + typeof value === 'string' && value.trim() ? value.trim() : null; + +/** + * The summary an approval entry is written with: the step's line, then the + * step's label where the step has one (`Approved · Manager review`). + */ +export function approvalActivitySummary(kind: string, stepLabel: unknown): string | null { + const line = APPROVAL_ACTIVITY_STEPS[kind as ApprovalActionKind]; + if (!line) return null; + const label = kind === 'approve' || kind === 'reject' ? text(stepLabel) : null; + return (label ? `${line} · ${label}` : line).slice(0, SUMMARY_MAX); +} + +/** What the entry names of the person who took the step. */ +export interface ApprovalActivityActor { + name: string | null; + avatarUrl: string | null; +} + +/** + * The `sys_activity` row for one decision-log row, or `null` when the row is + * not a step the stream shows or names no record. + */ +export function approvalActivityRow( + action: Record, + actor: ApprovalActivityActor, +): Record | null { + const kind = text(action.action); + const object = text(action.object_name); + const recordId = action.record_id == null ? null : String(action.record_id); + const requestId = action.request_id == null ? null : String(action.request_id); + if (!kind || !object || !recordId || !requestId) return null; + const summary = approvalActivitySummary(kind, action.step_label); + if (!summary) return null; + const actorId = text(action.actor_id); + const stepLabel = text(action.step_label); + return { + type: APPROVAL_ACTIVITY_TYPE, + timestamp: text(action.created_at) ?? new Date().toISOString(), + summary, + actor_id: actorId, + ...(actorId && actor.name ? { actor_name: actor.name } : {}), + ...(actorId && actor.avatarUrl ? { actor_avatar_url: actor.avatarUrl } : {}), + object_name: object, + record_id: recordId, + source_object: APPROVAL_ACTIVITY_SOURCE_OBJECT, + source_id: requestId, + metadata: JSON.stringify({ + kind: APPROVAL_ACTIVITY_KIND, + action: kind, + ...(stepLabel ? { step_label: stepLabel } : {}), + }), + }; +} + +/** + * Bind the producer: one `sys_activity` row per approval step written to + * `sys_approval_action` (see the header). + */ +export function bindApprovalActivityFeed(engine: ApprovalActivityEngine, logger?: Logger): void { + engine.unregisterHooksByPackage?.(APPROVAL_ACTIVITY_HOOK_PACKAGE); + const has = createFieldPresenceProbe(engine); + let reported = false; + + const actorOf = async (userId: string): Promise => { + const none = { name: null, avatarUrl: null }; + try { + const schema: any = engine.getSchema?.('sys_user'); + const titleField = typeof schema?.nameField === 'string' && has('sys_user', schema.nameField) + ? schema.nameField + : has('sys_user', 'name') ? 'name' : null; + const avatarField = has('sys_user', 'image') ? 'image' : null; + if (!titleField && !avatarField) return none; + const rows = await engine.find('sys_user', { + where: { id: userId }, + fields: ['id', ...(titleField ? [titleField] : []), ...(avatarField ? [avatarField] : [])], + limit: 1, + context: { isSystem: true }, + }); + const row: any = Array.isArray(rows) ? rows[0] : undefined; + if (!row) return none; + return { + name: titleField ? text(row[titleField]) : null, + avatarUrl: avatarField ? text(row[avatarField]) : null, + }; + } catch { + return none; + } + }; + + engine.registerHook('afterInsert', async (ctx: any) => { + const action = ctx?.result as Record | undefined; + if (!action || typeof action !== 'object') return; + // No activity stream on this deployment (no plugin-audit): nothing to write. + if (!has(ACTIVITY_OBJECT, 'type')) return; + const actorId = text(action.actor_id); + const row = approvalActivityRow(action, actorId ? await actorOf(actorId) : { name: null, avatarUrl: null }); + if (!row) return; + const organizationId = text(action.organization_id); + if (organizationId && has(ACTIVITY_OBJECT, 'organization_id')) row.organization_id = organizationId; + try { + await engine.insert(ACTIVITY_OBJECT, row, { + context: { + isSystem: true, + ...(organizationId ? { tenantId: organizationId } : {}), + ...(ctx?.transaction != null ? { transaction: ctx.transaction } : {}), + }, + }); + } catch (err: any) { + if (reported) return; + reported = true; + logger?.error?.( + '[approvals] an approval step was recorded but its entry on the record\'s activity stream was not written — ' + + 'the approval itself stands and the approvals tab shows it, but the record\'s activity will keep looking ' + + 'complete without it; later failures are not logged again. Check that sys_activity (plugin-audit) is ' + + 'provisioned and writable on this datasource.', + { action: action.action, request: action.request_id, error: err?.message ?? String(err) }, + ); + } + }, { object: APPROVAL_ACTION_OBJECT, packageId: APPROVAL_ACTIVITY_HOOK_PACKAGE, priority: 100 }); +} + +/** + * The conjunct that keeps every non-approval row and, of the approval rows, + * those whose request is in `visible`; `null` (every request in scope) adds + * none. + */ +export function approvalActivityVisibilityFilter( + visible: ReadonlySet | null, +): Readonly> | null { + if (visible === null) return null; + const notApproval = [ + { source_object: null }, + { source_object: { $ne: APPROVAL_ACTIVITY_SOURCE_OBJECT } }, + ]; + if (visible.size === 0) return { $or: notApproval }; + const ids = [...visible]; + return { $or: [...notApproval, { source_id: ids.length === 1 ? ids[0] : { $in: ids } }] }; +} + +/** + * Bind the read gate on `sys_activity` that serves an approval entry only to a + * caller the approvals door serves its request (see the header). + */ +export function bindApprovalActivityReadGate( + engine: MiddlewareEngine, + source: RequestVisibilitySource, + logger?: Logger, +): void { + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + const ast = opCtx?.ast as { where?: unknown } | undefined; + const context = opCtx?.context; + if (!REQUEST_READ_OPS.has(opCtx?.operation) || !ast || !context) return next(); + let filter: Readonly> | null; + try { + const object = pinnedEquality(ast.where, 'object_name'); + const recordId = pinnedEquality(ast.where, 'record_id'); + const target = object !== null && recordId !== null ? { object, recordId } : undefined; + filter = approvalActivityVisibilityFilter(await source.visibleRequestIdsFor(context, target)); + } catch (err: any) { + logger?.warn?.( + '[approvals] activity read gate could not resolve which approval requests the caller may see — ' + + 'the read is served without its approval entries (fail closed)', + { operation: opCtx.operation, error: err?.message ?? String(err) }, + ); + filter = approvalActivityVisibilityFilter(new Set()); + } + if (filter) ast.where = ast.where ? { $and: [ast.where, filter] } : filter; + return next(); + }, { object: ACTIVITY_OBJECT }); +} diff --git a/packages/plugins/plugin-approvals/src/approvals-plugin.ts b/packages/plugins/plugin-approvals/src/approvals-plugin.ts index cfb6b7a9716..0157099f16d 100644 --- a/packages/plugins/plugin-approvals/src/approvals-plugin.ts +++ b/packages/plugins/plugin-approvals/src/approvals-plugin.ts @@ -39,6 +39,7 @@ import { bindSnapshotRedactionMiddleware } from './payload-redaction-middleware. import { bindSnapshotPredicateGuard } from './payload-predicate-guard.js'; import { bindRequestChildReadGates, bindRequestReadGate } from './request-read-gate.js'; import { bindReaderLocaleLabelsMiddleware } from './reader-locale-labels-middleware.js'; +import { bindApprovalActivityFeed, bindApprovalActivityReadGate } from './approval-activity-feed.js'; import type { FieldVisibilitySource } from './payload-redaction.js'; import { registerApprovalNode, type ApprovalAutomationSurface } from './approval-node.js'; import { backfillActionSlots } from './action-slot-backfill.js'; @@ -452,6 +453,13 @@ export class ApprovalsServicePlugin implements Plugin { // Bound beside the gate, not behind `disableAutoHooks`, for the gate's // reason: the approvals door localizes whenever the service runs. bindReaderLocaleLabelsMiddleware(engine as any, i18nService, ctx.logger); + // [#35723] …and the approval entries on a record's activity stream: one + // `sys_activity` row per approval step, served only to a caller this + // service would serve the request (`approval-activity-feed.ts`). The + // gate and the producer bind together: an entry is never written where + // its reads could not be narrowed. + bindApprovalActivityReadGate(engine as any, visibility, ctx.logger); + bindApprovalActivityFeed(engine as any, ctx.logger); } else { ctx.logger.warn( 'ApprovalsServicePlugin: the ObjectQL engine has no middleware seam — reads of sys_approval_request, ' From dc72068faa30bf73d06c971d4d97565e0c16f353 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 00:02:52 +0000 Subject: [PATCH 02/14] =?UTF-8?q?wip(ui):=20approval=20activity=20rows=20r?= =?UTF-8?q?ead=20as=20the=20approval=20feed=20kind;=20=E7=9C=8B=E5=AE=A1?= =?UTF-8?q?=E6=89=B9=20opens=20the=20record's=20approvals?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg3KqwSpt61Y8ovKK7 --- .../app-shell/src/views/RecordDetailView.tsx | 35 +++-- .../plugin-detail/src/RecordChatterPanel.tsx | 6 +- ui/packages/plugin-detail/src/index.tsx | 2 + .../plugin-detail/src/recordTimelineStream.ts | 9 ++ ...rdActivityFeed.approvalStep-35723.test.tsx | 148 ++++++++++++++++++ .../__tests__/recordActivityFeed.test.ts | 40 ++--- .../src/renderers/record-activity.tsx | 4 + .../src/renderers/recordActivityFeed.ts | 46 +++++- 8 files changed, 255 insertions(+), 35 deletions(-) create mode 100644 ui/packages/plugin-detail/src/renderers/__tests__/recordActivityFeed.approvalStep-35723.test.tsx diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 64bfe38bcf8..63d06a72405 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -10,7 +10,7 @@ import { useState, useEffect, useLayoutEffect, useCallback, useContext, useMemo, useRef, type ReactElement } from 'react'; import { useParams, useNavigate, useLocation, useSearchParams, Link } from 'react-router-dom'; -import { activityRowToFeedItem, buildCommentThreads, CommentsButton, CommentsPage, RecordCommentsInPanelContext, composeImpersonatedActor, IMPERSONATED_ACTOR_FALLBACK, auditEntriesToFeedItems, bodyTableIdsOf, claimQueuedRecord, RECORD_PAGE_TIMELINE_PANEL, RECORD_TIMELINE_PANEL_MAX_ENTRIES, RecordFieldChangesContext, RecordFieldHistoryContext, RecordTimelineTotalContext, DefaultRecordPageContext, EMPTY_RELATED_ARRANGEMENT, InlineEditSaveBar, RECORD_PAGE_DETAILS_WIDTH, RecordBodyTablesContext, RecordMetaFooter, RecordPageColumns, buildDefaultPageColumns, buildDefaultPageSchema, extractMentions, recordSitsInQueue, resolveTitleField, useQueueClaimOffered, useRecordEditable, useRecordPageTier } from '@object-ui/plugin-detail'; +import { activityRowToFeedItem, buildCommentThreads, CommentsButton, CommentsPage, RecordCommentsInPanelContext, composeImpersonatedActor, IMPERSONATED_ACTOR_FALLBACK, auditEntriesToFeedItems, bodyTableIdsOf, claimQueuedRecord, RECORD_PAGE_TIMELINE_PANEL, RECORD_TIMELINE_PANEL_MAX_ENTRIES, RecordFieldChangesContext, RecordFieldHistoryContext, RecordTimelineTotalContext, RecordViewApprovalsContext, DefaultRecordPageContext, EMPTY_RELATED_ARRANGEMENT, InlineEditSaveBar, RECORD_PAGE_DETAILS_WIDTH, RecordBodyTablesContext, RecordMetaFooter, RecordPageColumns, buildDefaultPageColumns, buildDefaultPageSchema, extractMentions, recordSitsInQueue, resolveTitleField, useQueueClaimOffered, useRecordEditable, useRecordPageTier } from '@object-ui/plugin-detail'; import { isRefusedFeedRead } from '@object-ui/plugin-detail/core'; // objectstack#36075 — the comment panel's unresolved count and the moderator's verdict. import { unresolvedThreadCount, useRecordVerdict } from '@object-ui/plugin-detail'; @@ -6033,20 +6033,28 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri : approvals.latestRequest?.status === 'rejected' && !approvals.pendingRequest && !lockedForReader ? 'border-destructive/30 bg-destructive/10 text-destructive' : 'border-amber-300 bg-amber-50 text-amber-800 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-300'; + // Open the record's approvals: the panel where the page draws it, else its + // 审批 tab (objectstack#35595). The approval tag below and the activity + // stream's 「看审批」 on an approval entry (objectstack#35723) both open it. + const hasPageColumns = pageColumns !== null; + const openRecordApprovals = useCallback(() => { + const panel = pageRootEl?.querySelector('[data-testid="record-approvals-panel"]'); + if (panel) { + panel.scrollIntoView({ block: 'start', behavior: 'smooth' }); + return; + } + // objectstack#35595 — the approvals panel is the page's 审批 tab, not + // drawn on 概览: open that tab. + if (hasPageColumns) openEnlargedRelated('approvals'); + else if (!hasApprovalsNode) handleTabChange('approvals'); + }, [pageRootEl, hasPageColumns, hasApprovalsNode, openEnlargedRelated, handleTabChange]); + // objectstack#35723 — 「看审批」 only where there are approvals this reader is + // served, the same condition the page's 审批 tab is drawn on. + const viewApprovals = approvals.available && approvals.requests.length > 0 ? openRecordApprovals : null; const approvalTag = approvalTagText ? (