Skip to content

feat(chat): inline skill input context#1908

Merged
zhangmo8 merged 5 commits into
devfrom
fix/chat-input-skill-runtime
Jul 9, 2026
Merged

feat(chat): inline skill input context#1908
zhangmo8 merged 5 commits into
devfrom
fix/chat-input-skill-runtime

Conversation

@zhangmo8

@zhangmo8 zhangmo8 commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator
image

Summary

  • Render skill chips, file chips, and slash command argument forms as inline TipTap nodes inside the chat editor.
  • Replace the modal slash-command argument dialog with an inline commandForm node to avoid focus loss.
  • Fix skill runtime scoping so skill_list / skill_view use agent enabled skill/plugin policy instead of incorrectly treating current active skills as the allowlist.
  • Preserve current-message skill activation semantics for active skill display, skill content injection, and skill-run gating.
  • Add regression coverage for empty active skill lists no longer hiding available skills.

UI layout

BEFORE:

[✨ skillA ×] [📎 file.pdf ×]
我想要使用 /skill,把文件怎么样...

AFTER:

我想要使用 [✨ skillA ×],把 [📎 file.pdf ×] 文件怎么样...
/command [ inline args form ]

Notes

  • skill_view can now inspect available enabled skills even before they are active for the current message.
  • Root skill_view still activates a skill only for the current message/tool loop; it does not pin the skill to the conversation.

Verification

  • git diff --check
  • Not run: format, i18n, lint, typecheck, full/targeted tests per requester instruction.

Summary by CodeRabbit

  • New Features
    • Chat composer now uses inline editor nodes for skill chips, file attachments, and command forms, with injected node actions and exposed inline item snapshots.
    • User messages and session creation now carry optional inlineItems through to persistence and rendering.
    • Tool calls and runtime execution now support enabledSkillNames and enabledPluginIds, including explicit “no value” handling.
    • Skill tools add allowedPluginIds support for skill_list and skill_view.
  • Bug Fixes
    • Improved allowlist enforcement and active/pinned counting, plus consistent editor node synchronization.
  • Tests
    • Expanded allowlist/tool and editor synchronization test coverage with updated mocks.

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Backend changes thread enabled skill and plugin policy through tool execution and skill filtering. Frontend changes represent chat skills, files, and command prompts as TipTap nodes and pass inline items through message composition, storage, and rendering.

Changes

Skill/plugin allowlist propagation

Layer / File(s) Summary
Type contracts
src/main/presenter/agentRuntimePresenter/types.ts, src/main/presenter/toolPresenter/index.ts, src/shared/types/presenters/tool.presenter.d.ts
ProcessHooks and callTool option types now accept nullable enabled skill and plugin lists.
Runtime policy wiring
src/main/presenter/agentRuntimePresenter/index.ts, src/main/presenter/agentRuntimePresenter/dispatch.ts, src/main/presenter/toolPresenter/index.ts, src/main/presenter/agentRuntimePresenter/contextBuilder.ts
Agent runtime resolves extension policy values, exposes enabled skill and plugin hooks, and forwards enabled skill data into deferred tool calls and dispatch calls.
Agent tool normalization
src/main/presenter/toolPresenter/agentTools/agentToolManager.ts
AgentToolManager normalizes nullable enabled lists and passes them into skill list and skill view tool calls.
Skill filtering and checks
src/main/presenter/skillPresenter/skillTools.ts, test/main/presenter/skillPresenter/skillTools.test.ts
SkillTools filters listed skills by plugin ownership, updates active counts, and rejects skill view access when the plugin is not enabled; tests cover the new list behavior.
Tool manager test coverage
test/main/presenter/toolPresenter/agentTools/agentToolManagerSettings.test.ts
Tool manager tests assert skill_list does not treat activeSkillNames as an allowlist.

Inline chat items

