feat(chat): group conversations and consolidate header actions

This commit is contained in:
Sycun 2026-11-20 15:06:33 +08:00
parent ca5057f8d9
commit cb1507df6c
70 changed files with 1002 additions and 794 deletions

View File

@ -12,7 +12,7 @@
## 查看
首页 Token 卡片和设置页 Token 用量面板继续支持周期、模型、项目和明细查询。接口为 `GET /api/usage/tokens` 与 `GET /api/conversations/:id/token-usage`。
从首页 Token 卡片进入「系统设置 → Token 用量」,可按周期、项目查看汇总、模型统计和最近记录。在该页搜索并选择会话即可查看单会话用量。接口为 `GET /api/usage/tokens` 与 `GET /api/conversations/:id/token-usage`。
已有模型用量表保持兼容。旧时间线用量事件可作为历史记录补齐;新记录仅由原生 Pi 事件生成。原生流式消息只传输增量,完整消息在结束时提交,避免重复累计与逐块重复发送整份内容。

View File

@ -17,6 +17,39 @@ import (
// ProjectFilterUnbound 列表 API 中 project_id=__none__ 表示仅未绑定项目的对话。
const ProjectFilterUnbound = "__none__"
type ConversationProjectGroup struct {
ProjectID string `json:"projectId"`
Total int `json:"total"`
}
// ListConversationProjectGroups counts matching, accessible conversations by project.
func (db *DB) ListConversationProjectGroups(search, userID, scope string) ([]ConversationProjectGroup, error) {
where := " WHERE 1 = 1"
var args []interface{}
if search != "" {
where += ` AND (c.title LIKE ?
OR EXISTS (SELECT 1 FROM messages m WHERE m.conversation_id = c.id AND m.content LIKE ?))`
pattern := "%" + search + "%"
args = append(args, pattern, pattern)
}
where, args = appendConversationAccessFilter(where, args, userID, scope, "c")
rows, err := db.Query(`SELECT TRIM(COALESCE(c.project_id, '')), COUNT(*) FROM conversations c`+where+`
GROUP BY 1 ORDER BY MAX(c.updated_at) DESC, 1`, args...)
if err != nil {
return nil, err
}
defer rows.Close()
groups := []ConversationProjectGroup{}
for rows.Next() {
var group ConversationProjectGroup
if err := rows.Scan(&group.ProjectID, &group.Total); err != nil {
return nil, err
}
groups = append(groups, group)
}
return groups, rows.Err()
}
// Conversation 对话
type Conversation struct {
ID string `json:"id"`

View File

@ -207,6 +207,29 @@ func TestRBACProjectAndConversationListAccess(t *testing.T) {
if len(convs) != 1 || convs[0].ID != c1.ID {
t.Fatalf("conversations = %#v, want only %s", convs, c1.ID)
}
unbound, err := db.CreateConversation("visible workspace", ConversationCreateMeta{})
if err != nil {
t.Fatal(err)
}
if err := db.SetResourceOwner("conversation", unbound.ID, "u1"); err != nil {
t.Fatal(err)
}
groups, err := db.ListConversationProjectGroups("visible", "u1", RBACScopeOwn)
if err != nil || len(groups) != 2 {
t.Fatalf("groups = %#v, err = %v, want one project and the default workspace", groups, err)
}
totals := make(map[string]int)
for _, group := range groups {
totals[group.ProjectID] = group.Total
}
if totals[p1.ID] != 1 || totals[""] != 1 {
t.Fatalf("unexpected group totals: %#v", totals)
}
groups, err = db.ListConversationProjectGroups("conv", "u1", RBACScopeOwn)
if err != nil || len(groups) != 1 || groups[0].ProjectID != p1.ID || groups[0].Total != 1 {
t.Fatalf("groups filtered by search = %#v, err = %v", groups, err)
}
}
func TestRBACVulnerabilityAccessInheritsProject(t *testing.T) {

View File

@ -162,14 +162,19 @@ func (h *ConversationHandler) ListConversations(c *gin.Context) {
sortBy := strings.TrimSpace(c.Query("sort_by"))
session, _ := security.CurrentSession(c)
grouped := c.Query("group_by_project") == "1"
var conversations []*database.Conversation
var groups []database.ConversationProjectGroup
var total int
var err error
conversations, err = h.db.ListConversationsForAccess(limit, offset, search, sortBy, projectID, session.UserID, session.Scope)
if err == nil {
total, err = h.db.CountConversationsForAccess(search, projectID, session.UserID, session.Scope)
}
if err == nil && grouped {
groups, err = h.db.ListConversationProjectGroups(search, session.UserID, session.Scope)
}
if err != nil {
h.logger.Error("获取对话列表失败", zap.Error(err))
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
@ -178,12 +183,16 @@ func (h *ConversationHandler) ListConversations(c *gin.Context) {
if conversations == nil {
conversations = []*database.Conversation{}
}
c.JSON(http.StatusOK, gin.H{
response := gin.H{
"conversations": conversations,
"total": total,
"limit": limit,
"offset": offset,
})
}
if grouped {
response["projectGroups"] = groups
}
c.JSON(http.StatusOK, response)
}
// UpdateConversationPinnedRequest 更新对话置顶状态请求

View File

@ -23,6 +23,7 @@ import (
"cyberstrike-ai/internal/database"
"cyberstrike-ai/internal/mcp"
"cyberstrike-ai/internal/mcp/builtin"
"cyberstrike-ai/internal/reasoning"
"go.uber.org/zap"
)
@ -178,13 +179,16 @@ func piReply(w http.ResponseWriter, tool, id string, args map[string]any, text s
func TestPiDeepSeekOutputBudgetAndUsage(t *testing.T) {
for _, tc := range []struct {
profile, mode, thinking, effort string
reasoning int
name, profile, mode, thinking, effort string
intent *reasoning.ClientIntent
reasoning int
}{
{profile: "deepseek", mode: "auto", thinking: "enabled", effort: "low", reasoning: 6},
{profile: "deepseek_compat", mode: "off", thinking: "disabled"},
{name: "channel default", profile: "deepseek", mode: "auto", thinking: "enabled", effort: "low", reasoning: 6},
{name: "chat medium override", profile: "deepseek", mode: "auto", thinking: "enabled", effort: "medium",
intent: &reasoning.ClientIntent{Mode: "on", Effort: "medium"}, reasoning: 6},
{name: "thinking disabled", profile: "deepseek_compat", mode: "off", thinking: "disabled"},
} {
t.Run(tc.profile, func(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
cfg := piTestConfig(t)
cfg.OpenAI.Model = "deepseek-flash"
cfg.OpenAI.Reasoning = config.OpenAIReasoningConfig{Profile: tc.profile, Mode: tc.mode, Effort: "low"}
@ -237,7 +241,7 @@ func TestPiDeepSeekOutputBudgetAndUsage(t *testing.T) {
if kind == "agent_usage_summary" {
usage = data.(map[string]any)
}
}, nil, "")
}, tc.intent, "")
if err != nil || result == nil || result.Response != "ok" || result.RuntimeStatus != "completed" {
t.Fatalf("result=%+v err=%v", result, err)
}

View File

@ -1,6 +1,5 @@
/** 对话页头:标题、会话标签、用量/计划/刷新入口。 */
import { Button, Space, Tag, Typography } from '@douyinfe/semi-ui';
import { IconBolt, IconHistory, IconMenu, IconRefresh, IconSetting } from '@douyinfe/semi-icons';
import { IconMenu, IconRefresh } from '@douyinfe/semi-icons';
import { useT } from '../../lib/i18n';
const { Text, Title } = Typography;
@ -13,8 +12,7 @@ const MODE_TAG = {
};
export default function ChatHeader({
conversation, mode, hitlCount, conversationId, plan, narrow,
onToggleSidebar, onOpenUsage, onOpenPlan, onOpenSettings, onRefresh
conversation, mode, hitlCount, conversationId, narrow, onToggleSidebar, onRefresh
}) {
const t = useT();
const modeTag = MODE_TAG[mode] || MODE_TAG.single;
@ -28,9 +26,6 @@ export default function ChatHeader({
<Space spacing={6} wrap className="chat-header-tags">
{conversation?.pinned && <Tag size="small" color="amber">{t('chat.pinned', null, '已置顶')}</Tag>}
<Tag size="small" color={modeTag.color}>{t(modeTag.key, null, modeTag.label)}</Tag>
{conversation?.projectId && (
<Tag size="small" type="ghost">项目 {String(conversation.projectId).slice(0, 8)}</Tag>
)}
{hitlCount > 0 && (
<Tag size="small" color="orange">
{t('chat.pendingApprovals', { count: hitlCount }, `待审批 ${hitlCount}`)}
@ -50,20 +45,17 @@ export default function ChatHeader({
{t('chat.conversations', null, '会话')}
</Button>
)}
<Button theme="borderless" type="tertiary" icon={<IconHistory />} disabled={!conversationId} onClick={onOpenUsage}>
{t('chat.tokenUsage', null, 'Token 用量')}
</Button>
<Button theme="borderless" type="tertiary" icon={<IconBolt />} disabled={!conversationId} onClick={onOpenPlan}>
{t('chat.planTasks', null, '计划任务')}{plan?.total ? ` (${plan.completed}/${plan.total})` : ''}
</Button>
{onOpenSettings && (
<Button theme="borderless" type="tertiary" icon={<IconSetting aria-hidden="true" />} onClick={onOpenSettings}>
{t('chat.sessionSettingsTitle', null, '会话设置')}
{conversationId && (
<Button
theme="borderless"
type="tertiary"
icon={<IconRefresh aria-hidden="true" />}
title={t('chat.refreshConversationHint', null, '重新读取会话列表、消息、待审批项和执行计划')}
onClick={onRefresh}
>
{t('chat.refreshConversation', null, '刷新对话')}
</Button>
)}
<Button theme="borderless" type="tertiary" icon={<IconRefresh />} onClick={onRefresh}>
{t('common.refresh', null, '刷新')}
</Button>
</Space>
</header>
);

View File

@ -83,7 +83,7 @@ function SettingSelect({ label, ...props }) {
);
}
export function ModelSettings({ model, busy, canReadConfig, compact = false }) {
export function ModelSettings({ model, busy, canReadConfig }) {
const t = useT();
const channelLabelId = useId();
const pickerRef = useRef(null);
@ -95,139 +95,113 @@ export function ModelSettings({ model, busy, canReadConfig, compact = false }) {
...modelChannelOptions(model.channels)
];
const reasoningLabels = Object.fromEntries(REASONING_MODES.map(mode => [mode, reasoningSummary(t, mode, '')]));
if (compact) {
const levels = ['', ...REASONING_EFFORTS];
const marks = Object.fromEntries(levels.map((effort, index) => [
index, reasoningSummary(t, effort ? 'on' : 'default', effort)
]));
const resetReasoning = () => {
model.setMode('default');
model.setEffort('');
};
return (
<div className={`chat-reasoning-picker${model.mode !== 'off' && model.effort === 'max' ? ' is-max' : ''}${busy ? ' is-disabled' : ''}`} ref={pickerRef}>
<div className="chat-reasoning-heading">
<Dropdown
trigger="click"
position="bottomLeft"
className="chat-reasoning-mode-menu"
getPopupContainer={() => pickerRef.current}
showTick
menu={REASONING_MODES.map(mode => ({
node: 'item',
name: reasoningLabels[mode],
active: model.mode === mode,
disabled: busy,
onClick: () => mode === 'default' ? resetReasoning() : model.setMode(mode)
}))}
>
<Button
theme="borderless"
type="tertiary"
icon={<IconBolt />}
className="chat-reasoning-mode"
aria-label={t('chat.reasoningModeLabel', null, '模型推理')}
title={`${t('chat.reasoningModeLabel', null, '模型推理')} · ${reasoningLabels[model.mode]}`}
disabled={busy}
/>
</Dropdown>
<Text strong className="chat-reasoning-value" role="status">
{reasoningSummary(t, model.mode, model.effort)}
</Text>
const reasoningDisabled = busy || model.overrideBlocked;
const deepSeekMapsToHigh = model.officialDeepSeek && model.mode !== 'off' && ['medium', 'xhigh'].includes(model.effort);
const levels = ['', ...REASONING_EFFORTS];
const marks = Object.fromEntries(levels.map((effort, index) => [
index, reasoningSummary(t, effort ? 'on' : 'default', effort)
]));
const resetReasoning = () => {
model.setMode('default');
model.setEffort('');
};
return (
<div className={`chat-reasoning-picker${!model.overrideBlocked && model.mode !== 'off' && model.effort === 'max' ? ' is-max' : ''}${reasoningDisabled ? ' is-disabled' : ''}`} ref={pickerRef}>
<div className="chat-reasoning-heading">
<Dropdown
trigger="click"
position="bottomLeft"
className="chat-reasoning-mode-menu"
getPopupContainer={() => pickerRef.current}
showTick
menu={REASONING_MODES.map(mode => ({
node: 'item',
name: reasoningLabels[mode],
active: model.mode === mode,
disabled: reasoningDisabled,
onClick: () => mode === 'default' ? resetReasoning() : model.setMode(mode)
}))}
>
<Button
theme="borderless"
type="tertiary"
icon={<IconUndo />}
aria-label={t('chat.reasoningReset', null, '重置推理设置')}
title={t('chat.reasoningReset', null, '重置推理设置')}
disabled={busy}
onClick={resetReasoning}
icon={<IconBolt />}
className="chat-reasoning-mode"
aria-label={t('chat.reasoningModeLabel', null, '模型推理')}
title={`${t('chat.reasoningModeLabel', null, '模型推理')} · ${reasoningLabels[model.overrideBlocked ? 'default' : model.mode]}`}
disabled={reasoningDisabled}
/>
</div>
{canReadConfig ? (
<>
<span id={channelLabelId} hidden>{t('chat.aiChannelLabel', null, 'AI 通道')}</span>
<Select
className="chat-reasoning-channel"
aria-labelledby={channelLabelId}
value={model.channel}
optionList={channelOptions}
renderSelectedItem={option => option.value === ''
? defaultName || t('chat.aiChannelDefaultShort', null, '默认通道')
: selectedModelChannelName(option)}
arrowIcon={<IconChevronRight size="small" />}
borderless
onSelect={model.setChannel}
dropdownMatchSelectWidth={false}
dropdownStyle={{ maxWidth: 'calc(100vw - 32px)' }}
loading={model.config.loading}
disabled={busy || model.config.loading || Boolean(model.config.error)}
/>
<ErrorBanner error={model.config.error} onRetry={() => model.config.reload()} />
</>
) : <Text type="tertiary" className="chat-reasoning-channel-label">{defaultLabel}</Text>}
<Slider
className="chat-reasoning-slider"
aria-label={t('chat.reasoningEffortLabel', null, '推理强度')}
min={0}
max={levels.length - 1}
step={1}
marks={marks}
showMarkLabel={false}
tipFormatter={value => marks[value]}
getAriaValueText={value => model.mode === 'off' ? reasoningLabels.off : marks[value]}
value={levels.indexOf(model.effort)}
disabled={busy || model.mode === 'off'}
onChange={value => {
model.setEffort(levels[value]);
model.setMode(value === 0 ? 'default' : model.mode === 'auto' ? 'auto' : 'on');
}}
</Dropdown>
<Text strong className="chat-reasoning-value" role="status">
{model.overrideBlocked ? reasoningLabels.default : reasoningSummary(t, model.mode, model.effort)}
</Text>
<Button
theme="borderless"
type="tertiary"
icon={<IconUndo />}
aria-label={t('chat.reasoningReset', null, '重置推理设置')}
title={t('chat.reasoningReset', null, '重置推理设置')}
disabled={reasoningDisabled}
onClick={resetReasoning}
/>
</div>
);
}
return (
<>
{canReadConfig && (
{canReadConfig ? (
<>
<SettingSelect
label={t('chat.aiChannelLabel', null, 'AI 通道')}
<span id={channelLabelId} hidden>{t('chat.aiChannelLabel', null, 'AI 通道')}</span>
<Select
className="chat-reasoning-channel"
aria-labelledby={channelLabelId}
value={model.channel}
optionList={channelOptions}
renderSelectedItem={selectedModelChannelName}
renderSelectedItem={option => option.value === ''
? defaultName || t('chat.aiChannelDefaultShort', null, '默认通道')
: selectedModelChannelName(option)}
arrowIcon={<IconChevronRight size="small" />}
borderless
onSelect={model.setChannel}
dropdownMatchSelectWidth={false}
dropdownStyle={{ maxWidth: 'calc(100vw - 32px)' }}
loading={model.config.loading}
disabled={busy || model.config.loading || Boolean(model.config.error)}
/>
<ErrorBanner error={model.config.error} onRetry={() => model.config.reload()} />
</>
) : <Text type="tertiary" className="chat-reasoning-channel-label">{defaultLabel}</Text>}
<Slider
className="chat-reasoning-slider"
aria-label={t('chat.reasoningEffortLabel', null, '推理强度')}
min={0}
max={levels.length - 1}
step={1}
marks={marks}
showMarkLabel={false}
tipFormatter={value => marks[value]}
getAriaValueText={value => model.mode === 'off' && !model.overrideBlocked ? reasoningLabels.off : marks[value]}
value={model.overrideBlocked ? 0 : levels.indexOf(model.effort)}
disabled={reasoningDisabled || model.mode === 'off'}
onChange={value => {
model.setEffort(levels[value]);
model.setMode(value === 0 ? 'default' : model.mode === 'auto' ? 'auto' : 'on');
}}
/>
{model.overrideBlocked ? (
<Text type="tertiary" size="small" className="chat-reasoning-hint">
{t('chat.reasoningOverrideBlocked', null, '此通道使用系统设置中的推理强度。')}
</Text>
) : deepSeekMapsToHigh && (
<Text type="tertiary" size="small" className="chat-reasoning-hint">
{t('chat.deepSeekEffortHint', { effort: marks[levels.indexOf(model.effort)] }, 'DeepSeek 会按「高」执行此档。')}
</Text>
)}
<SettingSelect
label={t('chat.reasoningModeLabel', null, '模型推理')}
value={model.mode}
optionList={REASONING_MODES.map(value => ({ value, label: reasoningLabels[value] }))}
onSelect={model.setMode}
disabled={busy}
/>
<SettingSelect
label={t('chat.reasoningEffortLabel', null, '推理强度')}
value={model.mode === 'off' ? '' : model.effort}
optionList={[
{ value: '', label: t('chat.reasoningEffortUnset', null, '不指定') },
...REASONING_EFFORTS.map(value => ({ value, label: value }))
]}
onSelect={model.setEffort}
disabled={busy || model.mode === 'off'}
/>
</>
</div>
);
}
export default function ChatSettings({
onClose, narrow, busy, canReadConfig, canReadHitl, canEnableHitl,
model, conversationId, draftHitl, onDraftHitlChange, section = 'all'
onClose, narrow, canEnableHitl, conversationId, draftHitl, onDraftHitlChange
}) {
const t = useT();
const title = t('chat.hitlTitle', null, '人机协同');
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
const [form, setForm] = useState(null);
@ -240,8 +214,7 @@ export default function ChatSettings({
const approvals = useResource(
() => api.get(conversationId ? `/hitl/config/${encodeURIComponent(conversationId)}` : '/hitl/default-config'),
[conversationId, canReadHitl],
{ skip: !canReadHitl }
[conversationId]
);
useEffect(() => {
@ -316,7 +289,8 @@ export default function ChatSettings({
return (
<SideSheet
visible
title={section === 'hitl' ? t('chat.hitlTitle', null, '人机协同') : t('chat.sessionSettingsTitle', null, '会话设置')}
title={title}
aria-label={title}
width={narrow ? '100%' : 420}
closable={!saving}
maskClosable={!saving}
@ -324,77 +298,73 @@ export default function ChatSettings({
onCancel={onClose}
>
<div className="chat-settings-fields">
{section !== 'hitl' && <ModelSettings model={model} busy={busy} canReadConfig={canReadConfig} />}
{canReadHitl && (
<section className="chat-setting-field chat-setting-hitl">
{section !== 'hitl' && <Text strong>{t('chat.hitlTitle', null, '人机协同')}</Text>}
<Text type="tertiary" size="small">
{t('chat.sessionSettingsHint', null, '人机协同设置只影响后续消息。')}
<section className="chat-setting-field chat-setting-hitl">
<Text type="tertiary" size="small">
{t('chat.sessionSettingsHint', null, '人机协同设置只影响后续消息。')}
</Text>
{(saving || saved) && (
<Text type="tertiary" size="small" role="status">
{saving
? t('chat.systemModelSaving', null, '正在保存…')
: t('chat.hitlApplyOkSync', null, '人机协同配置已保存并同步到服务器。')}
</Text>
{(saving || saved) && (
<Text type="tertiary" size="small" role="status">
{saving
? t('chat.systemModelSaving', null, '正在保存…')
: t('chat.hitlApplyOkSync', null, '人机协同配置已保存并同步到服务器。')}
</Text>
)}
<ErrorBanner error={approvals.error} onRetry={() => approvals.reload()} />
{approvals.loading && <Spin />}
{form && approvals.data && !approvals.error && (
<>
<SettingSelect
label={t('chat.hitlModeLabel', null, '模式')}
value={form.mode}
optionList={HITL_MODES.map(value => ({ value, label: modeLabels[value] }))}
onSelect={value => updateConfig({ mode: value })}
)}
<ErrorBanner error={approvals.error} onRetry={() => approvals.reload()} />
{approvals.loading && <Spin />}
{form && approvals.data && !approvals.error && (
<>
<SettingSelect
label={t('chat.hitlModeLabel', null, '模式')}
value={form.mode}
optionList={HITL_MODES.map(value => ({ value, label: modeLabels[value] }))}
onSelect={value => updateConfig({ mode: value })}
disabled={hitlDisabled}
/>
<div className="chat-setting-field">
<Text id={reviewerId} strong>{t('chat.hitlReviewerLabel', null, '审批方')}</Text>
<RadioGroup
aria-labelledby={reviewerId}
type="button"
className="chat-setting-reviewer"
value={form.reviewer}
options={[
{ value: 'human', label: t('chat.hitlReviewerHuman', null, '人工审批') },
{ value: 'audit_agent', label: t('chat.hitlReviewerAgent', null, '审计 Agent') }
]}
onChange={event => updateConfig({ reviewer: event.target.value })}
disabled={hitlDisabled}
/>
<div className="chat-setting-field">
<Text id={reviewerId} strong>{t('chat.hitlReviewerLabel', null, '审批方')}</Text>
<RadioGroup
aria-labelledby={reviewerId}
type="button"
className="chat-setting-reviewer"
value={form.reviewer}
options={[
{ value: 'human', label: t('chat.hitlReviewerHuman', null, '人工审批') },
{ value: 'audit_agent', label: t('chat.hitlReviewerAgent', null, '审计 Agent') }
]}
onChange={event => updateConfig({ reviewer: event.target.value })}
disabled={hitlDisabled}
/>
<Text type="tertiary" size="small">
{t('chat.hitlReviewerHint', null, '可在人工与审计 Agent 之间随时切换;规则与白名单不变。人机协同为「关闭」时也可预先选择。')}
</Text>
</div>
<SettingSelect
label={t('chat.hitlTimeoutLabel', null, '审批等待时限')}
value={form.timeoutSeconds}
optionList={timeoutOptions}
onSelect={value => updateConfig({ timeoutSeconds: Number(value) })}
<Text type="tertiary" size="small">
{t('chat.hitlReviewerHint', null, '可在人工与审计 Agent 之间随时切换;规则与白名单不变。人机协同为「关闭」时也可预先选择。')}
</Text>
</div>
<SettingSelect
label={t('chat.hitlTimeoutLabel', null, '审批等待时限')}
value={form.timeoutSeconds}
optionList={timeoutOptions}
onSelect={value => updateConfig({ timeoutSeconds: Number(value) })}
disabled={hitlDisabled}
/>
<div className="chat-setting-field">
<Text id={toolsId} strong>
{t('chat.hitlWhitelistTools', null, '白名单工具(免审批,逗号分隔)')}
</Text>
<TextArea
aria-labelledby={toolsId}
value={form.sensitiveTools}
placeholder={t('chat.hitlWhitelistPlaceholder', null, '例:read_file, grep 或每行一个工具名(与 config 全局白名单合并)')}
rows={5}
disabled={hitlDisabled}
onChange={updateTools}
onBlur={saveTools}
/>
<div className="chat-setting-field">
<Text id={toolsId} strong>
{t('chat.hitlWhitelistTools', null, '白名单工具(免审批,逗号分隔)')}
</Text>
<TextArea
aria-labelledby={toolsId}
value={form.sensitiveTools}
placeholder={t('chat.hitlWhitelistPlaceholder', null, '例:read_file, grep 或每行一个工具名(与 config 全局白名单合并)')}
rows={5}
disabled={hitlDisabled}
onChange={updateTools}
onBlur={saveTools}
/>
<Text type="tertiary" size="small">
{t('chat.hitlWhitelistHint', null, '白名单内工具免审批;每行一个或逗号分隔,与 config 全局白名单合并。')}
</Text>
</div>
</>
)}
</section>
)}
<Text type="tertiary" size="small">
{t('chat.hitlWhitelistHint', null, '白名单内工具免审批;每行一个或逗号分隔,与 config 全局白名单合并。')}
</Text>
</div>
</>
)}
</section>
</div>
</SideSheet>
);

View File

@ -73,11 +73,14 @@ export default function Composer({
)
})), [t]);
const projectOptions = [
{ value: '', label: t('chat.noProject', null, '不绑定项目') },
...(Array.isArray(projects) ? projects : []).map(project => ({ value: project.id, label: project.name || project.id }))
{ value: '', label: t('chat.defaultWorkspace', null, '默认工作区') },
...(Array.isArray(projects) ? projects : []).map(project => ({
value: project.id,
label: project.name || t('chat.boundProject', null, '已绑定项目')
}))
];
if (projectId && !projectOptions.some(option => option.value === projectId)) {
projectOptions.push({ value: projectId, label: projectId });
projectOptions.push({ value: projectId, label: t('chat.boundProject', null, '已绑定项目') });
}
if (onCreateProject) {
projectOptions.push({ value: CREATE_PROJECT, label: `+ ${t('projects.newProject', null, '新建项目')}` });
@ -89,7 +92,9 @@ export default function Composer({
const channelName = channelId
? modelChannelName(channelId, model.config.data?.channels?.[channelId])
: t('chat.aiChannelDefaultShort', null, '默认通道');
const reasoningLabel = reasoningSummary(t, model.mode, model.effort);
const reasoningLabel = model.overrideBlocked
? reasoningSummary(t, 'default', '')
: reasoningSummary(t, model.mode, model.effort);
const handleKeyDown = event => {
if (event.key !== 'Enter' || event.shiftKey) return;
@ -120,14 +125,15 @@ export default function Composer({
optionList={modeOptions}
renderSelectedItem={option => option.title}
onChange={onModeChange}
prefix={<IconDesktop />}
prefix={<IconDesktop aria-hidden="true" />}
className="chat-context-select chat-composer-mode"
dropdownClassName="chat-mode-dropdown"
size="small"
position="topLeft"
aria-labelledby={modeLabelId}
disabled={busy || blocked}
/>
<span id={projectLabelId} hidden>{t('chat.filterByProject', null, '选择项目')}</span>
<span id={projectLabelId} hidden>{t('chat.chooseWorkspace', null, '选择会话工作区')}</span>
<Select
value={projectId}
optionList={projectOptions}
@ -135,8 +141,13 @@ export default function Composer({
if (value === CREATE_PROJECT) onCreateProject?.();
else onProjectChange(value);
}}
prefix={<IconFolder />}
prefix={<IconFolder aria-hidden="true" />}
className="chat-context-select chat-composer-project"
dropdownClassName="chat-project-dropdown"
dropdownMatchSelectWidth={false}
position="topLeft"
size="small"
renderSelectedItem={option => <span title={option.label}>{option.label}</span>}
aria-labelledby={projectLabelId}
disabled={busy || projectDisabled || !canWrite}
/>
@ -213,7 +224,7 @@ export default function Composer({
position="topRight"
className="chat-model-popover"
condition={!busy}
content={<ModelSettings compact model={model} busy={busy || blocked} canReadConfig={canReadConfig} />}
content={<ModelSettings model={model} busy={busy || blocked} canReadConfig={canReadConfig} />}
>
<Button
theme="borderless"

View File

@ -1,9 +1,9 @@
/** 左侧会话列表:搜索、项目过滤、分页、新建/重命名/置顶/删除/批量删除。 */
import { useEffect, useMemo, useState } from 'react';
import { useEffect, useId, useMemo, useState } from 'react';
import {
Button, Checkbox, Empty, Input, List, Pagination, Popconfirm, Select, Skeleton, Tag, Tooltip, Typography
Button, Checkbox, Empty, Input, List, Pagination, Popconfirm, Select, Skeleton, Tooltip, Typography
} from '@douyinfe/semi-ui';
import { IconDelete, IconEdit, IconPlus, IconRefresh, IconSearch, IconStar } from '@douyinfe/semi-icons';
import { IconChevronDown, IconDelete, IconEdit, IconFolder, IconPlus, IconRefresh, IconSearch, IconStar } from '@douyinfe/semi-icons';
import { ErrorBanner } from '../../components/ui';
import { useT } from '../../lib/i18n';
import { formatDateTime } from '../../lib/format';
@ -53,7 +53,6 @@ function ConversationRow({
</span>
<span className="chat-conv-meta">
{formatDateTime(item.updatedAt || item.createdAt)}
{item.projectId && <Tag size="small" type="ghost" className="chat-conv-project">{String(item.projectId).slice(0, 8)}</Tag>}
</span>
</button>
{!batchMode && (
@ -92,7 +91,7 @@ function ConversationRow({
}
export default function ConversationList({
items, total, loading, error, onRetry,
items, groups, expandedGroup, groupTotal, onToggleGroup, loading, error, onRetry,
search, onSearch, projectId, onProjectChange, projects,
page, pageSize, onPageChange,
selectedId, onSelect, onCreate,
@ -100,7 +99,8 @@ export default function ConversationList({
canWrite, canDelete
}) {
const t = useT();
const list = Array.isArray(items) ? items : [];
const list = items;
const groupContentId = useId();
const [editingId, setEditingId] = useState('');
const [editingTitle, setEditingTitle] = useState('');
const [batchMode, setBatchMode] = useState(false);
@ -111,7 +111,7 @@ export default function ConversationList({
useEffect(() => {
setSelectedIds([]);
setBatchMode(false);
}, [page, projectId, search]);
}, [page, projectId, search, expandedGroup]);
const projectOptions = useMemo(() => ([
{ value: '', label: t('chat.filterAllProjects', null, '全部项目') },
@ -138,6 +138,44 @@ export default function ConversationList({
onRename(id, title);
};
const groupContents = (
<>
{loading && !list.length && <Skeleton placeholder={<Skeleton.Paragraph rows={6} />} loading />}
{!loading && !error && !list.length && (
<Empty
title={t('chat.noHistoryConversations', null, '暂无历史对话')}
description={null}
className="chat-sidebar-empty"
/>
)}
<List
dataSource={list}
split={false}
renderItem={item => (
<ConversationRow
key={item.id}
item={item}
active={item.id === selectedId}
editing={editingId === item.id}
editingTitle={editingTitle}
onStartEdit={startEdit}
onEditingTitle={setEditingTitle}
onCommitEdit={commitEdit}
onCancelEdit={() => setEditingId('')}
onSelect={onSelect}
onPin={onPin}
onDelete={onDelete}
canWrite={canWrite}
canDelete={canDelete}
batchMode={batchMode}
selected={selectedIds.includes(item.id)}
onToggleSelect={toggleSelect}
/>
)}
/>
</>
);
return (
<div className="chat-sidebar-inner">
<div className="chat-sidebar-head">
@ -165,7 +203,7 @@ export default function ConversationList({
/>
</div>
<div className="chat-sidebar-tools">
<Text type="tertiary" size="small">{t('chat.recentConversations', null, '最近对话')} · {total ?? list.length}</Text>
<Text type="tertiary" size="small">{t('chat.recentConversations', null, '最近对话')} · {groups.reduce((total, group) => total + group.total, 0)}</Text>
<div className="chat-sidebar-tools-actions">
{canDelete && list.length > 0 && (
<Button
@ -179,7 +217,14 @@ export default function ConversationList({
{batchMode ? t('common.cancel', null, '取消') : t('chat.batchManage', null, '批量管理')}
</Button>
)}
<Button size="small" theme="borderless" aria-label={t('common.refresh', null, '刷新')} icon={<IconRefresh />} onClick={onRetry} />
<Button
size="small"
theme="borderless"
aria-label={t('chat.refreshConversationList', null, '刷新会话列表')}
title={t('chat.refreshConversationList', null, '刷新会话列表')}
icon={<IconRefresh />}
onClick={onRetry}
/>
</div>
</div>
{batchMode && (
@ -210,45 +255,39 @@ export default function ConversationList({
)}
<div className="chat-conv-list">
<ErrorBanner error={error} onRetry={onRetry} />
{loading && !list.length && <Skeleton placeholder={<Skeleton.Paragraph rows={6} />} loading />}
{!loading && !list.length && (
<Empty
title={t('chat.noHistoryConversations', null, '暂无历史对话')}
description={null}
className="chat-sidebar-empty"
/>
{!groups.length && !loading && !error && (
<Empty title={t('chat.noHistoryConversations', null, '暂无历史对话')} description={null} className="chat-sidebar-empty" />
)}
<List
dataSource={list}
split={false}
renderItem={item => (
<ConversationRow
key={item.id}
item={item}
active={item.id === selectedId}
editing={editingId === item.id}
editingTitle={editingTitle}
onStartEdit={startEdit}
onEditingTitle={setEditingTitle}
onCommitEdit={commitEdit}
onCancelEdit={() => setEditingId('')}
onSelect={onSelect}
onPin={onPin}
onDelete={onDelete}
canWrite={canWrite}
canDelete={canDelete}
batchMode={batchMode}
selected={selectedIds.includes(item.id)}
onToggleSelect={toggleSelect}
/>
)}
/>
{groups.map(group => {
const expanded = group.id === expandedGroup;
const contentId = groupContentId + '-' + group.id;
return (
<div className="chat-conv-group" key={group.id}>
<button
type="button"
className="chat-conv-group-toggle"
aria-expanded={expanded}
aria-controls={contentId}
title={group.projectId ? group.title + ' · ' + group.projectId : group.title}
onClick={() => onToggleGroup(group.id)}
>
<IconFolder aria-hidden="true" />
<span className="chat-conv-group-name">{group.title}</span>
<span className="chat-conv-group-count">{group.total}</span>
<IconChevronDown aria-hidden="true" className="chat-conv-group-chevron" />
</button>
<div id={contentId} className="chat-conv-group-content" hidden={!expanded}>
{expanded && groupContents}
</div>
</div>
);
})}
</div>
{(total || 0) > pageSize && (
{expandedGroup && groupTotal > pageSize && (
<div className="chat-sidebar-pager">
<Pagination
size="small"
total={total || 0}
total={groupTotal}
pageSize={pageSize}
currentPage={page}
onPageChange={onPageChange}

View File

@ -0,0 +1,80 @@
import { Button, Empty, Progress, SideSheet, Tag, Typography } from '@douyinfe/semi-ui';
import { IconRefresh } from '@douyinfe/semi-icons';
import { useT } from '../../lib/i18n';
const { Text } = Typography;
const TASK_STATUS = {
pending: { color: 'grey', label: '待处理' },
in_progress: { color: 'blue', label: '进行中' },
completed: { color: 'green', label: '已完成' },
blocked: { color: 'orange', label: '阻塞' },
deleted: { color: 'grey', label: '已删除' }
};
function PlanTasksPanel({ plan, loading, onRefresh }) {
const t = useT();
const tasks = Array.isArray(plan?.tasks)
? plan.tasks.filter(task => String(task.status || '').toLowerCase() !== 'deleted')
: [];
const total = Number(plan?.total) || tasks.length;
const completed = Number(plan?.completed) || tasks.filter(task => task.status === 'completed').length;
const percent = total ? Math.round((completed / total) * 100) : 0;
return (
<div className="chat-plan">
<div className="chat-plan-toolbar">
<Text type="tertiary" size="small">
{plan?.running ? t('chat.planRunning', null, '任务执行中') : t('chat.planIdle', null, '当前没有运行中的任务')}
</Text>
<Button size="small" icon={<IconRefresh />} onClick={onRefresh} loading={loading}>
{t('common.refresh', null, '刷新')}
</Button>
</div>
<Progress percent={percent} showInfo />
<Text type="tertiary" size="small">
{t('chat.planSummary', { total, done: completed }, `共 ${total} 项,已完成 ${completed} 项`)}
</Text>
{!tasks.length && (
<Empty
title={t('chat.planEmpty', null, '暂无执行计划')}
description={t('chat.planEmptyHint', null, '代理调用任务工具后,这里会显示任务看板。')}
style={{ padding: 24 }}
/>
)}
<div className="chat-plan-list">
{tasks.map((task, index) => {
const status = String(task.status || 'pending').toLowerCase();
const meta = TASK_STATUS[status] || TASK_STATUS.pending;
return (
<div className={`chat-plan-item ${status === 'in_progress' ? 'is-active' : ''}`} key={task.id || index}>
<div className="chat-plan-item-head">
<span className="chat-plan-index">{index + 1}</span>
<span className="chat-plan-subject">{task.subject || task.activeForm || '—'}</span>
<Tag size="small" color={meta.color} shape="circle">{meta.label}</Tag>
</div>
{task.description && <div className="chat-plan-desc">{task.description}</div>}
</div>
);
})}
</div>
</div>
);
}
export default function PlanTasksSheet({ visible, onClose, plan, loading, onRefresh }) {
const t = useT();
const title = t('chat.planTasks', null, '执行计划');
return (
<SideSheet
title={title}
aria-label={title}
visible={visible}
onCancel={onClose}
width="min(100%, 560px)"
placement="right"
>
<PlanTasksPanel plan={plan} loading={loading} onRefresh={onRefresh} />
</SideSheet>
);
}

View File

@ -1,200 +0,0 @@
/** 会话详情侧滑:Token 用量、计划任务。面板与侧滑壳分离,便于复用与自检。 */
import { useCallback, useEffect, useState } from 'react';
import { Button, Empty, Progress, SideSheet, Spin, Table, Tag, Typography } from '@douyinfe/semi-ui';
import { IconRefresh } from '@douyinfe/semi-icons';
import { ErrorBanner } from '../../components/ui';
import { api } from '../../lib/http';
import { useT } from '../../lib/i18n';
import { formatDateTime, formatNumber } from '../../lib/format';
const { Text } = Typography;
const TASK_STATUS = {
pending: { color: 'grey', label: '待处理' },
in_progress: { color: 'blue', label: '进行中' },
completed: { color: 'green', label: '已完成' },
blocked: { color: 'orange', label: '阻塞' },
deleted: { color: 'grey', label: '已删除' }
};
function StatCell({ label, value }) {
return (
<div className="chat-usage-cell">
<Text type="tertiary" size="small">{label}</Text>
<div className="chat-usage-value">{formatNumber(value || 0)}</div>
</div>
);
}
export function TokenUsagePanel({ conversationId }) {
const t = useT();
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const load = useCallback(async () => {
if (!conversationId) return;
setLoading(true);
setError(null);
try {
const payload = await api.get(`/conversations/${encodeURIComponent(conversationId)}/token-usage`, {
days: 365,
limit: 200
});
setData(payload);
} catch (err) {
setError(err);
setData(null);
} finally {
setLoading(false);
}
}, [conversationId]);
useEffect(() => {
load();
}, [load]);
const summary = data?.summary || {};
const byModel = Array.isArray(data?.byModel) ? data.byModel : [];
const recent = Array.isArray(data?.recent) ? data.recent : [];
const modelColumns = [
{ title: t('chat.usageModel', null, '模型'), dataIndex: 'key', render: value => <Text size="small">{value || '—'}</Text> },
{ title: t('chat.usageCalls', null, '调用'), dataIndex: 'modelCalls', width: 80, render: value => formatNumber(value || 0) },
{ title: t('chat.usagePrompt', null, '输入'), dataIndex: 'promptTokens', width: 100, render: value => formatNumber(value || 0) },
{ title: t('chat.usageCompletion', null, '输出'), dataIndex: 'completionTokens', width: 100, render: value => formatNumber(value || 0) },
{ title: t('chat.usageTotal', null, '合计'), dataIndex: 'totalTokens', width: 100, render: value => <Text strong>{formatNumber(value || 0)}</Text> }
];
const recentColumns = [
{ title: t('chat.usageTime', null, '时间'), dataIndex: 'createdAt', render: value => <Text size="small">{formatDateTime(value)}</Text> },
{ title: t('chat.usageModel', null, '模型'), dataIndex: 'model' },
{ title: t('chat.usageOrchestration', null, '编排'), dataIndex: 'orchestration', render: value => (value ? <Tag size="small">{value}</Tag> : '—') },
{ title: t('chat.usageTotal', null, '合计'), dataIndex: 'totalTokens', width: 90, render: value => formatNumber(value || 0) }
];
return (
<div className="chat-usage">
<div className="chat-usage-toolbar">
<Text type="tertiary" size="small">
{t('chat.usageScopeHint', null, '统计范围为该会话近 365 天的模型调用。')}
</Text>
<Button size="small" icon={<IconRefresh />} onClick={load} loading={loading}>
{t('common.refresh', null, '刷新')}
</Button>
</div>
<ErrorBanner error={error} onRetry={load} />
{loading && !data && <div className="chat-loading"><Spin /></div>}
{data && (
<>
<div className="chat-usage-grid">
<StatCell label={t('chat.piUsageModelCalls', null, '模型调用')} value={summary.modelCalls} />
<StatCell label={t('chat.piUsagePromptTokens', null, '输入 tokens')} value={summary.promptTokens} />
<StatCell label={t('chat.piUsageCompletionTokens', null, '输出 tokens')} value={summary.completionTokens} />
<StatCell label={t('chat.piUsageTotalTokens', null, '总 tokens')} value={summary.totalTokens} />
<StatCell label={t('chat.piUsageCachedTokens', null, '缓存 tokens')} value={summary.cachedTokens} />
<StatCell label={t('chat.piUsageReasoningTokens', null, '推理 tokens')} value={summary.reasoningTokens} />
</div>
<Text strong className="chat-sheet-subtitle">{t('chat.usageByModel', null, '按模型')}</Text>
<Table
size="small"
rowKey="key"
columns={modelColumns}
dataSource={byModel}
pagination={false}
empty={<Empty title={t('common.noData', null, '暂无数据')} description={null} style={{ padding: 16 }} />}
/>
<Text strong className="chat-sheet-subtitle">{t('chat.usageRecent', null, '最近调用')}</Text>
<Table
size="small"
rowKey={(row, index) => `${row.createdAt || ''}-${index}`}
columns={recentColumns}
dataSource={recent}
pagination={{ pageSize: 8 }}
empty={<Empty title={t('common.noData', null, '暂无数据')} description={null} style={{ padding: 16 }} />}
/>
</>
)}
</div>
);
}
export function TokenUsageSheet({ visible, onClose, conversationId }) {
const t = useT();
return (
<SideSheet
title={t('chat.tokenUsage', null, 'Token 用量')}
visible={visible}
onCancel={onClose}
width={680}
placement="right"
>
<TokenUsagePanel conversationId={conversationId} />
</SideSheet>
);
}
export function PlanTasksPanel({ plan, loading, onRefresh }) {
const t = useT();
const tasks = Array.isArray(plan?.tasks)
? plan.tasks.filter(task => String(task.status || '').toLowerCase() !== 'deleted')
: [];
const total = Number(plan?.total) || tasks.length;
const completed = Number(plan?.completed) || tasks.filter(task => task.status === 'completed').length;
const percent = total ? Math.round((completed / total) * 100) : 0;
return (
<div className="chat-plan">
<div className="chat-usage-toolbar">
<Text type="tertiary" size="small">
{plan?.running ? t('chat.planRunning', null, '任务执行中') : t('chat.planIdle', null, '当前没有运行中的任务')}
</Text>
<Button size="small" icon={<IconRefresh />} onClick={onRefresh} loading={loading}>
{t('common.refresh', null, '刷新')}
</Button>
</div>
<Progress percent={percent} showInfo />
<Text type="tertiary" size="small">
{t('chat.planSummary', null, '共 {{total}} 项,已完成 {{done}} 项', { total, done: completed })}
</Text>
{!tasks.length && (
<Empty
title={t('chat.planEmpty', null, '暂无计划任务')}
description={t('chat.planEmptyHint', null, '代理调用任务工具后,这里会显示任务看板。')}
style={{ padding: 24 }}
/>
)}
<div className="chat-plan-list">
{tasks.map((task, index) => {
const status = String(task.status || 'pending').toLowerCase();
const meta = TASK_STATUS[status] || TASK_STATUS.pending;
return (
<div className={`chat-plan-item ${status === 'in_progress' ? 'is-active' : ''}`} key={task.id || index}>
<div className="chat-plan-item-head">
<span className="chat-plan-index">{index + 1}</span>
<span className="chat-plan-subject">{task.subject || task.activeForm || '—'}</span>
<Tag size="small" color={meta.color} shape="circle">{meta.label}</Tag>
</div>
{task.description && <div className="chat-plan-desc">{task.description}</div>}
</div>
);
})}
</div>
</div>
);
}
export function PlanTasksSheet({ visible, onClose, plan, loading, onRefresh }) {
const t = useT();
return (
<SideSheet
title={t('chat.planTasks', null, '计划任务')}
visible={visible}
onCancel={onClose}
width={560}
placement="right"
>
<PlanTasksPanel plan={plan} loading={loading} onRefresh={onRefresh} />
</SideSheet>
);
}

View File

@ -1,4 +1,4 @@
/** 对话工作台:会话列表 + 消息区 + 流式发送 + 内联 HITL + 用量/计划侧滑。 */
/** 对话工作台:会话列表、消息区、流式发送、审批和执行计划。 */
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Button, Collapse, Progress, SideSheet, Typography } from '@douyinfe/semi-ui';
@ -15,7 +15,7 @@ import ConversationList from './ConversationList';
import MessageList from './MessageList';
import Composer, { AGENT_MODES } from './Composer';
import HitlDock from './HitlDock';
import { PlanTasksSheet, TokenUsageSheet } from './Sheets';
import PlanTasksSheet from './PlanTasksSheet';
import { useAgentRun } from './useAgentRun';
import { useConversationActions } from './useConversationActions';
import { useModelPreferences } from './useModelPreferences';
@ -24,6 +24,7 @@ import './page.css';
const { Text } = Typography;
const PAGE_SIZE = 20;
const DEFAULT_WORKSPACE = '__none__';
const MODE_STORAGE_KEY = 'csai-chat-agent-mode';
const EMPTY_PLAN = { tasks: [], total: 0, completed: 0, activeStep: 0, running: false };
const EMPTY_DETAIL = { conversation: null, messages: [], loading: false, error: null };
@ -67,6 +68,8 @@ export default function Page() {
const [search, setSearch] = useState('');
const debouncedSearch = useDebounced(search, 350);
const [projectFilter, setProjectFilter] = useState('');
const [projectGroup, setProjectGroup] = useState(DEFAULT_WORKSPACE);
const [groupOpen, setGroupOpen] = useState(true);
const [page, setPage] = useState(1);
const [newProjectId, setNewProjectId] = useState('');
const [projectSaving, setProjectSaving] = useState(false);
@ -74,7 +77,7 @@ export default function Page() {
const [storedMode, setStoredMode] = useLocalStorage(MODE_STORAGE_KEY, 'single');
const mode = AGENT_MODES.includes(storedMode) ? storedMode : 'single';
const model = useModelPreferences(canReadConfig);
const [settingsOpen, setSettingsOpen] = useState('');
const [hitlOpen, setHitlOpen] = useState(false);
const [draftHitl, setDraftHitl] = useState(null);
const [detail, setDetail] = useState(EMPTY_DETAIL);
@ -93,7 +96,6 @@ export default function Page() {
const [hitlBusy, setHitlBusy] = useState('');
const [plan, setPlan] = useState(EMPTY_PLAN);
const [planLoading, setPlanLoading] = useState(false);
const [usageOpen, setUsageOpen] = useState(false);
const [planOpen, setPlanOpen] = useState(false);
const [sidebarOpen, setSidebarOpen] = useState(false);
const narrow = useMediaQuery('(max-width: 900px)');
@ -110,13 +112,17 @@ export default function Page() {
const lastActive = useRef(null);
const conversations = useResource(
() => api.get('/conversations', {
limit: PAGE_SIZE,
offset: (page - 1) * PAGE_SIZE,
search: debouncedSearch || undefined,
project_id: projectFilter || undefined
async () => ({
...(await api.get('/conversations', {
limit: PAGE_SIZE,
offset: (page - 1) * PAGE_SIZE,
search: debouncedSearch || undefined,
project_id: projectGroup,
group_by_project: 1
})),
projectGroup, page, search: debouncedSearch
}),
[page, debouncedSearch, projectFilter]
[page, debouncedSearch, projectGroup]
);
const reloadConversations = useRef(conversations.reload);
@ -136,7 +142,23 @@ export default function Page() {
void changeProject(project.id);
};
const listItems = Array.isArray(conversations.data?.conversations) ? conversations.data.conversations : [];
const groups = Array.isArray(conversations.data?.projectGroups) ? conversations.data.projectGroups : [];
const currentGroup = conversations.data?.projectGroup === projectGroup && conversations.data?.search === debouncedSearch;
const currentPage = currentGroup && conversations.data?.page === page;
const listItems = currentPage && Array.isArray(conversations.data.conversations) ? conversations.data.conversations : [];
const groupTotal = currentGroup ? conversations.data.total || 0 : 0;
useEffect(() => {
if (!currentPage) return;
const lastPage = Math.max(1, Math.ceil(groupTotal / PAGE_SIZE));
if (page > lastPage) setPage(lastPage);
}, [currentPage, groupTotal, page]);
const openGroup = useCallback(id => {
setProjectGroup(id);
setGroupOpen(true);
setPage(1);
}, []);
const loadDetail = useCallback(async (id, { silent = false } = {}) => {
const seq = ++detailSeq.current;
@ -292,6 +314,7 @@ export default function Page() {
setDetail(previous => previous.conversation?.id === id
? { ...previous, conversation: { ...previous.conversation, projectId } }
: previous);
if (!projectFilter || projectFilter === projectId) openGroup(projectId || DEFAULT_WORKSPACE);
reloadList();
} catch (error) {
toastError(error, t('chat.projectChangeFailed', null, '更新对话所属项目失败'));
@ -444,18 +467,47 @@ export default function Page() {
}, [attachments, backgroundRunning, canWrite, canExecute, canDecideHitl, checkingRun, conversationId, draft, draftHitl, mode, model, newProjectId, projectSaving, resetRun, run, sending, t, updateComposer]);
const conversation = detail.conversation;
const revealedConversation = useRef('');
useEffect(() => {
if (!conversationId) {
revealedConversation.current = '';
return;
}
if (conversation?.id !== conversationId || revealedConversation.current === conversationId) return;
revealedConversation.current = conversationId;
const id = conversation.projectId || DEFAULT_WORKSPACE;
if ((!projectFilter || projectFilter === id) && (projectGroup !== id || !groupOpen)) openGroup(id);
}, [conversation, conversationId, groupOpen, openGroup, projectFilter, projectGroup]);
const defaultTotal = groups.find(group => !group.projectId)?.total || 0;
const workspaceGroups = [
{ id: DEFAULT_WORKSPACE, title: t('chat.defaultWorkspace', null, '默认工作区'), total: defaultTotal },
...groups.filter(group => group.projectId).map(group => ({
id: group.projectId,
title: projects.find(project => project.id === group.projectId)?.name || t('chat.boundProject', null, '已绑定项目'),
total: group.total,
projectId: group.projectId
}))
];
const sidebar = (
<ConversationList
items={listItems}
total={conversations.data?.total || 0}
loading={conversations.loading}
items={groupOpen ? listItems : []}
groups={workspaceGroups.filter(group => !projectFilter || group.id === projectFilter)}
expandedGroup={groupOpen ? projectGroup : ''}
groupTotal={groupTotal}
onToggleGroup={id => {
if (id === projectGroup && groupOpen) setGroupOpen(false);
else if (id === projectGroup) setGroupOpen(true);
else openGroup(id);
}}
loading={conversations.loading || (!currentPage && !conversations.error)}
error={conversations.error}
onRetry={() => conversations.reload()}
search={search}
onSearch={value => { setSearch(value); setPage(1); }}
projectId={projectFilter}
onProjectChange={value => { setProjectFilter(value || ''); setPage(1); }}
onProjectChange={value => { setProjectFilter(value || ''); openGroup(value || DEFAULT_WORKSPACE); }}
projects={projects}
page={page}
pageSize={PAGE_SIZE}
@ -481,16 +533,8 @@ export default function Page() {
mode={mode}
hitlCount={hitlPending.length}
conversationId={conversationId}
plan={plan}
narrow={narrow}
onToggleSidebar={() => setSidebarOpen(true)}
onOpenUsage={() => setUsageOpen(true)}
onOpenSettings={canReadConfig || canReadHitl || (canWrite && canExecute)
? () => setSettingsOpen('all') : undefined}
onOpenPlan={() => {
refreshPlan();
setPlanOpen(true);
}}
onRefresh={() => {
reloadConversations.current?.();
if (conversationId) loadDetail(conversationId);
@ -511,7 +555,7 @@ export default function Page() {
/>
{plan.running && plan.total > 0 && (
<div className="chat-plan-strip">
<Text size="small">{t('chat.planTasks', null, '计划任务')}</Text>
<Text size="small">{t('chat.planTasks', null, '执行计划')}</Text>
<Progress
percent={Math.round((Number(plan.completed || 0) / Math.max(1, Number(plan.total))) * 100)}
showInfo={false}
@ -571,7 +615,7 @@ export default function Page() {
projectDisabled={projectsResource.loading || Boolean(conversationId && (detail.loading || !conversation || detail.error))}
model={model}
canReadConfig={canReadConfig}
onOpenHitl={canReadHitl ? () => setSettingsOpen('hitl') : undefined}
onOpenHitl={canReadHitl ? () => setHitlOpen(true) : undefined}
attachments={attachments}
onPickFiles={uploadFiles}
onRemoveAttachment={removeAttachment}
@ -586,17 +630,12 @@ export default function Page() {
onSaved={handleProjectCreated}
/>
)}
{settingsOpen && (
{hitlOpen && canReadHitl && (
<ChatSettings
key={conversationId}
section={settingsOpen}
onClose={() => setSettingsOpen('')}
onClose={() => setHitlOpen(false)}
narrow={narrow}
busy={sending || backgroundRunning || checkingRun || !(canWrite && canExecute)}
canReadConfig={canReadConfig}
canReadHitl={canReadHitl}
canEnableHitl={canDecideHitl}
model={model}
conversationId={conversationId}
draftHitl={!conversationId ? draftHitl : null}
onDraftHitlChange={setDraftHitl}
@ -612,11 +651,6 @@ export default function Page() {
>
{sidebar}
</SideSheet>
<TokenUsageSheet
visible={usageOpen}
onClose={() => setUsageOpen(false)}
conversationId={conversationId}
/>
<PlanTasksSheet
visible={planOpen}
onClose={() => setPlanOpen(false)}

View File

@ -105,7 +105,28 @@
.chat-conv-title-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.chat-conv-pin { color: var(--semi-color-warning); flex: 0 0 auto; }
.chat-conv-meta { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; font-size: 11px; line-height: 1.6; color: var(--semi-color-text-2); overflow-wrap: anywhere; }
.chat-conv-project { max-width: 100%; }
.chat-conv-group + .chat-conv-group { margin-top: 4px; }
.chat-conv-group-toggle {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 9px 8px;
border: 0;
border-radius: 8px;
background: transparent;
color: var(--semi-color-text-1);
text-align: start;
font: inherit;
cursor: pointer;
}
.chat-conv-group-toggle:hover,
.chat-conv-group-toggle[aria-expanded="true"] { background: var(--semi-color-fill-0); }
.chat-conv-group-toggle > .semi-icon { flex: none; }
.chat-conv-group-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; }
.chat-conv-group-count { flex: none; color: var(--semi-color-text-2); font-size: 12px; }
.chat-conv-group-toggle[aria-expanded="true"] .chat-conv-group-chevron { transform: rotate(180deg); }
.chat-conv-group-content { margin-inline-start: 8px; }
.chat-conv-actions { display: flex; gap: 2px; flex: 0 0 auto; }
.chat-conv-edit { display: flex; flex-direction: column; gap: 8px; padding: 10px 6px; width: 100%; min-width: 0; }
.chat-conv-edit-actions { display: flex; gap: 6px; flex-wrap: wrap; }
@ -297,22 +318,27 @@
.chat-composer-context {
display: flex;
align-items: center;
gap: 4px;
gap: 6px;
min-width: 0;
margin-inline: 14px;
padding: 6px 6px 16px;
border-radius: 18px 18px 0 0;
background: var(--semi-color-fill-0);
padding: 0 6px 8px;
}
.chat-context-select.semi-select {
flex: 0 1 auto;
width: fit-content;
min-width: 0;
max-width: 100%;
background: transparent;
border-color: transparent;
height: 30px;
border-radius: 8px;
background: var(--semi-color-bg-1);
border-color: var(--semi-color-border);
}
.chat-context-select.semi-select:hover { background: var(--semi-color-fill-1); }
.chat-composer-mode { flex: 0 1 164px; width: 164px; }
.chat-context-select.semi-select:not(.semi-select-disabled):hover { background: var(--semi-color-primary-light-default); }
.chat-context-select .semi-select-selection { min-width: 0; margin-inline: 5px; }
.chat-context-select .semi-select-selection-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.chat-context-select .semi-select-prefix { padding-inline-start: 7px; }
.chat-context-select .semi-select-arrow { width: auto; padding-inline: 4px 7px; }
.chat-composer-mode { max-width: 45%; }
.chat-mode-dropdown { width: min(390px, calc(100vw - 48px)); }
.chat-project-dropdown { width: min(260px, calc(100vw - 48px)); }
.chat-mode-option { min-width: 0; white-space: normal; overflow-wrap: anywhere; }
.chat-mode-option-description {
display: block;
@ -322,10 +348,9 @@
font-weight: normal;
line-height: 1.5;
}
.chat-composer-project { flex: 0 1 260px; width: 260px; }
.chat-composer-project { max-width: min(260px, 55%); }
.chat-composer-box {
position: relative;
margin-top: -10px;
padding: 14px 16px 10px;
border: 1px solid var(--semi-color-border);
border-radius: 20px;
@ -378,6 +403,7 @@
.chat-reasoning-channel .semi-select-arrow { padding-inline: 0 4px; }
.chat-reasoning-channel.semi-select-borderless:not(:focus-within):not(:hover) .semi-select-arrow { opacity: 1; }
.chat-reasoning-channel-label { display: block; text-align: center; font-size: 12px; line-height: 22px; }
.chat-reasoning-hint.semi-typography { display: block; margin: 5px 4px 0; text-align: center; line-height: 1.4; }
.chat-reasoning-slider.semi-slider { padding: 0; margin: 10px 8px 0; }
.chat-reasoning-slider .semi-slider-wrapper { height: 28px; }
.chat-reasoning-slider .semi-slider-rail,
@ -422,37 +448,13 @@
}
.chat-settings-fields { display: grid; gap: 16px; }
.chat-setting-field { display: grid; gap: 8px; min-width: 0; }
.chat-setting-hitl { padding-top: 16px; border-top: 1px solid var(--semi-color-border); }
.chat-setting-hitl:first-child { padding-top: 0; border-top: 0; }
.chat-setting-reviewer { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); width: 100%; }
.chat-setting-reviewer .semi-radio-addon-buttonRadio { flex: 1; text-align: center; }
/* ---------- 侧滑面板 ---------- */
.chat-usage, .chat-plan { display: flex; flex-direction: column; gap: 10px; }
.chat-usage-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.chat-usage-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
}
.chat-usage-cell {
display: flex;
flex-direction: column;
gap: 2px;
padding: 8px 10px;
border: 1px solid var(--semi-color-border);
border-radius: 8px;
background: var(--semi-color-bg-2);
}
.chat-usage-value {
font-size: 18px;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.chat-sheet-subtitle { margin-top: 6px; display: block; }
.chat-plan { display: flex; flex-direction: column; gap: 10px; }
.chat-plan-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.chat-plan-list { display: flex; flex-direction: column; gap: 6px; }
.chat-plan-item {
@ -507,9 +509,8 @@
.chat-turn-body .cs-markdown,
.chat-stream-text { font-size: 14px; }
.chat-composer { padding-block: 8px 12px; }
.chat-composer-context { margin-inline: 8px; padding-inline: 2px; }
.chat-composer-mode { flex: 1 1 120px; width: 120px; }
.chat-composer-project { flex: 1 1 140px; width: 140px; }
.chat-composer-context { padding-inline: 2px; }
.chat-context-select.semi-select { height: 34px; }
.chat-composer-box { padding: 12px 12px 8px; border-radius: 18px; }
.chat-composer-box .semi-input-textarea { font-size: 16px; }
.chat-composer-toolbar { gap: 4px; }
@ -524,7 +525,6 @@
@media (max-width: 900px) {
.chat-page { gap: 0; }
.chat-sidebar { display: none; }
.chat-usage-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.chat-hitl-dock { max-height: 50%; }
}

View File

@ -35,6 +35,10 @@ export function useModelPreferences(canReadConfig) {
const normalizedChannel = storedChannel.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
const channel = channels.find(([id]) => id === storedChannel)?.[0]
|| channels.find(([id]) => id === normalizedChannel)?.[0] || '';
const channelConfig = config.data?.channels?.[channel || config.data?.default_channel];
const overrideBlocked = channelConfig?.reasoning?.allow_client_reasoning === false;
const officialDeepSeek = /^(?:https?:\/\/)?(?:www\.)?api\.deepseek\.com(?=[:/?#]|$)/i
.test(channelConfig?.base_url?.trim() || '');
const mode = REASONING_MODES.includes(storedMode) ? storedMode : 'default';
const effort = REASONING_EFFORTS.includes(storedEffort) ? storedEffort : '';
const reasoning = {
@ -43,7 +47,7 @@ export function useModelPreferences(canReadConfig) {
};
return {
channel, channels, setChannel, config, mode, setMode, effort, setEffort,
channel, channels, setChannel, config, mode, setMode, effort, setEffort, overrideBlocked, officialDeepSeek,
waitingForChannel: Boolean(canReadConfig && storedChannel && config.loading),
request: {
aiChannelId: canReadConfig ? channel || undefined : undefined,

View File

@ -11,6 +11,8 @@
.settings-tabs .semi-tabs-bar-top .semi-tabs-tab { font-size: 13px; }
.settings-loading-block { padding: 18px 4px; }
.settings-token-filters { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-bottom: 14px; }
.settings-token-conversation { width: 280px; max-width: 100%; }
.settings-hint {
display: inline-block;

View File

@ -1,6 +1,6 @@
/** Token 用量:GET /usage/tokens(days / limit / project_id),汇总 + 按日 + 按模型 + 最近记录。 */
import { useCallback, useMemo, useState } from 'react';
import { Input, Select, Space, Tag, Typography } from '@douyinfe/semi-ui';
import { useCallback, useId, useMemo, useState } from 'react';
import { Button, Input, Select, Space, Tag, Typography } from '@douyinfe/semi-ui';
import { IconRefresh } from '@douyinfe/semi-icons';
import { api } from '../../../lib/http';
import { useAuth } from '../../../lib/auth';
import { useT } from '../../../lib/i18n';
@ -49,19 +49,49 @@ function breakdownColumns(t, firstTitle) {
export default function TokenUsageSection() {
const t = useT();
const { hasPermission } = useAuth();
const canRead = hasPermission('dashboard:read');
const [days, setDays] = useState(7);
const canReadOverall = hasPermission('dashboard:read');
const canReadConversation = hasPermission('chat:read');
const filtersId = useId();
const [overallDays, setOverallDays] = useState(7);
const [conversationDays, setConversationDays] = useState(365);
const [limit, setLimit] = useState(20);
const [projectInput, setProjectInput] = useState('');
const projectId = useDebounced(projectInput.trim(), 400);
const [selectedConversation, setSelectedConversation] = useState(null);
const [pickerOpen, setPickerOpen] = useState(false);
const [pickerInput, setPickerInput] = useState('');
const conversationSearch = useDebounced(pickerInput.trim(), 300);
const conversationId = canReadConversation ? selectedConversation?.value : undefined;
const days = conversationId ? conversationDays : overallDays;
const canQueryUsage = Boolean(conversationId) || canReadOverall;
const loadPicker = canReadConversation && pickerOpen;
const picker = useResource(async () => {
const result = await api.get('/conversations', { search: conversationSearch || undefined, limit: 50 });
return (result?.conversations || []).map(conversation => ({
value: conversation.id,
label: [
conversation.title || t('chat.untitled', null, '未命名对话'),
formatDateTime(conversation.updatedAt || conversation.createdAt)
].join(' · ')
}));
}, [loadPicker, conversationSearch, t], { skip: !loadPicker });
const pickerOptions = picker.data || [];
const options = selectedConversation && !pickerOptions.some(option => option.value === selectedConversation.value)
? [selectedConversation, ...pickerOptions]
: pickerOptions;
const loader = useCallback(
() => api.get('/usage/tokens', { days, limit, project_id: projectId || undefined }),
[days, limit, projectId]
);
const usage = useResource(loader, [days, limit, projectId, canRead], { skip: !canRead });
const usageProjectId = conversationId ? undefined : projectId || undefined;
const scopeKey = conversationId ? ['conversation', conversationId].join(':') : usageProjectId || '';
const loader = useCallback(async () => ({
scopeKey,
result: conversationId
? await api.get(`/conversations/${encodeURIComponent(conversationId)}/token-usage`, { days, limit })
: await api.get('/usage/tokens', { days, limit, project_id: usageProjectId })
}), [conversationId, days, limit, scopeKey, usageProjectId]);
const usage = useResource(loader, [loader, canQueryUsage], { skip: !canQueryUsage });
const data = canQueryUsage && scopeKey === usage.data?.scopeKey ? usage.data.result : null;
const summary = usage.data?.summary || {};
const summary = data?.summary || {};
const metrics = useMemo(() => ([
{ id: 'total', label: t('tokenUsageUI.usageTotal', null, '总 Token'), value: formatNumber(count(summary.totalTokens)) },
{ id: 'input', label: t('tokenUsageUI.usageInput', null, '输入 Token'), value: formatNumber(count(summary.promptTokens)) },
@ -78,45 +108,66 @@ export default function TokenUsageSection() {
}
]), [summary, t]);
if (!canRead) {
if (!canReadOverall && !canReadConversation) {
return <PermissionBanner permission="dashboard:read" label={t('settings.nav.tokenUsage', null, '读取 Token 用量')} />;
}
if (usage.loading && !usage.data) return <LoadingBlock rows={6} />;
const byDay = Array.isArray(usage.data?.byDay) ? usage.data.byDay : [];
const byModel = Array.isArray(usage.data?.byModel) ? usage.data.byModel : [];
const recent = Array.isArray(usage.data?.recent) ? usage.data.recent : [];
const today = usage.data?.today || {};
const byDay = Array.isArray(data?.byDay) ? data.byDay : [];
const byModel = Array.isArray(data?.byModel) ? data.byModel : [];
const recent = Array.isArray(data?.recent) ? data.recent : [];
const today = data?.today || {};
const pickerLabel = t('tokenUsageUI.selectConversation', null, '搜索并选择会话');
return (
<>
<ErrorBanner error={usage.error} onRetry={usage.reload} />
{canQueryUsage && <ErrorBanner error={usage.error} onRetry={usage.reload} />}
<SectionCard
title={t('settings.nav.tokenUsage', null, 'Token 用量')}
description={t('tokenUsageUI.scopeNote', null, '统计口径与说明:按服务端本地日期聚合,当前登录用户可见的会话范围内统计。')}
extra={(
<Space>
<Text type="tertiary" size="small">{t('settings.usageDays', null, '时间范围')}</Text>
<Select
value={days}
onChange={value => setDays(Number(value))}
style={{ width: 120 }}
optionList={[
{ value: 7, label: '7 天' },
{ value: 30, label: '30 天' },
{ value: 90, label: '90 天' }
]}
/>
<Select
value={limit}
onChange={value => setLimit(Number(value))}
style={{ width: 130 }}
optionList={[
{ value: 20, label: '最近 20 条' },
{ value: 50, label: '最近 50 条' },
{ value: 100, label: '最近 100 条' }
]}
/>
>
<div className="settings-token-filters">
{canReadConversation && (
<>
<span id={filtersId + '-conversation'} hidden>{pickerLabel}</span>
<Select
className="settings-token-conversation"
aria-labelledby={filtersId + '-conversation'}
placeholder={pickerLabel}
value={conversationId}
optionList={options}
filter
remote
showClear
loading={picker.loading}
onSearch={setPickerInput}
onDropdownVisibleChange={open => {
setPickerOpen(open);
if (!open) setPickerInput('');
}}
onChange={value => setSelectedConversation(options.find(option => option.value === value) || null)}
/>
</>
)}
<span id={filtersId + '-days'} hidden>{t('settings.usageDays', null, '时间范围')}</span>
<Select
aria-labelledby={filtersId + '-days'}
value={days}
onChange={value => (conversationId ? setConversationDays : setOverallDays)(Number(value))}
style={{ width: 120 }}
optionList={[7, 30, 90, 365].map(value => ({
value, label: t('tokenUsageUI.periodDays', { count: value }, `${value} 天`)
}))}
/>
<span id={filtersId + '-limit'} hidden>{t('tokenUsageUI.recentTitle', null, '最近记录')}</span>
<Select
aria-labelledby={filtersId + '-limit'}
value={limit}
onChange={value => setLimit(Number(value))}
style={{ width: 130 }}
optionList={[20, 50, 100, 200].map(value => ({
value, label: t('tokenUsageUI.recentLimit', { count: value }, `最近 ${value} 条`)
}))}
/>
{canReadOverall && !conversationId && (
<Input
value={projectInput}
onChange={value => setProjectInput(value)}
@ -124,76 +175,88 @@ export default function TokenUsageSection() {
style={{ width: 180 }}
showClear
/>
</Space>
)}
<Button icon={<IconRefresh />} onClick={usage.reload} loading={usage.loading} disabled={!canQueryUsage}>
{t('common.refresh', null, '刷新')}
</Button>
</div>
{canReadConversation && <ErrorBanner error={picker.error} onRetry={picker.reload} />}
{canQueryUsage && (usage.loading || !usage.error) && !data && <LoadingBlock rows={3} />}
{data && (
<>
<StatGrid metrics={metrics} columns={4} />
<Space spacing={8} wrap>
<Tag size="small" color="blue">
{t('tokenUsageUI.todayTotal', { total: formatNumber(count(today.totalTokens)) }, `今日 ${formatNumber(count(today.totalTokens))} tokens`)}
</Tag>
<Tag size="small" color="grey">
{t('tokenUsageUI.todayCalls', { calls: formatNumber(count(today.modelCalls)) }, `今日 ${formatNumber(count(today.modelCalls))} 次模型调用`)}
</Tag>
<Tag size="small" color="green">
{t('tokenUsageUI.todayCache', { rate: cacheRate(today) }, `今日缓存命中 ${cacheRate(today)}`)}
</Tag>
</Space>
</>
)}
>
<StatGrid metrics={metrics} columns={4} />
<Space spacing={8}>
<Tag size="small" color="blue">
{t('tokenUsageUI.todayTotal', { total: formatNumber(count(today.totalTokens)) }, `今日 ${formatNumber(count(today.totalTokens))} tokens`)}
</Tag>
<Tag size="small" color="grey">
{t('tokenUsageUI.todayCalls', { calls: formatNumber(count(today.modelCalls)) }, `今日 ${formatNumber(count(today.modelCalls))} 次模型调用`)}
</Tag>
<Tag size="small" color="green">
{t('tokenUsageUI.todayCache', { rate: cacheRate(today) }, `今日缓存命中 ${cacheRate(today)}`)}
</Tag>
</Space>
</SectionCard>
<SectionCard title={t('tokenUsageUI.trendTitle', null, '每日用量')}>
<DataTable
columns={breakdownColumns(t, t('tokenUsageUI.colDay', null, '日期'))}
dataSource={byDay}
rowKey="key"
loading={usage.loading}
pagination={false}
emptyText={t('tokenUsageUI.noDailyData', null, '暂无每日用量记录')}
/>
</SectionCard>
{data && (
<>
<SectionCard title={t('tokenUsageUI.trendTitle', null, '每日用量')}>
<DataTable
columns={breakdownColumns(t, t('tokenUsageUI.colDay', null, '日期'))}
dataSource={byDay}
rowKey="key"
loading={usage.loading}
pagination={false}
emptyText={t('tokenUsageUI.noDailyData', null, '暂无每日用量记录')}
/>
</SectionCard>
<SectionCard title={t('tokenUsageUI.modelTitle', null, '按模型')}>
<DataTable
columns={breakdownColumns(t, t('tokenUsageUI.colModel', null, '模型'))}
dataSource={byModel}
rowKey="key"
loading={usage.loading}
pagination={false}
emptyText={t('common.noData', null, '暂无数据')}
/>
</SectionCard>
<SectionCard title={t('tokenUsageUI.modelTitle', null, '按模型')}>
<DataTable
columns={breakdownColumns(t, t('tokenUsageUI.colModel', null, '模型'))}
dataSource={byModel}
rowKey="key"
loading={usage.loading}
pagination={false}
emptyText={t('common.noData', null, '暂无数据')}
/>
</SectionCard>
<SectionCard title={t('tokenUsageUI.recentTitle', null, '最近记录')}>
<DataTable
columns={[
{
title: t('tokenUsageUI.colTime', null, '时间'),
dataIndex: 'createdAt',
width: 180,
render: value => formatDateTime(value)
},
{ title: t('tokenUsageUI.colModel', null, '模型'), dataIndex: 'model', render: value => value || '—' },
{ title: t('settingsDisplay.usageSource', null, '用量来源'), dataIndex: 'source', render: value => value || '—' },
{ title: t('settingsDisplay.orchestration', null, '协作方式'), dataIndex: 'orchestration', render: value => value || '—' },
{
title: t('settingsDisplay.tokensBreakdown', null, '输入 / 输出 / 总令牌数'),
align: 'right',
render: (_, row) => `${formatNumber(count(row.promptTokens))} / ${formatNumber(count(row.completionTokens))} / ${formatNumber(count(row.totalTokens))}`
},
{
title: t('settingsDisplay.conversation', null, '对话'),
dataIndex: 'conversationId',
width: 200,
render: value => <Text type="tertiary">{truncate(value || '—', 18)}</Text>
}
]}
dataSource={recent}
rowKey="id"
loading={usage.loading}
pagination={{ pageSize: 10, showSizeChanger: false }}
emptyText={t('common.noData', null, '暂无数据')}
/>
</SectionCard>
<SectionCard title={t('tokenUsageUI.recentTitle', null, '最近记录')}>
<DataTable
columns={[
{
title: t('tokenUsageUI.colTime', null, '时间'),
dataIndex: 'createdAt',
width: 180,
render: value => formatDateTime(value)
},
{ title: t('tokenUsageUI.colModel', null, '模型'), dataIndex: 'model', render: value => value || '—' },
{ title: t('settingsDisplay.usageSource', null, '用量来源'), dataIndex: 'source', render: value => value || '—' },
{ title: t('settingsDisplay.orchestration', null, '协作方式'), dataIndex: 'orchestration', render: value => value || '—' },
{
title: t('settingsDisplay.tokensBreakdown', null, '输入 / 输出 / 总令牌数'),
align: 'right',
render: (_, row) => `${formatNumber(count(row.promptTokens))} / ${formatNumber(count(row.completionTokens))} / ${formatNumber(count(row.totalTokens))}`
},
{
title: t('settingsDisplay.conversation', null, '对话'),
dataIndex: 'conversationId',
width: 200,
render: value => <Text type="tertiary">{truncate(value || '—', 18)}</Text>
}
]}
dataSource={recent}
rowKey="id"
loading={usage.loading}
pagination={{ pageSize: 10, showSizeChanger: false }}
emptyText={t('common.noData', null, '暂无数据')}
/>
</SectionCard>
</>
)}
</>
);
}

View File

@ -65,6 +65,25 @@ export const CONVERSATION = {
export const STREAM_REPLY = '模拟回复完成:仅处理匿名 localhost 数据,未执行真实任务。';
const STREAM_ID = 'fixture-stream-conversation';
export function conversationListFixture(items, url) {
const search = url.searchParams.get('search') || '';
const project = url.searchParams.get('project_id') || '';
const offset = Number(url.searchParams.get('offset') || 0);
const limit = Number(url.searchParams.get('limit') || 50);
const matching = items.filter(item => item.title.includes(search));
const filtered = matching.filter(item => !project || (item.projectId || '__none__') === project);
const response = { conversations: filtered.slice(offset, offset + limit), total: filtered.length };
if (url.searchParams.get('group_by_project') === '1') {
const totals = new Map();
for (const item of matching) {
const id = item.projectId || '';
totals.set(id, (totals.get(id) || 0) + 1);
}
response.projectGroups = [...totals].map(([projectId, total]) => ({ projectId, total }));
}
return response;
}
function makeReads(session) {
const vulnerabilities = [
VULNERABILITY,
@ -124,7 +143,7 @@ function makeReads(session) {
[`/api/projects/${PROJECT.id}`]: PROJECT,
[`/api/projects/${PROJECT.id}/stats`]: { fact_count: 1, vuln_count: 3, conversation_count: 1, sparse_fact_count: 0 },
[`/api/projects/${PROJECT.id}/facts`]: url => url.searchParams.has('fact_key') ? FACT : [FACT],
'/api/conversations': { conversations: [CONVERSATION], total: 1 },
'/api/conversations': url => conversationListFixture([CONVERSATION], url),
[`/api/conversations/${CONVERSATION.id}`]: CONVERSATION,
[`/api/conversations/${CONVERSATION.id}/plan-tasks`]: { tasks: [], total: 0, completed: 0, running: false },
'/api/deep-assessments': { tasks: [ASSESSMENT], has_more: false },
@ -187,7 +206,7 @@ class MockApi {
this.respond('POST', '/api/agent/stream', () => {
this.reads.set(`/api/conversations/${STREAM_ID}`, conversation);
this.reads.set(`/api/conversations/${STREAM_ID}/plan-tasks`, { tasks: [], total: 0, completed: 0, running: false });
this.reads.set('/api/conversations', { conversations: [conversation, CONVERSATION], total: 2 });
this.reads.set('/api/conversations', url => conversationListFixture([conversation, CONVERSATION], url));
const events = [
{ type: 'conversation', data: { conversationId: STREAM_ID } },
{ type: 'response_start', data: { conversationId: STREAM_ID } },

View File

@ -1,4 +1,4 @@
import { test, expect, visit, ready, label, UI_PERMISSIONS, PROJECT, CONVERSATION, ASSESSMENT, STAMP } from './fixtures.mjs';
import { conversationListFixture, test, expect, visit, ready, label, UI_PERMISSIONS, PROJECT, CONVERSATION, ASSESSMENT, STAMP } from './fixtures.mjs';
test('token usage: summary values render with daily rows and update to zero after filtering', async ({ page, mockApi }, testInfo) => {
const summary = {
@ -49,6 +49,53 @@ test('token usage: explicit dashboard loading still resolves and links to visibl
expect(mockApi.writes()).toEqual([]);
});
test.describe('token usage with conversation access only', () => {
test.use({ appPermissions: UI_PERMISSIONS.filter(permission => permission !== 'dashboard:read') });
test('searches for a conversation and loads its usage in settings', async ({ page, mockApi }) => {
const path = `/api/conversations/${CONVERSATION.id}/token-usage`;
mockApi.respond('GET', path, { json: {
summary: { totalTokens: 5432 }, byModel: [{ key: 'fixture-model', totalTokens: 5432 }],
recent: [{ id: 'fixture-usage', conversationId: CONVERSATION.id, model: 'fixture-model', totalTokens: 5432 }]
} });
const main = await visit(page, 'settings?section=token-usage');
const picker = main.getByRole('combobox', { name: label('tokenUsageUI.selectConversation') });
await picker.click();
await page.keyboard.type(CONVERSATION.title);
await expect.poll(() => mockApi.calls('GET', '/api/conversations').some(call =>
new URLSearchParams(call.query).get('search') === CONVERSATION.title
)).toBe(true);
await page.getByRole('option', { name: new RegExp(CONVERSATION.title) }).click();
await expect(main.locator('.cs-stat-grid .cs-stat-value').first()).toHaveText('5,432');
await expect(main.getByRole('gridcell', { name: 'fixture-model', exact: true })).toHaveCount(2);
expect(new URLSearchParams(mockApi.calls('GET', path)[0].query).get('days')).toBe('365');
expect(mockApi.calls('GET', '/api/usage/tokens')).toHaveLength(0);
});
});
test('chat: shows active plan details and reloads the current conversation on request', async ({ page, mockApi }) => {
const path = `/api/conversations/${CONVERSATION.id}`;
const planPath = `${path}/plan-tasks`;
mockApi.respond('GET', '/api/agent-loop/tasks', { json: { tasks: [] } });
mockApi.respond('GET', planPath, { json: {
running: true, total: 2, completed: 1, activeStep: 2, tasks: [
{ id: '1', subject: '整理现有资料', status: 'completed' },
{ id: '2', subject: '汇总检查结果', status: 'in_progress' }
]
} });
const main = await visit(page, `chat?conversation=${CONVERSATION.id}`);
const header = main.locator('.chat-header');
await expect(header.getByRole('button', { name: label('chat.planTasks') })).toHaveCount(0);
const strip = main.locator('.chat-plan-strip');
await expect(strip).toContainText('1/2');
await strip.getByRole('button', { name: label('chat.planDetails', '详情') }).click();
await expect(page.getByRole('dialog', { name: label('chat.planTasks') })).toContainText('汇总检查结果');
await page.getByRole('dialog', { name: label('chat.planTasks') }).locator('.semi-sidesheet-close').click();
const before = mockApi.calls('GET', path).length;
await header.getByRole('button', { name: label('chat.refreshConversation') }).click();
await expect.poll(() => mockApi.calls('GET', path).length).toBeGreaterThan(before);
expect(mockApi.writes()).toEqual([]);
});
test('legacy update bookmark opens the current settings tab', async ({ page, mockApi }) => {
mockApi.respond('GET', '/api/system/update', { json: { status: {} } });
mockApi.respond('GET', '/api/storage/meta', { json: {} });
@ -86,7 +133,7 @@ function mockEmptyConversation(mockApi, projectId = '') {
const conversation = { ...CONVERSATION, projectId, messages: [] };
mockApi.respond('GET', '/api/agent-loop/tasks', { json: { tasks: [] } });
mockApi.respond('GET', `/api/conversations/${conversation.id}`, () => ({ json: conversation }));
mockApi.respond('GET', '/api/conversations', () => ({ json: { conversations: [conversation], total: 1 } }));
mockApi.respond('GET', '/api/conversations', (_, url) => ({ json: conversationListFixture([conversation], url) }));
return conversation;
}
@ -108,7 +155,7 @@ test.describe('chat composer projects', () => {
test('binds and unbinds an existing empty conversation without losing its draft or sending during save', async ({ page, mockApi }) => {
const conversation = mockEmptyConversation(mockApi);
const path = `/api/conversations/${conversation.id}/project`;
const noProject = label('chat.noProject', '不绑定项目');
const noProject = label('chat.defaultWorkspace', '默认工作区');
const draft = 'FAKE:切换项目时保留这份会话草稿。';
let releaseSave;
const pendingSave = new Promise(resolve => { releaseSave = resolve; });
@ -123,11 +170,12 @@ test.describe('chat composer projects', () => {
const project = context.getByRole('combobox').filter({ hasText: new RegExp(`${noProject}|${PROJECT.name}`) });
const input = main.getByRole('textbox', { name: label('chat.composerLabel', '对话内容') });
const send = main.getByRole('button', { name: /发送$/ });
// The header may display the project name or its existing abbreviated ID.
const headerProject = main.locator('.chat-header-tags .semi-tag').filter({ hasText: new RegExp(`${PROJECT.name}|${PROJECT.id.slice(0, 8)}`) });
const sidebar = main.locator('.chat-sidebar');
const projectGroup = sidebar.getByRole('button', { name: PROJECT.name + ' 1', exact: true });
const workspace = sidebar.getByRole('button', { name: label('chat.defaultWorkspace') + ' 1', exact: true });
await expect(context.getByRole('combobox')).toHaveCount(2);
await expect(project).toHaveText(noProject);
await expect(headerProject).toHaveCount(0);
await expect(workspace).toHaveAttribute('aria-expanded', 'true');
await input.fill(draft);
await expect(send).toBeEnabled();
await expect.poll(() => mockApi.calls('GET', '/api/conversations').some(call => call.fulfilled)).toBe(true);
@ -146,7 +194,7 @@ test.describe('chat composer projects', () => {
releaseSave();
await expect(project).toBeEnabled();
await expect(project).toHaveText(PROJECT.name);
await expect(headerProject).toBeVisible();
await expect(projectGroup).toHaveAttribute('aria-expanded', 'true');
await expect(main.getByRole('heading', { name: conversation.title, exact: true })).toBeVisible();
await expect.poll(() => mockApi.calls('GET', '/api/conversations').length).toBeGreaterThan(initialListReads);
await expect(input).toHaveValue(draft);
@ -156,7 +204,7 @@ test.describe('chat composer projects', () => {
await page.getByRole('listbox').getByText(noProject, { exact: true }).click();
await expect(project).toBeEnabled();
await expect(project).toHaveText(noProject);
await expect(headerProject).toHaveCount(0);
await expect(workspace).toHaveAttribute('aria-expanded', 'true');
await expect(send).toBeEnabled();
await expect(input).toHaveValue(draft);
await expect.poll(() => mockApi.calls('GET', '/api/conversations').length).toBeGreaterThan(boundListReads);
@ -178,16 +226,16 @@ test.describe('chat composer projects', () => {
const context = main.locator('.chat-composer-context');
const project = context.getByRole('combobox').filter({ hasText: PROJECT.name });
const input = main.getByRole('textbox', { name: label('chat.composerLabel', '对话内容') });
const headerProject = main.locator('.chat-header-tags .semi-tag').filter({ hasText: new RegExp(`${PROJECT.name}|${PROJECT.id.slice(0, 8)}`) });
const projectGroup = main.locator('.chat-sidebar').getByRole('button', { name: PROJECT.name + ' 1', exact: true });
await expect(project).toHaveText(PROJECT.name);
await expect(headerProject).toBeVisible();
await expect(projectGroup).toHaveAttribute('aria-expanded', 'true');
await input.fill(draft);
await project.click();
await page.getByRole('listbox').getByText(label('chat.noProject', '不绑定项目'), { exact: true }).click();
await page.getByRole('listbox').getByText(label('chat.defaultWorkspace', '默认工作区'), { exact: true }).click();
await expect(page.getByText('fixture 项目保存失败', { exact: false })).toBeVisible();
await expect(project).toBeEnabled();
await expect(project).toHaveText(PROJECT.name);
await expect(headerProject).toBeVisible();
await expect(projectGroup).toHaveAttribute('aria-expanded', 'true');
await expect(input).toHaveValue(draft);
await expect(main.getByRole('button', { name: /发送$/ })).toBeEnabled();
expect(mockApi.writes().map(({ method, path, body }) => ({ method, path, body }))).toEqual([
@ -210,7 +258,7 @@ test.describe('chat composer projects', () => {
await expect(page.getByRole('listbox').getByText(label(key), { exact: true })).toBeVisible();
}
await page.getByRole('listbox').getByText(label('chat.agentModePiSingle'), { exact: true }).click();
await context.getByRole('combobox').filter({ hasText: label('chat.noProject', '不绑定项目') }).click();
await context.getByRole('combobox').filter({ hasText: label('chat.defaultWorkspace', '默认工作区') }).click();
await page.getByRole('listbox').getByText(PROJECT.name, { exact: true }).click();
await expect(context.getByRole('combobox').filter({ hasText: PROJECT.name })).toBeVisible();
await expect(input).toHaveValue(message);
@ -226,7 +274,7 @@ test.describe('chat composer projects', () => {
});
});
test.describe('chat session settings', () => {
test.describe('chat composer settings', () => {
test.use({ appPermissions: [...UI_PERMISSIONS, 'hitl:write'] });
test('restores legacy model preferences, saves changes, and sends them with a new message', async ({ page, mockApi }) => {
@ -234,7 +282,7 @@ test.describe('chat session settings', () => {
mockApi.respond('GET', '/api/config', { json: { ai: {
default_channel: 'demo-primary',
channels: {
'demo-primary': { name: '示例通道 A', model: 'fixture-a' },
'demo-primary': { name: '示例通道 A', model: 'fixture-a', base_url: 'https://api.deepseek.com' },
'demo-backup': { name: '示例通道 B', model: 'fixture-b' }
}
} } });
@ -251,31 +299,35 @@ test.describe('chat session settings', () => {
});
await page.reload();
await ready(page);
const openSettings = main.getByRole('button', { name: label('chat.sessionSettingsTitle'), exact: true });
await openSettings.click();
const settings = page.getByRole('dialog').filter({ hasText: label('chat.sessionSettingsTitle') });
const channel = settings.getByRole('combobox', { name: label('chat.aiChannelLabel') });
const mode = settings.getByRole('combobox', { name: label('chat.reasoningModeLabel') });
const effort = settings.getByRole('combobox', { name: label('chat.reasoningEffortLabel') });
const openModel = main.getByRole('button', { name: label('chat.modelSettingsAria'), exact: true });
const popover = page.locator('.chat-model-popover');
const channel = popover.getByRole('combobox', { name: label('chat.aiChannelLabel') });
const effort = popover.getByRole('slider', { name: label('chat.reasoningEffortLabel') });
const mode = popover.getByRole('button', { name: label('chat.reasoningModeLabel') });
const menu = page.locator('.chat-reasoning-mode-menu');
await openModel.click();
await expect(channel).toHaveText('示例通道 B');
await expect(effort).toContainText('low');
await expect(effort).toHaveAttribute('aria-valuenow', '1');
await channel.click();
await expect(page.getByRole('option', { name: `${label('chat.aiChannelDefault')} · 示例通道 A` })).toBeVisible();
await page.getByRole('listbox').getByText('示例通道 A', { exact: true }).click();
await mode.click();
await page.getByRole('listbox').getByText(label('chat.reasoningModeOff'), { exact: true }).click();
await expect(effort).toBeDisabled();
await menu.getByRole('menuitem', { name: label('chat.reasoningModeOff') }).click();
await expect(effort).toHaveAttribute('aria-disabled', 'true');
await mode.click();
await page.getByRole('listbox').getByText(label('chat.reasoningModeOn'), { exact: true }).click();
await effort.click();
await page.getByRole('listbox').getByText('medium', { exact: true }).click();
await expect(effort).toContainText('medium');
await expect.poll(async () => (await settings.boundingBox())?.width).toBeLessThanOrEqual(390);
await menu.getByRole('menuitem', { name: label('chat.reasoningModeOn') }).click();
await effort.press('ArrowRight');
await expect(effort).toHaveAttribute('aria-valuenow', '2');
const mediumHint = label('chat.deepSeekEffortHint').replace('{{effort}}', label('chat.reasoningEffortLabels.medium'));
await expect(popover.getByText(mediumHint, { exact: true })).toBeVisible();
await page.reload();
await ready(page);
await openSettings.click();
await openModel.click();
await expect(channel).toHaveText('示例通道 A');
await expect(effort).toContainText('medium');
await expect(effort).toHaveAttribute('aria-valuenow', '2');
await main.locator('.chat-header-title').click();
await main.getByRole('button', { name: label('chat.hitlTitle'), exact: true }).click();
const settings = page.getByRole('dialog', { name: label('chat.hitlTitle') });
const collaborationMode = settings.getByRole('combobox', { name: label('chat.hitlModeLabel') });
await collaborationMode.click();
await page.getByRole('listbox').getByText(label('chat.hitlModeApproval'), { exact: true }).click();
@ -315,7 +367,7 @@ test.describe('chat session settings', () => {
});
await page.goto('/static/app/#/chat?conversation=' + CONVERSATION.id);
const main = await ready(page);
const openSettings = main.getByRole('button', { name: label('chat.sessionSettingsTitle'), exact: true });
const openSettings = main.getByRole('button', { name: label('chat.hitlTitle'), exact: true });
const settings = page.getByRole('dialog');
await openSettings.click();
const mode = settings.getByRole('combobox', { name: label('chat.hitlModeLabel') });
@ -387,7 +439,7 @@ test.describe('chat session settings', () => {
defaultMode: 'approval', defaultReviewer: 'audit_agent', defaultTimeoutSeconds: 180, conversationHumanApproval: true
} });
const main = await visit(page, 'chat');
const settingsButton = main.getByRole('button', { name: label('chat.sessionSettingsTitle'), exact: true });
const settingsButton = main.getByRole('button', { name: label('chat.hitlTitle'), exact: true });
await settingsButton.click();
const settings = page.getByRole('dialog');
const auditAgent = settings.getByRole('radio', { name: label('chat.hitlReviewerAgent') });
@ -422,7 +474,7 @@ test.describe('chat session settings', () => {
mockApi.fail('PUT', '/api/hitl/config', 'fixture 保存失败');
await page.goto('/static/app/#/chat?conversation=' + CONVERSATION.id);
const main = await ready(page);
await main.getByRole('button', { name: label('chat.sessionSettingsTitle'), exact: true }).click();
await main.getByRole('button', { name: label('chat.hitlTitle'), exact: true }).click();
const settings = page.getByRole('dialog');
const mode = settings.getByRole('combobox', { name: label('chat.hitlModeLabel') });
await expect(mode).toHaveText(label('chat.hitlModeOff'));
@ -800,7 +852,7 @@ test.describe('chat session settings', () => {
}]);
});
test('composer HITL entry saves an existing conversation and shares the full header settings', async ({ page, mockApi }) => {
test('composer HITL entry saves an existing conversation and restores its configuration', async ({ page, mockApi }) => {
const conversation = mockEmptyConversation(mockApi, PROJECT.id);
let hitl = {
enabled: true, mode: 'approval', reviewer: 'human',
@ -833,13 +885,7 @@ test.describe('chat session settings', () => {
await expect(settings.getByRole('status')).toHaveText(label('chat.hitlApplyOkSync'));
await settings.locator('button.semi-sidesheet-close').click();
await main.locator('.chat-header').getByRole('button', { name: label('chat.sessionSettingsTitle'), exact: true }).click();
const fullSettings = page.getByRole('dialog').filter({ hasText: label('chat.sessionSettingsTitle') });
for (const key of ['chat.aiChannelLabel', 'chat.reasoningModeLabel', 'chat.reasoningEffortLabel']) {
await expect(fullSettings.getByRole('combobox', { name: label(key), exact: true })).toBeVisible();
}
await expect(fullSettings.getByRole('combobox', { name: label('chat.hitlModeLabel'), exact: true })).toHaveText(label('chat.hitlModeReviewEdit'));
await fullSettings.locator('button.semi-sidesheet-close').click();
await expect(main.locator('.chat-header').getByRole('button', { name: label('chat.sessionSettingsTitle'), exact: true })).toHaveCount(0);
await openHitl.click();
await expect(mode).toHaveText(label('chat.hitlModeReviewEdit'));
await settings.locator('button.semi-sidesheet-close').click();
@ -962,7 +1008,7 @@ test.describe('running-status stop permission', () => {
test('switching conversation hides the previous approval and keeps each draft separate', async ({ page, mockApi }) => {
const second = { ...CONVERSATION, id: 'fixture-conversation-other', title: '另一个示例会话' };
const item = { id: 'fixture-approval', toolName: 'fixture-read-only-request', conversationId: CONVERSATION.id };
mockApi.respond('GET', '/api/conversations', { json: { conversations: [CONVERSATION, second] } });
mockApi.respond('GET', '/api/conversations', (_, url) => ({ json: conversationListFixture([CONVERSATION, second], url) }));
mockApi.respond('GET', '/api/conversations/' + second.id, { json: second });
mockApi.respond('GET', '/api/conversations/' + second.id + '/plan-tasks', { json: { tasks: [], total: 0 } });
let release;

View File

@ -1,6 +1,6 @@
import { readFileSync } from 'node:fs';
import {
test, expect, visit, ready, screenshot, label,
test, expect, visit, ready, screenshot, label, conversationListFixture,
READ_PERMISSIONS, UI_PERMISSIONS, PROJECT, FACT, VULNERABILITY, ASSESSMENT,
CONVERSATION, STREAM_REPLY, APP_VERSION
} from './fixtures.mjs';
@ -438,7 +438,7 @@ for (const uploadFails of [false, true]) {
}
for (const width of [1440, 1024, 390]) {
test(`chat: header spacing and session settings stay usable at ${width}px`, async ({ page, mockApi }, testInfo) => {
test(`chat: header spacing and composer settings stay usable at ${width}px`, async ({ page, mockApi }, testInfo) => {
await page.setViewportSize({ width, height: 900 });
const longTitle = '用于验证对话页标题换行与操作区布局的长会话名称'.repeat(4);
mockApi.respond('GET', `/api/conversations/${CONVERSATION.id}`, { json: { ...CONVERSATION, title: longTitle, projectId: PROJECT.id } });
@ -454,11 +454,12 @@ for (const width of [1440, 1024, 390]) {
const main = await visit(page, stored ? `chat?conversation=${CONVERSATION.id}` : 'chat');
const header = main.locator('.chat-header');
const title = header.locator('.chat-header-title');
const settingsButton = button(header, label('chat.sessionSettingsTitle', '会话设置'));
const composer = main.locator('.chat-composer');
const input = composer.getByRole('textbox', { name: label('chat.composerLabel', '对话内容') });
await expect(title).toHaveText(stored ? longTitle : label('chat.newChat', '新对话'));
await expect(settingsButton).toBeInViewport({ ratio: 1 });
await expect(button(header, label('chat.sessionSettingsTitle'))).toHaveCount(0);
await expect(button(header, label('chat.tokenUsage', 'Token 用量'))).toHaveCount(0);
await expect(button(header, label('chat.refreshConversation'))).toHaveCount(stored ? 1 : 0);
await expect(button(composer, label('chat.sessionSettingsTitle', '会话设置'))).toHaveCount(0);
const [workspaceBox, titleBox, textBox, actionsBox] = await Promise.all(
[main.locator('.chat-main'), title, header.locator('.chat-header-main'), header.locator('.chat-header-actions')]
@ -474,7 +475,10 @@ for (const width of [1440, 1024, 390]) {
const context = composer.locator('.chat-composer-context');
await expect(context.getByRole('combobox')).toHaveCount(2);
const project = context.locator('.chat-composer-project');
await expect(project).toHaveText(stored ? PROJECT.name : label('chat.noProject', '不绑定项目'));
await expect(project).toHaveText(stored ? PROJECT.name : label('chat.defaultWorkspace', '默认工作区'));
const contextBox = await context.boundingBox();
const projectBounds = await project.boundingBox();
expect(projectBounds.x + projectBounds.width).toBeLessThan(contextBox.x + contextBox.width - 16);
const box = await composer.locator('.chat-composer-box').boundingBox();
for (const control of await context.getByRole('combobox').all()) {
await expect(control).toBeInViewport({ ratio: 1 });
@ -505,9 +509,9 @@ for (const width of [1440, 1024, 390]) {
await expect(modelPopover).not.toBeVisible();
await input.fill('保留会话草稿');
await settingsButton.click();
const settings = page.getByRole('dialog').filter({ hasText: label('chat.sessionSettingsTitle', '会话设置') });
await expect(settings.getByRole('combobox', { name: label('chat.reasoningModeLabel') })).toBeVisible();
await hitl.click();
const settings = page.getByRole('dialog').filter({ hasText: label('chat.hitlTitle') });
await expect(settings.getByRole('combobox', { name: label('chat.hitlModeLabel') })).toBeVisible();
await settings.locator('button.semi-sidesheet-close').click();
await expect(settings).not.toBeVisible();
await expect(input).toHaveValue('保留会话草稿');
@ -611,11 +615,11 @@ for (const width of [1440, 390]) {
}
}
test.describe('chat: session settings permission boundary', () => {
test.describe('chat: composer settings permission boundary', () => {
test.use({ appPermissions: READ_PERMISSIONS.filter(permission => !['config:read', 'hitl:read'].includes(permission)) });
test('hides session settings without configuration, approval or execution access', async ({ page, mockApi }) => {
test('disables the approval shortcut without approval access', async ({ page, mockApi }) => {
const main = await visit(page, 'chat');
await expect(button(main, label('chat.sessionSettingsTitle', '会话设置'))).toHaveCount(0);
await expect(button(main, label('chat.hitlTitle'))).toBeDisabled();
expect(mockApi.writes()).toEqual([]);
});
});
@ -661,7 +665,7 @@ test('chat: create a project from the composer and select it for the current dra
const main = await visit(page, 'chat');
const composer = main.locator('.chat-composer');
const input = composer.getByRole('textbox', { name: label('chat.composerLabel', '对话内容') });
const projectSelect = composer.getByRole('combobox').filter({ hasText: label('chat.noProject', '不绑定项目') });
const projectSelect = composer.getByRole('combobox').filter({ hasText: label('chat.defaultWorkspace', '默认工作区') });
const createOption = page.getByRole('option').filter({ hasText: `+ ${label('projects.newProject', '新建项目')}` });
const dialog = page.getByRole('dialog', { name: label('projects.modalNewTitle', '新建项目') });
@ -700,7 +704,7 @@ test.describe('chat: read-only permissions', () => {
await expect(main.getByText(label('chat.noWritePermission', '当前账号没有对话写入权限(chat:write),发送已禁用。'), { exact: true })).toBeVisible();
await readsCompleted(mockApi, ['/api/projects', '/api/conversations']);
await expect(button(main, label('chat.batchManage', '批量管理'))).toHaveCount(0);
await expect(main.locator('.chat-composer-context').getByRole('combobox').filter({ hasText: label('chat.noProject', '不绑定项目') })).toBeDisabled();
await expect(main.locator('.chat-composer-context').getByRole('combobox').filter({ hasText: label('chat.defaultWorkspace', '默认工作区') })).toBeDisabled();
await expect(main.locator('.chat-composer-mode')).toBeDisabled();
// Send real keyboard events, without force-enabling a disabled application control.
await main.locator('.chat-header-title').click();
@ -777,19 +781,18 @@ test.describe('chat: batch selection', () => {
...CONVERSATION,
id: `fixture-batch-${index + 1}`,
title: `批量示例 ${String(index + 1).padStart(2, '0')}`,
projectId: index % 2 ? PROJECT.id : ''
projectId: ''
}));
const projectConversations = conversations.slice(0, 21).map((item, index) => ({
...item,
id: 'fixture-project-chat-' + (index + 1),
title: '项目示例 ' + String(index + 1).padStart(2, '0'),
projectId: PROJECT.id
}));
test.beforeEach(async ({ mockApi }) => {
let remaining = [...conversations];
mockApi.respond('GET', '/api/conversations', (_, url) => {
const search = url.searchParams.get('search') || '';
const project = url.searchParams.get('project_id') || '';
const filtered = remaining.filter(item => item.title.includes(search) && (!project || item.projectId === project));
const offset = Number(url.searchParams.get('offset') || 0);
const limit = Number(url.searchParams.get('limit') || 20);
return { json: { conversations: filtered.slice(offset, offset + limit), total: filtered.length } };
});
let remaining = [...conversations, ...projectConversations];
mockApi.respond('GET', '/api/conversations', (_, url) => ({ json: conversationListFixture(remaining, url) }));
for (const item of conversations) {
mockApi.respond('DELETE', `/api/conversations/${item.id}`, () => {
remaining = remaining.filter(row => row.id !== item.id);
@ -849,6 +852,28 @@ test.describe('chat: batch selection', () => {
});
}
test('keeps default workspace and project conversations in their own collapsible pages', async ({ page }) => {
const main = await visit(page, 'chat');
const sidebar = main.locator('.chat-sidebar-inner');
const workspace = button(sidebar, label('chat.defaultWorkspace') + ' 23');
const project = button(sidebar, PROJECT.name + ' 21');
await expect(workspace).toHaveAttribute('aria-expanded', 'true');
await expect(project).toHaveAttribute('aria-expanded', 'false');
await expect(sidebar.getByText('批量示例 01', { exact: true })).toBeVisible();
await project.click();
await expect(workspace).toHaveAttribute('aria-expanded', 'false');
await expect(project).toHaveAttribute('aria-expanded', 'true');
await expect(sidebar.getByText('批量示例 01', { exact: true })).toHaveCount(0);
await expect(sidebar.getByText('项目示例 01', { exact: true })).toBeVisible();
await sidebar.getByRole('button', { name: 'Next', exact: true }).click();
await expect(sidebar.getByText('项目示例 21', { exact: true })).toBeVisible();
await expect(sidebar.getByText(PROJECT.id.slice(0, 8), { exact: true })).toHaveCount(0);
await project.click();
await expect(sidebar.locator('.chat-conv-item')).toHaveCount(0);
await workspace.click();
await expect(sidebar.getByText('批量示例 01', { exact: true })).toBeVisible();
});
test('resets selections on pagination, search, project filtering and cancel', async ({ page, mockApi }) => {
await visit(page, 'chat');
const sidebar = page.locator('.chat-sidebar-inner:visible');
@ -873,6 +898,8 @@ test.describe('chat: batch selection', () => {
await bar.getByText(label('chat.selectPage'), { exact: true }).click();
await expect(bar).toContainText('已选 4');
await sidebar.getByRole('textbox', { name: label('chat.searchHistory') }).fill('项目示例 2');
await expect(button(sidebar, PROJECT.name + ' 2')).toBeVisible();
await sidebar.getByRole('combobox').filter({ hasText: label('chat.filterAllProjects', '全部项目') }).click();
await page.getByRole('option').filter({ hasText: PROJECT.name }).click();
await expect(bar).toHaveCount(0);

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{At as r,Dt as i,F as a,H as o,L as s,M as c,W as l,i as u,lt as d,ot as f,st as p}from"./semi-BxhBcqdj.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-DZWb6CUM.js";var k=e(t(),1),A=e(n(),1),{Text:j}=l;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),l=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(a,{children:[(0,A.jsx)(s,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(s,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(d,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(a,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(a,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(c,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(c,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(a,{children:[(0,A.jsx)(s,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(s,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(i,{}),onClick:()=>L({record:t,form:{}})}),l&&(0,A.jsx)(s,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(r,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(o,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(u,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(u.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(u.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(u.Input,{field:`description`,label:`描述`}),(0,A.jsx)(u.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(u.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(u.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{Et as r,F as i,H as a,L as o,M as s,W as c,i as l,kt as u,lt as d,ot as f,st as p}from"./semi-CYW2cRsN.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-BQJID8wL.js";var k=e(t(),1),A=e(n(),1),{Text:j}=c;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),c=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(i,{children:[(0,A.jsx)(o,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(o,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(d,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(i,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(i,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(s,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(s,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(i,{children:[(0,A.jsx)(o,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(o,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(r,{}),onClick:()=>L({record:t,form:{}})}),c&&(0,A.jsx)(o,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(u,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(a,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(l,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(l.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(l.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(l.Input,{field:`description`,label:`描述`}),(0,A.jsx)(l.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(l.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-BxhBcqdj.js";import{E as i,P as a,k as o}from"./index-DZWb6CUM.js";import"./c2-shared-CZQii_1n.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=r,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:r,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(t,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-CYW2cRsN.js";import{E as i,P as a,k as o}from"./index-BQJID8wL.js";import"./c2-shared-CMvsAx2-.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=r,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:r,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(t,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};

View File

@ -1 +1 @@
import{I as e,L as t}from"./index-DZWb6CUM.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};
import{I as e,L as t}from"./index-BQJID8wL.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{t}from"./react-QV7DAAIx.js";import{Ht as n,St as r,Tt as i,Wt as a,X as o,Xt as s,_t as c,ht as l,it as u,ot as d,wt as f,xt as p}from"./semi-BxhBcqdj.js";var m=e(t(),1),h={target:r,infra:u,auth:c,finding:d,chain:n,exploit:a,poc:o,vulnerability:s,missing:p,goal:f,step:n,fact:i,receipt:o,observation:d,memory:l,digest:i,guidance:a};function g({type:e}){let t=h[e]||i;return(0,m.jsx)(`span`,{className:`graph-node-icon`,"aria-hidden":`true`,children:(0,m.jsx)(t,{size:`small`})})}function _({id:e,title:t,type:n,category:r,color:i,factKey:a,boundary:o,ports:s=[],selected:c,card:l,onSelect:u}){let{density:d,box:f}=l,p=d===`detail`,h=Math.min(Math.max(f.width/216,1),1.6);return(0,m.jsxs)(`button`,{type:`button`,className:`graph-node graph-node--${d}`,title:t,"aria-label":t,"aria-pressed":c,"data-root":n===`goal`||n===`target`||void 0,"data-boundary":o||void 0,"data-wrap":d===`standard`&&f.height>=50||void 0,style:{...f,"--graph-node-color":i,"--graph-node-text-scale":h},onClick:()=>u(e),children:[(0,m.jsxs)(`span`,{className:`graph-node-content`,children:[d!==`compact`&&(0,m.jsxs)(`span`,{className:`graph-node-kind`,children:[(0,m.jsx)(g,{type:n}),(0,m.jsx)(`span`,{children:r})]}),(0,m.jsx)(`span`,{className:`graph-node-title`,dir:`auto`,children:t}),p&&f.height>=84&&a&&t!==a&&(0,m.jsx)(`span`,{className:`graph-node-keyline`,dir:`auto`,children:a})]}),p&&[...s].map(e=>(0,m.jsx)(`span`,{className:`graph-node-port is-${e}`,"aria-hidden":`true`},e))]})}function v(e,{anchorId:t,allowCompact:n=()=>!0}={}){let r=e.width(),i=e.height(),a=216*e.zoom(),o=98*e.zoom(),s=o>=68?`detail`:o>=36?`standard`:`compact`,c=[];for(let l of e.nodes(`:visible`)){let e=l.id();if(l.hasClass(`dim`)||s===`compact`&&e!==t&&(a<49||!n(l)))continue;let{x:u,y:d}=l.renderedPosition(),f=u-a/2,p=d-o/2;if(f+a<=0||f>=r||p+o<=0||p>=i)continue;let m={left:f,top:p,width:a,height:o};e===t&&a<49&&(m={left:Math.max(3,f),top:d-13,width:Math.min(108,r-Math.max(3,f)),height:26}),c.push({id:e,density:s,box:m})}return c}function y(e,t,n={x:e.width()/2,y:e.height()/2}){e.zoom({level:e.zoom()*t,renderedPosition:n})}function b(e,t){let n=n=>{if(!n.deltaY)return;n.preventDefault();let{left:r,top:i,height:a}=e.getBoundingClientRect(),o=n.deltaMode===1?33:n.deltaMode===2?a:1;y(t,10**(-n.deltaY*o/1250),{x:n.clientX-r,y:n.clientY-i})};return e.addEventListener(`wheel`,n,{passive:!1}),()=>e.removeEventListener(`wheel`,n)}function x(e,t){let n=new Map,r=new Set;for(let i of e){if(t(i.target)||n.has(i.target))continue;let e=i.source;for(;e&&e!==i.target;)e=n.get(e);e!==i.target&&(n.set(i.target,i.source),r.add(i))}return{parents:n,parentEdges:r}}export{v as a,b as i,_ as n,y as o,g as r,x as t};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{t}from"./react-QV7DAAIx.js";import{Ct as n,Ut as r,Vt as i,X as a,Yt as o,_t as s,bt as c,ht as l,it as u,ot as d,wt as f,xt as p}from"./semi-CYW2cRsN.js";var m=e(t(),1),h={target:p,infra:u,auth:s,finding:d,chain:i,exploit:r,poc:a,vulnerability:o,missing:c,goal:n,step:i,fact:f,receipt:a,observation:d,memory:l,digest:f,guidance:r};function g({type:e}){let t=h[e]||f;return(0,m.jsx)(`span`,{className:`graph-node-icon`,"aria-hidden":`true`,children:(0,m.jsx)(t,{size:`small`})})}function _({id:e,title:t,type:n,category:r,color:i,factKey:a,boundary:o,ports:s=[],selected:c,card:l,onSelect:u}){let{density:d,box:f}=l,p=d===`detail`,h=Math.min(Math.max(f.width/216,1),1.6);return(0,m.jsxs)(`button`,{type:`button`,className:`graph-node graph-node--${d}`,title:t,"aria-label":t,"aria-pressed":c,"data-root":n===`goal`||n===`target`||void 0,"data-boundary":o||void 0,"data-wrap":d===`standard`&&f.height>=50||void 0,style:{...f,"--graph-node-color":i,"--graph-node-text-scale":h},onClick:()=>u(e),children:[(0,m.jsxs)(`span`,{className:`graph-node-content`,children:[d!==`compact`&&(0,m.jsxs)(`span`,{className:`graph-node-kind`,children:[(0,m.jsx)(g,{type:n}),(0,m.jsx)(`span`,{children:r})]}),(0,m.jsx)(`span`,{className:`graph-node-title`,dir:`auto`,children:t}),p&&f.height>=84&&a&&t!==a&&(0,m.jsx)(`span`,{className:`graph-node-keyline`,dir:`auto`,children:a})]}),p&&[...s].map(e=>(0,m.jsx)(`span`,{className:`graph-node-port is-${e}`,"aria-hidden":`true`},e))]})}function v(e,{anchorId:t,allowCompact:n=()=>!0}={}){let r=e.width(),i=e.height(),a=216*e.zoom(),o=98*e.zoom(),s=o>=68?`detail`:o>=36?`standard`:`compact`,c=[];for(let l of e.nodes(`:visible`)){let e=l.id();if(l.hasClass(`dim`)||s===`compact`&&e!==t&&(a<49||!n(l)))continue;let{x:u,y:d}=l.renderedPosition(),f=u-a/2,p=d-o/2;if(f+a<=0||f>=r||p+o<=0||p>=i)continue;let m={left:f,top:p,width:a,height:o};e===t&&a<49&&(m={left:Math.max(3,f),top:d-13,width:Math.min(108,r-Math.max(3,f)),height:26}),c.push({id:e,density:s,box:m})}return c}function y(e,t,n={x:e.width()/2,y:e.height()/2}){e.zoom({level:e.zoom()*t,renderedPosition:n})}function b(e,t){let n=n=>{if(!n.deltaY)return;n.preventDefault();let{left:r,top:i,height:a}=e.getBoundingClientRect(),o=n.deltaMode===1?33:n.deltaMode===2?a:1;y(t,10**(-n.deltaY*o/1250),{x:n.clientX-r,y:n.clientY-i})};return e.addEventListener(`wheel`,n,{passive:!1}),()=>e.removeEventListener(`wheel`,n)}function x(e,t){let n=new Map,r=new Set;for(let i of e){if(t(i.target)||n.has(i.target))continue;let e=i.source;for(;e&&e!==i.target;)e=n.get(e);e!==i.target&&(n.set(i.target,i.source),r.add(i))}return{parents:n,parentEdges:r}}export{v as a,b as i,_ as n,y as o,g as r,x as t};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{At as r,F as i,H as a,L as o,M as s,W as c,ot as l,st as u}from"./semi-BxhBcqdj.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-DZWb6CUM.js";var T=e(t(),1),E=e(n(),1),{Text:D}=c;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[c,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:c||void 0,limit:k}),[c,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(o,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(s,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(i,{children:[(0,E.jsx)(o,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(o,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(r,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(i,{children:[(0,E.jsx)(a,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:c,onChange:O,style:{width:260}}),(0,E.jsx)(a,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,W as s,kt as c,ot as l,st as u}from"./semi-CYW2cRsN.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-BQJID8wL.js";var T=e(t(),1),E=e(n(),1),{Text:D}=s;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[s,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:s||void 0,limit:k}),[s,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(a,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(o,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(r,{children:[(0,E.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(c,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(r,{children:[(0,E.jsx)(i,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:s,onChange:O,style:{width:260}}),(0,E.jsx)(i,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{W as r,i}from"./semi-BxhBcqdj.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-DZWb6CUM.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=o(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await a.put(`/projects/${t.id}`,n):await a.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{W as r,i}from"./semi-CYW2cRsN.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-BQJID8wL.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=o(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await a.put(`/projects/${t.id}`,n):await a.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{At as r,Dt as i,F as a,H as o,L as s,M as c,W as l,i as u,lt as d,ot as f,st as p}from"./semi-BxhBcqdj.js";import{F as m,I as h,P as g,a as _,b as v,c as y,l as b,m as x,p as S,s as C,x as w,y as T}from"./index-DZWb6CUM.js";var E=e(t(),1),D=e(n(),1),{Text:O}=l;function k(){let e=g(),{hasPermission:t}=m(),n=t(`roles:write`),l=t(`roles:delete`),[k,A]=(0,E.useState)(``),[j,M]=(0,E.useState)(null),[N,P]=(0,E.useState)(!1),F=_(()=>h.get(`/roles`),[]),I=(Array.isArray(F.data?.roles)?F.data.roles:[]).filter(e=>{if(!k)return!0;let t=k.toLowerCase();return[e.name,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),L=async()=>{let e=await j.form.validate();P(!0);try{let t={name:e.name.trim(),description:e.description?.trim()||``,user_prompt:e.user_prompt||``,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean),enabled:e.enabled!==!1},n=j.role?.name;n&&n!==t.name?(await h.post(`/roles`,t),await h.del(`/roles/${encodeURIComponent(n)}`)):n?await h.put(`/roles/${encodeURIComponent(n)}`,t):await h.post(`/roles`,t),w(`角色已保存`),M(null),F.reload()}catch(e){v(e,`保存角色失败`)}finally{P(!1)}},R=e=>T({title:`删除角色「${e.name}」?`,content:`已绑定该角色的对话将失去对应提示词与工具配置。`,onOk:async()=>{await h.del(`/roles/${encodeURIComponent(e.name)}`),w(`已删除`),F.reload()}});return(0,D.jsxs)(`div`,{children:[(0,D.jsx)(S,{title:e(`roles.title`,null,`角色管理`),description:`角色定义对话的系统提示词、可用工具与绑定工作流。`,extra:(0,D.jsxs)(a,{children:[(0,D.jsx)(s,{icon:(0,D.jsx)(p,{}),onClick:()=>F.reload(),loading:F.loading,children:`刷新`}),n&&(0,D.jsx)(s,{theme:`solid`,type:`primary`,icon:(0,D.jsx)(d,{}),onClick:()=>M({role:null,form:{}}),children:`新建角色`})]})}),(0,D.jsxs)(x,{title:`角色(${I.length})`,children:[(0,D.jsx)(b,{error:F.error,onRetry:()=>F.reload()}),(0,D.jsx)(C,{columns:[{title:`角色`,dataIndex:`name`,render:(e,t)=>(0,D.jsxs)(a,{vertical:!0,spacing:0,align:`start`,children:[(0,D.jsxs)(a,{children:[(0,D.jsx)(O,{strong:!0,children:e}),t.enabled===!1&&(0,D.jsx)(c,{size:`small`,color:`grey`,children:`已停用`})]}),(0,D.jsx)(O,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:t.description||`—`})]})},{title:`工具`,dataIndex:`tools`,width:260,render:e=>Array.isArray(e)&&e.length?(0,D.jsxs)(a,{wrap:!0,spacing:4,children:[e.slice(0,4).map(e=>(0,D.jsx)(c,{size:`small`,children:e},e)),e.length>4&&(0,D.jsxs)(O,{type:`tertiary`,children:[`+`,e.length-4]})]}):(0,D.jsx)(O,{type:`tertiary`,children:`未绑定`})},{title:`工作流`,dataIndex:`workflow_id`,width:160,render:e=>e||`—`},{title:`操作`,width:150,render:(e,t)=>(0,D.jsxs)(a,{children:[n&&(0,D.jsx)(s,{size:`small`,theme:`borderless`,icon:(0,D.jsx)(i,{}),onClick:()=>M({role:t,form:{}}),children:`编辑`}),l&&(0,D.jsx)(s,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,D.jsx)(r,{}),onClick:()=>R(t)})]})}],dataSource:I,rowKey:`name`,loading:F.loading,pagination:{pageSize:20},toolbar:(0,D.jsx)(o,{prefix:(0,D.jsx)(f,{}),value:k,onChange:A,placeholder:`搜索角色名称`,style:{width:260}})})]}),(0,D.jsx)(y,{title:j?.role?`编辑角色`:`新建角色`,visible:!!j,onCancel:()=>M(null),onOk:L,confirmLoading:N,width:760,children:(0,D.jsxs)(u,{getFormApi:e=>M(t=>t&&{...t,form:e}),initValues:j?.role?{name:j.role.name,description:j.role.description,user_prompt:j.role.user_prompt,tools:Array.isArray(j.role.tools)?j.role.tools.join(`, `):``,enabled:j.role.enabled!==!1}:{enabled:!0},children:[(0,D.jsx)(u.Input,{field:`name`,label:`角色名称`,rules:[{required:!0,message:`请输入角色名称`}]}),(0,D.jsx)(u.Input,{field:`description`,label:`描述`}),(0,D.jsx)(u.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::toolName`}),(0,D.jsx)(u.TextArea,{field:`user_prompt`,label:`用户提示词(追加到用户消息前)`,autosize:{minRows:6,maxRows:18}}),(0,D.jsx)(u.Slot,{label:`启用`,children:(0,D.jsx)(u.Switch,{field:`enabled`})})]})},j?.role?.name||`new-role`)]})}export{k as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{Et as r,F as i,H as a,L as o,M as s,W as c,i as l,kt as u,lt as d,ot as f,st as p}from"./semi-CYW2cRsN.js";import{F as m,I as h,P as g,a as _,b as v,c as y,l as b,m as x,p as S,s as C,x as w,y as T}from"./index-BQJID8wL.js";var E=e(t(),1),D=e(n(),1),{Text:O}=c;function k(){let e=g(),{hasPermission:t}=m(),n=t(`roles:write`),c=t(`roles:delete`),[k,A]=(0,E.useState)(``),[j,M]=(0,E.useState)(null),[N,P]=(0,E.useState)(!1),F=_(()=>h.get(`/roles`),[]),I=(Array.isArray(F.data?.roles)?F.data.roles:[]).filter(e=>{if(!k)return!0;let t=k.toLowerCase();return[e.name,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),L=async()=>{let e=await j.form.validate();P(!0);try{let t={name:e.name.trim(),description:e.description?.trim()||``,user_prompt:e.user_prompt||``,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean),enabled:e.enabled!==!1},n=j.role?.name;n&&n!==t.name?(await h.post(`/roles`,t),await h.del(`/roles/${encodeURIComponent(n)}`)):n?await h.put(`/roles/${encodeURIComponent(n)}`,t):await h.post(`/roles`,t),w(`角色已保存`),M(null),F.reload()}catch(e){v(e,`保存角色失败`)}finally{P(!1)}},R=e=>T({title:`删除角色「${e.name}」?`,content:`已绑定该角色的对话将失去对应提示词与工具配置。`,onOk:async()=>{await h.del(`/roles/${encodeURIComponent(e.name)}`),w(`已删除`),F.reload()}});return(0,D.jsxs)(`div`,{children:[(0,D.jsx)(S,{title:e(`roles.title`,null,`角色管理`),description:`角色定义对话的系统提示词、可用工具与绑定工作流。`,extra:(0,D.jsxs)(i,{children:[(0,D.jsx)(o,{icon:(0,D.jsx)(p,{}),onClick:()=>F.reload(),loading:F.loading,children:`刷新`}),n&&(0,D.jsx)(o,{theme:`solid`,type:`primary`,icon:(0,D.jsx)(d,{}),onClick:()=>M({role:null,form:{}}),children:`新建角色`})]})}),(0,D.jsxs)(x,{title:`角色(${I.length})`,children:[(0,D.jsx)(b,{error:F.error,onRetry:()=>F.reload()}),(0,D.jsx)(C,{columns:[{title:`角色`,dataIndex:`name`,render:(e,t)=>(0,D.jsxs)(i,{vertical:!0,spacing:0,align:`start`,children:[(0,D.jsxs)(i,{children:[(0,D.jsx)(O,{strong:!0,children:e}),t.enabled===!1&&(0,D.jsx)(s,{size:`small`,color:`grey`,children:`已停用`})]}),(0,D.jsx)(O,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:t.description||`—`})]})},{title:`工具`,dataIndex:`tools`,width:260,render:e=>Array.isArray(e)&&e.length?(0,D.jsxs)(i,{wrap:!0,spacing:4,children:[e.slice(0,4).map(e=>(0,D.jsx)(s,{size:`small`,children:e},e)),e.length>4&&(0,D.jsxs)(O,{type:`tertiary`,children:[`+`,e.length-4]})]}):(0,D.jsx)(O,{type:`tertiary`,children:`未绑定`})},{title:`工作流`,dataIndex:`workflow_id`,width:160,render:e=>e||`—`},{title:`操作`,width:150,render:(e,t)=>(0,D.jsxs)(i,{children:[n&&(0,D.jsx)(o,{size:`small`,theme:`borderless`,icon:(0,D.jsx)(r,{}),onClick:()=>M({role:t,form:{}}),children:`编辑`}),c&&(0,D.jsx)(o,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,D.jsx)(u,{}),onClick:()=>R(t)})]})}],dataSource:I,rowKey:`name`,loading:F.loading,pagination:{pageSize:20},toolbar:(0,D.jsx)(a,{prefix:(0,D.jsx)(f,{}),value:k,onChange:A,placeholder:`搜索角色名称`,style:{width:260}})})]}),(0,D.jsx)(y,{title:j?.role?`编辑角色`:`新建角色`,visible:!!j,onCancel:()=>M(null),onOk:L,confirmLoading:N,width:760,children:(0,D.jsxs)(l,{getFormApi:e=>M(t=>t&&{...t,form:e}),initValues:j?.role?{name:j.role.name,description:j.role.description,user_prompt:j.role.user_prompt,tools:Array.isArray(j.role.tools)?j.role.tools.join(`, `):``,enabled:j.role.enabled!==!1}:{enabled:!0},children:[(0,D.jsx)(l.Input,{field:`name`,label:`角色名称`,rules:[{required:!0,message:`请输入角色名称`}]}),(0,D.jsx)(l.Input,{field:`description`,label:`描述`}),(0,D.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::toolName`}),(0,D.jsx)(l.TextArea,{field:`user_prompt`,label:`用户提示词(追加到用户消息前)`,autosize:{minRows:6,maxRows:18}}),(0,D.jsx)(l.Slot,{label:`启用`,children:(0,D.jsx)(l.Switch,{field:`enabled`})})]})},j?.role?.name||`new-role`)]})}export{k as default};

File diff suppressed because one or more lines are too long

View File

@ -1 +0,0 @@
.settings-page{flex-direction:column;min-width:0;display:flex}.settings-tabs .semi-tabs-content{min-width:0;padding-top:0}.settings-tabs .semi-tabs-pane{min-width:0}.settings-tabs .semi-tabs-bar-left{flex:0 0 156px;margin-inline-end:24px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab{text-align:start;border-radius:8px;margin-bottom:4px;padding:12px 16px;font-size:13px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab-active{background:var(--semi-color-primary-light-default)}.settings-tabs .semi-tabs-bar-top{margin-bottom:16px}.settings-tabs .semi-tabs-bar-top .semi-tabs-tab{font-size:13px}.settings-loading-block{padding:18px 4px}.settings-hint{color:var(--semi-color-text-2);font-size:12px;line-height:1.6;display:inline-block}.settings-mono{word-break:break-all;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12px}.settings-yaml-toolbar{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;margin-bottom:10px;display:flex}.settings-yaml-input .semi-input-textarea{-moz-tab-size:2;tab-size:2;min-height:420px;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12.5px;line-height:1.6}.settings-yaml-notice{margin-bottom:12px}.settings-schema{flex-direction:column;gap:14px;display:flex}.settings-schema-table{border-collapse:collapse;width:100%;font-size:12.5px}.settings-schema-table th,.settings-schema-table td{border-bottom:1px solid var(--semi-color-border);text-align:left;vertical-align:top;padding:8px 10px}.settings-schema-table th{color:var(--semi-color-text-2);font-weight:600}.settings-probe-form{grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px 16px;display:grid}.settings-field{flex-direction:column;gap:6px;min-width:0;display:flex}.settings-field-wide{grid-column:span 2}.settings-probe-actions{margin-top:14px}.settings-channel-panel .semi-card-header-wrapper{align-items:center;gap:8px}.settings-channel-notices{gap:8px;margin-top:14px;display:grid}.settings-probe-result{flex-direction:column;gap:10px;margin-top:12px;display:flex}.settings-model-tags{flex-wrap:wrap;gap:6px;max-height:190px;padding:2px;display:flex;overflow:auto}.settings-audit-model{border-top:1px solid var(--semi-color-border);margin-top:18px}.settings-probe-card{flex-direction:column;gap:8px;min-width:0;display:flex}.settings-probe-inline{grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;display:grid}.settings-disk{flex-direction:column;gap:6px;max-width:720px;margin-bottom:16px;display:flex}.settings-policy-grid{grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:12px 16px;margin-bottom:10px;display:grid}.settings-incoming{margin-top:12px}.settings-incoming ul{margin:6px 0 0;padding-left:18px;font-size:12.5px;line-height:1.8}.settings-update-steps{max-height:360px;margin-top:16px;padding-right:4px;overflow:auto}.settings-audit-filters{flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:12px;display:flex}.settings-audit-banner{margin-bottom:12px}.settings-audit-detail{flex-direction:column;gap:16px;display:flex}.settings-audit-message-block{border:1px solid var(--semi-color-border);background:var(--semi-color-fill-0);word-break:break-word;border-radius:8px;flex-direction:column;gap:4px;padding:10px 12px;display:flex}.settings-appearance-status{margin-top:12px}@media (max-width:900px){.settings-field-wide{grid-column:span 1}.settings-yaml-input .semi-input-textarea{min-height:300px}}@media (max-width:480px){.settings-channel-panel .semi-card-header-wrapper{flex-direction:column-reverse;align-items:stretch}.settings-channel-panel .semi-card-header-wrapper-title{margin-inline-start:0;margin-inline-end:0}}.settings-update-source-form{flex-direction:column;gap:8px;max-width:760px;display:flex}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
.settings-page{flex-direction:column;min-width:0;display:flex}.settings-tabs .semi-tabs-content{min-width:0;padding-top:0}.settings-tabs .semi-tabs-pane{min-width:0}.settings-tabs .semi-tabs-bar-left{flex:0 0 156px;margin-inline-end:24px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab{text-align:start;border-radius:8px;margin-bottom:4px;padding:12px 16px;font-size:13px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab-active{background:var(--semi-color-primary-light-default)}.settings-tabs .semi-tabs-bar-top{margin-bottom:16px}.settings-tabs .semi-tabs-bar-top .semi-tabs-tab{font-size:13px}.settings-loading-block{padding:18px 4px}.settings-token-filters{flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:14px;display:flex}.settings-token-conversation{width:280px;max-width:100%}.settings-hint{color:var(--semi-color-text-2);font-size:12px;line-height:1.6;display:inline-block}.settings-mono{word-break:break-all;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12px}.settings-yaml-toolbar{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;margin-bottom:10px;display:flex}.settings-yaml-input .semi-input-textarea{-moz-tab-size:2;tab-size:2;min-height:420px;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12.5px;line-height:1.6}.settings-yaml-notice{margin-bottom:12px}.settings-schema{flex-direction:column;gap:14px;display:flex}.settings-schema-table{border-collapse:collapse;width:100%;font-size:12.5px}.settings-schema-table th,.settings-schema-table td{border-bottom:1px solid var(--semi-color-border);text-align:left;vertical-align:top;padding:8px 10px}.settings-schema-table th{color:var(--semi-color-text-2);font-weight:600}.settings-probe-form{grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px 16px;display:grid}.settings-field{flex-direction:column;gap:6px;min-width:0;display:flex}.settings-field-wide{grid-column:span 2}.settings-probe-actions{margin-top:14px}.settings-channel-panel .semi-card-header-wrapper{align-items:center;gap:8px}.settings-channel-notices{gap:8px;margin-top:14px;display:grid}.settings-probe-result{flex-direction:column;gap:10px;margin-top:12px;display:flex}.settings-model-tags{flex-wrap:wrap;gap:6px;max-height:190px;padding:2px;display:flex;overflow:auto}.settings-audit-model{border-top:1px solid var(--semi-color-border);margin-top:18px}.settings-probe-card{flex-direction:column;gap:8px;min-width:0;display:flex}.settings-probe-inline{grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;display:grid}.settings-disk{flex-direction:column;gap:6px;max-width:720px;margin-bottom:16px;display:flex}.settings-policy-grid{grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:12px 16px;margin-bottom:10px;display:grid}.settings-incoming{margin-top:12px}.settings-incoming ul{margin:6px 0 0;padding-left:18px;font-size:12.5px;line-height:1.8}.settings-update-steps{max-height:360px;margin-top:16px;padding-right:4px;overflow:auto}.settings-audit-filters{flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:12px;display:flex}.settings-audit-banner{margin-bottom:12px}.settings-audit-detail{flex-direction:column;gap:16px;display:flex}.settings-audit-message-block{border:1px solid var(--semi-color-border);background:var(--semi-color-fill-0);word-break:break-word;border-radius:8px;flex-direction:column;gap:4px;padding:10px 12px;display:flex}.settings-appearance-status{margin-top:12px}@media (max-width:900px){.settings-field-wide{grid-column:span 1}.settings-yaml-input .semi-input-textarea{min-height:300px}}@media (max-width:480px){.settings-channel-panel .semi-card-header-wrapper{flex-direction:column-reverse;align-items:stretch}.settings-channel-panel .semi-card-header-wrapper-title{margin-inline-start:0;margin-inline-end:0}}.settings-update-source-form{flex-direction:column;gap:8px;max-width:760px;display:flex}

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{At as t,F as n,L as r,W as i,st as a}from"./semi-BxhBcqdj.js";import{D as o,F as s,I as c,O as l,P as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-DZWb6CUM.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=i;function S(){let e=u(),{hasPermission:i}=s(),y=i(`skills:delete`),S=f(()=>c.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await c.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await c.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(n,{children:[(0,b.jsx)(r,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(r,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:l(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,n)=>y&&Number(n.total_calls)>0?(0,b.jsx)(r,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(t,{}),onClick:()=>O(n.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r,kt as i,st as a}from"./semi-CYW2cRsN.js";import{D as o,F as s,I as c,O as l,P as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-BQJID8wL.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=r;function S(){let e=u(),{hasPermission:r}=s(),y=r(`skills:delete`),S=f(()=>c.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await c.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await c.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(t,{children:[(0,b.jsx)(n,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(n,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:l(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(n,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(i,{}),onClick:()=>O(t.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};

File diff suppressed because one or more lines are too long

View File

@ -18,10 +18,10 @@
} catch (error) { /* first paint fallback */ }
})();
</script>
<script type="module" crossorigin src="/static/app/assets/index-DZWb6CUM.js"></script>
<script type="module" crossorigin src="/static/app/assets/index-BQJID8wL.js"></script>
<link rel="modulepreload" crossorigin href="/static/app/assets/rolldown-runtime-WkwZ5CU-.js">
<link rel="modulepreload" crossorigin href="/static/app/assets/react-QV7DAAIx.js">
<link rel="modulepreload" crossorigin href="/static/app/assets/semi-BxhBcqdj.js">
<link rel="modulepreload" crossorigin href="/static/app/assets/semi-CYW2cRsN.js">
<link rel="stylesheet" crossorigin href="/static/app/assets/semi-BUXPdXzR.css">
<link rel="stylesheet" crossorigin href="/static/app/assets/index-BwdEm4YK.css">
</head>

View File

@ -277,6 +277,9 @@
"administration": "الإدارة"
},
"tokenUsageUI": {
"selectConversation": "ابحث عن محادثة واخترها",
"periodDays": "{{count}} يومًا",
"recentLimit": "أحدث {{count}} سجلًا",
"chartHint": "مرّر المؤشّر فوق شريط أو ركّز عليه لعرض الاستهلاك الدقيق",
"scopeProject": "المشروع الحالي",
"scopeAccessible": "المحادثات المتاحة",
@ -772,6 +775,16 @@
"generatedFromFact": "مُولّدة من حقيقة المشروع {{factKey}}"
},
"chat": {
"chooseWorkspace": "اختر مساحة عمل المحادثة",
"deepSeekEffortHint": "يستخدم DeepSeek المستوى العالي عند اختيار «{{effort}}».",
"reasoningOverrideBlocked": "تستخدم هذه القناة مستوى الاستدلال المحدد في إعدادات النظام.",
"defaultWorkspace": "مساحة العمل الافتراضية",
"boundProject": "مشروع مرتبط",
"refreshConversation": "تحديث المحادثة",
"refreshConversationList": "تحديث قائمة المحادثات",
"refreshConversationHint": "إعادة تحميل قائمة المحادثات والرسائل والموافقات المعلقة وخطة التنفيذ",
"planTasks": "خطة التنفيذ",
"planEmpty": "لا توجد خطة تنفيذ",
"taskSummary": "ملخص المهمة",
"toolExecBlocked": "تم حظر الأداة {{name}}",
"newChat": "محادثة جديدة",
@ -3065,7 +3078,7 @@
"maxCompletionTokensPlaceholder": "32768",
"maxCompletionTokensHint": "أقصى عدد للرموز (Tokens) في استجابة واحدة للنموذج. الافتراضي: 32768",
"openaiReasoningTitle": "إعدادات الاستدلال",
"openaiReasoningHint": "إعدادات الاستدلال الافتراضية لقناة الذكاء الاصطناعي هذه؛ ويمكن لإعدادات جلسة المحادثة تجاوزها.",
"openaiReasoningHint": "إعدادات الاستدلال الافتراضية لهذه القناة. يمكن تغييرها من خيارات النموذج في مربع كتابة المحادثة.",
"openaiReasoningProfile": "ملف تعريف الإرسال",
"openaiReasoningAllowClient": "السماح لصفحة المحادثة بتجاوز خيارات الاستدلال",
"fofaBaseUrlPlaceholder": "https://fofa.info/api/v1/search/all (اختياري)",

View File

@ -278,6 +278,9 @@
"administration": "Administration"
},
"tokenUsageUI": {
"selectConversation": "Search and select a conversation",
"periodDays": "{{count}} days",
"recentLimit": "Latest {{count}} records",
"chartHint": "Hover or focus a bar for exact usage",
"scopeProject": "Current project",
"scopeAccessible": "Accessible conversations",
@ -773,6 +776,16 @@
"generatedFromFact": "Generated from project fact {{factKey}}"
},
"chat": {
"chooseWorkspace": "Choose the conversation workspace",
"deepSeekEffortHint": "DeepSeek runs {{effort}} at High effort.",
"reasoningOverrideBlocked": "This channel uses the reasoning effort from system settings.",
"defaultWorkspace": "Default workspace",
"boundProject": "Linked project",
"refreshConversation": "Refresh conversation",
"refreshConversationList": "Refresh conversation list",
"refreshConversationHint": "Reload the conversation list, messages, pending approvals, and execution plan",
"planTasks": "Execution plan",
"planEmpty": "No execution plan",
"taskSummary": "Task summary",
"toolExecBlocked": "Tool {{name}} blocked",
"newChat": "New chat",
@ -3353,7 +3366,7 @@
"contextWarnLlamaCppSlots": "llama.cpp is running multiple parallel slots; the per-request window may be smaller than n_ctx. Check --parallel and the KV mode",
"contextWarnUnknown": "No context window detected; enter it manually",
"openaiReasoningTitle": "Reasoning settings",
"openaiReasoningHint": "Default reasoning settings for this AI channel; chat Session settings can override them.",
"openaiReasoningHint": "Default reasoning settings for this AI channel. Override them in the model options in the chat composer.",
"openaiReasoningProfile": "Wire profile",
"openaiReasoningAllowClient": "Allow chat page to override reasoning options",
"fofaBaseUrlPlaceholder": "https://fofa.info/api/v1/search/all (optional)",

View File

@ -278,6 +278,9 @@
"administration": "Администрирование"
},
"tokenUsageUI": {
"selectConversation": "Найдите и выберите диалог",
"periodDays": "{{count}} дн.",
"recentLimit": "Последние записи: {{count}}",
"chartHint": "Наведите или выберите столбец для точных значений",
"scopeProject": "Текущий проект",
"scopeAccessible": "Доступные диалоги",
@ -785,6 +788,16 @@
"generatedFromFact": "Создано из факта проекта {{factKey}}"
},
"chat": {
"chooseWorkspace": "Выберите рабочую область диалога",
"deepSeekEffortHint": "DeepSeek интерпретирует уровень «{{effort}}» как высокий.",
"reasoningOverrideBlocked": "Этот канал использует уровень рассуждения из системных настроек.",
"defaultWorkspace": "Рабочая область по умолчанию",
"boundProject": "Связанный проект",
"refreshConversation": "Обновить диалог",
"refreshConversationList": "Обновить список диалогов",
"refreshConversationHint": "Перезагрузить список диалогов, сообщения, ожидающие подтверждения и план выполнения",
"planTasks": "План выполнения",
"planEmpty": "Нет плана выполнения",
"taskSummary": "Итоги задачи",
"toolExecBlocked": "Инструмент {{name}} заблокирован",
"newChat": "Новый диалог",
@ -3240,7 +3253,7 @@
"contextWarnLlamaCppSlots": "llama.cpp запущен с несколькими параллельными слотами; окно одного запроса может быть меньше n_ctx. Проверьте --parallel и режим KV",
"contextWarnUnknown": "Окно контекста не обнаружено; укажите его вручную",
"openaiReasoningTitle": "Настройки рассуждения",
"openaiReasoningHint": "Настройки рассуждения этого канала ИИ по умолчанию; настройки сессии чата могут их переопределить.",
"openaiReasoningHint": "Настройки рассуждения этого канала ИИ по умолчанию. Их можно изменить в настройках модели в поле ввода сообщения.",
"openaiReasoningProfile": "Профиль передачи",
"openaiReasoningAllowClient": "Разрешить странице чата переопределять параметры рассуждения",
"fofaBaseUrlPlaceholder": "https://fofa.info/api/v1/search/all (необязательно)",

View File

@ -278,6 +278,9 @@
"administration": "平台管理"
},
"tokenUsageUI": {
"selectConversation": "搜索并选择会话",
"periodDays": "{{count}} 天",
"recentLimit": "最近 {{count}} 条",
"chartHint": "悬停或聚焦柱形查看精确用量",
"scopeProject": "当前项目",
"scopeAccessible": "可访问会话",
@ -761,6 +764,16 @@
"generatedFromFact": "由项目事实 {{factKey}} 生成"
},
"chat": {
"chooseWorkspace": "选择会话工作区",
"deepSeekEffortHint": "DeepSeek 会把「{{effort}}」按「高」处理。",
"reasoningOverrideBlocked": "此通道使用系统设置中的推理强度。",
"defaultWorkspace": "默认工作区",
"boundProject": "已绑定项目",
"refreshConversation": "刷新对话",
"refreshConversationList": "会话列表刷新",
"refreshConversationHint": "重新读取会话列表、消息、待审批项和执行计划",
"planTasks": "执行计划",
"planEmpty": "暂无执行计划",
"taskSummary": "任务总结",
"toolExecBlocked": "工具 {{name}} 已拦截",
"newChat": "新对话",
@ -3341,7 +3354,7 @@
"contextWarnLlamaCppSlots": "llama.cpp 配置了多个并行槽位,单请求可用窗口可能小于 n_ctx;请按 --parallel/KV 模式确认",
"contextWarnUnknown": "未检测到上下文窗口,请手动填写",
"openaiReasoningTitle": "推理设置",
"openaiReasoningHint": "作为该 AI 通道的默认推理设置;对话页「会话设置」可覆盖。",
"openaiReasoningHint": "作为该 AI 通道的默认推理设置。可在对话输入框的模型选项中覆盖。",
"openaiReasoningProfile": "线路 profile",
"openaiReasoningAllowClient": "允许对话页覆盖推理选项",
"fofaBaseUrlPlaceholder": "https://fofa.info/api/v1/search/all(可选)",