feat(ui): 将权限请求改为内联显示在聊天流中

- 添加 PermissionMessagePart 类型
- 创建 PermissionRequestInline 内联组件
- 修改 useChat 将权限请求作为 Part 处理
- 移除模态对话框,不再阻断 IDE 操作
This commit is contained in:
2025-12-17 22:03:00 +08:00
parent 2ff74e446c
commit 00680b8ed3
6 changed files with 533 additions and 30 deletions
+61 -1
View File
@@ -95,10 +95,70 @@ export interface QuestionMessagePart {
answers?: string[];
}
// ============ 权限请求相关 ============
/** 权限类型 */
export type PermissionType = 'bash' | 'file' | 'git' | 'web';
/** 权限请求上下文 */
export interface PermissionRequestContext {
command?: string;
operation?: string;
path?: string;
gitOperation?: string;
query?: string;
patterns?: string[];
externalPaths?: string[];
}
/** Diff 行 */
export interface PermissionDiffLine {
type: 'add' | 'remove' | 'context';
lineNumber: number | null;
content: string;
}
/** Diff hunk */
export interface PermissionDiffHunk {
oldStart: number;
oldCount: number;
newStart: number;
newCount: number;
lines: PermissionDiffLine[];
}
/** Diff 信息 */
export interface PermissionDiffInfo {
isNew: boolean;
additions: number;
deletions: number;
hunks: PermissionDiffHunk[];
}
/**
* 权限请求 Part(内联到聊天流中)
*/
export interface PermissionMessagePart {
type: 'permission';
id: string;
/** 权限请求 ID(用于响应) */
requestId: string;
/** 权限类型 */
permissionType: PermissionType;
/** 请求上下文 */
context: PermissionRequestContext;
/** 文件变更 diff */
diff?: PermissionDiffInfo;
/** 是否已处理 */
handled?: boolean;
/** 处理结果 */
result?: 'allowed' | 'denied';
}
/**
* 消息 Part 联合类型
*/
export type MessagePart = TextMessagePart | ToolMessagePart | ReasoningMessagePart | QuestionMessagePart;
export type MessagePart = TextMessagePart | ToolMessagePart | ReasoningMessagePart | QuestionMessagePart | PermissionMessagePart;
/**
* 消息格式(存储层已经是 2-message 格式,无需 API 层合并)
+20 -2
View File
@@ -23,8 +23,9 @@ import { fadeInUp, smoothTransition } from '../utils/animations';
import { getAgentDisplayName } from '../utils/agent';
import { Markdown } from './Markdown';
import { FileMentionText } from './FileMentionTag';
import type { Message, ToolStatus, ToolMessagePart, QuestionMessagePart, FileDiffInfo } from '../api/types.js';
import type { Message, ToolStatus, ToolMessagePart, QuestionMessagePart, PermissionMessagePart, FileDiffInfo } from '../api/types.js';
import { AskUserQuestion } from './AskUserQuestion.js';
import { PermissionRequestInline } from './PermissionRequestInline.js';
interface ChatMessageProps {
message: Message;
@@ -34,10 +35,14 @@ interface ChatMessageProps {
onAnswerQuestion?: (questionPartId: string, answers: string[]) => void;
/** 查看文件 Diff 的回调 */
onViewDiff?: (diff: FileDiffInfo) => void;
/** 允许权限请求的回调 */
onAllowPermission?: (requestId: string, remember: boolean) => void;
/** 拒绝权限请求的回调 */
onDenyPermission?: (requestId: string, remember: boolean) => void;
}
export const ChatMessage = forwardRef<HTMLDivElement, ChatMessageProps>(
({ message, isStreaming = false, onAnswerQuestion, onViewDiff }, ref) => {
({ message, isStreaming = false, onAnswerQuestion, onViewDiff, onAllowPermission, onDenyPermission }, ref) => {
const isUser = message.role === 'user';
const [copied, setCopied] = useState(false);
@@ -109,6 +114,19 @@ export const ChatMessage = forwardRef<HTMLDivElement, ChatMessageProps>(
{part.text}
</div>
);
case 'permission': {
// 权限请求组件:内联显示,不阻断用户操作
const permissionPart = part as PermissionMessagePart;
return (
<PermissionRequestInline
key={part.id}
part={permissionPart}
onAllow={onAllowPermission || (() => {})}
onDeny={onDenyPermission || (() => {})}
disabled={permissionPart.handled}
/>
);
}
default:
return null;
}
@@ -0,0 +1,348 @@
/**
* PermissionRequestInline Component
*
* 内联权限请求组件,渲染在聊天消息中,不阻断用户操作 IDE
*/
import { useState } from 'react';
import {
Shield,
Terminal,
FileEdit,
GitBranch,
Globe,
X,
Check,
AlertTriangle,
ChevronDown,
ChevronRight,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '../utils/cn';
import type {
PermissionMessagePart,
PermissionType,
PermissionDiffInfo,
} from '../api/types.js';
interface PermissionRequestInlineProps {
part: PermissionMessagePart;
onAllow: (requestId: string, remember: boolean) => void;
onDeny: (requestId: string, remember: boolean) => void;
disabled?: boolean;
}
// 获取权限类型图标
function getPermissionIcon(type: PermissionType) {
switch (type) {
case 'bash':
return <Terminal size={16} className="text-yellow-400" />;
case 'file':
return <FileEdit size={16} className="text-blue-400" />;
case 'git':
return <GitBranch size={16} className="text-purple-400" />;
case 'web':
return <Globe size={16} className="text-green-400" />;
default:
return <Shield size={16} className="text-fg-muted" />;
}
}
// 获取权限类型标题
function getPermissionTitle(type: PermissionType) {
switch (type) {
case 'bash':
return '执行命令';
case 'file':
return '文件操作';
case 'git':
return 'Git 操作';
case 'web':
return '网络访问';
default:
return '权限请求';
}
}
// 获取权限类型的边框和背景颜色
function getPermissionColors(type: PermissionType) {
switch (type) {
case 'bash':
return 'border-yellow-500/30 bg-yellow-500/5';
case 'file':
return 'border-blue-500/30 bg-blue-500/5';
case 'git':
return 'border-purple-500/30 bg-purple-500/5';
case 'web':
return 'border-green-500/30 bg-green-500/5';
default:
return 'border-line bg-surface-subtle';
}
}
// Diff 查看器
function DiffViewer({ diff }: { diff: PermissionDiffInfo }) {
const [expanded, setExpanded] = useState(false);
if (!diff.hunks || diff.hunks.length === 0) {
return null;
}
return (
<div className="mt-3 rounded-lg border border-line overflow-hidden">
<button
onClick={() => setExpanded(!expanded)}
className="w-full flex items-center justify-between px-3 py-2 bg-surface-base/50 hover:bg-surface-muted/50 transition-colors"
>
<span className="text-xs text-fg-muted">
{diff.isNew ? '新文件' : '变更预览'}
</span>
<div className="flex items-center gap-3 text-xs">
<span className="text-green-400">+{diff.additions}</span>
<span className="text-red-400">-{diff.deletions}</span>
{expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
</div>
</button>
<AnimatePresence>
{expanded && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.2 }}
className="overflow-hidden"
>
<div className="max-h-48 overflow-auto border-t border-line">
<pre className="text-xs font-mono">
{diff.hunks.map((hunk, hunkIndex) => (
<div key={hunkIndex}>
<div className="px-3 py-1 bg-blue-500/10 text-blue-400 border-b border-line/50">
@@ -{hunk.oldStart},{hunk.oldCount} +{hunk.newStart},{hunk.newCount} @@
</div>
{hunk.lines.map((line, lineIndex) => {
let className = 'px-3 py-0.5 ';
let prefix = ' ';
if (line.type === 'add') {
className += 'bg-green-500/10 text-green-400';
prefix = '+';
} else if (line.type === 'remove') {
className += 'bg-red-500/10 text-red-400';
prefix = '-';
} else {
className += 'text-fg-muted';
}
return (
<div key={lineIndex} className={className}>
<span className="select-none opacity-50 mr-2">{prefix}</span>
{line.content}
</div>
);
})}
</div>
))}
</pre>
</div>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
export function PermissionRequestInline({
part,
onAllow,
onDeny,
disabled = false,
}: PermissionRequestInlineProps) {
const [remember, setRemember] = useState(false);
const { requestId, permissionType, context, diff, handled, result } = part;
const handleAllow = () => {
if (disabled || handled) return;
onAllow(requestId, remember);
};
const handleDeny = () => {
if (disabled || handled) return;
onDeny(requestId, remember);
};
// 已处理状态
if (handled) {
return (
<div
className={cn(
'rounded-lg border p-4',
result === 'allowed'
? 'border-green-500/30 bg-green-500/5'
: 'border-red-500/30 bg-red-500/5'
)}
>
<div className="flex items-center gap-2">
{result === 'allowed' ? (
<>
<Check size={16} className="text-green-500" />
<span className="text-sm text-green-500"></span>
</>
) : (
<>
<X size={16} className="text-red-500" />
<span className="text-sm text-red-500"></span>
</>
)}
<span className="text-xs text-fg-muted ml-2">
{getPermissionTitle(permissionType)}
</span>
</div>
{/* 显示简要信息 */}
<div className="mt-2 text-xs text-fg-muted font-mono truncate">
{context.command || context.path || context.query}
</div>
</div>
);
}
// 渲染上下文信息
const renderContext = () => {
switch (permissionType) {
case 'bash':
return (
<div className="space-y-2">
<code className="block px-3 py-2 bg-surface-base rounded-lg font-mono text-xs text-yellow-300 break-all max-h-24 overflow-auto">
{context.command}
</code>
{context.externalPaths && context.externalPaths.length > 0 && (
<div className="flex items-start gap-2 p-2 bg-yellow-500/10 rounded-lg">
<AlertTriangle size={14} className="text-yellow-400 mt-0.5 flex-shrink-0" />
<div className="text-xs text-yellow-300">
<div className="font-medium">:</div>
<div className="mt-1 text-yellow-400/80 font-mono">
{context.externalPaths.map((p, i) => (
<div key={i}>{p}</div>
))}
</div>
</div>
</div>
)}
</div>
);
case 'file':
return (
<div className="space-y-2">
<div className="flex items-center gap-2 text-xs">
<span className="text-fg-muted">:</span>
<span
className={cn(
'px-2 py-0.5 rounded text-xs font-medium',
context.operation === 'delete'
? 'bg-red-500/20 text-red-400'
: context.operation === 'write'
? 'bg-yellow-500/20 text-yellow-400'
: 'bg-blue-500/20 text-blue-400'
)}
>
{context.operation?.toUpperCase()}
</span>
</div>
<code className="block px-3 py-2 bg-surface-base rounded-lg font-mono text-xs text-blue-300 break-all">
{context.path}
</code>
{diff && <DiffViewer diff={diff} />}
</div>
);
case 'git':
return (
<div className="space-y-2">
<div className="flex items-center gap-2 text-xs">
<span className="text-fg-muted">Git :</span>
<span className="px-2 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400">
{context.gitOperation?.toUpperCase()}
</span>
</div>
{context.command && (
<code className="block px-3 py-2 bg-surface-base rounded-lg font-mono text-xs text-purple-300 break-all">
{context.command}
</code>
)}
</div>
);
case 'web':
return (
<code className="block px-3 py-2 bg-surface-base rounded-lg font-mono text-xs text-green-300 break-all">
{context.query || context.command}
</code>
);
default:
return (
<pre className="bg-surface-base p-3 rounded-lg overflow-auto text-xs">
{JSON.stringify(context, null, 2)}
</pre>
);
}
};
return (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className={cn('rounded-lg border p-4', getPermissionColors(permissionType))}
>
{/* 标题 */}
<div className="flex items-center gap-2 mb-3">
{getPermissionIcon(permissionType)}
<span className="text-sm font-medium">{getPermissionTitle(permissionType)}</span>
<span className="text-xs text-fg-subtle">AI </span>
</div>
{/* 内容 */}
<div className="mb-4">{renderContext()}</div>
{/* Remember 选项 */}
<label className="flex items-center gap-2 text-xs text-fg-muted cursor-pointer mb-3">
<input
type="checkbox"
checked={remember}
onChange={(e) => setRemember(e.target.checked)}
disabled={disabled}
className="w-3.5 h-3.5 rounded border-line-muted bg-surface-base text-primary-500 focus:ring-primary-500"
/>
</label>
{/* 操作按钮 */}
<div className="flex items-center gap-2">
<button
onClick={handleDeny}
disabled={disabled}
className={cn(
'flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors',
'border border-red-400/50 text-red-400 hover:border-red-400 hover:bg-red-400/10',
disabled && 'opacity-50 cursor-not-allowed'
)}
>
<X size={14} />
</button>
<button
onClick={handleAllow}
disabled={disabled}
className={cn(
'flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors',
'bg-primary-600 text-white hover:bg-primary-700',
disabled && 'opacity-50 cursor-not-allowed'
)}
>
<Check size={14} />
</button>
</div>
</motion.div>
);
}
+85 -13
View File
@@ -6,7 +6,6 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { createWebSocket, getMessages, type Message } from '../api/client.js';
import type { PermissionRequest } from '../components/PermissionDialog.js';
import type {
ConfigErrorPayload,
ToolStartPayload,
@@ -15,6 +14,7 @@ import type {
MessagePart,
ToolMessagePart,
QuestionMessagePart,
PermissionMessagePart,
Question,
AgentModeType,
SubagentStartPayload,
@@ -25,8 +25,19 @@ import type {
SubagentState,
SubagentToolInfo,
FileDiffInfo,
PermissionType,
PermissionRequestContext,
PermissionDiffInfo,
} from '../api/types.js';
/** 权限请求事件 payload(服务端发送格式) */
interface PermissionRequestPayload {
requestId: string;
permissionType: PermissionType;
context: PermissionRequestContext;
diff?: PermissionDiffInfo;
}
interface UseChatOptions {
sessionId: string;
onError?: (error: Error) => void;
@@ -46,7 +57,6 @@ interface ChatState {
isLoading: boolean;
/** 流式消息对象,复用 Message 结构 */
streamingMessage: Message | null;
permissionRequest: PermissionRequest | null;
/** Agent 模式 (会话级别) */
agentMode: AgentModeType;
/** 是否自动授权文件写入/编辑 (会话级别) */
@@ -63,7 +73,6 @@ export function useChat({ sessionId, onError, onSessionNotFound, onSessionUpdate
isConnected: false,
isLoading: false,
streamingMessage: null,
permissionRequest: null,
agentMode: 'build',
autoApprove: false,
currentAgent: 'build',
@@ -469,15 +478,46 @@ export function useChat({ sessionId, onError, onSessionNotFound, onSessionUpdate
}
break;
case 'permission_request':
// 权限请求
if (message.payload) {
setState((prev) => ({
...prev,
permissionRequest: message.payload as PermissionRequest,
}));
case 'permission_request': {
// 权限请求 - 作为 Part 添加到流式消息中
const payload = message.payload as PermissionRequestPayload;
if (payload) {
const permissionPart: PermissionMessagePart = {
type: 'permission',
id: `permission-${payload.requestId}`,
requestId: payload.requestId,
permissionType: payload.permissionType,
context: payload.context,
diff: payload.diff,
handled: false,
};
setState((prev) => {
const streaming = prev.streamingMessage;
if (!streaming) {
// 如果没有流式消息,创建一个新的
return {
...prev,
streamingMessage: {
id: `streaming-${Date.now()}`,
role: 'assistant',
timestamp: new Date().toISOString(),
parts: [permissionPart],
},
};
}
// 添加到现有流式消息的 parts 中
return {
...prev,
streamingMessage: {
...streaming,
parts: [...streaming.parts, permissionPart],
},
};
});
}
break;
}
// ============ 子 Agent 事件处理 ============
@@ -717,8 +757,41 @@ export function useChat({ sessionId, onError, onSessionNotFound, onSessionUpdate
})
);
// 清除权限请求状态
setState((prev) => ({ ...prev, permissionRequest: null }));
// 更新权限请求 Part 的状态(标记为已处理)
setState((prev) => {
const updatePermissionPart = (parts: MessagePart[]): MessagePart[] => {
return parts.map((part) => {
if (part.type === 'permission' && part.requestId === requestId) {
return {
...part,
handled: true,
result: allow ? 'allowed' : 'denied',
} as PermissionMessagePart;
}
return part;
});
};
// 更新流式消息中的 Part
const updatedStreaming = prev.streamingMessage
? {
...prev.streamingMessage,
parts: updatePermissionPart(prev.streamingMessage.parts),
}
: null;
// 同时更新历史消息中的 Part(以防消息已完成)
const updatedMessages = prev.messages.map((msg) => ({
...msg,
parts: updatePermissionPart(msg.parts),
}));
return {
...prev,
streamingMessage: updatedStreaming,
messages: updatedMessages,
};
});
},
[sessionId]
);
@@ -855,7 +928,6 @@ export function useChat({ sessionId, onError, onSessionNotFound, onSessionUpdate
isConnected: false,
isLoading: false,
streamingMessage: null,
permissionRequest: null,
agentMode: 'build',
autoApprove: false,
currentAgent: 'build',
+3 -1
View File
@@ -239,7 +239,9 @@ export { CheckpointPanel } from './components/CheckpointPanel.js';
export { CheckpointDiffViewer } from './components/CheckpointDiffViewer.js';
export { RestoreDialog } from './components/RestoreDialog.js';
export { PermissionDialog } from './components/PermissionDialog.js';
export type { PermissionRequest, PermissionType, PermissionRequestContext, DiffInfo as PermissionDiffInfo } from './components/PermissionDialog.js';
export type { PermissionRequest, PermissionRequestContext, DiffInfo as PermissionDiffInfo } from './components/PermissionDialog.js';
export { PermissionRequestInline } from './components/PermissionRequestInline.js';
export type { PermissionType, PermissionMessagePart, PermissionDiffInfo as PermissionDiffInfoType, PermissionDiffHunk, PermissionDiffLine } from './api/types.js';
export { Sidebar } from './components/Sidebar.js';
export { FileBrowser } from './components/FileBrowser.js';
export { ConfigPanel } from './components/ConfigPanel.js';
+16 -13
View File
@@ -11,7 +11,6 @@ import {
ChatMessage,
TypingIndicator,
ChatInput,
PermissionDialog,
ContextUsage,
SubagentProgress,
DiagnosticsIndicator,
@@ -78,7 +77,6 @@ export function ChatPage({
streamingMessage,
sendMessage,
cancelProcessing,
permissionRequest,
allowPermission,
denyPermission,
agentMode,
@@ -216,13 +214,27 @@ export function ChatPage({
<AnimatePresence mode="popLayout">
{messages.map((message) => (
<ChatMessage key={message.id} message={message} onAnswerQuestion={answerQuestion} onViewDiff={onViewDiff ?? onFileDiff} />
<ChatMessage
key={message.id}
message={message}
onAnswerQuestion={answerQuestion}
onViewDiff={onViewDiff ?? onFileDiff}
onAllowPermission={allowPermission}
onDenyPermission={denyPermission}
/>
))}
</AnimatePresence>
{/* 流式消息 - 复用 ChatMessage 组件 */}
{streamingMessage && (
<ChatMessage message={streamingMessage} isStreaming onAnswerQuestion={answerQuestion} onViewDiff={onViewDiff ?? onFileDiff} />
<ChatMessage
message={streamingMessage}
isStreaming
onAnswerQuestion={answerQuestion}
onViewDiff={onViewDiff ?? onFileDiff}
onAllowPermission={allowPermission}
onDenyPermission={denyPermission}
/>
)}
{/* 子 Agent 进度显示 */}
@@ -252,15 +264,6 @@ export function ChatPage({
onAutoAttachActiveFileToggle={onAutoAttachActiveFileToggle}
/>
{/* Permission Dialog */}
{permissionRequest && (
<PermissionDialog
request={permissionRequest}
onAllow={(requestId, remember) => allowPermission(requestId, remember)}
onDeny={(requestId, remember) => denyPermission(requestId, remember)}
responsive={responsive}
/>
)}
</div>
);
}