Layer / File(s) Summary
Shared inline item contracts
src/shared/chat.d.ts, src/shared/types/core/chat.ts, src/shared/types/agent-interface.d.ts, src/shared/contracts/common.ts, src/shared/contracts/routes/sessions.routes.ts
Shared chat and agent-interface types plus send-message and session schemas now include inline skill and file items.
Message and session plumbing
src/main/presenter/agentRuntimePresenter/contextBuilder.ts, src/main/presenter/agentRuntimePresenter/index.ts, src/main/presenter/agentRuntimePresenter/messageStore.ts, src/main/presenter/agentRuntimePresenter/pendingInputCoordinator.ts, src/main/presenter/agentRuntimePresenter/pendingInputStore.ts, src/main/presenter/agentSessionPresenter/index.ts, src/renderer/src/stores/ui/message.ts
Agent runtime, pending-input, message-store, and session presenter code now normalize, persist, rebuild, and edit user inline items.
Inline node types and input actions
src/renderer/src/components/chat/nodes/symbols.ts, src/renderer/src/components/chat/nodes/skillChip.ts, src/renderer/src/components/chat/nodes/fileAttachment.ts, src/renderer/src/components/chat/nodes/commandForm.ts, src/renderer/src/components/chat/nodes/*View.vue
TipTap node actions, skill chips, file attachments, and command forms are defined with their node views and inline input action contracts.
Chat input editor sync
src/renderer/src/components/chat/ChatInputBox.vue, test/renderer/components/ChatInputBox.test.ts
Chat input now renders inline editor nodes, synchronizes them with reactive skills and files, exposes inline item snapshots, and updates tests for inline reconciliation behavior.
Message rendering
src/renderer/src/components/chat/messageListItems.ts, src/renderer/src/components/message/MessageContent.vue, src/renderer/src/components/message/MessageItemUser.vue, src/renderer/src/pages/ChatPage.vue, src/renderer/src/pages/NewThreadPage.vue, test/renderer/components/message/MessageItemUser.test.ts
Message list types, user message rendering, and page-level composition now include inline skill and file blocks and pass inline items through chat submission and session creation.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

Suggested reviewers: zerob13, deepinfect

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and clearly reflects the main chat UI change: moving skill input context inline.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/chat-input-skill-runtime

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.

@zerob13

zerob13 commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator

Nice

@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.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/renderer/src/components/chat/composables/useChatInputMentions.ts (1)

323-383: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Hardcoded user-facing strings violate i18n guidelines.

confirmText: 'Send' (line 329), confirmText: 'Insert' (line 373), and description: 'Fill prompt arguments before insertion.' (line 372) are user-facing strings displayed in CommandFormView.vue but are not internationalized. As per coding guidelines, all user-facing strings should use vue-i18n keys from src/renderer/src/i18n.

The composable already receives translated strings via options (e.g., compactCommandDescription). Consider adding sendText and insertText options, or importing useI18n directly in the composable since it's called within a component setup.

🌍 Proposed fix: add i18n options
 export interface UseChatInputMentionsOptions {
   // ... existing options ...
   compactCommandDescription?: ComputedRef<string>
+  sendButtonText?: ComputedRef<string>
+  insertButtonText?: ComputedRef<string>
+  promptArgsDescription?: ComputedRef<string>
 }

Then in ChatInputBox.vue:

 const mentions = useChatInputMentions({
   // ... existing options ...
   compactCommandDescription: computed(() => t('chat.compaction.commandDescription')),
+  sendButtonText: computed(() => t('common.send')),
+  insertButtonText: computed(() => t('common.insert')),
+  promptArgsDescription: computed(() => t('chat.input.promptArgsDescription'))
 })

And in useChatInputMentions.ts:

-        confirmText: 'Send',
+        confirmText: options.sendButtonText?.value ?? 'Send',
-        description: action.prompt.description || 'Fill prompt arguments before insertion.',
-        confirmText: 'Insert',
+        description: action.prompt.description || options.promptArgsDescription?.value ?? '',
+        confirmText: options.insertButtonText?.value ?? 'Insert',
🤖 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 `@src/renderer/src/components/chat/composables/useChatInputMentions.ts` around
lines 323 - 383, The user-facing strings in useChatInputMentions are hardcoded
and should be localized. Update the command and prompt paths in this composable
so the confirm labels and prompt-description text come from vue-i18n instead of
literal strings, using either new options passed in from the caller or useI18n
within the composable. Keep the changes focused around insertCommandFormNode,
the request-prompt-args branch, and the existing translated options pattern used
by ChatInputBox.

Source: Coding guidelines

🧹 Nitpick comments (5)
src/main/presenter/agentRuntimePresenter/index.ts (1)

3448-3459: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Redundant resolveAgentExtensionPolicy fetch in the pre-stream path.

resolveActiveSkillNamesForToolProfile (Line 6718) already calls resolveAgentExtensionPolicy internally. Immediately after using it at Line 3448-3449, runStreamForMessage calls resolveAgentExtensionPolicy again at the new Line 3450 for the same sessionId — a duplicate async round trip to configPresenter.resolveDeepChatAgentConfig. The same pattern repeats in loadToolDefinitionsForSession (Line 6631-6637) whenever activeSkillNamesOverride is undefined. Given this file explicitly instruments pre-stream steps for slowness (logSlowPreStreamStep), avoiding the extra round trip is worth doing.

Consider letting resolveActiveSkillNamesForToolProfile accept an optional pre-resolved policy (mirroring how resolveToolProfile already accepts extensionPolicy?: AgentExtensionPolicy), so callers that already have the policy don't trigger a second resolution.

Also applies to: 6631-6643, 6718-6736

🤖 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 `@src/main/presenter/agentRuntimePresenter/index.ts` around lines 3448 - 3459,
`runStreamForMessage` and `loadToolDefinitionsForSession` are doing a redundant
`resolveAgentExtensionPolicy` call for the same session after
`resolveActiveSkillNamesForToolProfile` already resolves it internally. Update
`resolveActiveSkillNamesForToolProfile` to accept an optional pre-resolved
policy, similar to `resolveToolProfile`, and thread that policy through the
pre-stream path so `loadToolDefinitionsForSession` can reuse it instead of
triggering a second async fetch via
`configPresenter.resolveDeepChatAgentConfig`.
test/main/presenter/skillPresenter/skillTools.test.ts (1)

155-163: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Add test coverage for allowedPluginIds filtering.

The new allowedPluginIds parameter in handleSkillList and handleSkillView is untested. Both methods now perform plugin-based authorization filtering, but no test verifies that a skill with an ownerPluginId not in the allowlist is correctly blocked. The mock data also lacks ownerPluginId on any skill, so the plugin filtering path is never exercised.

Consider adding:

  1. Mock skill metadata with ownerPluginId set.
  2. A handleSkillList test passing allowedPluginIds and verifying plugin-owned skills are filtered.
  3. A handleSkillView test passing allowedPluginIds and verifying rejection when ownerPluginId is not in the allowlist.
♻️ Suggested test additions
     {
       name: 'git-commit',
       description: 'Git commit message generator',
       path: '/skills/git-commit/SKILL.md',
       skillRoot: '/skills/git-commit',
       allowedTools: ['run_terminal_cmd'],
-      metadata: { tags: ['git'] }
+      metadata: { tags: ['git'] }
+    },
+    {
+      name: 'plugin-skill',
+      description: 'A plugin-provided skill',
+      path: '/skills/plugin-skill/SKILL.md',
+      skillRoot: '/skills/plugin-skill',
+      allowedTools: ['read_file'],
+      ownerPluginId: 'plugin-abc'
     }
   ]
+    it('filters skills by allowedPluginIds', async () => {
+      const result = await skillTools.handleSkillList(
+        'conv-123',
+        undefined,
+        undefined,
+        ['plugin-abc']
+      )
+
+      expect(result.totalCount).toBe(1)
+      expect(result.skills.map((s) => s.name)).toEqual(['plugin-skill'])
+    })
+
+    it('blocks plugin-owned skills when plugin id is not in allowlist', async () => {
+      const result = await skillTools.handleSkillList(
+        'conv-123',
+        undefined,
+        undefined,
+        ['other-plugin']
+      )
+
+      expect(result.totalCount).toBe(0)
+    })
+    it('rejects viewing a plugin-owned skill not in the allowedPluginIds', async () => {
+      const result = await skillTools.handleSkillView(
+        'conv-123',
+        { name: 'plugin-skill' },
+        undefined,
+        ['other-plugin']
+      )
+
+      expect(mockSkillPresenter.viewSkill).not.toHaveBeenCalled()
+      expect(result).toEqual({
+        success: false,
+        name: 'plugin-skill',
+        error: "Skill 'plugin-skill' is not enabled for this agent"
+      })
+    })
🤖 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 `@test/main/presenter/skillPresenter/skillTools.test.ts` around lines 155 -
163, The new allowedPluginIds authorization path in handleSkillList and
handleSkillView is not covered, so add tests that exercise plugin-based
filtering. Update the mock skill metadata to include ownerPluginId on at least
one skill, then add a handleSkillList case that passes an allowlist and verifies
skills with a non-allowed ownerPluginId are excluded. Also add a handleSkillView
case that passes allowedPluginIds and confirms a skill owned by a blocked plugin
is rejected, using the existing skillTools and mockSkillPresenter setup.
src/renderer/src/components/chat/nodes/commandForm.ts (1)

33-38: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove unused pendingCommand and pendingPrompt attributes.

These attributes are defined on the node schema but never read by CommandFormView.vue or any other consumer. The pending form state is managed via pendingFormData in useChatInputMentions.ts. Dead schema attributes add noise and may confuse future maintainers.

♻️ Proposed fix
       fields: {
         default: '[]'
       },
-      pendingCommand: {
-        default: null
-      },
-      pendingPrompt: {
-        default: null
-      }
     }
   },
🤖 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 `@src/renderer/src/components/chat/nodes/commandForm.ts` around lines 33 - 38,
Remove the unused node schema attributes pendingCommand and pendingPrompt from
the CommandForm definition, since CommandFormView.vue and the rest of the chat
flow rely on pendingFormData from useChatInputMentions.ts instead. Update the
CommandForm schema so only actively consumed fields remain, and make sure any
references in the CommandForm-related node setup or consumers are cleaned up if
present.
src/renderer/src/components/chat/ChatInputBox.vue (1)

189-218: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove dead code: insertSkillChipNode and insertFileAttachmentNode are never called.

These functions are defined but not invoked by any watcher, handler, or defineExpose. The sync functions (syncSkillNodes, syncFileNodes) handle all node insertion/removal. Additionally, the insertFileAttachmentNode comment says "at the end of the first paragraph" but inserts at position 1 (the start), which is misleading.

♻️ Proposed fix
-/** Insert a SkillChip node at the start of the first paragraph */
-function insertSkillChipNode(skillName: string) {
-  const firstChild = editor.state.doc.firstChild
-  if (!firstChild) return
-  const insertPos = 1
-  editor
-    .chain()
-    .focus()
-    .insertContentAt(insertPos, { type: 'skillChip', attrs: { skillName } })
-    .run()
-}
-
-/** Insert a FileAttachment node at the end of the first paragraph */
-function insertFileAttachmentNode(file: MessageFile) {
-  const firstChild = editor.state.doc.firstChild
-  if (!firstChild) return
-  const insertPos = 1
-  editor
-    .chain()
-    .focus()
-    .insertContentAt(insertPos, {
-      type: 'fileAttachment',
-      attrs: {
-        fileName: file.name || 'file',
-        filePath: file.path || file.name,
-        mimeType: file.mimeType || ''
-      }
-    })
-    .run()
-}
-
 /** Ensure editor SkillChip nodes mirror skillsData.activeSkills */
 function syncSkillNodes() {
🤖 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 `@src/renderer/src/components/chat/ChatInputBox.vue` around lines 189 - 218,
Remove the unused helper functions insertSkillChipNode and
insertFileAttachmentNode from ChatInputBox.vue since they are dead code and not
referenced by any watcher, handler, or defineExpose; keep the syncSkillNodes and
syncFileNodes flows as the only node insertion/removal paths. If you decide to
keep insertFileAttachmentNode for future use, update its comment to match the
actual insertion position or change the insertion logic so the implementation
matches the “end of the first paragraph” description.
test/renderer/components/ChatInputBox.test.ts (1)

27-79: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Mock extensions are adequate but descendants returning undefined limits sync logic coverage.

The descendants: vi.fn() mock returns undefined by default, so syncSkillNodes/syncFileNodes will see no existing nodes and skip deletion paths entirely. Consider providing a mock implementation that returns an empty array or configurable node list to test both insertion and removal flows.

♻️ Proposed fix
-        descendants: vi.fn(),
+        descendants: vi.fn((cb: (node: any, pos: number) => void | boolean) => {
+          // Default: no nodes; tests can override via mockReturnValue
+          return undefined
+        }),

Then in specific tests:

editor.state.doc.descendants.mockImplementation((cb) => {
  cb({ type: { name: 'fileAttachment' }, attrs: { filePath: '/tmp/a.txt' }, nodeSize: 1 }, 1)
})
🤖 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 `@test/renderer/components/ChatInputBox.test.ts` around lines 27 - 79, The
MockEditor in ChatInputBox tests leaves state.doc.descendants as a bare vi.fn(),
so syncSkillNodes and syncFileNodes can’t exercise existing-node deletion paths.
Update the MockEditor mock to give descendants a usable implementation (for
example, returning a configurable node list or invoking the callback for
supplied nodes) so tests can cover both insertion and removal behavior. Keep the
change localized to MockEditor and any tests that need to simulate
fileAttachment or skill nodes.
🤖 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.

Inline comments:
In `@src/renderer/src/components/chat/ChatInputBox.vue`:
- Around line 220-304: The sync logic in syncSkillNodes and syncFileNodes is
using stale ProseMirror positions within a single chained transaction, so
multiple deletes/inserts can target the wrong place. Update the deletion loops
to remove nodes in reverse document order (or otherwise map positions through
the transaction) in both syncSkillNodes and syncFileNodes, and avoid reusing
cursorPos/findFileInsertPos() from the pre-transaction state when inserting.
Recompute the insertion anchor from the current editor state or map it through
the chain before each insert so SkillChip and fileAttachment nodes stay aligned.

In `@src/renderer/src/components/chat/nodes/CommandFormView.vue`:
- Around line 32-38: The `CommandFormView` inputs currently submit on every
Enter press via `@keydown.enter.prevent="handleSubmit"`, which is too aggressive
for multi-field prompt argument forms. Update the `Input` handling so Enter only
calls `handleSubmit` when the form has a single field (the
`request-command-input` case), and otherwise allow normal field
navigation/behavior for multi-field scenarios. Use the existing `field.name`,
`formValues`, and `handleSubmit` logic to conditionally apply the Enter handler
based on the number of fields.

In `@src/renderer/src/components/chat/nodes/FileAttachmentView.vue`:
- Around line 9-15: The remove button in FileAttachmentView.vue is missing an
accessible name, so add an aria-label to the button used by the handleRemove
action. Update the button element that wraps the lucide:x Icon so screen readers
can announce its purpose clearly, keeping the existing click/removal behavior
unchanged.

In `@src/renderer/src/components/chat/nodes/SkillChipView.vue`:
- Around line 9-15: The remove button in SkillChipView.vue lacks an accessible
name, so screen readers cannot identify its purpose. Update the button element
in SkillChipView so the remove action has an explicit aria-label on the existing
icon-only button, keeping the current handleRemove behavior unchanged.

---

Outside diff comments:
In `@src/renderer/src/components/chat/composables/useChatInputMentions.ts`:
- Around line 323-383: The user-facing strings in useChatInputMentions are
hardcoded and should be localized. Update the command and prompt paths in this
composable so the confirm labels and prompt-description text come from vue-i18n
instead of literal strings, using either new options passed in from the caller
or useI18n within the composable. Keep the changes focused around
insertCommandFormNode, the request-prompt-args branch, and the existing
translated options pattern used by ChatInputBox.

---

Nitpick comments:
In `@src/main/presenter/agentRuntimePresenter/index.ts`:
- Around line 3448-3459: `runStreamForMessage` and
`loadToolDefinitionsForSession` are doing a redundant
`resolveAgentExtensionPolicy` call for the same session after
`resolveActiveSkillNamesForToolProfile` already resolves it internally. Update
`resolveActiveSkillNamesForToolProfile` to accept an optional pre-resolved
policy, similar to `resolveToolProfile`, and thread that policy through the
pre-stream path so `loadToolDefinitionsForSession` can reuse it instead of
triggering a second async fetch via
`configPresenter.resolveDeepChatAgentConfig`.

In `@src/renderer/src/components/chat/ChatInputBox.vue`:
- Around line 189-218: Remove the unused helper functions insertSkillChipNode
and insertFileAttachmentNode from ChatInputBox.vue since they are dead code and
not referenced by any watcher, handler, or defineExpose; keep the syncSkillNodes
and syncFileNodes flows as the only node insertion/removal paths. If you decide
to keep insertFileAttachmentNode for future use, update its comment to match the
actual insertion position or change the insertion logic so the implementation
matches the “end of the first paragraph” description.

In `@src/renderer/src/components/chat/nodes/commandForm.ts`:
- Around line 33-38: Remove the unused node schema attributes pendingCommand and
pendingPrompt from the CommandForm definition, since CommandFormView.vue and the
rest of the chat flow rely on pendingFormData from useChatInputMentions.ts
instead. Update the CommandForm schema so only actively consumed fields remain,
and make sure any references in the CommandForm-related node setup or consumers
are cleaned up if present.

In `@test/main/presenter/skillPresenter/skillTools.test.ts`:
- Around line 155-163: The new allowedPluginIds authorization path in
handleSkillList and handleSkillView is not covered, so add tests that exercise
plugin-based filtering. Update the mock skill metadata to include ownerPluginId
on at least one skill, then add a handleSkillList case that passes an allowlist
and verifies skills with a non-allowed ownerPluginId are excluded. Also add a
handleSkillView case that passes allowedPluginIds and confirms a skill owned by
a blocked plugin is rejected, using the existing skillTools and
mockSkillPresenter setup.

In `@test/renderer/components/ChatInputBox.test.ts`:
- Around line 27-79: The MockEditor in ChatInputBox tests leaves
state.doc.descendants as a bare vi.fn(), so syncSkillNodes and syncFileNodes
can’t exercise existing-node deletion paths. Update the MockEditor mock to give
descendants a usable implementation (for example, returning a configurable node
list or invoking the callback for supplied nodes) so tests can cover both
insertion and removal behavior. Keep the change localized to MockEditor and any
tests that need to simulate fileAttachment or skill nodes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9de2567a-184f-4445-8681-59c20f822a4b

📥 Commits

Reviewing files that changed from the base of the PR and between a13a735 and 2cef137.

📒 Files selected for processing (20)
  • src/main/presenter/agentRuntimePresenter/dispatch.ts
  • src/main/presenter/agentRuntimePresenter/index.ts
  • src/main/presenter/agentRuntimePresenter/types.ts
  • src/main/presenter/skillPresenter/skillTools.ts
  • src/main/presenter/toolPresenter/agentTools/agentToolManager.ts
  • src/main/presenter/toolPresenter/index.ts
  • src/renderer/src/components/chat/ChatInputBox.vue
  • src/renderer/src/components/chat/composables/useChatInputMentions.ts
  • src/renderer/src/components/chat/mentions/CommandInputDialog.vue
  • src/renderer/src/components/chat/nodes/CommandFormView.vue
  • src/renderer/src/components/chat/nodes/FileAttachmentView.vue
  • src/renderer/src/components/chat/nodes/SkillChipView.vue
  • src/renderer/src/components/chat/nodes/commandForm.ts
  • src/renderer/src/components/chat/nodes/fileAttachment.ts
  • src/renderer/src/components/chat/nodes/skillChip.ts
  • src/renderer/src/components/chat/nodes/symbols.ts
  • src/shared/types/presenters/tool.presenter.d.ts
  • test/main/presenter/skillPresenter/skillTools.test.ts
  • test/main/presenter/toolPresenter/agentTools/agentToolManagerSettings.test.ts
  • test/renderer/components/ChatInputBox.test.ts
💤 Files with no reviewable changes (1)
  • src/renderer/src/components/chat/mentions/CommandInputDialog.vue

Comment thread src/renderer/src/components/chat/ChatInputBox.vue Outdated
Comment thread src/renderer/src/components/chat/nodes/CommandFormView.vue
Comment thread src/renderer/src/components/chat/nodes/FileAttachmentView.vue
Comment thread src/renderer/src/components/chat/nodes/SkillChipView.vue
@zhangmo8 zhangmo8 changed the title fix(chat): inline skill input context feat(chat): inline skill input context Jul 9, 2026
@zerob13

zerob13 commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator

Review: fix(chat): inline skill input context

已切到本地分支 pr-1908-reviewfix/chat-input-skill-runtime)逐文件 review,并跑了相关检查:

  • pnpm run format:check
  • pnpm run typecheck:web
  • pnpm run typecheck:node
  • pnpm exec oxlint ... on changed files ✅ 0 warnings / 0 errors
  • pnpm vitest run test/main/presenter/skillPresenter/skillTools.test.ts test/main/presenter/toolPresenter/agentTools/agentToolManagerSettings.test.ts test/renderer/components/ChatInputBox.test.ts ✅ PASS

