Skip to content

feat(preset): add support for keyword triggers in presets configuration - #973

Merged
dingyi222666 merged 4 commits into
ChatLunaLab:v1-devfrom
Hoshino-Yumetsuki:v1-dev
Jul 13, 2026
Merged

dingyi222666 merged 4 commits into
ChatLunaLab:v1-devfrom
Hoshino-Yumetsuki:v1-dev

Conversation

@Hoshino-Yumetsuki

Copy link
Copy Markdown
Member

No description provided.

Copilot AI review requested due to automatic review settings July 13, 2026 08:43
@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 442684fc-8260-4862-9373-d3e917fdd533

📥 Commits

Reviewing files that changed from the base of the PR and between 9a4dd2b and 7421d0e.

⛔ Files ignored due to path filters (2)
  • packages/core/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/core/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
📒 Files selected for processing (1)
  • packages/core/src/preset.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/preset.ts

Walkthrough

新增预设关键词触发总开关和单个预设开关,PresetService 汇总可用触发别名,聊天中间件改用别名集合解析预设车道,并补充相关测试及异常处理。

Changes

预设关键词触发

Layer / File(s) Summary
触发配置与预设类型契约
packages/core/src/config.ts, packages/core/src/llm-core/prompt/type.ts, packages/core/tests/helpers.ts
新增全局 enablePresetKeywordTrigger 配置及预设级 enableKeywordTrigger 字段,全局配置默认值为 true。
关键词别名收集
packages/core/src/preset.ts, packages/core/tests/preset-keyword-trigger.spec.ts
新增关键词别名汇总方法,根据全局及预设级开关过滤、拆分并清理触发关键词;测试覆盖禁用和过滤场景,并调整 ENOENT 异常判断。
聊天预设解析接入
packages/core/src/middlewares/chat/allow_reply.ts, packages/core/src/middlewares/chat/read_chat_message.ts
预设车道解析改用 getKeywordTriggerAliases() 返回的关键词别名集合。

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ChatMessage
  participant ChatMiddleware
  participant PresetService
  participant parsePresetLaneInput
  ChatMessage->>ChatMiddleware: 处理聊天消息
  ChatMiddleware->>PresetService: 获取关键词触发别名
  PresetService-->>ChatMiddleware: 返回别名数组
  ChatMiddleware->>parsePresetLaneInput: 使用消息与别名解析预设车道
Loading

Suggested reviewers: copilot

Poem

小兔蹦跳查配置,
关键词儿排成队。
总开关儿轻轻拨,
可用别名随风飞。
聊天解析认新词,
测试萝卜也加倍。

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive 作者未提供实际描述,当前内容过于泛泛,无法判断具体变更细节。 请补充一段简短说明,概述本次变更的目的、范围和对 preset 配置的影响。
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed 标题准确概括了为 preset 配置新增 keyword trigger 支持的主要变更。
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a global configuration option 'enablePresetKeywordTrigger' and a per-preset override 'enableKeywordTrigger' to control whether preset keywords are detected at the start of messages. It refactors the middleware to use a new 'getKeywordTriggerAliases' helper in 'PresetService' and adds corresponding unit tests. The review feedback points out a potential runtime 'TypeError' in 'PresetService' when accessing 'preset.config' directly, as 'config' is optional, and suggests using optional chaining ('preset.config?.enableKeywordTrigger') to prevent crashes.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread packages/core/src/preset.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds configurable “keyword trigger” support for preset lane switching in ChatLuna core, allowing the feature to be disabled globally and per-preset while centralizing alias extraction logic in PresetService.

Changes:

  • Added Config.enablePresetKeywordTrigger (default true) to globally enable/disable preset keyword detection.
  • Added per-preset opt-out preset.config.enableKeywordTrigger and a new PresetService.getKeywordTriggerAliases() helper used by chat middlewares.
  • Added Mocha spec coverage for the new alias/opt-out behavior and updated test config defaults.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated no comments.

