|
1 | 1 | export class SkillRegistry { |
2 | | - constructor(skills = {}) { |
| 2 | + constructor(skills = {}, { onChange } = {}) { |
3 | 3 | this.skillNames = Object.keys(skills).sort(); |
4 | 4 | this.chatStates = new Map(); |
| 5 | + this.onChange = onChange; |
5 | 6 | } |
6 | 7 |
|
7 | 8 | normalizeSkillName(name) { |
@@ -47,13 +48,47 @@ export class SkillRegistry { |
47 | 48 | const normalized = this.ensureKnownSkill(name); |
48 | 49 | const state = this.ensureChatState(chatId); |
49 | 50 | state.enabledSkills.add(normalized); |
| 51 | + this.onChange?.(this.exportState()); |
50 | 52 | return this.list(chatId); |
51 | 53 | } |
52 | 54 |
|
53 | 55 | disable(chatId, name) { |
54 | 56 | const normalized = this.ensureKnownSkill(name); |
55 | 57 | const state = this.ensureChatState(chatId); |
56 | 58 | state.enabledSkills.delete(normalized); |
| 59 | + this.onChange?.(this.exportState()); |
57 | 60 | return this.list(chatId); |
58 | 61 | } |
| 62 | + |
| 63 | + exportState() { |
| 64 | + const chats = {}; |
| 65 | + for (const [chatId, state] of this.chatStates.entries()) { |
| 66 | + chats[chatId] = { |
| 67 | + enabledSkills: [...state.enabledSkills].sort() |
| 68 | + }; |
| 69 | + } |
| 70 | + |
| 71 | + return { |
| 72 | + chats |
| 73 | + }; |
| 74 | + } |
| 75 | + |
| 76 | + restoreState(snapshot = {}) { |
| 77 | + const chats = snapshot?.chats; |
| 78 | + if (!chats || typeof chats !== "object") return; |
| 79 | + |
| 80 | + this.chatStates.clear(); |
| 81 | + |
| 82 | + for (const [chatId, state] of Object.entries(chats)) { |
| 83 | + const enabledSkills = Array.isArray(state?.enabledSkills) |
| 84 | + ? state.enabledSkills |
| 85 | + .map((skill) => this.normalizeSkillName(skill)) |
| 86 | + .filter((skill) => this.skillNames.includes(skill)) |
| 87 | + : this.skillNames; |
| 88 | + |
| 89 | + this.chatStates.set(String(chatId), { |
| 90 | + enabledSkills: new Set(enabledSkills) |
| 91 | + }); |
| 92 | + } |
| 93 | + } |
59 | 94 | } |
0 commit comments