整体方向认可:后端把 enabledSkillNames/enabledPluginIds 从 agent policy 透传到 skill_list/skill_view 是合理的修正;前端用 TipTap inline node 替代外部 chip / modal dialog 的架构也清晰,能避免 focus loss。

以下是在代码里发现的问题,按优先级排序:


1. 死代码:insertSkillChipNode / insertFileAttachmentNode 未被调用

位置src/renderer/src/components/chat/ChatInputBox.vue(约 L190–L218)

这两个函数只在文件内定义,没有其它地方调用。syncSkillNodes / syncFileNodes 都是自己 inline 构造 insertContentAt 调用。建议要么删除它们,要么在统一入口里复用,避免留下死代码。


2. 键盘删除 inline node 时状态不同步(中等风险)

位置src/renderer/src/components/chat/nodes/SkillChipView.vueFileAttachmentView.vue

目前只有点击 chip 上的 × 按钮才会调用 actions.removeSkill / actions.removeFile。但用户可以直接把光标移到 skillChip / fileAttachment 前面按 Backspace,或在 node 上按 Delete 把 TipTap atom node 删掉,这种场景不会触发 actions,导致:

  • 编辑器里 chip 已经消失;
  • skillsData.activeSkills / files.selectedFiles 里仍然保留该 skill/file;
  • 外部 watch 下次触发时可能会把 chip 重新插回编辑器,造成「删不掉」的错觉。