Show a summary per file
File Description
packages/core/tests/preset-keyword-trigger.spec.ts Adds tests for global disable and per-preset opt-out behavior for keyword triggers.
packages/core/tests/helpers.ts Updates test config helper to include enablePresetKeywordTrigger.
packages/core/src/preset.ts Introduces getKeywordTriggerAliases() and filters aliases based on global/per-preset flags.
packages/core/src/middlewares/chat/read_chat_message.ts Switches lane parsing input to use getKeywordTriggerAliases() (centralized alias list).
packages/core/src/middlewares/chat/allow_reply.ts Uses getKeywordTriggerAliases() for prefix detection consistency with lane parsing.
packages/core/src/locales/zh-CN.schema.yml Documents enablePresetKeywordTrigger in schema i18n (zh-CN).
packages/core/src/locales/en-US.schema.yml Documents enablePresetKeywordTrigger in schema i18n (en-US).
packages/core/src/llm-core/prompt/type.ts Adds enableKeywordTrigger?: boolean to preset config typing (raw + template).
packages/core/src/config.ts Adds enablePresetKeywordTrigger to Config and schema with default true.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/core/tests/preset-keyword-trigger.spec.ts (1)

1-47: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

补充逗号拆分行为的测试覆盖。

getKeywordTriggerAliases 的核心变换是将 triggerKeyword 条目按逗号拆分、trim 并过滤空字符串,但当前测试未覆盖此行为。建议增加一个测试用例验证逗号拆分逻辑,防止回归。

♻️ 建议补充的测试用例
 it('getKeywordTriggerAliases omits presets with config.enableKeywordTrigger false', () => {
     const preset = createPresetService({ enablePresetKeywordTrigger: true })
     preset.addPreset({
         ...EMPTY_PRESET,
         triggerKeyword: ['hidden'],
         config: { enableKeywordTrigger: false }
     })
     preset.addPreset({
         ...EMPTY_PRESET,
         triggerKeyword: ['visible'],
         config: {}
     })
     assert.deepEqual(preset.getKeywordTriggerAliases().value, ['visible'])
 })
+
+it('getKeywordTriggerAliases splits comma-separated keywords', () => {
+    const preset = createPresetService({ enablePresetKeywordTrigger: true })
+    preset.addPreset({
+        ...EMPTY_PRESET,
+        triggerKeyword: ['catgirl, 猫娘'],
+        config: {}
+    })
+    assert.deepEqual(
+        preset.getKeywordTriggerAliases().value,
+        ['catgirl', '猫娘']
+    )
+})
+
+it('getKeywordTriggerAliases filters empty entries from comma split', () => {
+    const preset = createPresetService({ enablePresetKeywordTrigger: true })
+    preset.addPreset({
+        ...EMPTY_PRESET,
+        triggerKeyword: ['catgirl, , cat'],
+        config: {}
+    })
+    assert.deepEqual(
+        preset.getKeywordTriggerAliases().value,
+        ['catgirl', 'cat']
+    )
+})
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/tests/preset-keyword-trigger.spec.ts` around lines 1 - 47, 在现有
getKeywordTriggerAliases 测试附近新增测试用例,启用
enablePresetKeywordTrigger,并添加包含逗号、额外空格及空条目的 triggerKeyword。断言返回值会按逗号拆分、trim
每项并过滤空字符串,同时保留有效别名。
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/core/tests/preset-keyword-trigger.spec.ts`:
- Around line 1-47: 在现有 getKeywordTriggerAliases 测试附近新增测试用例,启用
enablePresetKeywordTrigger,并添加包含逗号、额外空格及空条目的 triggerKeyword。断言返回值会按逗号拆分、trim
每项并过滤空字符串,同时保留有效别名。

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: fa6d3005-859e-4351-8ffe-874bbc341cc3

📥 Commits

Reviewing files that changed from the base of the PR and between fe54ae4 and 1e5428b.

⛔ Files ignored due to path filters (2)
  • packages/core/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/core/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
