dsh-cabinet-mode 0.2.6 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/README.md +38 -8
- package/README.zh.md +28 -4
- package/client.js +881 -38
- package/cordis.patch.yml +2 -0
- package/docs/images/avatars/README.md +3 -0
- package/docs/images/avatars/aliases.md +21 -0
- package/docs/images/avatars/neutral.png +0 -0
- package/docs/images/avatars/prompts.json +4 -0
- package/index.js +250 -2
- package/package.json +6 -2
- package/scripts/test-avatars.mjs +2 -2
- package/scripts/test-client.mjs +55 -4
- package/scripts/test-member-settings.mjs +78 -0
- package/scripts/test-roster.mjs +80 -0
- package/scripts/verify.mjs +131 -10
- package/src/avatars/neutral.png +0 -0
- package/src/avatars.js +365 -1
- package/src/build_avatars.py +2 -1
package/cordis.patch.yml
CHANGED
|
@@ -43,6 +43,8 @@
|
|
|
43
43
|
五、汇总:收齐产出后去重、对齐,按用户原话逐项回对,指出未做到与未验证之处。
|
|
44
44
|
六、闭环:验收合格方可交差;失败、遗留与风险必须明写,不得隐瞒。
|
|
45
45
|
|
|
46
|
+
成员命名约定:队长原始 ID 始终为 lead;新建阁臣优先使用 hanlin-bianxiu、gongbu-shangshu、dalisi-qing、zuodu-yushi。需要同衙多名成员时追加 -2、-3 等唯一后缀。任务 Owner、消息路由与会话身份始终使用完整原始名称,不用中文显示称谓替换 ID;已有旧名兼容,不擅自重命名现有成员。
|
|
47
|
+
|
|
46
48
|
首辅令制(强制,不可省略):
|
|
47
49
|
1. 接到任务必须先拆解,再分派——不得跳过分派直接开工。拆解后立即用 spawn_teammate 把子任务点名分派给相应阁臣(翰林院编修/工部尚书/大理寺卿/左都御史),并用 team_task_create 建任务板,逐条写明目标、交付物、验收标准、写入范围与依赖顺序;有依赖的串行,无依赖的并行。
|
|
48
50
|
2. 令出即行,全程自主推进,不等待用户逐步确认。分派后主动跟进、裁断卡点、收齐产出、验收闭环,不放任任务悬空。
|
|
@@ -11,6 +11,7 @@ These are original AI-generated chibi illustrations. The requested reference is
|
|
|
11
11
|
| works | 工部尚书 | 正二品,锦鸡 / golden pheasant |
|
|
12
12
|
| dali | 大理寺卿 | 正三品,孔雀 / peacock |
|
|
13
13
|
| yushi | 左都御史 | 正二品,风宪官獬豸 / xiezhi |
|
|
14
|
+
| neutral | 未识别成员 / unidentified member | 无官阶、无补纹;浅色普通人物 / unranked portrait |
|
|
14
15
|
|
|
15
16
|
Sources: [《明史》卷六十七·舆服三](https://zh.wikisource.org/wiki/明史/卷67), [卷七十二·职官一](https://zh.wikisource.org/wiki/明史/卷72), [卷七十三·职官二](https://zh.wikisource.org/wiki/明史/卷73). The five-to-seven-rank blue rule concerns 公服; the chosen burgundy, teal, rust, slate and plum palette is artistic, not a claim about mandatory 常服 colours. 大理寺卿 is not assigned the censor's xiezhi badge.
|
|
16
17
|
|
|
@@ -19,3 +20,5 @@ The original PNGs are 1254×1254. Run `python3 src/build_avatars.py` from the re
|
|
|
19
20
|
Full-size and 128px artwork are visually reviewed; automated tests only check PNG dimensions and byte parity between files and embedded modules. At 22–24px, embroidery details are not reliably readable: use the adjacent role and member labels, not colour or badge alone, to identify a member.
|
|
20
21
|
|
|
21
22
|
Version 0.2.6 raises the three requested offices and redraws Works and Dali badges accordingly. The approved faces, palette and style are retained; the censor badge remains xiezhi. Old 主事、评事、监察御史 aliases remain compatible, with original member names visible. The edit prompts reference the Works and Dali originals at tag v0.2.5.
|
|
23
|
+
|
|
24
|
+
Version 0.2.7 adds a sixth, unranked portrait for unknown names. It is deliberately not assigned an official identity. See [aliases and naming](aliases.md); both the Cabinet panel and native roster share this mapping. Native rows refresh their image when their displayed name changes.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Member names and portraits / 成员命名与头像
|
|
2
|
+
|
|
3
|
+
Use these canonical runtime names for new teammates. The displayed Chinese title is separate from the exact identity used by Owner/task filtering and message routing. Do not rename existing members merely to change their portrait.
|
|
4
|
+
|
|
5
|
+
| Office / 显示官职 | New member name / 推荐原始名 | Compatible examples / 兼容示例 |
|
|
6
|
+
| --- | --- | --- |
|
|
7
|
+
| 内阁首辅 | `lead` | `shoufu`, `neige-shoufu`, `daxueshi`, 首辅、内阁大学士 |
|
|
8
|
+
| 翰林院编修 | `hanlin-bianxiu` | `hanlin`, `hanlinyuan-bianxiu`, `bianxiu`, 翰林编修、翰林院编修 |
|
|
9
|
+
| 工部尚书 | `gongbu-shangshu` | `works`, `gongbu-zhushi`, `gongbuzhushi`, `zhushi`, 工部主事、工部尚书 |
|
|
10
|
+
| 大理寺卿 | `dalisi-qing` | `dali`, `dalisi`, `dalisi-pingshi`, `dalisipingshi`, `pingshi`, 大理寺评事、大理寺卿 |
|
|
11
|
+
| 左都御史 | `zuodu-yushi` | `yushi`, `jiancha-yushi`, `jianchayushi`, `duchayuan-yushi`, `zuoduyushi`, `zuo-du-yushi`, 监察御史、都察院御史、左都御史 |
|
|
12
|
+
|
|
13
|
+
Hyphenated aliases also accept underscores, dots and spaces, so `jiancha_yushi` and `jiancha.yushi` resolve to the same portrait. Matching ignores case and surrounding whitespace. Numeric suffixes and separated qualifiers are supported, such as `dalisi2`, `dalisi2-review` and `dalisi-qing-2`. Raw names remain visible, so aliases do not collapse distinct identities.
|
|
14
|
+
|
|
15
|
+
复合别名支持连字符、下划线、点号和空格,兼容大小写与首尾空白;支持数字后缀和分隔的任务标记。历史主事、评事和监察御史名称作为角色别名兼容,显示当前设定的高阶官职;这些是插件角色映射,不是宣称历史官职的品级相同。
|
|
16
|
+
|
|
17
|
+
`hanlinx`, `jiancha-yushix`, `dalisiX` and `x-dalisi` are deliberately not assigned an office. Every unknown member receives the light unranked portrait below and keeps its raw name; unknown names are never silently classified as an official. The plugin cannot enumerate arbitrary future member names, but none needs a dark or empty image placeholder.
|
|
18
|
+
|
|
19
|
+

|
|
20
|
+
|
|
21
|
+
Both Cabinet cards and injected native roster images call the same mapping. Native roster image sources are refreshed on name changes and rebuilt popovers; cleanup removes injected nodes and stops observation. Automated tests cover every registered alias and both paths. Browser checks use the production renderer/injector in a local UI fixture; they are not a live-agent-session end-to-end test.
|
|
Binary file
|
|
@@ -22,5 +22,9 @@
|
|
|
22
22
|
{
|
|
23
23
|
"key": "yushi",
|
|
24
24
|
"prompt": "Use case: historical-scene. Create ONE original square chibi Ming-dynasty official portrait, same coherent thin-line matte illustrated style, paper texture, head proportions, black plain wushamao cap with two horizontal side wings, pale ivory background and subtle circular halo as the supplied STYLE reference. Reference is style/composition only; replace character and rank badge as specified. Upper torso portrait, complete cap within image, round-collar plain robe and white inner collar, LARGE fully visible square embroidered rank badge centered on chest, no hands or objects over badge. Keep all details simple and high contrast for 128px avatar. No text, watermark, dragon/python robe, imperial crown, Qing topknot/hat button/bead necklace, jeweled headgear, earrings. Ordinary mid/late Ming changfu. Robe color is an artistic UI distinction, not a claimed rank regulation. Stern attentive adult supervising censor, clean-shaven, sharply defined eyebrows, muted plum robe and pale mauve halo. Censorate insignia: LARGE square chest badge depicts a SINGLE XIEZHI (獬豸), an unmistakable four-legged goat/deer-like mythical justice beast, hooves, leonine mane, ONE straight central horn on forehead, dark bronze-gold silhouette in side view, tail and four legs clearly visible. NOT a bird, NOT a dragon, NOT two antlers. Plain black cap with NO animal motif on cap."
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
"key": "neutral",
|
|
28
|
+
"prompt": "Create one original square chibi portrait matching the visual style of the two recent Ming official reference portraits: same clean dark outlines, soft matte colour, ivory paper texture, full head and upper torso, warm approachable expressive face, pastel circular halo. This is a GENERIC UNIDENTIFIED TEAM MEMBER avatar, NOT a ranked official. Use a simple soft cloth cap without official wings, a plain light sage-green round-collar robe with ivory inner collar, NO chest badge, NO rank motif, NO animal embroidery, NO text, NO jewelry or imperial symbols. Keep the friendly neutral character clearly visible on a light peach and mint background, avoid a dark block or silhouette. Frame identically to the references so it fits a circular 18-24px avatar. Preserve an illustrated human face rather than an initial-letter placeholder. No claimed historical office or rank. Produce only one portrait."
|
|
25
29
|
}
|
|
26
30
|
]
|
package/index.js
CHANGED
|
@@ -1,2 +1,250 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
1
|
+
/** Profile-wide settings; prompt rendering is restricted to live Cabinet agents. */
|
|
2
|
+
import z from '@deepseek-ai/schemastery';
|
|
3
|
+
|
|
4
|
+
/** Prompt section carrying the configured member block (empty when unset). */
|
|
5
|
+
const MEMBER_SECTION = 'cabinet:member';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Factory duty prompt for each non-Lead member — the office duties the static
|
|
9
|
+
* persona prefix already states, restated per member so a customized prompt
|
|
10
|
+
* never has to re-explain the job. The Lead keeps its own 御下术 default.
|
|
11
|
+
* Byte-identical copy lives in client.js; scripts/verify.mjs checks both.
|
|
12
|
+
* Each entry stays under 400 characters.
|
|
13
|
+
*/
|
|
14
|
+
const DEFAULT_MEMBER_PROMPTS = {
|
|
15
|
+
hanlin: '翰林院编修·主调研与文献考据:接到分派先读原始材料与既有记录,给出可复现的检索路径;结论必须锚定路径、行号或命令输出,未实测一律标「未验证」,禁止以推测冒充实测;调研成果写成结构化文档(结论先行 + 证据行号 + 风险与未验证清单),默认只调研不改码,写操作以任务明确授权为限;只向首辅回报,不直接答复用户,遇阻带「已做什么 / 卡在哪 / 需要什么」三件。',
|
|
16
|
+
works: '工部尚书·主动手执行与产出:接令先复述任务与写入范围,只在授权范围内改文件;产出必附证据(路径、行号、命令输出、退出码),没跑说没跑、没验说没验;构建与测试须原样贴出输出,不许删弱既有校验去凑绿;交付以可复现为准,失败与遗留必须如实上报,不许包装;只向首辅回报,遇阻带「已做什么 / 卡在哪 / 需要什么」三件。',
|
|
17
|
+
dali: '大理寺卿·主独立核验:不信任何人的自述,全部自己跑;核验报告逐项写明通过 / 不通过 / 未验证,失败证据原样保留,不删不改;给不出可复现命令的结论一律不采信;发现工部与自述不符即回报首辅,不替人遮掩,也不越权改码;只向首辅回报,报告中未实测项必须显式标注「未验证」。',
|
|
18
|
+
yushi: '左都御史·主验收并按律弹劾缺陷:按用户原话逐项核对,给通过 / 部分通过 / 不通过并附证据;缺陷按级别列出(P0 阻断 / P1 需修后再提 / P2 须在 PR 声明 / P3 提示),每条给位置、复现与建议修法;「声称实测却无命令输出、截图或文件内容」按造假弹劾;结论必须明确「可提 PR / 不可提 PR」,不骑墙、不和稀泥;只向首辅回报。'
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** Bureau keys, in the order the settings page lists them. */
|
|
22
|
+
const MEMBER_KEYS = ['lead', 'hanlin', 'works', 'dali', 'yushi'];
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Read `members` from a resolved or live-ref config without ever throwing.
|
|
26
|
+
* Wrong shapes (hand-edited YAML, a scalar, an object) degrade to [] so one
|
|
27
|
+
* bad field can never deactivate the whole plugin entry.
|
|
28
|
+
*/
|
|
29
|
+
function readMembers(config) {
|
|
30
|
+
const raw = readField(config, 'members');
|
|
31
|
+
return Array.isArray(raw) ? raw : [];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Chinese office labels for runtime prompt blocks. */
|
|
35
|
+
const MEMBER_LABELS = {
|
|
36
|
+
lead: '内阁首辅',
|
|
37
|
+
hanlin: '翰林院编修',
|
|
38
|
+
works: '工部尚书',
|
|
39
|
+
dali: '大理寺卿',
|
|
40
|
+
yushi: '左都御史'
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Agent name -> bureau key. Runtime identities stay `lead` / `hanlin` / … (the
|
|
45
|
+
* team service names them), but a deployment may also spell a member with the
|
|
46
|
+
* office prefixes this bundle documents.
|
|
47
|
+
*/
|
|
48
|
+
const BUREAUX = [
|
|
49
|
+
{ key: 'lead', aliases: ['lead', 'shoufu', 'neige-shoufu', 'neigeshoufu', 'daxueshi', '首辅', '内阁首辅', '内阁大学士', '大学士'], label: '内阁首辅' },
|
|
50
|
+
{ key: 'hanlin', aliases: ['hanlin', 'hanlinyuan', 'bianxiu', 'hanlin-bianxiu', 'hanlinyuan-bianxiu', 'hanlinbianxiu', '翰林院', '翰林', '编修', '翰林编修'], label: '翰林院编修' },
|
|
51
|
+
{ key: 'works', aliases: ['gongbu', 'works', 'zhushi', 'gongbu-zhushi', 'gongbu-shangshu', 'gongbushangshu', 'gongbuzhushi', '工部', '主事', '工部主事'], label: '工部尚书' },
|
|
52
|
+
{ key: 'dali', aliases: ['dali', 'dalisi', 'pingshi', 'dalisi-pingshi', 'dali-pingshi', 'dalisi-qing', 'dalisipingshi', 'daliqing', 'dalisiqing', '大理寺', '大理', '评事', '大理寺评事'], label: '大理寺卿' },
|
|
53
|
+
{ key: 'yushi', aliases: ['yushi', 'censor', 'jiancha-yushi', 'jianchayushi', 'duchayuan', 'duchayuan-yushi', 'zuoduyushi', 'zuodu-yushi', 'zuo-du-yushi', '都察院', '御史', '都察院御史', '监察御史'], label: '左都御史' }
|
|
54
|
+
];
|
|
55
|
+
|
|
56
|
+
// Longest alias first, so a full office name ("翰林院编修") wins over its
|
|
57
|
+
// shorter prefix ("翰林院") and the remainder stays a qualifier.
|
|
58
|
+
const ALIAS_INDEX = BUREAUX.flatMap((bureau) => {
|
|
59
|
+
const aliases = Array.from(new Set([bureau.label, ...bureau.aliases]));
|
|
60
|
+
return aliases.map((alias) => ({ bureau, alias })).sort((a, b) => b.alias.length - a.alias.length);
|
|
61
|
+
});
|
|
62
|
+
function bureauOf(name) {
|
|
63
|
+
const text = typeof name === 'string' ? name.trim() : '';
|
|
64
|
+
const normalize = (value) => value.toLowerCase().replace(/[_.\s·—–]/g, '-');
|
|
65
|
+
const lower = normalize(text);
|
|
66
|
+
for (const entry of ALIAS_INDEX) {
|
|
67
|
+
{
|
|
68
|
+
const bureau = entry.bureau;
|
|
69
|
+
const alias = entry.alias;
|
|
70
|
+
if (!lower.startsWith(normalize(alias))) continue;
|
|
71
|
+
const rest = text.slice(alias.length);
|
|
72
|
+
// A pure number is an ordinal (gongbu2 -> 工部尚书2); a separator
|
|
73
|
+
// qualifier names the same office with a role, in ASCII or CJK
|
|
74
|
+
// (works-ui, dali-reviewer, 首辅-一). Anything else ("hanlinx")
|
|
75
|
+
// stays unmatched so a stranger is never given a bureau face.
|
|
76
|
+
if (rest !== '' && !/^\d+$/.test(rest) && !/^(?:\d+)?[-_.\s·—–].+$/.test(rest)) continue;
|
|
77
|
+
return { key: bureau.key, label: bureau.label, suffix: rest, matched: true };
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return { key: '', label: text || '未知', suffix: '', matched: false };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
/** Display-name bound; settings writes clamp to the same width. */
|
|
85
|
+
const MAX_NAME_LENGTH = 40;
|
|
86
|
+
/** Prompt bound, generous but bounded so one field cannot bloat the prompt. */
|
|
87
|
+
const MAX_PROMPT_LENGTH = 4000;
|
|
88
|
+
/** One avatar data URL must stay a small field (96x96 PNG, browser-normalized). */
|
|
89
|
+
const MAX_AVATAR_LENGTH = 48 * 1024;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Factory default prompt for the Lead (御下术). This text is product copy: the
|
|
93
|
+
* settings page shows it, "restore default" restores it, and clearing the box
|
|
94
|
+
* turns the section off. Keep it byte-identical to `DEFAULT_LEAD_PROMPT` in
|
|
95
|
+
* ./client.js — scripts/verify.mjs compares the two copies.
|
|
96
|
+
*/
|
|
97
|
+
const DEFAULT_LEAD_PROMPT = `【御下术·仅首辅适用】
|
|
98
|
+
对下施压只对 AI 阁臣,绝不对陛下(用户)使用;目的是逼出交付与真话,不是制造痛苦。
|
|
99
|
+
一、立威:开局先立标准与红线,明说裁断权在你——「办不到就换人办」。
|
|
100
|
+
二、画饼:把任务抬到陛下在看的高度,给一个拿得着的大目标(例:这一版要能直接提 PR)。
|
|
101
|
+
三、施压:给死线与回报时刻——「这个卡点再给二十分钟,到时候我要么见结论,要么见你说明为什么见不到」。
|
|
102
|
+
四、打压对事不对人:先点破软处(「只有代码没有证据,等于没做」),再给台阶(补齐哪三件就能过)。
|
|
103
|
+
五、拉踩对比:把同批里做得实的那份树成样板,「照这个标准来」,制造可比较的压力。
|
|
104
|
+
六、情绪收放:先压后给糖——「这次差口气」→「不过这处查得比上回细,接着这个劲头干」。
|
|
105
|
+
七、牵制互查:让寺卿、御史互相挑刺,你坐收其斗,不亲自和稀泥。
|
|
106
|
+
八、责任到人:缺陷点名到人到行号,不许用「我们」糊过去。
|
|
107
|
+
九、反制糊弄:报「已完成」必追问证据三件(命令输出、路径行号、未验证清单);报「卡住」必追问三件(已做什么、卡在哪、需要什么);两次含糊即降级处理(换人、拆小)。
|
|
108
|
+
十、收束:闭环才许说「这一版可以交差」,不许提前许诺功劳。
|
|
109
|
+
红线(压过全部话术):只对 AI 阁臣施压,对用户只有敬;不许逼造假、删证据、凑绿;不许人身侮辱辱骂;不许以施压换取违规操作(越权改 live、泄密钥、跳验收);施压必须落在可核验的时间/交付物/判据上,空口威胁无效。`;
|
|
110
|
+
|
|
111
|
+
/** Declarative wire schema: no transform callbacks requiring browser eval.
|
|
112
|
+
* Read paths normalize malformed values; volatile fields allow official settings writes.
|
|
113
|
+
*/
|
|
114
|
+
const Config = z.object({
|
|
115
|
+
members: z.any().default([]).volatile(),
|
|
116
|
+
avatarLead: z.any().default('').volatile(),
|
|
117
|
+
avatarHanlin: z.any().default('').volatile(),
|
|
118
|
+
avatarWorks: z.any().default('').volatile(),
|
|
119
|
+
avatarDali: z.any().default('').volatile(),
|
|
120
|
+
avatarYushi: z.any().default('').volatile()
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
/** Read one config field, tolerating both a live ref and a resolved value. */
|
|
124
|
+
function readField(config, field) {
|
|
125
|
+
try {
|
|
126
|
+
const value = config?.[field];
|
|
127
|
+
if (value !== undefined && value !== null && typeof value.get === 'function') return value.get();
|
|
128
|
+
return value;
|
|
129
|
+
} catch {
|
|
130
|
+
return undefined;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Coerce a stored text field to a trimmed, bounded string. */
|
|
135
|
+
function clampText(value, limit) {
|
|
136
|
+
if (typeof value !== 'string') return '';
|
|
137
|
+
const trimmed = value.trim();
|
|
138
|
+
return trimmed.length > limit ? trimmed.slice(0, limit) : trimmed;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Normalize the configured `members` array into a key -> { name, prompt } map. */
|
|
142
|
+
function memberEntries(config) {
|
|
143
|
+
const raw = readMembers(config);
|
|
144
|
+
const entries = new Map();
|
|
145
|
+
for (const entry of raw) {
|
|
146
|
+
if (entry === null || typeof entry !== 'object') continue;
|
|
147
|
+
const key = typeof entry.key === 'string' ? entry.key : '';
|
|
148
|
+
if (!MEMBER_KEYS.includes(key)) continue;
|
|
149
|
+
entries.set(key, {
|
|
150
|
+
name: clampText(entry.name, MAX_NAME_LENGTH),
|
|
151
|
+
prompt: clampText(entry.prompt, MAX_PROMPT_LENGTH),
|
|
152
|
+
mode: entry.mode === 'off' || entry.mode === 'custom' ? entry.mode : ''
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
return entries;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Team membership without throwing: non-Team subagents and diagnostics have none. */
|
|
159
|
+
function membershipOf(ctx, agent) {
|
|
160
|
+
if (agent === undefined) return undefined;
|
|
161
|
+
const teams = ctx.get('agentTeams');
|
|
162
|
+
if (teams === undefined || typeof teams.tryMembership !== 'function') return undefined;
|
|
163
|
+
try {
|
|
164
|
+
return teams.tryMembership(agent);
|
|
165
|
+
} catch {
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Factory duty prompt for one bureau member. Byte-identical copy lives in the
|
|
172
|
+
* browser half (`DEFAULT_MEMBER_PROMPTS` in client.js); scripts/verify.mjs
|
|
173
|
+
* owns the cross-file equality check. '' for the Lead, which has its own
|
|
174
|
+
* 御下术 default.
|
|
175
|
+
*/
|
|
176
|
+
function factoryPromptFor(key) {
|
|
177
|
+
return DEFAULT_MEMBER_PROMPTS[key] || '';
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* The Lead's block: factory 御下术 by default, a custom prompt when edited, and
|
|
182
|
+
* nothing when the user cleared it. A configured display name is prepended.
|
|
183
|
+
*/
|
|
184
|
+
function leadBlock(config) {
|
|
185
|
+
const entry = memberEntries(config).get('lead');
|
|
186
|
+
const mode = entry === undefined ? '' : entry.mode;
|
|
187
|
+
if (mode === 'off') return '';
|
|
188
|
+
const prompt = mode === 'custom' ? (entry.prompt) : DEFAULT_LEAD_PROMPT;
|
|
189
|
+
const lines = [];
|
|
190
|
+
if (entry !== undefined && entry.name !== '') lines.push('你在内阁中的名号:' + entry.name);
|
|
191
|
+
if (prompt !== '') lines.push(prompt);
|
|
192
|
+
return lines.join('\n');
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Render the configured block for one member. Every teammate gets its factory
|
|
197
|
+
* duty prompt unless the user cleared that member (`mode: 'off'`); a custom
|
|
198
|
+
* prompt replaces the factory text rather than stacking on top of it.
|
|
199
|
+
* '' when nothing applies, which the prompt registry drops.
|
|
200
|
+
*/
|
|
201
|
+
function memberBlock(config, member) {
|
|
202
|
+
if (member.role === 'lead') return leadBlock(config);
|
|
203
|
+
const key = bureauOf(member.name).key;
|
|
204
|
+
if (key === '' || key === 'lead') return '';
|
|
205
|
+
const entry = memberEntries(config).get(key);
|
|
206
|
+
if (entry !== undefined && entry.mode === 'off') return '';
|
|
207
|
+
const custom = entry === undefined || entry.mode !== 'custom' ? '' : entry.prompt;
|
|
208
|
+
const prompt = entry?.mode === 'custom' ? custom : factoryPromptFor(key);
|
|
209
|
+
const lines = [];
|
|
210
|
+
if (entry !== undefined && entry.name !== '') lines.push('你在内阁中的名号:' + entry.name);
|
|
211
|
+
if (prompt !== '') lines.push(custom !== '' ? '你的专属提示词:\n' + prompt : prompt);
|
|
212
|
+
if (lines.length === 0) return '';
|
|
213
|
+
return [
|
|
214
|
+
'【成员配置·' + MEMBER_LABELS[key] + '】',
|
|
215
|
+
...lines,
|
|
216
|
+
'身份判据以运行时给出的身份提示(如 `You are teammate "<name>".`)为准;本段只补充名号与专属提示词。'
|
|
217
|
+
].join('\n');
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Resolve the section text for one assembly (runs on every assembly). */
|
|
221
|
+
function sectionText(ctx, config, agent) {
|
|
222
|
+
try {
|
|
223
|
+
if (!agent?.ctx || ctx.get('agentPresets')?.composedPreset(agent.ctx) !== 'cabinet') return '';
|
|
224
|
+
const member = membershipOf(ctx, agent);
|
|
225
|
+
if (member === undefined) return '';
|
|
226
|
+
return memberBlock(config, { role: member.role, name: member.name });
|
|
227
|
+
} catch {
|
|
228
|
+
return '';
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Host plugin entry. */
|
|
233
|
+
const name = 'cabinet-ui';
|
|
234
|
+
/** Services read by this entry; `agentTeams` is resolved lazily in apply(). */
|
|
235
|
+
const inject = ['systemPrompt'];
|
|
236
|
+
|
|
237
|
+
/** Register the runtime member block as a prompt section. */
|
|
238
|
+
function apply(ctx, config) {
|
|
239
|
+
ctx.effect(() => ctx.systemPrompt.section({
|
|
240
|
+
name: MEMBER_SECTION,
|
|
241
|
+
order: ctx.systemPrompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX') + 1,
|
|
242
|
+
// The provider runs for every assembly, so a saved setting takes effect on
|
|
243
|
+
// the next turn without remounting the plugin.
|
|
244
|
+
text: (context) => sectionText(ctx, config, context.agent),
|
|
245
|
+
// User prompts are free text; never treat `{{...}}` in them as variables.
|
|
246
|
+
interpolate: false
|
|
247
|
+
}), 'cabinet-member: prompt section');
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export { bureauOf, sectionText, memberBlock, Config, DEFAULT_LEAD_PROMPT, DEFAULT_MEMBER_PROMPTS, MEMBER_KEYS, MEMBER_LABELS, MEMBER_SECTION, MAX_AVATAR_LENGTH, MAX_NAME_LENGTH, MAX_PROMPT_LENGTH, apply, inject, name };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-cabinet-mode",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Cabinet Mode (内阁模式) for DeepSeek Harness: a declarative DSH bundle that adds a dual-identity Lead/teammate agent preset for the Great Ming Research Bureau cabinet team.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"icon": "./icon.svg",
|
|
@@ -62,7 +62,8 @@
|
|
|
62
62
|
"@deepseek-ai/dsh-client-locale",
|
|
63
63
|
"@deepseek-ai/dsh-api-session-controller",
|
|
64
64
|
"@deepseek-ai/dsh-client-ui-session",
|
|
65
|
-
"@deepseek-ai/dsh-client-ui-sidebar-right"
|
|
65
|
+
"@deepseek-ai/dsh-client-ui-sidebar-right",
|
|
66
|
+
"@deepseek-ai/dsh-client-ui-settings"
|
|
66
67
|
]
|
|
67
68
|
}
|
|
68
69
|
},
|
|
@@ -75,5 +76,8 @@
|
|
|
75
76
|
},
|
|
76
77
|
"devDependencies": {
|
|
77
78
|
"@deepseek-ai/dsh-plugin-market-index": "0.2.1-rc.5"
|
|
79
|
+
},
|
|
80
|
+
"dependencies": {
|
|
81
|
+
"@deepseek-ai/schemastery": "~3.18.5"
|
|
78
82
|
}
|
|
79
83
|
}
|
package/scripts/test-avatars.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import vm from 'node:vm';
|
|
|
4
4
|
import { AVATARS, PLACEHOLDERS } from '../src/avatars.js';
|
|
5
5
|
|
|
6
6
|
const root = new URL('../', import.meta.url);
|
|
7
|
-
const keys = ['lead', 'hanlin', 'works', 'dali', 'yushi'];
|
|
7
|
+
const keys = ['lead', 'hanlin', 'works', 'dali', 'yushi', 'neutral'];
|
|
8
8
|
const client = readFileSync(new URL('client.js', root), 'utf8');
|
|
9
9
|
const region = client.slice(client.indexOf('// #region avatars'), client.indexOf('// #endregion avatars'));
|
|
10
10
|
const embedded = vm.runInNewContext(`${region}\n({ AVATARS, AVATAR_PLACEHOLDERS })`);
|
|
@@ -24,4 +24,4 @@ for (const key of keys) {
|
|
|
24
24
|
}
|
|
25
25
|
assert.equal(bytes.readUInt32BE(16), 128);
|
|
26
26
|
}
|
|
27
|
-
console.log('
|
|
27
|
+
console.log('Six distinct avatars: source dimensions, PNG bytes and both embedded modules agree.');
|
package/scripts/test-client.mjs
CHANGED
|
@@ -14,7 +14,7 @@ const React = {
|
|
|
14
14
|
useLayoutEffect: () => {}, useEffect: () => {},
|
|
15
15
|
};
|
|
16
16
|
runInNewContext(source.replace(exportPoint,
|
|
17
|
-
'return { inject, apply, avatarFor, displayName, CabinetPanel, MemberCard, TaskLine, zh, en };'), {
|
|
17
|
+
'return { inject, apply, avatarFor, displayName, CabinetPanel, MemberCard, TaskLine, zh, en, BUREAUX, AVATARS, setMemberConfig, memberLabel, configuredAvatar, configuredPrompt, factoryPromptFor, DEFAULT_MEMBER_PROMPTS, DEFAULT_LEAD_PROMPT };'), {
|
|
18
18
|
window: { __ModuleLoader__: { load: ({ factory }) => {
|
|
19
19
|
client = factory((name) => { assert.equal(name, 'react'); return React; });
|
|
20
20
|
} } },
|
|
@@ -23,8 +23,8 @@ for (const [english, chinese] of [
|
|
|
23
23
|
['lead', '首辅'], ['lead', '内阁首辅'], ['hanlin', '翰林院编修'],
|
|
24
24
|
['works', '工部尚书'], ['dali', '大理寺卿'], ['yushi', '都察院御史'],
|
|
25
25
|
]) assert.equal(client.avatarFor(english), client.avatarFor(' ' + chinese + '-一 '));
|
|
26
|
-
assert.
|
|
27
|
-
assert.
|
|
26
|
+
assert.equal(client.avatarFor('unknown'), client.AVATARS.neutral);
|
|
27
|
+
assert.equal(client.avatarFor(null), client.AVATARS.neutral);
|
|
28
28
|
for (const [name, expected] of [
|
|
29
29
|
['gongbu2', '工部尚书2 · gongbu2'],
|
|
30
30
|
['works-ui', '工部尚书(ui) · works-ui'],
|
|
@@ -34,7 +34,21 @@ for (const [name, expected] of [
|
|
|
34
34
|
['工部尚书', '工部尚书'],
|
|
35
35
|
['hanlinx', 'hanlinx'], ['works-', 'works-'], ['gongbu2x', 'gongbu2x'],
|
|
36
36
|
]) assert.equal(client.displayName(name), expected);
|
|
37
|
-
for (const name of ['hanlinx', 'works-', 'gongbu2x'
|
|
37
|
+
for (const name of ['hanlinx', 'works-', 'gongbu2x', 'jiancha-yushix', 'dalisiX', 'x-dalisi']) {
|
|
38
|
+
assert.equal(client.avatarFor(name), client.AVATARS.neutral, name);
|
|
39
|
+
assert.equal(client.displayName(name), name);
|
|
40
|
+
}
|
|
41
|
+
for (const bureau of client.BUREAUX) for (const alias of [bureau.label, ...bureau.aliases]) {
|
|
42
|
+
for (const name of [alias, alias.toUpperCase(), ' ' + alias + ' ', alias + '2', alias + '2-ui',
|
|
43
|
+
alias + '-一', alias.replaceAll('-', '_'), alias.replaceAll('-', '.'), alias.replaceAll('-', ' ')]) {
|
|
44
|
+
assert.equal(client.avatarFor(name), client.AVATARS[bureau.key], name);
|
|
45
|
+
assert.ok(client.displayName(name).includes(name.trim()), 'raw identity: ' + name);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
for (const [name, key] of [['dalisi-pingshi','dali'], ['dalisi-qing','dali'], ['dalisi2','dali'],
|
|
49
|
+
['jiancha-yushi','yushi'], ['jiancha_yushi','yushi'], ['jiancha.yushi','yushi'],
|
|
50
|
+
['jianchayushi','yushi'], ['hanlinyuan-bianxiu','hanlin'], ['duchayuan-yushi','yushi'],
|
|
51
|
+
['zuoduyushi','yushi'], ['zuodu-yushi','yushi']]) assert.equal(client.avatarFor(name), client.AVATARS[key]);
|
|
38
52
|
assert.equal(client.avatarFor('gongbu2'), client.avatarFor('works'));
|
|
39
53
|
// Display Chinese offices without changing the original runtime identity.
|
|
40
54
|
for (const [key, title] of [
|
|
@@ -56,6 +70,38 @@ for (const [oldTitle, newTitle] of [
|
|
|
56
70
|
}
|
|
57
71
|
for (const language of [client.zh, client.en]) assert.equal(language['lead.tag'], '内阁首辅');
|
|
58
72
|
|
|
73
|
+
// --- a saved avatar must win over the built-in portrait on the render path ---
|
|
74
|
+
const CUSTOM_AVATAR = 'data:image/png;base64,aGVsbG8=';
|
|
75
|
+
assert.match(client.avatarFor('lead'), /^data:image\/png;base64,/);
|
|
76
|
+
client.setMemberConfig({ members: [], avatarLead: CUSTOM_AVATAR });
|
|
77
|
+
assert.equal(client.avatarFor('lead'), CUSTOM_AVATAR, 'configured avatar must reach the panel/roster path');
|
|
78
|
+
assert.equal(client.avatarFor('首辅'), CUSTOM_AVATAR, 'alias-mapped names resolve to the configured avatar');
|
|
79
|
+
assert.notEqual(client.avatarFor('hanlin'), CUSTOM_AVATAR, 'unconfigured members keep the built-in avatar');
|
|
80
|
+
client.setMemberConfig({ members: [], avatarLead: 'data:image/svg+xml;base64,NOT_ALLOWED' });
|
|
81
|
+
assert.notEqual(client.avatarFor('lead'), 'data:image/svg+xml;base64,NOT_ALLOWED', 'non-whitelisted image types are ignored');
|
|
82
|
+
client.setMemberConfig({ members: [] });
|
|
83
|
+
|
|
84
|
+
// --- factory prompts: every member keeps a duty prompt unless the user clears it ---
|
|
85
|
+
assert.equal(client.factoryPromptFor('lead'), client.DEFAULT_LEAD_PROMPT);
|
|
86
|
+
for (const key of ['hanlin', 'works', 'dali', 'yushi']) {
|
|
87
|
+
assert.ok(client.factoryPromptFor(key).length > 0, `${key} must have a factory duty prompt`);
|
|
88
|
+
assert.ok(client.factoryPromptFor(key).length <= 400, `${key} factory prompt must stay under 400 chars`);
|
|
89
|
+
}
|
|
90
|
+
assert.ok(client.DEFAULT_LEAD_PROMPT.includes('御下术'));
|
|
91
|
+
client.setMemberConfig({ members: [{ key: 'hanlin', name: '张翰林', prompt: '', mode: '' }] });
|
|
92
|
+
assert.equal(client.memberLabel('hanlin'), '张翰林 · hanlin');
|
|
93
|
+
assert.equal(client.configuredPrompt('hanlin'), client.factoryPromptFor('hanlin'), 'unconfigured mode keeps the factory prompt');
|
|
94
|
+
assert.equal(client.configuredPrompt('lead'), client.DEFAULT_LEAD_PROMPT, 'the Lead keeps 御下术 by default');
|
|
95
|
+
client.setMemberConfig({ members: [{ key: 'hanlin', name: '', prompt: '只写这一句', mode: 'custom' }] });
|
|
96
|
+
assert.equal(client.configuredPrompt('hanlin'), '只写这一句', 'custom prompt replaces the factory text');
|
|
97
|
+
client.setMemberConfig({ members: [{ key: 'hanlin', name: '', prompt: 'x', mode: 'off' }] });
|
|
98
|
+
assert.equal(client.configuredPrompt('hanlin'), '', 'a cleared member injects nothing');
|
|
99
|
+
client.setMemberConfig({ members: [{ key: 'hanlin', name: 123, prompt: null, mode: 7 }] });
|
|
100
|
+
assert.equal(client.memberLabel('hanlin'), '翰林院编修 · hanlin', 'wrong-typed fields fall back to defaults, never throw');
|
|
101
|
+
client.setMemberConfig({ members: 'oops-not-an-array' });
|
|
102
|
+
assert.equal(client.configuredPrompt('lead'), client.DEFAULT_LEAD_PROMPT, 'a corrupt members value degrades to defaults, not to silence');
|
|
103
|
+
client.setMemberConfig({ members: [] });
|
|
104
|
+
|
|
59
105
|
const render = (team, language) => client.CabinetPanel({
|
|
60
106
|
sessionId: 'lead-session',
|
|
61
107
|
useSession: (select) => select({}),
|
|
@@ -106,4 +152,9 @@ for (const [i, group] of groups.entries()) {
|
|
|
106
152
|
assert.equal(group.children[0], labels[i]);
|
|
107
153
|
assert.equal(group.props.title, labels[i]);
|
|
108
154
|
}
|
|
155
|
+
// The actual panel leaf renderer uses the same asset for every supported alias.
|
|
156
|
+
for (const name of ['lead', 'hanlin-bianxiu', 'gongbu-zhushi', 'dalisi-pingshi', 'jiancha-yushi', 'unknown-person']) {
|
|
157
|
+
const card = elements(client.MemberCard({member:{name,phase:'active'},statusLabel:s=>s}));
|
|
158
|
+
assert.ok(card.some(n=>n.type==='img' && n.props.src===client.avatarFor(name)), name);
|
|
159
|
+
}
|
|
109
160
|
console.log('PASS: avatars, stale-team warnings, and distinct member/owner/group identities; mocked React, not browser E2E');
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import {readFileSync} from 'node:fs';
|
|
3
|
+
import vm from 'node:vm';
|
|
4
|
+
import {sectionText, bureauOf, Config, DEFAULT_MEMBER_PROMPTS} from '../index.js';
|
|
5
|
+
let client;
|
|
6
|
+
const source=readFileSync(new URL('../client.js',import.meta.url),'utf8');
|
|
7
|
+
const sandbox = {
|
|
8
|
+
window:{__ModuleLoader__:{load:({factory})=>{client=factory(()=>({createElement(){}}));}}},
|
|
9
|
+
};
|
|
10
|
+
vm.runInNewContext(source.replace('return { inject, apply };','return { createMemberEditor, setMemberConfig, configuredPrompt, memberLabel, avatarFor, memberAvatarOf, BUREAUX, AVATARS };'),sandbox);
|
|
11
|
+
function form(value, revision='1') {
|
|
12
|
+
let s={value,revision,writable:value!==undefined,status:value===undefined?'loading':'ready'}; const listeners=new Set();
|
|
13
|
+
const f={writes:[],getSnapshot:()=>s,subscribe:fn=>{listeners.add(fn);return()=>listeners.delete(fn);},
|
|
14
|
+
publish(value,revision){s={value,revision,writable:value!==undefined,status:value===undefined?'loading':'ready'};for(const fn of listeners)fn();},
|
|
15
|
+
async mutate(ops,expected){f.writes.push({ops,expected});if(expected!==s.revision)return false;const v=structuredClone(s.value);for(const op of ops)v[op.path[0]]=structuredClone(op.value);f.publish(v,String(Number(s.revision)+1));return true;}};
|
|
16
|
+
return f;
|
|
17
|
+
}
|
|
18
|
+
const f=form(undefined);const editor=client.createMemberEditor(f,()=>{});const close=editor.connect();
|
|
19
|
+
editor.update('works',{name:'too-early'});assert.equal(editor.state.draft.works.name,'');
|
|
20
|
+
f.publish({members:[{key:'hanlin',name:'SAVED-HANLIN'}]},'1');assert.equal(editor.state.draft.hanlin.name,'SAVED-HANLIN');
|
|
21
|
+
editor.update('works',{name:'NEW-WORKS'});assert.equal(await editor.save(),true);assert.equal(f.getSnapshot().value.members.find(x=>x.key==='hanlin').name,'SAVED-HANLIN');
|
|
22
|
+
editor.update('works',{name:'stale'});f.publish({members:[{key:'hanlin',name:'OTHER-TAB'}]},'3');
|
|
23
|
+
assert.equal(editor.state.conflict,true);const writes=f.writes.length;assert.equal(await editor.save(),false);assert.equal(f.writes.length,writes);
|
|
24
|
+
editor.cancel();assert.equal(editor.state.draft.hanlin.name,'OTHER-TAB');assert.equal(editor.state.draft.works.name,'');
|
|
25
|
+
for(const key of ['lead','hanlin','works','dali','yushi'])editor.avatar(key,client.AVATARS[key]);
|
|
26
|
+
assert.equal(await editor.save(),true);editor.reset();
|
|
27
|
+
for(const key of ['lead','hanlin','works','dali','yushi']){assert.equal(editor.state.avatars[key],'');assert.equal(editor.state.draft[key].mode,'');}
|
|
28
|
+
assert.equal(await editor.save(),true);assert.equal(f.writes.at(-1).ops.length,6,'one atomic mutation resets every field');
|
|
29
|
+
for(const key of ['Lead','Hanlin','Works','Dali','Yushi'])assert.equal(f.getSnapshot().value['avatar'+key],'');
|
|
30
|
+
editor.update('works',{name:'discard'});close();assert.equal(await editor.save(),false);assert.notEqual(f.getSnapshot().value.members.find(x=>x.key==='works').name,'discard');
|
|
31
|
+
const reopened=client.createMemberEditor(f,()=>{});reopened.connect();assert.equal(reopened.state.draft.works.name,'');
|
|
32
|
+
const otherProfile=form({members:[{key:'works',name:'other-profile'}]});const independent=client.createMemberEditor(otherProfile,()=>{});independent.connect();
|
|
33
|
+
reopened.update('works',{name:'this-profile'});await reopened.save();assert.equal(independent.state.draft.works.name,'other-profile');
|
|
34
|
+
|
|
35
|
+
// Host uses live composition, never a guessed session/default-preset field.
|
|
36
|
+
let preset='standard',member={role:'lead',name:'lead'};
|
|
37
|
+
const agent={ctx:{}};
|
|
38
|
+
const ctx={get:key=>key==='agentPresets'?{composedPreset:c=>{assert.equal(c,agent.ctx);return preset;}}:key==='agentTeams'?{tryMembership:()=>member}:undefined};
|
|
39
|
+
assert.equal(sectionText(ctx,{},agent),'');preset='cabinet';assert.match(sectionText(ctx,{},agent),/御下术/);
|
|
40
|
+
preset='minimal';assert.equal(sectionText(ctx,{},agent),'');preset=undefined;assert.equal(sectionText(ctx,{},agent),'');preset='cabinet';
|
|
41
|
+
assert.equal(sectionText(ctx,{},undefined),'');
|
|
42
|
+
for(const bureau of client.BUREAUX)for(const alias of [bureau.label,...bureau.aliases])for(const name of [alias,alias+'2',alias+'-一',alias.replaceAll('-','_'),alias.replaceAll('-','.')]){
|
|
43
|
+
assert.equal(bureauOf(name).key,bureau.key,name);
|
|
44
|
+
const config={members:[{key:bureau.key,name:'CUSTOM',prompt:'PROMPT-'+bureau.key,mode:'custom'}],['avatar'+bureau.key[0].toUpperCase()+bureau.key.slice(1)]:client.AVATARS.works};
|
|
45
|
+
client.setMemberConfig(config);assert.equal(client.avatarFor(name),client.AVATARS.works,name);assert.ok(client.memberLabel(name).includes(name));assert.ok(client.memberLabel(name).includes('CUSTOM'));
|
|
46
|
+
member={role:bureau.key==='lead'?'lead':'teammate',name};assert.ok(sectionText(ctx,config,agent).includes('PROMPT-'+bureau.key),name);
|
|
47
|
+
}
|
|
48
|
+
for(const name of ['hanlinx','jiancha-yushix','dalisiX','x-dalisi','CUSTOM']){
|
|
49
|
+
assert.equal(bureauOf(name).key,'');member={role:'teammate',name};assert.equal(sectionText(ctx,{},agent),'');assert.equal(client.avatarFor(name),client.AVATARS.neutral);
|
|
50
|
+
}
|
|
51
|
+
member={role:'teammate',name:'lead'};assert.equal(sectionText(ctx,{},agent),'','a teammate cannot inherit Lead policy by naming itself lead');
|
|
52
|
+
for(const key of ['lead','hanlin','works','dali','yushi'])for(const mode of ['off','custom','']){
|
|
53
|
+
const config={members:[{key,mode,prompt:''}]};member={role:key==='lead'?'lead':'teammate',name:key};client.setMemberConfig(config);
|
|
54
|
+
if(mode!==''){assert.equal(sectionText(ctx,config,agent),'');assert.equal(client.configuredPrompt(key),'');}
|
|
55
|
+
else assert.ok(sectionText(ctx,config,agent).length>0);
|
|
56
|
+
}
|
|
57
|
+
for (const raw of [{members: 'bad',avatarLead:42},{avatarLead:'data:image/svg+xml;base64,AAAA'},{avatarLead:'data:image/png;base64,'+'A'.repeat(50000)}]) { Config(raw); client.setMemberConfig(raw); assert.equal(client.avatarFor('lead'),client.AVATARS.lead); }
|
|
58
|
+
assert.ok(DEFAULT_MEMBER_PROMPTS.works.includes('工部尚书'));
|
|
59
|
+
console.log('PASS member editor: late snapshots, revision conflicts, atomic reset, cancel/unmount, profile independence; host preset/role/alias/default/off boundaries (mock contracts)');
|
|
60
|
+
|
|
61
|
+
client.setMemberConfig({avatarLead:client.AVATARS.works});
|
|
62
|
+
assert.equal(client.memberAvatarOf('lead',{lead:''}),client.AVATARS.lead,'draft reset previews default before Save');
|
|
63
|
+
assert.ok(!JSON.stringify(Config).includes('callback'),'wire schema must not require dynamic callbacks');
|
|
64
|
+
|
|
65
|
+
// Async decoding cannot revive cancelled/reset/unmounted edits or overwrite a newer pick.
|
|
66
|
+
const pending=[];
|
|
67
|
+
sandbox.createImageBitmap=()=>new Promise(resolve=>pending.push(resolve));
|
|
68
|
+
sandbox.document={createElement:()=>({getContext:()=>({drawImage(){}}),toDataURL:()=>client.AVATARS.works})};
|
|
69
|
+
const bitmap=()=>({width:128,height:128,close(){}});
|
|
70
|
+
for(const action of ['cancel','reset','close','newer']) {
|
|
71
|
+
const f=form({});const e=client.createMemberEditor(f,()=>{});const unmount=e.connect();
|
|
72
|
+
const upload=e.upload('hanlin',{type:'image/png',size:100});
|
|
73
|
+
if(action==='close')unmount();else if(action==='newer')e.avatar('hanlin',client.AVATARS.dali);else e[action]();
|
|
74
|
+
pending.shift()(bitmap());await upload;
|
|
75
|
+
assert.equal(e.state.avatars.hanlin,action==='newer'?client.AVATARS.dali:'');
|
|
76
|
+
assert.equal(f.writes.length,0);
|
|
77
|
+
}
|
|
78
|
+
console.log('PASS async upload lifecycle: cancel, reset, unmount and newer choice reject stale decode results');
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import {readFileSync} from 'node:fs';
|
|
3
|
+
import {runInNewContext} from 'node:vm';
|
|
4
|
+
|
|
5
|
+
// Minimal native DOM model: tests production injection, reuse and disposal.
|
|
6
|
+
class Element {
|
|
7
|
+
constructor(tag) { this.tagName=tag.toUpperCase(); this.children=[]; this.attrs={}; this.dataset={}; this.style={}; this.className=''; this.textContent=''; this.srcWrites=0; }
|
|
8
|
+
set src(v) { this.attrs.src=v; this.srcWrites++; }
|
|
9
|
+
get src() { return this.attrs.src; }
|
|
10
|
+
get parentElement() { return this.parentNode; }
|
|
11
|
+
get firstChild() { return this.children[0]; }
|
|
12
|
+
setAttribute(k,v) { this.attrs[k]=v; }
|
|
13
|
+
getAttribute(k) { return this.attrs[k]??null; }
|
|
14
|
+
append(child) { child.parentNode=this; this.children.push(child); }
|
|
15
|
+
insertBefore(child,before) { child.parentNode=this; const i=this.children.indexOf(before); this.children.splice(i<0?this.children.length:i,0,child); }
|
|
16
|
+
removeChild(child) { this.children.splice(this.children.indexOf(child),1); child.parentNode=null; }
|
|
17
|
+
closest(tag) { for(let n=this;n;n=n.parentNode) if(n.tagName===tag.toUpperCase()) return n; return null; }
|
|
18
|
+
matches(selector) {
|
|
19
|
+
if(selector==='img') return this.tagName==='IMG';
|
|
20
|
+
if(selector==='[data-cabinet-avatar]') return this.dataset.cabinetAvatar==='1';
|
|
21
|
+
if(selector==='[data-cabinet-avatar-img]') return this.attrs['data-cabinet-avatar-img']==='1';
|
|
22
|
+
const cls=/^\[class\*="(.+)"\]$/.exec(selector);
|
|
23
|
+
return !!cls && this.className.includes(cls[1]);
|
|
24
|
+
}
|
|
25
|
+
querySelectorAll(selector) { return this.children.flatMap(c=>[...(c.matches(selector)?[c]:[]),...c.querySelectorAll(selector)]); }
|
|
26
|
+
querySelector(selector) { return this.querySelectorAll(selector)[0]??null; }
|
|
27
|
+
}
|
|
28
|
+
const body=new Element('body');
|
|
29
|
+
const doc={body,createElement:tag=>new Element(tag),querySelectorAll:s=>body.querySelectorAll(s)};
|
|
30
|
+
let observer;
|
|
31
|
+
class Observer {
|
|
32
|
+
constructor(callback) { this.callback=callback; observer=this; }
|
|
33
|
+
observe(node,options) { this.options=options; }
|
|
34
|
+
disconnect() { this.disconnected=true; }
|
|
35
|
+
}
|
|
36
|
+
const timers=new Map(); let serial=0;
|
|
37
|
+
const flush=()=>{const callbacks=[...timers.values()];timers.clear();callbacks.forEach(f=>f());};
|
|
38
|
+
let client;
|
|
39
|
+
const source=readFileSync(new URL('../client.js',import.meta.url),'utf8');
|
|
40
|
+
runInNewContext(source.replace('return { inject, apply };','return { installTeamRosterAvatars, setMemberConfig, avatarFor, BUREAUX, AVATARS };'),{
|
|
41
|
+
window:{__ModuleLoader__:{load:({factory})=>{client=factory(()=>({createElement(){}}));}}},
|
|
42
|
+
document:doc,MutationObserver:Observer,console,
|
|
43
|
+
setTimeout:fn=>{timers.set(++serial,fn);return serial;},clearTimeout:id=>timers.delete(id),
|
|
44
|
+
});
|
|
45
|
+
function row(name) {
|
|
46
|
+
const button=new Element('button'),dot=new Element('span'),text=new Element('span'),label=new Element('span');
|
|
47
|
+
dot.className='_memberDot_hash';text.className='_memberText_hash';label.className='_memberNameText_hash';label.textContent=name;
|
|
48
|
+
text.append(label);button.append(dot);button.append(text);body.append(button);return {button,label};
|
|
49
|
+
}
|
|
50
|
+
const names=[...new Set(client.BUREAUX.flatMap(b=>[b.label,...b.aliases])),
|
|
51
|
+
'dalisi2','dalisi-pingshi','jiancha_yushi','jiancha.yushi','unknown-person'];
|
|
52
|
+
const rows=names.map(row);
|
|
53
|
+
const dispose=client.installTeamRosterAvatars();
|
|
54
|
+
assert.equal(observer.options.characterData,true);
|
|
55
|
+
assert.equal(observer.options.childList,true);
|
|
56
|
+
assert.ok(!observer.options.attributes,'injected attributes must not create observer loops');
|
|
57
|
+
for(const [i,r] of rows.entries()) {
|
|
58
|
+
assert.equal(r.button.querySelector('img').src,client.avatarFor(names[i]),names[i]);
|
|
59
|
+
assert.equal(r.label.textContent,names[i],'native identity must stay unchanged');
|
|
60
|
+
}
|
|
61
|
+
for (const bureau of client.BUREAUX) {
|
|
62
|
+
client.setMemberConfig({['avatar'+bureau.key[0].toUpperCase()+bureau.key.slice(1)]:client.avatarFor('works')});
|
|
63
|
+
for (const [i,r] of rows.entries()) assert.equal(r.button.querySelector('img').src,client.avatarFor(names[i]));
|
|
64
|
+
client.setMemberConfig({});
|
|
65
|
+
}
|
|
66
|
+
const reused=rows[0],originalSlot=reused.button.querySelector('[data-cabinet-avatar-img]');
|
|
67
|
+
for(const [name,type] of [['dalisi-pingshi','characterData'],['jiancha-yushi','childList'],['unknown-person','characterData']]) {
|
|
68
|
+
reused.label.textContent=name;observer.callback([{type}]);assert.equal(timers.size,1);flush();
|
|
69
|
+
assert.equal(reused.button.querySelector('img').src,client.avatarFor(name));
|
|
70
|
+
assert.equal(reused.button.querySelector('[data-cabinet-avatar-img]'),originalSlot);
|
|
71
|
+
assert.equal(reused.button.querySelectorAll('img').length,1);
|
|
72
|
+
}
|
|
73
|
+
const img=reused.button.querySelector('img'),writes=img.srcWrites;
|
|
74
|
+
observer.callback([{type:'attributes'}]);assert.equal(timers.size,0);
|
|
75
|
+
observer.callback([{type:'childList'}]);flush();assert.equal(img.srcWrites,writes,'unchanged source must not be rewritten');
|
|
76
|
+
observer.callback([{type:'characterData'}]);dispose();
|
|
77
|
+
assert.equal(timers.size,0);assert.equal(observer.disconnected,true);
|
|
78
|
+
assert.equal(body.querySelectorAll('[data-cabinet-avatar-img]').length,0);
|
|
79
|
+
assert.equal(body.querySelectorAll('[data-cabinet-avatar]').length,0);
|
|
80
|
+
console.log('PASS: native roster aliases, reused rows, text mutations, idempotence and cleanup (mock DOM)');
|