建议在 editoronUpdatetransactions 里监听 node 删除事件,反向同步状态;或者把 node 设为不可删除(如 selectable: false + atom: true 还不够,Backspace 在边界仍会删除)。

同样的问题也适用于 commandForm:用户按 Delete 删除 form 后,pendingFormData 仍留在内存里,后续 submitDialog 可能误操作(虽然当前代码会先判断 pendingFormData 存在,但状态已经不同步)。


3. skill 激活失败时留下 orphan chip(中等风险)

位置src/renderer/src/components/chat/composables/useChatInputMentions.tshandleSlashSelectionactivate-skill 分支

当前逻辑是:

editor.chain().focus().insertContentAt(range.from, { type: 'skillChip', ... }).run()
if (options.onActivateSkill) {
  await options.onActivateSkill(action.skillName)
  return
}

如果 onActivateSkill 抛出异常或后端返回失败,skill chip 已经插入到编辑器里,但 skillsData.activeSkills 里没有这个 skill。用户会看到 chip 在输入框里,但消息实际不会携带该 skill。

建议:先调用 onActivateSkill 并在成功后再插入 chip;或者插入后在 catch 中删除 chip 并提示用户。


4. syncSkillNodes / syncFileNodesfocus() 会抢夺焦点

位置src/renderer/src/components/chat/ChatInputBox.vuesyncSkillNodes / syncFileNodes