📒 Files selected for processing (7)
  • packages/core/src/config.ts
  • packages/core/src/llm-core/prompt/type.ts
  • packages/core/src/middlewares/chat/allow_reply.ts
  • packages/core/src/middlewares/chat/read_chat_message.ts
  • packages/core/src/preset.ts
  • packages/core/tests/helpers.ts
  • packages/core/tests/preset-keyword-trigger.spec.ts

Copilot AI review requested due to automatic review settings July 13, 2026 12:12

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/core/src/preset.ts (1)

172-177: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

统一两处 ENOENT 异常处理的类型检查方式。

watchPreset 的 catch 块(172-177)使用了冗长的类型收窄(typeof e === 'object' && e !== null && 'code' in e),而 _checkPresetDir(326-327)直接用 catch (err: any) + err?.code。两处功能一致但风格不一致,且 326 行的 any 被 CodeFactor 标记为 @typescript-eslint/no-explicit-any。

建议统一为同一种模式。根据编码指南"Write the simplest possible code"和"Avoid any where possible",推荐两处都使用简洁的类型断言方式:

♻️ 统一为简洁的类型断言

watchPreset catch 块(172-177)简化为:

                 } catch (e) {
-                    if (
-                        typeof e === 'object' &&
-                        e !== null &&
-                        'code' in e &&
-                        (e as NodeJS.ErrnoException).code === 'ENOENT'
-                    ) {
+                    if ((e as NodeJS.ErrnoException)?.code === 'ENOENT') {
                         this._removePreset(filePath)

_checkPresetDir catch 块(326-327)去掉 any:

-        } catch (err: any) {
-            if (err?.code === 'ENOENT') {
+        } catch (err) {
+            if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') {

Also applies to: 326-327

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/preset.ts` around lines 172 - 177, 统一 watchPreset 与
_checkPresetDir 的 ENOENT 异常检查方式:将 watchPreset 中冗长的对象类型收窄改为对捕获异常进行
NodeJS.ErrnoException 类型断言并安全读取 code,同时将 _checkPresetDir 的 catch 参数从 any 改为默认的
unknown/省略显式 any,并采用相同的 code 检查模式,保持现有 ENOENT 分支行为不变。

Sources: Coding guidelines, Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/core/src/preset.ts`:
- Around line 172-177: 统一 watchPreset 与 _checkPresetDir 的 ENOENT 异常检查方式:将
watchPreset 中冗长的对象类型收窄改为对捕获异常进行 NodeJS.ErrnoException 类型断言并安全读取 code,同时将
_checkPresetDir 的 catch 参数从 any 改为默认的 unknown/省略显式 any,并采用相同的 code 检查模式,保持现有
ENOENT 分支行为不变。

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 22ecc859-8dc1-4b76-912d-2d22e58a4978

📥 Commits

Reviewing files that changed from the base of the PR and between 1e5428b and 5d14f22.

📒 Files selected for processing (1)
  • packages/core/src/preset.ts

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (1)

packages/core/src/preset.ts:333

  • _checkPresetDir() uses catch (err: any) plus optional-chaining for code. This weakens type safety and is inconsistent with the project’s common pattern of casting to NodeJS.ErrnoException when checking code (e.g. packages/core/src/utils/logger.ts). Prefer keeping the catch variable typed as unknown/implicit and using a narrow cast for the ENOENT check.
    private async _checkPresetDir() {
        const presetDir = path.join(this.resolvePresetDir())

        // check if preset dir exists
        try {
            await fs.access(presetDir)
        } catch (err) {
            if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
                await fs.mkdir(presetDir, { recursive: true })
                await this._copyDefaultPresets()
            } else {
                throw err
            }
        }

Comment thread packages/core/src/preset.ts Resolved
Copilot AI review requested due to automatic review settings July 13, 2026 12:16

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Comment thread packages/core/src/preset.ts Resolved
Copilot AI review requested due to automatic review settings July 13, 2026 13:52

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@dingyi222666
dingyi222666 merged commit 9f6d7c5 into ChatLunaLab:v1-dev Jul 13, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants