wishforge-ide/tests/notifications.test.ts
eust-w bf3313620e ✨ Let each wish stay frontend-only, and optimize wishes into short goals with choices
- Each wish says whether it may change backend code. A frontend-only wish is told
  which paths it must leave alone; a change to them goes back before any check runs,
  the platform puts those files back before the repair round, and the control plane
  never integrates them. A wish that may change backend code integrates directly for
  people with backend permission and waits for a code review otherwise.
- Owners and admins grant backend permission per person on the members page as well
  as per project in the project settings.
- AI optimization has its own button for the wish and for the criteria. It writes a
  wish of at most three lines (goal, scope, limits), keeps the details in checkable
  criteria, and asks only what the person must decide, as choices whose answers join
  the wish; suggested criteria are taken one by one.
- Lists, run titles, Feishu cards and pull request titles show a wish's first line;
  the run details show the rest.
- Changed paths no longer follow renames, so moving backend code into a frontend
  directory counts at both places for code review and for the frontend-only scope.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 20:37:30 +08:00

176 lines
7.2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Feishu messages tell people what needs them (approvals, reviews, stopped runs) and what was
* delivered, each once, and never let text from a run act as card markup.
*/
import { describe, expect, it } from 'vitest';
import { createHmac } from 'node:crypto';
import type { CodeReview, Project, Release, Run } from '@wishforge/contracts';
import {
feishuCard,
feishuSender,
feishuSignature,
noticesFor,
notificationsConfigured,
Notifier,
type Notice,
} from '../apps/api/src/domain/notifications.js';
import { MemoryStore } from './helpers/memory-store.js';
const time = new Date().toISOString();
const base = { tenantId: 'demo', version: 1, createdAt: time, updatedAt: time };
const project = { ...base, id: 'p1', name: 'DroboticFlow' } as Project;
const run = (fields: Partial<Run>) =>
({
...base,
id: 'r1',
projectId: 'p1',
goal: 'Show [the docs](http://evil.example) <at id=all></at> to **everyone**',
requestedBy: 'local:zhanghm',
...fields,
}) as Run;
const release = (fields: Partial<Release>) =>
({
...base,
id: 'rel1',
runId: 'r1',
projectId: 'p1',
sourceCommit: 'a'.repeat(40),
riskReasons: ['Environment is not preauthorized for automatic release', 'Protected change: go.mod'],
...fields,
}) as Release;
const env = {
WF_FEISHU_WEBHOOK_URL: 'https://open.feishu.cn/open-apis/bot/v2/hook/0123456789abcdef',
WF_FEISHU_MENTIONS: 'ou_0123456789abcdef, not-an-id',
WF_NOTIFY_WEB_URL: 'http://10.0.0.5:3000/ignored-path',
};
describe('notices', () => {
it('asks the decision makers to approve, and names why in Chinese', () => {
const [notice] = noticesFor({
runs: [run({ status: 'waiting', waitingReason: 'approval' })],
releases: [release({ status: 'awaiting_approval' })],
reviews: [],
projects: [project],
});
expect(notice).toMatchObject({ key: 'release:rel1:awaiting_approval', mention: true, link: { path: '/releases' } });
expect(notice!.title).toContain('【待审批】DroboticFlow');
expect(notice!.lines.join('\n')).toContain('这个环境设置为每次发布都需人工确认');
expect(notice!.lines.join('\n')).toContain('改动了受保护的文件:go.mod');
expect(notice!.lines.join('\n')).toContain('**提交人**:zhanghm');
const card = JSON.stringify(feishuCard(notice!, env));
expect(card).toContain('<at id=ou_0123456789abcdef></at>');
expect(card).not.toContain('not-an-id');
expect(card).toContain('"url":"http://10.0.0.5:3000/releases"');
});
it('shows text from a run as text: no links, mentions or emphasis', () => {
const [notice] = noticesFor({
runs: [run({ status: 'waiting', waitingReason: 'infrastructure', waitingDetail: 'npm ci <failed>' })],
releases: [],
reviews: [],
projects: [project],
});
const text = notice!.lines.join('\n');
expect(text).not.toMatch(/\[the docs\]\(|<at id=all>|\*\*everyone\*\*/);
expect(text).toContain('[the docs]');
expect(notice).toMatchObject({ mention: false });
expect(notice!.title).toContain('基础设施故障');
});
it('tells about reviews, deliveries and failures, and nothing about waits that resolve themselves', () => {
const review = {
...base,
id: 'cr1',
runId: 'r1',
projectId: 'p1',
revision: 1,
sourceCommit: 'b'.repeat(40),
baseCommit: 'c'.repeat(40),
paths: ['cmd/main.go'],
status: 'pending',
} as CodeReview;
const notices = noticesFor({
runs: [
run({ id: 'r1', status: 'waiting', waitingReason: 'code_review' }),
run({ id: 'r2', status: 'succeeded', integratedCommit: 'd'.repeat(40) }),
run({ id: 'r3', status: 'waiting', waitingReason: 'deployment' }),
run({ id: 'r4', status: 'waiting', waitingReason: 'worker_unavailable' }),
],
releases: [
release({ id: 'rel2', runId: 'r2', status: 'healthy', deliveryUrl: 'http://120.48.164.19' }),
release({ id: 'rel3', runId: 'r3', status: 'failed', failureReason: 'Smoke check failed' }),
],
reviews: [review],
projects: [project],
});
expect(notices.map(notice => notice.key).sort()).toEqual(['release:rel3:failed', 'review:cr1', 'run:r2:succeeded']);
expect(notices.find(notice => notice.key === 'run:r2:succeeded')!.lines.join('\n')).toContain(
'http://120.48.164.19',
);
expect(notices.find(notice => notice.key === 'review:cr1')).toMatchObject({ mention: true });
});
it('names a wish by its goal, the first line, without the requirements below it', () => {
const [notice] = noticesFor({
runs: [
run({
status: 'succeeded',
integratedCommit: 'd'.repeat(40),
goal: '为每次执行保存记录。\n1. 写明开始和结束时间\n2. 不修改现有执行流程',
}),
],
releases: [],
reviews: [],
projects: [project],
});
expect(notice!.title).toBe('【已完成】DroboticFlow:为每次执行保存记录。');
expect(notice!.lines).toContain('**愿望**:为每次执行保存记录。');
});
});
describe('Feishu delivery', () => {
it('signs messages with the bot secret and keeps the webhook out of errors', async () => {
expect(notificationsConfigured(env)).toBe(true);
expect(notificationsConfigured({ WF_FEISHU_WEBHOOK_URL: 'https://evil.example/open-apis/bot/v2/hook/x' })).toBe(
false,
);
const timestamp = '1700000000';
expect(feishuSignature(timestamp, 'secret')).toBe(
createHmac('sha256', `${timestamp}\nsecret`).update('').digest('base64'),
);
const bodies: Record<string, unknown>[] = [];
const send = feishuSender({ ...env, WF_FEISHU_WEBHOOK_SECRET: 'secret' }, async (_url, init) => {
bodies.push(JSON.parse(String(init!.body)));
return Response.json({ code: bodies.length === 1 ? 0 : 19021, msg: 'sign match fail' });
});
const notice: Notice = { key: 'k', title: 't', tone: 'blue', lines: ['x'], mention: false };
await send(notice);
expect(bodies[0]).toMatchObject({
msg_type: 'interactive',
sign: expect.any(String),
timestamp: expect.any(String),
});
const failure = await send(notice).catch((error: Error) => error);
expect(String(failure)).toContain('19021');
expect(String(failure)).not.toContain('0123456789abcdef');
});
it('sends each notice once and retries one Feishu refused', async () => {
const store = new MemoryStore();
store.seed('demo');
await store.transaction('demo', async tx => {
await tx.put('project', project);
await tx.put('run', run({ status: 'waiting', waitingReason: 'clarification', executionGeneration: 'g1' }));
});
const sent: string[] = [];
let refuse = true;
const notifier = new Notifier(store, env, async notice => {
if (refuse) throw new Error('Feishu rejected the message (9499)');
sent.push(notice.key);
});
await expect(notifier.tick('demo')).rejects.toThrow('9499');
refuse = false;
expect(await notifier.tick('demo')).toBe(1);
expect(await notifier.tick('demo')).toBe(0);
expect(sent).toEqual(['run:r1:waiting:clarification:g1']);
// State older than the window was before notifications started.
expect(await notifier.tick('demo', Date.now() + 31 * 60_000)).toBe(0);
});
});