两个同步函数都使用 editor.chain().focus()。当外部状态变化(比如从会话面板激活 skill、父组件更新 files)时,会把焦点强行切回输入框,可能打断用户在其他地方的交互。

建议:同步操作本身不要 .focus(),只在用户主动触发(如点击 skill 按钮、选择文件)时 focus;如果必须保留 focus,请明确说明原因。


5. commandForm 数据分两处保存,序列化后可能丢失提交上下文

位置src/renderer/src/components/chat/composables/useChatInputMentions.tssrc/renderer/src/components/chat/nodes/CommandFormView.vue

pendingFormData(包含 command / prompt 对象)保存在 composable 的 ref 中,而 inline node 的 attrs 只保存了 commandNamefields 等展示字段。如果父组件在 form 存在时重置 modelValuesetContent 重建文档),commandForm node 会重建,但 pendingFormData 不会恢复,提交会失效。

因为 modelValuegetText()(chip/form 的 renderText 返回空字符串),实际 setContent 后 form 不会保留,所以影响有限。但如果后续想持久化草稿或支持 undo,这里会是个隐患。建议把 command / prompt payload 一并放进 node attrs,或显式说明不持久化。


6. getEditorSkillNames / getEditorFileAttachments 目前没有外部调用者

位置src/renderer/src/components/chat/ChatInputBox.vue L557–L580

这两个 expose 出来的 helper 在当前代码库里没有被其它组件使用。如果是为后续功能预留,建议加注释说明;否则可以删除,避免暴露未使用的 API。


7. 测试对真实 TipTap 行为覆盖不足

ChatInputBox.test.ts 目前重度依赖 mock,基本无法验证:

  • syncSkillNodes / syncFileNodes 是否正确增删 node;
  • 键盘删除 chip 后状态是否同步;
  • commandForm 的提交/取消是否按预期工作。

建议后续补充集成测试或组件测试,用真实的 TipTap editor 实例验证这些交互。


总结

后端逻辑和类型透传看起来 solid,测试也覆盖到了核心回归点。前端 inline node 的体验方向很好,但需要在「node 删除与外部状态同步」和「焦点管理」上再打磨一下,避免给用户带来「删不掉」「乱跳焦点」的感觉。如果上面 2、3、4 点能在合并前处理,我会更放心。

需要我补充 line-level 评论或者针对某条建议再展开吗?

@zerob13 zerob13 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Code Review Summary

这个 PR 实现了将 skill chips、file attachments 和 slash command 参数表单作为内联 TipTap 节点渲染到聊天编辑器中的功能。整体架构合理,但有几个需要关注的问题:

✅ 优点

  1. 架构设计清晰:使用 TipTap 自定义节点 + Vue NodeView 的方式实现内联编辑,符合 WYSIWYG 编辑器最佳实践
  2. 双向同步机制:通过 syncSkillNodessyncFileNodes 实现 editor ↔ state 的双向同步,避免状态不一致
  3. 类型安全UserMessageInlineItem 类型定义完整,涵盖 skill 和 file 两种内联项
  4. 测试覆盖:为 ChatInputBoxMessageItemUser 新增了内联节点相关的测试用例

⚠️ 主要问题

1. 双向同步的竞态条件风险 ⚙️

function reconcileEditorNodes() {
  if (isSyncingNodes) return  // ✅ 有保护
  
  // 问题:如果用户快速删除多个 chip,可能导致状态不一致
  const editorSkillNames = new Set(getEditorSkillNames())
  activeSkillNames.value
    .filter((name) => !editorSkillNames.has(name))
    .forEach((name) => {
      void skillsData.deactivateSkill(name)  // ⚠️ async 操作可能延迟
    })
}

建议:考虑使用 debounce 或批量更新机制,避免频繁触发状态变更。

2. 命令表单提交的时序依赖 🔄

function handleSubmit() {
  if (!canSubmit.value) return
  actions?.prepareCommandFormSubmit()  // 设置标志
  props.deleteNode()                   // 删除节点
  if (actions?.submitCommandForm) {
    actions.submitCommandForm({ ...formValues })  // 提交表单
  }
}

问题isSubmittingCommandForm 标志依赖于严格的调用顺序,如果 deleteNode() 触发了异步更新,可能导致 reconcileEditorNodes 误判。

建议:使用 Promise 链或 nextTick 确保时序正确。

3. 内联项序列化缺少位置验证 📍

const inlineContentBlocks = computed(() => {
  const items = message.content.inlineItems || []
  // ⚠️ 没有验证 offset 是否在有效范围内
  const sorted = [...items].sort((a, b) => a.offset - b.offset)
  // ...
})

风险:如果 offset 越界或重叠,可能导致渲染错误。

建议:添加边界检查和重叠检测逻辑。

4. skill runtime 作用域变更影响面较大 🎯

const activeSkills = (Array.isArray(activeSkillNames) ? activeSkillNames : pinnedSkills).filter(
  (skillName) => listedSkillNames.has(skillName)
)

变更skill_listskill_view 现在使用 enabledSkillNames 作为允许列表,而不是当前激活的 skills。

问题:这个语义变化可能影响现有工作流,特别是依赖于「只看到当前激活 skills」的场景。

建议

  • 在 PR 描述中明确说明这是 breaking change
  • 考虑添加兼容层或配置开关
  • 确保所有相关文档和测试都更新

🐛 潜在 Bug

5. CommandForm 节点在某些情况下可能不被清理

if (!hasCommandFormNode() && !isSubmittingCommandForm) {
  mentions.closeDialog()
}

场景:如果用户在表单提交前手动关闭编辑器或切换会话,isSubmittingCommandForm 可能卡在 true

建议:在 onUnmounted 中重置标志。

6. 文件删除逻辑使用倒序遍历但可能影响索引

for (let i = files.selectedFiles.value.length - 1; i >= 0; i -= 1) {
  const file = files.selectedFiles.value[i]
  if (!editorFilePaths.has(file.path || file.name)) {
    files.deleteFile(i)  // ⚠️ deleteFile 内部实现需要确保索引安全
  }
}

建议:确认 deleteFile 不会修改数组长度导致索引错位。

📝 代码质量建议

  1. Magic Numbermax-w-[120px]max-w-[160px] 应该提取为常量或 Tailwind 配置
  2. Error HandlingJSON.parse(props.node.attrs.fields) 在 catch 块中应该记录错误日志
  3. 性能优化getEditorSkillNamesgetEditorFilePaths 频繁调用,考虑缓存结果
  4. i18n 遗漏CommandFormView.vue 中的一些文本可能需要国际化

🧪 测试建议

由于测试超时,建议手动验证以下场景:

  1. 快速连续删除多个 skill chips
  2. 在命令表单未提交时切换会话
  3. 粘贴包含内联项的长文本
  4. 文件和 skill 混合使用时的渲染顺序
  5. 编辑器失焦后重新聚焦的状态恢复

✨ 总体评价

这是一个高质量的 PR,实现了复杂的编辑器内联功能。主要风险在于双向同步的边界情况和 skill runtime 作用域的语义变更。建议:

  1. 补充 边界条件测试
  2. CHANGELOG 中标注 breaking change
  3. 考虑添加 性能监控(大量内联项时的渲染性能)
  4. 更新相关 用户文档

代码逻辑清晰,架构合理,通过后续迭代解决上述问题即可合并。 💪

@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.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/presenter/agentRuntimePresenter/index.ts (1)

3451-3451: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Policy resolution should fail closed. resolveAgentExtensionPolicy returns {} on config-resolution errors, and the new stream/deferred-tool consumers treat missing enabledSkillNames/enabledPluginIds as unrestricted access. A transient config failure therefore reopens skill/plugin access instead of denying it; make that fallback explicit or surface the error.

🤖 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 `@src/main/presenter/agentRuntimePresenter/index.ts` at line 3451, Policy
resolution is currently failing open because resolveAgentExtensionPolicy can
return an empty object on config errors, and the stream/deferred-tool paths then
interpret missing enabledSkillNames and enabledPluginIds as unrestricted access.
Update agentRuntimePresenter’s policy flow so the fallback is fail-closed:
either surface the error from resolveAgentExtensionPolicy or return an explicit
denying policy that blocks all skills/plugins, and make sure the
stream/deferred-tool consumers use that explicit result instead of treating
absent fields as allow-all.
🧹 Nitpick comments (3)
src/shared/chat.d.ts (1)

64-77: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

Deduplicate the shared chat message types

UserMessageInlineItem is declared verbatim in src/shared/chat.d.ts, src/shared/types/core/chat.ts, and src/shared/types/agent-interface.d.ts. UserMessageContent is also split across those shared files, so the shapes can drift over time. Consider centralizing the shared pieces in one canonical type and re-exporting them from the others.

🤖 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 `@src/shared/chat.d.ts` around lines 64 - 77, `UserMessageInlineItem` and
`UserMessageContent` are duplicated across the shared chat type definitions, so
centralize these shapes in one canonical shared type and re-export them from
`chat.d.ts`, `types/core/chat.ts`, and `types/agent-interface.d.ts`. Update the
shared type declarations to reference the single source of truth rather than
repeating the union definitions, and keep the existing symbols
(`UserMessageInlineItem`, `UserMessageContent`) available through re-exports for
callers.
src/renderer/src/components/message/MessageContent.vue (1)

26-44: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add title tooltips to skill/file chips for truncated labels.

Skill/file chip labels are truncated (max-w-[160px]/max-w-[120px]) but, unlike the mention chip above which sets :title, there's no way to see the full name/path on hover.

💡 Proposed fix
       <span
         v-else-if="block.type === 'skill'"
         class="inline-flex items-center gap-1 rounded-md border border-primary/30 bg-primary/10 px-1.5 py-0.5 text-xs text-primary align-middle"
         data-testid="user-message-inline-skill"
+        :title="block.skillName"
       >
         <Icon icon="lucide:sparkles" class="h-3 w-3 shrink-0" />
         <span class="truncate max-w-[160px]">{{ block.skillName }}</span>
       </span>

       <!-- File chip -->
       <span
         v-else-if="block.type === 'file'"
         class="inline-flex items-center gap-1 rounded-md border border-muted-foreground/25 bg-muted/25 px-1.5 py-0.5 text-xs text-muted-foreground align-middle"
         data-testid="user-message-inline-file"
+        :title="block.filePath || block.fileName"
       >
         <Icon :icon="getFileIcon(block)" class="h-3 w-3 shrink-0" />
         <span class="truncate max-w-[120px]">{{ block.fileName }}</span>
       </span>
🤖 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 `@src/renderer/src/components/message/MessageContent.vue` around lines 26 - 44,
Add hover tooltips to the truncated skill and file chips in MessageContent so
the full value is visible on hover. Update the inline chip spans in the
skill/file block branches to set a title using block.skillName and
block.fileName, mirroring the mention chip’s existing title behavior.
src/renderer/src/components/message/MessageItemUser.vue (1)

161-171: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate "base text" derivation.

getVisibleMessageText's baseText (161-166) and the new inlineBaseText computed (210-217) both re-implement the identical "blocks-or-text" fallback logic. Extracting a single shared helper (e.g. resolveBaseText(message)) would avoid the two implementations silently diverging later.

Also applies to: 209-217

🤖 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 `@src/renderer/src/components/message/MessageItemUser.vue` around lines 161 -
171, The visible message text logic is duplicating the same blocks-or-text
fallback in both getVisibleMessageText and the inlineBaseText path, so extract a
shared helper such as resolveBaseText(message) and reuse it in
MessageItemUser.vue. Update getVisibleMessageText and the inline text
composition to call that helper instead of re-implementing the
blocks/content.text fallback, keeping the logic in one place to prevent
divergence.
🤖 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.

Inline comments:
In `@src/renderer/src/components/message/MessageItemUser.vue`:
- Around line 163-170: The copy output is missing inline skill/file chip names
because `getCopyText` only uses `content` blocks or `content.text`, unlike the
new inline rendering path in `MessageItemUser.vue`. Update `getCopyText` to
mirror the `inlineText` composition used here by reading
`message.content.inlineItems` and appending each `skillName` or `fileName`
alongside the existing visible block/text content, so copied text preserves
those references.

---

Outside diff comments:
In `@src/main/presenter/agentRuntimePresenter/index.ts`:
- Line 3451: Policy resolution is currently failing open because
resolveAgentExtensionPolicy can return an empty object on config errors, and the
stream/deferred-tool paths then interpret missing enabledSkillNames and
enabledPluginIds as unrestricted access. Update agentRuntimePresenter’s policy
flow so the fallback is fail-closed: either surface the error from
resolveAgentExtensionPolicy or return an explicit denying policy that blocks all
skills/plugins, and make sure the stream/deferred-tool consumers use that
explicit result instead of treating absent fields as allow-all.

---

Nitpick comments:
In `@src/renderer/src/components/message/MessageContent.vue`:
- Around line 26-44: Add hover tooltips to the truncated skill and file chips in
MessageContent so the full value is visible on hover. Update the inline chip
spans in the skill/file block branches to set a title using block.skillName and
block.fileName, mirroring the mention chip’s existing title behavior.

In `@src/renderer/src/components/message/MessageItemUser.vue`:
- Around line 161-171: The visible message text logic is duplicating the same
blocks-or-text fallback in both getVisibleMessageText and the inlineBaseText
path, so extract a shared helper such as resolveBaseText(message) and reuse it
in MessageItemUser.vue. Update getVisibleMessageText and the inline text
composition to call that helper instead of re-implementing the
blocks/content.text fallback, keeping the logic in one place to prevent
divergence.

In `@src/shared/chat.d.ts`:
- Around line 64-77: `UserMessageInlineItem` and `UserMessageContent` are
duplicated across the shared chat type definitions, so centralize these shapes
in one canonical shared type and re-export them from `chat.d.ts`,
`types/core/chat.ts`, and `types/agent-interface.d.ts`. Update the shared type
declarations to reference the single source of truth rather than repeating the
union definitions, and keep the existing symbols (`UserMessageInlineItem`,
`UserMessageContent`) available through re-exports for callers.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1d7bda1e-3147-47f8-8bcf-9bd8d9d7e451

📥 Commits

Reviewing files that changed from the base of the PR and between 33467eb and 6592d1f.

📒 Files selected for processing (20)
  • src/main/presenter/agentRuntimePresenter/contextBuilder.ts
  • src/main/presenter/agentRuntimePresenter/index.ts
  • src/main/presenter/agentRuntimePresenter/messageStore.ts
  • src/main/presenter/agentRuntimePresenter/pendingInputCoordinator.ts
  • src/main/presenter/agentRuntimePresenter/pendingInputStore.ts
  • src/main/presenter/agentSessionPresenter/index.ts
  • src/renderer/src/components/chat/ChatInputBox.vue
  • src/renderer/src/components/chat/messageListItems.ts
  • src/renderer/src/components/message/MessageContent.vue
  • src/renderer/src/components/message/MessageItemUser.vue
  • src/renderer/src/pages/ChatPage.vue
  • src/renderer/src/pages/NewThreadPage.vue
  • src/renderer/src/stores/ui/message.ts
  • src/shared/chat.d.ts
  • src/shared/contracts/common.ts
  • src/shared/contracts/routes/sessions.routes.ts
  • src/shared/types/agent-interface.d.ts
  • src/shared/types/core/chat.ts
  • test/renderer/components/ChatInputBox.test.ts
  • test/renderer/components/message/MessageItemUser.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/components/chat/ChatInputBox.vue

Comment thread src/renderer/src/components/message/MessageItemUser.vue
@zhangmo8 zhangmo8 merged commit 9e2c619 into dev Jul 9, 2026
3 checks passed
@zhangmo8 zhangmo8 deleted the fix/chat-input-skill-runtime branch July 9, 2026 08:43
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.

2 participants