豆包复刻:原生安卓(Compose + 内嵌 Termux)+ Web / Windows
一个界面照着豆包抠的 AI 助手。主力是安卓端,完全离线自主:不依赖电脑、 不需要另外装 Termux。 安卓端 - 原生 Jetpack Compose,7 个页面,配色/圆角/间距对着真机截图量出来的 - 完整动效:抽屉滑入、页面切换、气泡淡入上移、面板底部升起、typing 三点、按钮回弹 - 内置 Termux:bash/apt/pkg 388 个命令、真 pty 终端; pty 不可用的 ROM 上自动降级成命令控制台 - APK 内嵌 CPython 3.13(Chaquopy),AI 内核跑在手机上 - 设备能力:定位 / 陀螺仪 / 加速度计 / 光线 / 电量 / 剪贴板 - 语音:朗读 + 语音输入,火山豆包音色 / OpenAI 兼容 / 设备自带三级引擎 AI 能力 - 10 家 OpenAI 兼容提供商:方舟 / OpenAI / DeepSeek / Kimi / 智谱 / 通义 / 硅基流动 / OpenRouter / 本地 Ollama / 自定义 - 思考强度按各家支持情况发不同字段(thinking / reasoning_effort / 不发), 认不出来的一律不发,避免给不支持的厂商发字段直接 400 - MCP 三种传输(http / stdio / inproc)、工具热加载、文件上传、权限模式 跨端 - 安卓走原生 Compose,Web / Windows 走 Lynx - Node 与 Python 两份内核接口逐字段一致,关键路径都有对拍脚本 自检脚本(都不需要真 Key) - verify-phone.mjs 设备端 24 项验收 - verify-speech.mjs 语音链路 31 项,两份内核各跑一遍 - parity-thinking.mjs 思考强度映射对拍 - probe-settings-wipe.mjs 设置防清空攻击测试 - mock-llm.mjs 假的 OpenAI + 火山语音服务 许可 MIT;第三方组件(Termux Apache-2.0、Chaquopy、Compose、LynxJS、Electron) 的授权见 LICENSE。
This commit is contained in:
236
app/src/pages/Agents.tsx
Normal file
236
app/src/pages/Agents.tsx
Normal file
@@ -0,0 +1,236 @@
|
||||
import { useCallback, useState } from '@lynx-js/react';
|
||||
|
||||
import type { Agent, AppState } from '../types.js';
|
||||
import { api } from '../api.js';
|
||||
import { cv } from '../lynx-input.js';
|
||||
import { AgentAvatar, Icon } from '../Icon.js';
|
||||
|
||||
interface AgentsProps {
|
||||
state: AppState;
|
||||
activeAgentId: string;
|
||||
onBack: () => void;
|
||||
onUse: (agent: Agent) => void;
|
||||
onRefresh: () => Promise<void>;
|
||||
}
|
||||
|
||||
const AVATAR_KEYS = ['doubao', 'coder', 'writer', 'analyst', 'cat', 'robot', 'star', 'cloud', 'custom'];
|
||||
|
||||
interface Draft {
|
||||
id: string;
|
||||
name: string;
|
||||
avatar: string;
|
||||
tagline: string;
|
||||
systemPrompt: string;
|
||||
}
|
||||
|
||||
const EMPTY: Draft = { id: '', name: '', avatar: 'cat', tagline: '', systemPrompt: '' };
|
||||
|
||||
export function AgentsPage(props: AgentsProps) {
|
||||
const { state, activeAgentId, onBack, onUse, onRefresh } = props;
|
||||
const [draft, setDraft] = useState<Draft | null>(null);
|
||||
const [busy, setBusy] = useState('');
|
||||
const [message, setMessage] = useState('');
|
||||
|
||||
const patch = useCallback((next: Partial<Draft>) => {
|
||||
setDraft((prev) => (prev ? { ...prev, ...next } : prev));
|
||||
}, []);
|
||||
|
||||
const save = useCallback(async () => {
|
||||
if (!draft) return;
|
||||
if (!draft.name.trim()) {
|
||||
setMessage('名称不能为空');
|
||||
return;
|
||||
}
|
||||
setBusy('save');
|
||||
setMessage('');
|
||||
try {
|
||||
if (draft.id) {
|
||||
await api.updateAgent(draft.id, {
|
||||
name: draft.name,
|
||||
avatar: draft.avatar,
|
||||
tagline: draft.tagline,
|
||||
systemPrompt: draft.systemPrompt,
|
||||
});
|
||||
} else {
|
||||
await api.createAgent({
|
||||
name: draft.name,
|
||||
avatar: draft.avatar,
|
||||
tagline: draft.tagline,
|
||||
systemPrompt: draft.systemPrompt,
|
||||
});
|
||||
}
|
||||
await onRefresh();
|
||||
setDraft(null);
|
||||
setMessage('已保存');
|
||||
} catch (err) {
|
||||
setMessage(`保存失败:${(err as Error).message}`);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
}, [draft, onRefresh]);
|
||||
|
||||
const remove = useCallback(async (id: string) => {
|
||||
setBusy(`del:${id}`);
|
||||
try {
|
||||
await api.deleteAgent(id);
|
||||
await onRefresh();
|
||||
setDraft(null);
|
||||
setMessage('已删除');
|
||||
} catch (err) {
|
||||
setMessage(`删除失败:${(err as Error).message}`);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
}, [onRefresh]);
|
||||
|
||||
return (
|
||||
<view className="page">
|
||||
<view className="sub-header">
|
||||
<view className="back-btn" bindtap={onBack}>
|
||||
<text style={{ fontSize: '24px', color: '#1f2329' }}>‹</text>
|
||||
</view>
|
||||
<text className="sub-header-title">{draft ? (draft.id ? '编辑智能体' : '新建智能体') : '智能体'}</text>
|
||||
{draft
|
||||
? (
|
||||
<view className="hdr-btn" bindtap={() => setDraft(null)}>
|
||||
<text style={{ fontSize: '14px', color: '#8a8f99' }}>取消</text>
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
</view>
|
||||
|
||||
<scroll-view className="form-scroll" scroll-orientation="vertical" scroll-y>
|
||||
<view className="form-inner">
|
||||
{draft
|
||||
? (
|
||||
<view className="form-card fade-in-up">
|
||||
<text className="form-label">头像</text>
|
||||
<view className="avatar-picker">
|
||||
{AVATAR_KEYS.map((key) => (
|
||||
<view
|
||||
key={key}
|
||||
className={draft.avatar === key ? 'avatar-choice avatar-choice-on' : 'avatar-choice'}
|
||||
bindtap={() => patch({ avatar: key })}
|
||||
>
|
||||
<AgentAvatar avatar={key} className="avatar-choice-img" />
|
||||
</view>
|
||||
))}
|
||||
</view>
|
||||
|
||||
<text className="form-label" style={{ marginTop: '14px' }}>名称</text>
|
||||
<input
|
||||
className="form-input"
|
||||
placeholder="例如:翻译官"
|
||||
{...cv(draft.name)}
|
||||
bindinput={(e: { detail: { value: string } }) => patch({ name: e.detail.value })}
|
||||
/>
|
||||
|
||||
<text className="form-label" style={{ marginTop: '14px' }}>一句话介绍</text>
|
||||
<input
|
||||
className="form-input"
|
||||
placeholder="显示在列表里,可留空"
|
||||
{...cv(draft.tagline)}
|
||||
bindinput={(e: { detail: { value: string } }) => patch({ tagline: e.detail.value })}
|
||||
/>
|
||||
|
||||
<text className="form-label" style={{ marginTop: '14px' }}>系统提示词</text>
|
||||
<textarea
|
||||
className="form-textarea"
|
||||
style={{ height: '200px' }}
|
||||
placeholder="这个智能体的人设、规则、说话风格…"
|
||||
{...cv(draft.systemPrompt)}
|
||||
bindinput={(e: { detail: { value: string } }) => patch({ systemPrompt: e.detail.value })}
|
||||
/>
|
||||
<text className="form-hint">
|
||||
和这个智能体聊天时,这段提示词会覆盖全局系统提示词。
|
||||
</text>
|
||||
|
||||
<view className="primary-btn" bindtap={save}>
|
||||
<text className="primary-btn-text">{busy === 'save' ? '保存中…' : '保存'}</text>
|
||||
</view>
|
||||
{draft.id && !state.agents.find((a) => a.id === draft.id)?.builtin
|
||||
? (
|
||||
<view
|
||||
className="ghost-btn"
|
||||
style={{ marginTop: '10px', alignSelf: 'center' }}
|
||||
bindtap={() => remove(draft.id)}
|
||||
>
|
||||
<text className="ghost-btn-text">{busy === `del:${draft.id}` ? '删除中…' : '删除这个智能体'}</text>
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
</view>
|
||||
)
|
||||
: (
|
||||
<view className="form-card fade-in-up">
|
||||
<view className="tool-actions" style={{ marginTop: '0px' }}>
|
||||
<view className="ghost-btn" bindtap={() => setDraft({ ...EMPTY })}>
|
||||
<text className="ghost-btn-text">+ 新建智能体</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
{state.agents.map((agent) => (
|
||||
<view className="agent-item" key={agent.id} bindtap={() => onUse(agent)}>
|
||||
<AgentAvatar avatar={agent.avatar} className="agent-avatar" />
|
||||
<view className="agent-info">
|
||||
<view className="agent-name-row">
|
||||
<text className="agent-name">{agent.name}</text>
|
||||
{agent.id === activeAgentId
|
||||
? (
|
||||
<view className="badge badge-ok">
|
||||
<text className="badge-text badge-text-ok">使用中</text>
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
</view>
|
||||
<text className="agent-tagline">
|
||||
{agent.tagline || (agent.systemPrompt ? agent.systemPrompt.split('\n')[0] : '通用助手')}
|
||||
</text>
|
||||
</view>
|
||||
<view className="ghost-btn" catchtap={() => setDraft({
|
||||
id: agent.id,
|
||||
name: agent.name,
|
||||
avatar: agent.avatar,
|
||||
tagline: agent.tagline || '',
|
||||
systemPrompt: agent.systemPrompt || '',
|
||||
})}>
|
||||
<text className="ghost-btn-text">编辑</text>
|
||||
</view>
|
||||
</view>
|
||||
))}
|
||||
</view>
|
||||
)}
|
||||
|
||||
{message
|
||||
? (
|
||||
<text className="form-hint" style={{ textAlign: 'center', marginTop: '10px' }}>{message}</text>
|
||||
)
|
||||
: null}
|
||||
|
||||
{!draft
|
||||
? (
|
||||
<view className="form-card">
|
||||
<text className="form-label">怎么用</text>
|
||||
<text className="form-hint" style={{ marginTop: '0px' }}>
|
||||
点任意智能体即可切换,之后所有新消息都按它的人设回答;聊天页顶部也会显示它。每个智能体的系统提示词互相独立。
|
||||
</text>
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
</view>
|
||||
</scroll-view>
|
||||
</view>
|
||||
);
|
||||
}
|
||||
|
||||
/** 聊天页顶部的小头像入口用得到 */
|
||||
export function AgentChip(props: { agent: Agent | null; onTap: () => void }) {
|
||||
if (!props.agent) return null;
|
||||
return (
|
||||
<view className="hdr-btn" bindtap={props.onTap}>
|
||||
<AgentAvatar avatar={props.agent.avatar} className="icon-lg round" />
|
||||
</view>
|
||||
);
|
||||
}
|
||||
|
||||
export { Icon };
|
||||
415
app/src/pages/Chat.tsx
Normal file
415
app/src/pages/Chat.tsx
Normal file
@@ -0,0 +1,415 @@
|
||||
import { useCallback } from '@lynx-js/react';
|
||||
|
||||
import type { Agent, Attachment, ChatMessage } from '../types.js';
|
||||
import { apiBase } from '../api.js';
|
||||
import { cv } from '../lynx-input.js';
|
||||
import { AgentAvatar, Icon } from '../Icon.js';
|
||||
|
||||
interface ChatProps {
|
||||
messages: ChatMessage[];
|
||||
streaming: boolean;
|
||||
draft: string;
|
||||
agent: Agent | null;
|
||||
attachments: Attachment[];
|
||||
scrollAnchor: string;
|
||||
/** 每次 +1 触发一次"滚到底" */
|
||||
scrollSignal: number;
|
||||
/** 当前思考强度,用于在思维链标题上显示 */
|
||||
thinkingLevel: string;
|
||||
/** 哪些消息的思维链被展开了 */
|
||||
openReasoning: Record<number, boolean>;
|
||||
onToggleReasoning: (index: number) => void;
|
||||
/** 打开某条消息的「思考过程」底部弹层 */
|
||||
onOpenThink: (index: number) => void;
|
||||
/** 当前展开思考过程的消息下标,null 表示关着 */
|
||||
thinkIndex: number | null;
|
||||
onCloseThink: () => void;
|
||||
copyHint: string;
|
||||
onDraftChange: (value: string) => void;
|
||||
onSend: () => void;
|
||||
onOpenDrawer: () => void;
|
||||
onOpenAgents: () => void;
|
||||
onOpenSettings: () => void;
|
||||
onPickFile: () => void;
|
||||
onRemoveAttachment: (id: string) => void;
|
||||
onRegenerate: () => void;
|
||||
onFeedback: (index: number, value: 'up' | 'down') => void;
|
||||
onCopy: (text: string) => void;
|
||||
/** 朗读某条回复;正在念的那条把喇叭图标点亮 */
|
||||
onSpeak: (text: string, index: number) => void;
|
||||
speakingIndex: number;
|
||||
}
|
||||
|
||||
const DEFAULT_GREETING = '嗨,我是豆包,可以帮你解答问题,给你工作和学习提供帮助,也能陪你聊天。今天有什么可以帮你的吗?';
|
||||
|
||||
function greetingOf(agent: Agent | null): string {
|
||||
if (!agent || agent.id === 'a_doubao') return DEFAULT_GREETING;
|
||||
const tail = agent.tagline ? `,${agent.tagline}` : '';
|
||||
return `我是${agent.name}${tail}。有什么要处理的,直接说。`;
|
||||
}
|
||||
|
||||
function isImageAttachment(item: Attachment): boolean {
|
||||
return /^image\//.test(item.mime || '') || /\.(png|jpe?g|webp|gif|bmp)$/i.test(item.name);
|
||||
}
|
||||
|
||||
function prettySize(bytes: number): string {
|
||||
if (!bytes) return '';
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
const THINKING_LABEL: Record<string, string> = {
|
||||
off: '已关闭',
|
||||
low: '低',
|
||||
medium: '中',
|
||||
high: '高',
|
||||
auto: '自动',
|
||||
};
|
||||
|
||||
export function ChatPage(props: ChatProps) {
|
||||
const {
|
||||
messages, streaming, draft, agent, attachments, scrollAnchor, scrollSignal, copyHint,
|
||||
thinkingLevel, openReasoning, onToggleReasoning, onOpenThink, thinkIndex, onCloseThink,
|
||||
onDraftChange, onSend, onOpenDrawer, onOpenAgents, onOpenSettings,
|
||||
onPickFile, onRemoveAttachment, onRegenerate, onFeedback, onCopy,
|
||||
onSpeak, speakingIndex,
|
||||
} = props;
|
||||
|
||||
const handleInput = useCallback((e: { detail: { value: string } }) => {
|
||||
onDraftChange(e.detail.value);
|
||||
}, [onDraftChange]);
|
||||
|
||||
const handleConfirm = useCallback(() => {
|
||||
onSend();
|
||||
}, [onSend]);
|
||||
|
||||
const hasImage = attachments.some(isImageAttachment);
|
||||
const canSend = Boolean(draft.trim()) || attachments.length > 0;
|
||||
|
||||
return (
|
||||
<view className="page">
|
||||
{/* 顶栏 */}
|
||||
<view className="chat-header">
|
||||
<view className="hdr-btn" bindtap={onOpenDrawer}>
|
||||
<Icon name="menu" className="icon-lg" />
|
||||
</view>
|
||||
<view className="hdr-btn" bindtap={onOpenSettings}>
|
||||
<Icon name="compose" className="icon" />
|
||||
</view>
|
||||
<view className="hdr-title" bindtap={onOpenAgents}>
|
||||
<view className="hdr-title-row">
|
||||
{agent ? <AgentAvatar avatar={agent.avatar} className="hdr-agent-avatar" /> : null}
|
||||
<text className="hdr-title-text">{agent ? agent.name : '豆包'}</text>
|
||||
<text className="hdr-caret">›</text>
|
||||
</view>
|
||||
<text className="hdr-sub">AI生成可能有误 注意核实</text>
|
||||
</view>
|
||||
<view className="hdr-btn">
|
||||
<Icon name="phone" className="icon-sm" />
|
||||
</view>
|
||||
<view className="hdr-btn">
|
||||
<Icon name="speaker" className="icon-sm" />
|
||||
</view>
|
||||
</view>
|
||||
|
||||
{/* 对话区 */}
|
||||
<scroll-view
|
||||
className="chat-body"
|
||||
scroll-orientation="vertical"
|
||||
scroll-y
|
||||
scroll-into-view={scrollAnchor}
|
||||
scroll-top={scrollSignal === 0 ? 0 : 900000 + scrollSignal}
|
||||
>
|
||||
<view className="chat-body-inner">
|
||||
<view className="hero">
|
||||
<AgentAvatar avatar={agent?.avatar || 'doubao'} className="hero-avatar" />
|
||||
</view>
|
||||
|
||||
<view className="bubble bubble-bot bubble-enter">
|
||||
<text className="bubble-text">{greetingOf(agent)}</text>
|
||||
</view>
|
||||
|
||||
{messages.map((msg, index) => {
|
||||
if (msg.role === 'user') {
|
||||
const files = msg.attachments || [];
|
||||
return (
|
||||
<view key={`u${index}`} className="bubble bubble-user bubble-enter">
|
||||
{files.length > 0
|
||||
? (
|
||||
<view className="bubble-files">
|
||||
{files.map((file) => (
|
||||
<view className="bubble-file" key={file.id}>
|
||||
{isImageAttachment(file) && file.url
|
||||
? <image className="bubble-file-img" src={`${apiBase()}${file.url}`} />
|
||||
: <Icon name="attach" className="icon-sm" />}
|
||||
<text className="bubble-file-name">{file.name}</text>
|
||||
</view>
|
||||
))}
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
{msg.content ? <text className="bubble-text-user">{msg.content}</text> : null}
|
||||
</view>
|
||||
);
|
||||
}
|
||||
|
||||
const hasTrace = msg.toolTrace && msg.toolTrace.length > 0;
|
||||
const hasReasoning = Boolean(msg.reasoning);
|
||||
const isLast = index === messages.length - 1;
|
||||
return (
|
||||
<view key={`a${index}`} className="bubble-group bubble-enter">
|
||||
{/* 「深度思考」入口:点开看完整思维链
|
||||
只要有思维链**或调过工具**就显示 —— 否则模型没吐 reasoning 时,
|
||||
界面上会找不到任何"过程"入口,用户会以为坏掉了 */}
|
||||
{hasReasoning || hasTrace || (streaming && isLast && thinkingLevel !== 'off')
|
||||
? (
|
||||
<view className="think-entry" bindtap={() => onOpenThink(index)}>
|
||||
<Icon name="sparkle" className="icon-sm" />
|
||||
<text className="think-entry-text">
|
||||
{hasReasoning ? '深度思考' : hasTrace ? '执行过程' : '深度思考中'}
|
||||
{THINKING_LABEL[thinkingLevel] ? ` · ${THINKING_LABEL[thinkingLevel]}` : ''}
|
||||
</text>
|
||||
{hasReasoning || hasTrace
|
||||
? <text className="hdr-caret">›</text>
|
||||
: (
|
||||
<view className="typing">
|
||||
<view className="typing-dot dot-1" />
|
||||
<view className="typing-dot dot-2" />
|
||||
<view className="typing-dot dot-3" />
|
||||
</view>
|
||||
)}
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
|
||||
{/* 工具步骤:正文里一行一步,点一下展开这一步的结果 */}
|
||||
{hasTrace
|
||||
? (
|
||||
<view className="steps">
|
||||
{msg.toolTrace!.map((trace, ti) => {
|
||||
const key = index * 100 + ti;
|
||||
const open = Boolean(openReasoning[key]);
|
||||
return (
|
||||
<view className="step-item" key={`t${ti}`}>
|
||||
<view className="step-row" bindtap={() => onToggleReasoning(key)}>
|
||||
<Icon name="gear" className="icon-sm" />
|
||||
<text className="step-name">{trace.name}</text>
|
||||
<text className={trace.ok === false ? 'step-badge step-badge-bad' : 'step-badge'}>
|
||||
{trace.ok === false ? '失败' : '完成'}
|
||||
</text>
|
||||
<text className="hdr-caret">›</text>
|
||||
</view>
|
||||
{open
|
||||
? <text className="step-result">{String(trace.result || '(无输出)').slice(0, 600)}</text>
|
||||
: null}
|
||||
</view>
|
||||
);
|
||||
})}
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
|
||||
<view className={msg.error ? 'bubble bubble-bot bubble-error' : 'bubble bubble-bot'}>
|
||||
{msg.content
|
||||
? <text className="bubble-text">{msg.content}</text>
|
||||
: (
|
||||
<view className="typing">
|
||||
<view className="typing-dot dot-1" />
|
||||
<view className="typing-dot dot-2" />
|
||||
<view className="typing-dot dot-3" />
|
||||
</view>
|
||||
)}
|
||||
</view>
|
||||
|
||||
{/* 消息操作栏:只在回答完成后出现 */}
|
||||
{!streaming && msg.content && !msg.error
|
||||
? (
|
||||
<view className="msg-actions">
|
||||
<view className="msg-action" bindtap={() => onCopy(msg.content)}>
|
||||
<Icon name="copy" className="icon-sm" />
|
||||
</view>
|
||||
<view
|
||||
className="msg-action"
|
||||
bindtap={() => onSpeak(msg.content, index)}
|
||||
>
|
||||
<Icon
|
||||
name="speaker"
|
||||
className={speakingIndex === index ? 'icon-sm active' : 'icon-sm'}
|
||||
/>
|
||||
</view>
|
||||
<view className="msg-action" bindtap={() => onFeedback(index, 'up')}>
|
||||
<Icon name="like" className={msg.feedback === 'up' ? 'icon-sm active' : 'icon-sm'} />
|
||||
</view>
|
||||
<view className="msg-action" bindtap={() => onFeedback(index, 'down')}>
|
||||
<Icon name="dislike" className={msg.feedback === 'down' ? 'icon-sm active' : 'icon-sm'} />
|
||||
</view>
|
||||
<view className="msg-action">
|
||||
<Icon name="share" className="icon-sm" />
|
||||
</view>
|
||||
{isLast
|
||||
? (
|
||||
<view className="msg-action msg-action-right" bindtap={onRegenerate}>
|
||||
<Icon name="refresh" className="icon-sm" />
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
</view>
|
||||
);
|
||||
})}
|
||||
|
||||
{copyHint ? <text className="copy-hint">{copyHint}</text> : null}
|
||||
|
||||
{/* 锚点常驻:流式结束后还要能把操作栏滚进可视区 */}
|
||||
<view id="chat-anchor" style={{ height: '6px' }} />
|
||||
</view>
|
||||
</scroll-view>
|
||||
|
||||
{/* 快捷入口:有图片时换成图片相关的 */}
|
||||
<view className="quick-row">
|
||||
{hasImage
|
||||
? (
|
||||
<>
|
||||
<view className="chip" bindtap={() => onDraftChange('帮我把这张图修一下')}>
|
||||
<Icon name="sparkle" className="icon-sm" />
|
||||
<text className="chip-text">豆包P图</text>
|
||||
</view>
|
||||
<view className="chip" bindtap={() => onDraftChange('这是什么?详细说说')}>
|
||||
<Icon name="search" className="icon-sm" />
|
||||
<text className="chip-text">这是什么</text>
|
||||
</view>
|
||||
<view className="chip" bindtap={() => onDraftChange('帮我找同款商品')}>
|
||||
<Icon name="layers" className="icon-sm" />
|
||||
<text className="chip-text">找同款商品</text>
|
||||
</view>
|
||||
</>
|
||||
)
|
||||
: (
|
||||
<>
|
||||
<view className="chip">
|
||||
<Icon name="message-circle" className="icon-sm" />
|
||||
<text className="chip-text">对话</text>
|
||||
</view>
|
||||
<view className="chip">
|
||||
<Icon name="sparkle" className="icon-sm" />
|
||||
<text className="chip-text">AI创作</text>
|
||||
</view>
|
||||
<view className="chip">
|
||||
<Icon name="map" className="icon-sm" />
|
||||
<text className="chip-text">出行用豆包</text>
|
||||
</view>
|
||||
<view className="chip">
|
||||
<Icon name="avatar-circle" className="icon-sm" />
|
||||
<text className="chip-text">豆包</text>
|
||||
</view>
|
||||
</>
|
||||
)}
|
||||
</view>
|
||||
|
||||
{/* 附件区:缩略图 + 加号 */}
|
||||
{attachments.length > 0
|
||||
? (
|
||||
<view className="attach-strip">
|
||||
{attachments.map((file) => (
|
||||
<view className="attach-tile" key={file.id}>
|
||||
{isImageAttachment(file) && file.url
|
||||
? <image className="attach-thumb" src={`${apiBase()}${file.url}`} />
|
||||
: (
|
||||
<view className="attach-file">
|
||||
<Icon name="attach" className="icon-sm" />
|
||||
<text className="attach-file-name">{file.name}</text>
|
||||
<text className="attach-file-size">{prettySize(file.size)}</text>
|
||||
</view>
|
||||
)}
|
||||
<view className="attach-remove" catchtap={() => onRemoveAttachment(file.id)}>
|
||||
<Icon name="close" className="icon-xs" />
|
||||
</view>
|
||||
</view>
|
||||
))}
|
||||
<view className="attach-add" bindtap={onPickFile}>
|
||||
<text className="attach-add-plus">+</text>
|
||||
</view>
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
|
||||
{/* 输入栏 */}
|
||||
<view className="input-bar">
|
||||
<view className="input-pill">
|
||||
{attachments.length === 0
|
||||
? (
|
||||
<view className="input-btn" bindtap={onPickFile}>
|
||||
<Icon name="camera" className="icon" />
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
<input
|
||||
className="input-field"
|
||||
placeholder={attachments.length > 0 ? '说点什么…' : '发消息或按住说话…'}
|
||||
{...cv(draft)}
|
||||
bindinput={handleInput}
|
||||
bindconfirm={handleConfirm}
|
||||
/>
|
||||
<view className="input-btn">
|
||||
<Icon name="voice" className="icon" />
|
||||
</view>
|
||||
{canSend
|
||||
? (
|
||||
<view className="send-btn" bindtap={onSend}>
|
||||
<Icon name="send" className="icon-sm" />
|
||||
</view>
|
||||
)
|
||||
: (
|
||||
<view className="input-btn" bindtap={onPickFile}>
|
||||
<Icon name="plus" className="icon-lg" />
|
||||
</view>
|
||||
)}
|
||||
</view>
|
||||
</view>
|
||||
|
||||
{/* 「思考过程」底部弹层:和豆包一样,从底部升起、左上角一个 X */}
|
||||
{thinkIndex != null && messages[thinkIndex]
|
||||
? (
|
||||
<view className="sheet-mask drawer-fade" bindtap={onCloseThink}>
|
||||
<view className="sheet think-sheet" catchtap={stop}>
|
||||
<view className="think-head">
|
||||
<view className="think-close" bindtap={onCloseThink}>
|
||||
<Icon name="close" className="icon-sm" />
|
||||
</view>
|
||||
<text className="think-title">思考过程</text>
|
||||
<view className="think-close" />
|
||||
</view>
|
||||
|
||||
<scroll-view className="think-scroll" scroll-orientation="vertical" scroll-y>
|
||||
<view>
|
||||
{/* 这一步读了哪些东西 / 调了哪些工具,先列出来 */}
|
||||
{messages[thinkIndex].toolTrace && messages[thinkIndex].toolTrace!.length > 0
|
||||
? (
|
||||
<view className="think-facts">
|
||||
{messages[thinkIndex].toolTrace!.map((trace, ti) => (
|
||||
<view className="think-fact" key={`f${ti}`}>
|
||||
<Icon name="gear" className="icon-sm" />
|
||||
<text className="think-fact-text">
|
||||
{`${trace.ok === false ? '失败' : '已调用'} ${trace.name}`}
|
||||
</text>
|
||||
</view>
|
||||
))}
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
|
||||
<text className="think-body">
|
||||
{messages[thinkIndex].reasoning || '这次没有返回思维链(模型不支持,或思考强度被关掉了)。'}
|
||||
</text>
|
||||
</view>
|
||||
</scroll-view>
|
||||
</view>
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
</view>
|
||||
);
|
||||
}
|
||||
157
app/src/pages/Drawer.tsx
Normal file
157
app/src/pages/Drawer.tsx
Normal file
@@ -0,0 +1,157 @@
|
||||
import { useCallback } from '@lynx-js/react';
|
||||
|
||||
import type { Conversation } from '../types.js';
|
||||
import { AgentAvatar, Icon, avatarMain } from '../Icon.js';
|
||||
|
||||
interface DrawerProps {
|
||||
conversations: Conversation[];
|
||||
activeId: string;
|
||||
nickname: string;
|
||||
onSelect: (id: string) => void;
|
||||
onClose: () => void;
|
||||
onNewTopic: () => void;
|
||||
onOpenProfile: () => void;
|
||||
onOpenSettings: () => void;
|
||||
onOpenSkills: () => void;
|
||||
onOpenAgents: () => void;
|
||||
onOpenTerminal: () => void;
|
||||
/** 「模型」那一栏右边显示的文案(模型 + 思考强度) */
|
||||
modelLabel: string;
|
||||
onOpenModel: () => void;
|
||||
onDelete: (conv: Conversation) => void;
|
||||
}
|
||||
|
||||
/** 列表上显示"什么时候聊的" */
|
||||
function timeLabel(iso?: string): string {
|
||||
if (!iso) return '';
|
||||
const then = new Date(iso).getTime();
|
||||
if (!then) return '';
|
||||
const diff = Date.now() - then;
|
||||
if (diff < 60_000) return '刚刚';
|
||||
if (diff < 3600_000) return `${Math.floor(diff / 60_000)} 分钟前`;
|
||||
if (diff < 86400_000) return `${Math.floor(diff / 3600_000)} 小时前`;
|
||||
const date = new Date(then);
|
||||
if (diff < 172800_000) return '昨天';
|
||||
return `${date.getMonth() + 1}/${date.getDate()}`;
|
||||
}
|
||||
|
||||
export function Drawer(props: DrawerProps) {
|
||||
const {
|
||||
conversations, activeId, nickname, onSelect, onClose, onNewTopic,
|
||||
onOpenProfile, onOpenSettings, onOpenSkills, onOpenAgents, onDelete,
|
||||
modelLabel, onOpenModel, onOpenTerminal,
|
||||
} = props;
|
||||
|
||||
const stop = useCallback(() => {}, []);
|
||||
const pinned = conversations.filter((c) => c.pinned);
|
||||
const recents = conversations.filter((c) => !c.pinned);
|
||||
|
||||
return (
|
||||
<view className="drawer-mask drawer-fade" bindtap={onClose}>
|
||||
<view className="drawer drawer-slide" catchtap={stop}>
|
||||
<view className="drawer-header">
|
||||
<text className="drawer-title">豆包</text>
|
||||
<view className="hdr-btn" bindtap={onOpenSettings}>
|
||||
<Icon name="search" className="icon" />
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view className="drawer-menu">
|
||||
<view className="menu-item" bindtap={onNewTopic}>
|
||||
<Icon name="message-circle" className="icon" />
|
||||
<text className="menu-item-text">开启新话题</text>
|
||||
</view>
|
||||
<view className="menu-item" bindtap={onOpenAgents}>
|
||||
<Icon name="sparkle-square" className="icon" />
|
||||
<text className="menu-item-text">智能体</text>
|
||||
</view>
|
||||
<view className="menu-item" bindtap={onOpenSkills}>
|
||||
<Icon name="layers" className="icon" />
|
||||
<text className="menu-item-text">技能·连接器</text>
|
||||
</view>
|
||||
<view className="menu-item" bindtap={onOpenTerminal}>
|
||||
<Icon name="compose" className="icon" />
|
||||
<text className="menu-item-text">终端</text>
|
||||
<text className="menu-model-value">Termux / shell</text>
|
||||
</view>
|
||||
<view className="menu-item menu-item-model" bindtap={onOpenModel}>
|
||||
<Icon name="model" className="icon" />
|
||||
<text className="menu-item-text">模型</text>
|
||||
<text className="menu-model-value">{modelLabel}</text>
|
||||
<text className="menu-caret">⌄</text>
|
||||
</view>
|
||||
<view className="menu-item" bindtap={onOpenSettings}>
|
||||
<Icon name="gear" className="icon" />
|
||||
<text className="menu-item-text">设置</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view className="section-head">
|
||||
<text className="section-label">置顶</text>
|
||||
<Icon name="more" className="icon-sm" />
|
||||
</view>
|
||||
{pinned.map((conv) => (
|
||||
<view
|
||||
key={conv.id}
|
||||
className={conv.id === activeId ? 'conv-item conv-item-active' : 'conv-item'}
|
||||
bindtap={() => onSelect(conv.id)}
|
||||
>
|
||||
<AgentAvatar avatar="doubao" className="conv-avatar" />
|
||||
<view className="conv-text">
|
||||
<text className="conv-title">{conv.title}</text>
|
||||
<text className="conv-preview">{conv.preview || '还没有消息'}</text>
|
||||
</view>
|
||||
<text className="conv-time">{timeLabel(conv.updatedAt)}</text>
|
||||
</view>
|
||||
))}
|
||||
|
||||
<view className="section-head">
|
||||
<text className="section-label">最近</text>
|
||||
<Icon name="more" className="icon-sm" />
|
||||
</view>
|
||||
<scroll-view className="drawer-list" scroll-orientation="vertical" scroll-y>
|
||||
<view>
|
||||
{recents.map((conv, index) => (
|
||||
<view
|
||||
key={conv.id}
|
||||
className={conv.id === activeId ? 'conv-item conv-item-active' : 'conv-item'}
|
||||
bindtap={() => onSelect(conv.id)}
|
||||
>
|
||||
<AgentAvatar avatar={['cat', 'star', 'cloud', 'robot', 'writer'][index % 5]} className="conv-avatar" />
|
||||
<view className="conv-text">
|
||||
<text className="conv-title">{conv.title}</text>
|
||||
<text className="conv-preview">{conv.preview || '还没有消息'}</text>
|
||||
</view>
|
||||
<text className="conv-time">{timeLabel(conv.updatedAt)}</text>
|
||||
<view className="conv-del" catchtap={() => onDelete(conv)}>
|
||||
<Icon name="more" className="icon-sm" />
|
||||
</view>
|
||||
</view>
|
||||
))}
|
||||
{recents.length === 0
|
||||
? <text className="empty-tip">还没有其他对话,点「开启新话题」开始。</text>
|
||||
: null}
|
||||
</view>
|
||||
</scroll-view>
|
||||
|
||||
<view className="drawer-bottom">
|
||||
<view className="user-pill" bindtap={onOpenProfile}>
|
||||
<image className="user-pill-avatar" src={avatarMain} />
|
||||
<text className="user-pill-text">{nickname}</text>
|
||||
<text className="hdr-caret">›</text>
|
||||
</view>
|
||||
<view className="hdr-btn">
|
||||
<Icon name="scan" className="icon" />
|
||||
</view>
|
||||
<view className="bell-wrap">
|
||||
<Icon name="bell" className="icon" />
|
||||
<view className="bell-dot" />
|
||||
</view>
|
||||
<view className="hdr-btn" bindtap={onOpenSettings}>
|
||||
<Icon name="gear" className="icon" />
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
);
|
||||
}
|
||||
121
app/src/pages/ModelPicker.tsx
Normal file
121
app/src/pages/ModelPicker.tsx
Normal file
@@ -0,0 +1,121 @@
|
||||
import { useCallback } from '@lynx-js/react';
|
||||
|
||||
import type { AppState } from '../types.js';
|
||||
import { Icon } from '../Icon.js';
|
||||
|
||||
interface ModelPickerProps {
|
||||
state: AppState;
|
||||
onClose: () => void;
|
||||
onPick: (patch: Record<string, unknown>) => void;
|
||||
}
|
||||
|
||||
/** 思考强度:和设置页里的选项保持一致 */
|
||||
const THINKING_OPTIONS = [
|
||||
{ value: 'off', label: '快速', hint: '不思考,直接答' },
|
||||
{ value: 'auto', label: '自动', hint: '交给模型决定' },
|
||||
{ value: 'low', label: '低', hint: '' },
|
||||
{ value: 'medium', label: '中', hint: '' },
|
||||
{ value: 'high', label: '深度思考', hint: '想得最久,难题用' },
|
||||
];
|
||||
|
||||
/** 把模型 ID 变短一点,列表里好看 */
|
||||
export function shortModelName(model: string): string {
|
||||
const id = String(model || '');
|
||||
if (!id) return '未设置';
|
||||
if (id.startsWith('ep-')) return `接入点 ${id.slice(0, 8)}`;
|
||||
if (/^doubao-seed-2-1-pro/i.test(id)) return '豆包 Pro';
|
||||
if (/^doubao-seed-2-1/i.test(id)) return '豆包 2.1';
|
||||
if (/^doubao-seed-1-8/i.test(id)) return '豆包 1.8';
|
||||
if (/^doubao-seed-1-6/i.test(id)) return '豆包 1.6';
|
||||
if (/^doubao/i.test(id)) return '豆包';
|
||||
if (/^deepseek-r1/i.test(id)) return 'DeepSeek R1';
|
||||
if (/^deepseek/i.test(id)) return 'DeepSeek';
|
||||
if (/^gpt-5/i.test(id)) return `GPT-5${id.includes('mini') ? ' mini' : ''}`;
|
||||
if (/^gpt-4o/i.test(id)) return `GPT-4o${id.includes('mini') ? ' mini' : ''}`;
|
||||
if (/^gpt-4/i.test(id)) return `GPT-4${id.includes('mini') ? ' mini' : ''}`;
|
||||
return id.length > 18 ? `${id.slice(0, 16)}…` : id;
|
||||
}
|
||||
|
||||
export function thinkingLabel(level: string): string {
|
||||
const found = THINKING_OPTIONS.find((o) => o.value === level);
|
||||
return found ? found.label : '自动';
|
||||
}
|
||||
|
||||
/** 抽屉里那一栏右边显示的文案:模型 + 思考强度 */
|
||||
export function modelRowLabel(state: AppState): string {
|
||||
const model = state.settings?.model || '';
|
||||
return `${shortModelName(model)} ${thinkingLabel(state.settings?.thinkingLevel || 'auto')}`;
|
||||
}
|
||||
|
||||
export function ModelPicker(props: ModelPickerProps) {
|
||||
const { state, onClose, onPick } = props;
|
||||
const stop = useCallback(() => {}, []);
|
||||
|
||||
const preset = state.providers?.[state.settings.provider];
|
||||
// 列表:优先用设置里的候选,兜底当前模型,保证至少有一项
|
||||
const models: string[] = (() => {
|
||||
const list = preset?.models ? [...preset.models] : [];
|
||||
const current = state.settings.model;
|
||||
if (current && !list.includes(current)) list.unshift(current);
|
||||
return list;
|
||||
})();
|
||||
|
||||
return (
|
||||
<view className="sheet-mask drawer-fade" bindtap={onClose}>
|
||||
<view className="sheet model-sheet popIn" catchtap={stop}>
|
||||
<view className="sheet-head">
|
||||
<text className="sheet-title">模型</text>
|
||||
<view className="hdr-btn" bindtap={onClose}>
|
||||
<Icon name="close" className="icon-sm" />
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view className="model-tip-row">
|
||||
<Icon name="model" className="icon-sm" />
|
||||
<text className="model-tip">
|
||||
{preset?.label || state.settings.provider} · 换模型和思考强度立即生效,不用重启
|
||||
</text>
|
||||
</view>
|
||||
|
||||
<text className="sheet-section">选模型</text>
|
||||
<view className="model-list">
|
||||
{models.map((m) => (
|
||||
<view
|
||||
key={m}
|
||||
className={m === state.settings.model ? 'model-option model-option-active' : 'model-option'}
|
||||
bindtap={() => onPick({ model: m })}
|
||||
>
|
||||
<view className="model-option-text">
|
||||
<text className="model-name">{shortModelName(m)}</text>
|
||||
<text className="model-id">{m}</text>
|
||||
</view>
|
||||
{m === state.settings.model ? <Icon name="check" className="icon-sm" /> : null}
|
||||
</view>
|
||||
))}
|
||||
</view>
|
||||
|
||||
<text className="sheet-section">思考强度</text>
|
||||
<view className="segment">
|
||||
{THINKING_OPTIONS.map((item) => {
|
||||
const active = (state.settings.thinkingLevel || 'auto') === item.value;
|
||||
return (
|
||||
<view
|
||||
key={item.value}
|
||||
className={active ? 'segment-item segment-item-active' : 'segment-item'}
|
||||
bindtap={() => onPick({ thinkingLevel: item.value })}
|
||||
>
|
||||
<text className={active ? 'segment-text segment-text-active' : 'segment-text'}>
|
||||
{item.label}
|
||||
</text>
|
||||
</view>
|
||||
);
|
||||
})}
|
||||
</view>
|
||||
<text className="form-hint">
|
||||
{THINKING_OPTIONS.find((o) => o.value === (state.settings.thinkingLevel || 'auto'))?.hint
|
||||
|| '方舟:thinking=enabled;OpenAI:reasoning_effort'}
|
||||
</text>
|
||||
</view>
|
||||
</view>
|
||||
);
|
||||
}
|
||||
119
app/src/pages/Profile.tsx
Normal file
119
app/src/pages/Profile.tsx
Normal file
@@ -0,0 +1,119 @@
|
||||
import { useCallback } from '@lynx-js/react';
|
||||
|
||||
import { Icon } from '../Icon.js';
|
||||
import avatarMain from '../assets/avatar-main.png';
|
||||
import avatarPhoto from '../assets/avatar-photo.png';
|
||||
|
||||
interface ProfileProps {
|
||||
nickname: string;
|
||||
doubaoId: string;
|
||||
memoryEnabled: boolean;
|
||||
onToggleMemory: () => void;
|
||||
onOpenDrawer: () => void;
|
||||
onOpenSettings: () => void;
|
||||
onOpenAgents: () => void;
|
||||
onNewTopic: () => void;
|
||||
}
|
||||
|
||||
export function ProfilePage(props: ProfileProps) {
|
||||
const {
|
||||
nickname, doubaoId, memoryEnabled, onToggleMemory,
|
||||
onOpenDrawer, onOpenSettings, onOpenAgents, onNewTopic,
|
||||
} = props;
|
||||
|
||||
const noop = useCallback(() => {}, []);
|
||||
|
||||
return (
|
||||
<view className="page profile-page">
|
||||
<view className="profile-header">
|
||||
<view className="hdr-btn" bindtap={onOpenDrawer}>
|
||||
<Icon name="menu" className="icon-lg" />
|
||||
</view>
|
||||
<view className="hdr-btn">
|
||||
<Icon name="more" className="icon" />
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view className="profile-hero">
|
||||
<view className="avatar-row">
|
||||
<view className="avatar-add">
|
||||
<Icon name="plus" className="icon-sm" />
|
||||
</view>
|
||||
<Icon name="avatar-circle" className="avatar-main-big" />
|
||||
<image className="avatar-photo-big" src={avatarPhoto} />
|
||||
</view>
|
||||
<text className="profile-name" bindtap={noop}>{`${nickname} ›`}</text>
|
||||
<text className="profile-id">{`豆包号:${doubaoId}`}</text>
|
||||
<view className="account-btn">
|
||||
<text className="account-btn-text">豆包账号管理</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view className="profile-card">
|
||||
<view className="profile-row">
|
||||
<Icon name="upgrade" className="profile-row-icon" />
|
||||
<text className="profile-row-text">升级套餐</text>
|
||||
<Icon name="chevron-right" className="icon-sm" />
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view className="profile-card">
|
||||
<view className="profile-row">
|
||||
<image className="profile-row-icon" src={avatarMain} />
|
||||
<text className="profile-row-text">豆包形象</text>
|
||||
<Icon name="chevron-right" className="icon-sm" />
|
||||
</view>
|
||||
<view className="row-divider" />
|
||||
<view className="profile-row">
|
||||
<Icon name="speaker-purple" className="profile-row-icon" />
|
||||
<text className="profile-row-text">声音</text>
|
||||
<Icon name="chevron-right" className="icon-sm" />
|
||||
</view>
|
||||
<view className="row-divider" />
|
||||
<view className="profile-row">
|
||||
<Icon name="text-size" className="profile-row-icon" />
|
||||
<text className="profile-row-text">字号与背景</text>
|
||||
<Icon name="chevron-right" className="icon-sm" />
|
||||
</view>
|
||||
<view className="row-divider" />
|
||||
<view className="profile-row">
|
||||
<Icon name="memory" className="profile-row-icon" />
|
||||
<text className="profile-row-text">记忆</text>
|
||||
<text className="profile-row-value">{memoryEnabled ? '已开启' : '已关闭'}</text>
|
||||
<Icon name="chevron-right" className="icon-sm" />
|
||||
</view>
|
||||
<view className="row-divider" />
|
||||
<view className="profile-row">
|
||||
<Icon name="bell-purple" className="profile-row-icon" />
|
||||
<text className="profile-row-text">通知设置</text>
|
||||
<Icon name="chevron-right" className="icon-sm" />
|
||||
</view>
|
||||
<view className="row-divider" />
|
||||
<view className="profile-row" bindtap={onNewTopic}>
|
||||
<Icon name="plus-circle-blue" className="profile-row-icon" />
|
||||
<text className="profile-row-text">开启新话题</text>
|
||||
<Icon name="chevron-right" className="icon-sm" />
|
||||
</view>
|
||||
<view className="row-divider" />
|
||||
<view className="profile-row" bindtap={onOpenAgents}>
|
||||
<Icon name="sparkle-square" className="profile-row-icon" />
|
||||
<text className="profile-row-text">智能体</text>
|
||||
<text className="profile-row-value">多个人设</text>
|
||||
<Icon name="chevron-right" className="icon-sm" />
|
||||
</view>
|
||||
<view className="row-divider" />
|
||||
<view className="profile-row" bindtap={onOpenSettings}>
|
||||
<Icon name="gear" className="profile-row-icon" />
|
||||
<text className="profile-row-text">AI 内核设置</text>
|
||||
<Icon name="chevron-right" className="icon-sm" />
|
||||
</view>
|
||||
<view className="row-divider" />
|
||||
<view className="profile-row" bindtap={onToggleMemory}>
|
||||
<Icon name="person" className="profile-row-icon" />
|
||||
<text className="profile-row-text">{`记忆开关(当前${memoryEnabled ? '开' : '关'})`}</text>
|
||||
<Icon name="chevron-right" className="icon-sm" />
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
);
|
||||
}
|
||||
303
app/src/pages/Settings.tsx
Normal file
303
app/src/pages/Settings.tsx
Normal file
@@ -0,0 +1,303 @@
|
||||
import { useCallback, useEffect, useState } from '@lynx-js/react';
|
||||
|
||||
import type { AppState, Settings } from '../types.js';
|
||||
import { cv } from '../lynx-input.js';
|
||||
import { Icon } from '../Icon.js';
|
||||
|
||||
interface SettingsProps {
|
||||
state: AppState;
|
||||
onBack: () => void;
|
||||
onSaved: (patch: Record<string, unknown>) => Promise<void>;
|
||||
}
|
||||
|
||||
/** 思考强度:方舟/智谱映射顶层 thinking,OpenAI/OpenRouter 映射 reasoning_effort,其余不发 */
|
||||
const THINKING_OPTIONS = [
|
||||
{ value: 'auto', label: '自动' },
|
||||
{ value: 'off', label: '关' },
|
||||
{ value: 'low', label: '低' },
|
||||
{ value: 'medium', label: '中' },
|
||||
{ value: 'high', label: '高' },
|
||||
];
|
||||
|
||||
const THINKING_HINT: Record<string, string> = {
|
||||
auto: '不干预,由模型自己决定要不要想。',
|
||||
off: '发 thinking=disabled / reasoning_effort=minimal;不支持的厂商则什么都不发。回答最快。',
|
||||
low: '方舟、智谱:thinking=enabled;OpenAI、OpenRouter:reasoning_effort=low。',
|
||||
medium: '方舟、智谱:thinking=enabled;OpenAI、OpenRouter:reasoning_effort=medium。',
|
||||
high: '方舟、智谱:thinking=enabled;OpenAI、OpenRouter:reasoning_effort=high。想得最久、最慢,难题用。',
|
||||
};
|
||||
|
||||
/** 提供商显示名:去掉括号里的补充说明,段选里才排得下('Kimi(月之暗面)' → 'Kimi') */
|
||||
function shortProviderLabel(label: string, key: string): string {
|
||||
const base = label.split('(')[0].split('(')[0].trim();
|
||||
return base || key;
|
||||
}
|
||||
|
||||
/**
|
||||
* 只生成"真正改动过"的字段。
|
||||
*
|
||||
* 为什么不能全量下发:/api/settings 是浅合并,多带一个空字符串就等于把它清空。
|
||||
* 之前这里就是把整个 form 发出去,一旦表单还没从服务端设置同步好(首屏 state 还在路上),
|
||||
* 一次保存就把配置清空了。内核那边现在也拒收空的关键字段,但前端不该依赖那个兜底。
|
||||
*/
|
||||
function diffForm(form: Settings, base: Settings): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {};
|
||||
|
||||
if (form.provider && form.provider !== base.provider) out.provider = form.provider;
|
||||
if (form.baseUrl?.trim() && form.baseUrl.trim() !== base.baseUrl) out.baseUrl = form.baseUrl.trim();
|
||||
if (form.model?.trim() && form.model.trim() !== base.model) out.model = form.model.trim();
|
||||
if (form.temperature !== base.temperature) out.temperature = Number(form.temperature) || 0.7;
|
||||
if (form.maxRounds !== base.maxRounds) out.maxRounds = Number(form.maxRounds) || 6;
|
||||
if (form.thinkingLevel && form.thinkingLevel !== base.thinkingLevel) out.thinkingLevel = form.thinkingLevel;
|
||||
if ((form.toolsDir ?? '') !== (base.toolsDir ?? '')) out.toolsDir = form.toolsDir ?? '';
|
||||
if ((form.systemPrompt ?? '') !== (base.systemPrompt ?? '')) out.systemPrompt = form.systemPrompt;
|
||||
if (form.nickname?.trim() && form.nickname !== base.nickname) out.nickname = form.nickname.trim();
|
||||
if ((form.doubaoId ?? '') !== (base.doubaoId ?? '')) out.doubaoId = form.doubaoId ?? '';
|
||||
if (form.tools?.python !== base.tools?.python || form.tools?.mcp !== base.tools?.mcp) {
|
||||
out.tools = form.tools;
|
||||
}
|
||||
// API Key 只有真敲了才发;空白 = 不改
|
||||
if (form.apiKey?.trim()) out.apiKey = form.apiKey.trim();
|
||||
return out;
|
||||
}
|
||||
|
||||
export function SettingsPage(props: SettingsProps) {
|
||||
const { state, onBack, onSaved } = props;
|
||||
const [form, setForm] = useState<Settings>({ ...state.settings });
|
||||
/**
|
||||
* 记住"上一次看到的服务端设置"。
|
||||
*
|
||||
* 为什么需要:这个页面可能在 state 还没加载完时就挂载了,那时 form 里全是**默认值**
|
||||
* (provider=ark、空 baseUrl),界面上会显示成"火山方舟",用户一保存就把配置改掉了。
|
||||
* 现在只在服务端设置真的变了(首次加载完成 / 保存回来)时才重建草稿,
|
||||
* 既不会漏同步,也不会因为一次无关的 state 刷新把正在输入的内容冲掉。
|
||||
*/
|
||||
const [snapshot, setSnapshot] = useState<Settings>({ ...state.settings });
|
||||
useEffect(() => {
|
||||
if (JSON.stringify(snapshot) !== JSON.stringify(state.settings)) {
|
||||
setSnapshot({ ...state.settings });
|
||||
setForm({ ...state.settings });
|
||||
}
|
||||
}, [state.settings, snapshot]);
|
||||
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
|
||||
const patch = useCallback((next: Partial<Settings>) => {
|
||||
setForm((prev) => ({ ...prev, ...next }));
|
||||
}, []);
|
||||
|
||||
const setTools = useCallback((key: 'python' | 'mcp', value: boolean) => {
|
||||
setForm((prev) => ({ ...prev, tools: { ...prev.tools, [key]: value } }));
|
||||
}, []);
|
||||
|
||||
const switchProvider = useCallback((provider: string) => {
|
||||
const preset = state.providers[provider];
|
||||
if (!preset) return;
|
||||
setForm((prev) => ({ ...prev, provider, baseUrl: preset.baseUrl, model: preset.defaultModel }));
|
||||
}, [state.providers]);
|
||||
|
||||
const save = useCallback(async () => {
|
||||
setSaving(true);
|
||||
setMessage('');
|
||||
try {
|
||||
// 只发改动过的字段(见 diffForm 的注释:全量下发会把没填的字段清空)
|
||||
const changed = diffForm(form, state.settings);
|
||||
if (Object.keys(changed).length === 0) {
|
||||
setMessage('没有改动');
|
||||
return;
|
||||
}
|
||||
await onSaved(changed);
|
||||
setMessage('已保存 ✅');
|
||||
} catch (err) {
|
||||
setMessage(`保存失败:${(err as Error).message}`);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, [form, onSaved, state.settings]);
|
||||
|
||||
const preset = state.providers[form.provider] || state.provider;
|
||||
|
||||
return (
|
||||
<view className="page">
|
||||
<view className="sub-header">
|
||||
<view className="back-btn" bindtap={onBack}>
|
||||
<text style={{ fontSize: '24px', color: '#1f2329' }}>‹</text>
|
||||
</view>
|
||||
<text className="sub-header-title">AI 内核设置</text>
|
||||
<text style={{ fontSize: '13px', color: '#8a8f99' }}>{saving ? '保存中…' : ''}</text>
|
||||
</view>
|
||||
|
||||
<scroll-view className="form-scroll" scroll-orientation="vertical" scroll-y>
|
||||
<view className="form-inner">
|
||||
<view className="form-card">
|
||||
<text className="form-label">模型提供商</text>
|
||||
{/* ★ 有几家列几家:内核现在有十来家兼容厂商(方舟/OpenAI/DeepSeek/Kimi/智谱/通义/
|
||||
硅基流动/OpenRouter/本地 Ollama/自定义),它们都是 OpenAI 兼容协议,
|
||||
区别只在地址和思考参数 —— 往这里写死两家,新加的厂商界面上就选不到。 */}
|
||||
<view className="segment segment-wrap">
|
||||
{Object.keys(state.providers).map((key) => (
|
||||
<view
|
||||
key={key}
|
||||
className={form.provider === key ? 'segment-item segment-item-active' : 'segment-item'}
|
||||
bindtap={() => switchProvider(key)}
|
||||
>
|
||||
<text className={form.provider === key ? 'segment-text segment-text-active' : 'segment-text'}>
|
||||
{shortProviderLabel(state.providers[key]?.label || key, key)}
|
||||
</text>
|
||||
</view>
|
||||
))}
|
||||
</view>
|
||||
<text className="form-hint">{preset.modelHint}</text>
|
||||
</view>
|
||||
|
||||
<view className="form-card">
|
||||
<text className="form-label">Base URL</text>
|
||||
<input
|
||||
className="form-input"
|
||||
{...cv(form.baseUrl)}
|
||||
bindinput={(e: { detail: { value: string } }) => patch({ baseUrl: e.detail.value })}
|
||||
/>
|
||||
<text className="form-hint">{`默认:${preset.baseUrl}`}</text>
|
||||
|
||||
<text className="form-label" style={{ marginTop: '14px' }}>API Key</text>
|
||||
<input
|
||||
className="form-input"
|
||||
placeholder={state.settings.hasApiKey ? '已配置(留空则不变)' : '粘贴你的 API Key'}
|
||||
{...cv(form.apiKey)}
|
||||
bindinput={(e: { detail: { value: string } }) => patch({ apiKey: e.detail.value })}
|
||||
/>
|
||||
<text className="form-hint">{`也可以写在 server/.env 里:${preset.apiKeyEnv}=xxx`}</text>
|
||||
|
||||
<text className="form-label" style={{ marginTop: '14px' }}>模型</text>
|
||||
<input
|
||||
className="form-input"
|
||||
{...cv(form.model)}
|
||||
bindinput={(e: { detail: { value: string } }) => patch({ model: e.detail.value })}
|
||||
/>
|
||||
<view className="chip-row">
|
||||
{(preset.models || []).map((m) => (
|
||||
<view
|
||||
key={m}
|
||||
className={form.model === m ? 'model-chip model-chip-active' : 'model-chip'}
|
||||
bindtap={() => patch({ model: m })}
|
||||
>
|
||||
<text className={form.model === m ? 'model-chip-text model-chip-text-active' : 'model-chip-text'}>
|
||||
{m}
|
||||
</text>
|
||||
</view>
|
||||
))}
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view className="form-card">
|
||||
<text className="form-label">思考强度</text>
|
||||
<view className="segment">
|
||||
{THINKING_OPTIONS.map((item) => (
|
||||
<view
|
||||
key={item.value}
|
||||
className={form.thinkingLevel === item.value ? 'segment-item segment-item-active' : 'segment-item'}
|
||||
bindtap={() => patch({ thinkingLevel: item.value })}
|
||||
>
|
||||
<text
|
||||
className={
|
||||
form.thinkingLevel === item.value ? 'segment-text segment-text-active' : 'segment-text'
|
||||
}
|
||||
>
|
||||
{item.label}
|
||||
</text>
|
||||
</view>
|
||||
))}
|
||||
</view>
|
||||
<text className="form-hint">
|
||||
{THINKING_HINT[form.thinkingLevel] || THINKING_HINT.auto}
|
||||
</text>
|
||||
|
||||
<text className="form-label" style={{ marginTop: '14px' }}>工具目录(可选)</text>
|
||||
<input
|
||||
className="form-input"
|
||||
placeholder="留空 = 用内置的 tools/ 目录"
|
||||
{...cv(form.toolsDir)}
|
||||
bindinput={(e: { detail: { value: string } }) => patch({ toolsDir: e.detail.value })}
|
||||
/>
|
||||
<text className="form-hint">
|
||||
目录里的 *.py 会自动变成工具(同 tools/_protocol.py 协议)。安卓端可以指到手机上的目录,
|
||||
例如 /sdcard/Documents/doubao-tools
|
||||
</text>
|
||||
</view>
|
||||
|
||||
<view className="form-card">
|
||||
<text className="form-label">系统提示词(System Prompt)</text>
|
||||
<textarea
|
||||
className="form-textarea"
|
||||
{...cv(form.systemPrompt)}
|
||||
bindinput={(e: { detail: { value: string } }) => patch({ systemPrompt: e.detail.value })}
|
||||
/>
|
||||
<text className="form-hint">这段提示词会在每次对话最前面发给模型,可随意改成你想要的性格和规则。</text>
|
||||
|
||||
<text className="form-label" style={{ marginTop: '14px' }}>工具循环上限(最多调用几轮工具)</text>
|
||||
<input
|
||||
className="form-input"
|
||||
{...cv(String(form.maxRounds))}
|
||||
bindinput={(e: { detail: { value: string } }) => patch({ maxRounds: Number(e.detail.value) || 6 })}
|
||||
/>
|
||||
</view>
|
||||
|
||||
<view className="form-card">
|
||||
<text className="form-label">工具</text>
|
||||
<view className="switch-row">
|
||||
<text className="switch-label">Python 工具(tools/*.py)</text>
|
||||
<view
|
||||
className={form.tools.python ? 'switch switch-on' : 'switch'}
|
||||
bindtap={() => setTools('python', !form.tools.python)}
|
||||
>
|
||||
<view className="switch-knob" />
|
||||
</view>
|
||||
</view>
|
||||
<view className="row-divider" />
|
||||
<view className="switch-row">
|
||||
<text className="switch-label">MCP 服务</text>
|
||||
<view
|
||||
className={form.tools.mcp ? 'switch switch-on' : 'switch'}
|
||||
bindtap={() => setTools('mcp', !form.tools.mcp)}
|
||||
>
|
||||
<view className="switch-knob" />
|
||||
</view>
|
||||
</view>
|
||||
<text className="form-hint">
|
||||
{`当前解释器:${state.python.interpreter || '未找到'} · Python 工具 ${state.python.tools.length} 个 · MCP 工具 ${
|
||||
state.mcp.reduce((sum, s) => sum + s.tools.length, 0)
|
||||
} 个`}
|
||||
</text>
|
||||
</view>
|
||||
|
||||
<view className="form-card">
|
||||
<text className="form-label">个人资料</text>
|
||||
<input
|
||||
className="form-input"
|
||||
{...cv(form.nickname)}
|
||||
bindinput={(e: { detail: { value: string } }) => patch({ nickname: e.detail.value })}
|
||||
/>
|
||||
<text className="form-label" style={{ marginTop: '14px' }}>豆包号</text>
|
||||
<input
|
||||
className="form-input"
|
||||
{...cv(form.doubaoId)}
|
||||
bindinput={(e: { detail: { value: string } }) => patch({ doubaoId: e.detail.value })}
|
||||
/>
|
||||
</view>
|
||||
|
||||
<view className="primary-btn" bindtap={save}>
|
||||
<text className="primary-btn-text">保存设置</text>
|
||||
</view>
|
||||
{message
|
||||
? (
|
||||
<text className="form-hint" style={{ textAlign: 'center', marginTop: '10px' }}>
|
||||
{message}
|
||||
</text>
|
||||
)
|
||||
: null}
|
||||
</view>
|
||||
</scroll-view>
|
||||
</view>
|
||||
);
|
||||
}
|
||||
548
app/src/pages/Skills.tsx
Normal file
548
app/src/pages/Skills.tsx
Normal file
@@ -0,0 +1,548 @@
|
||||
import { useCallback, useEffect, useState } from '@lynx-js/react';
|
||||
|
||||
import type { AppState, Security } from '../types.js';
|
||||
import { api } from '../api.js';
|
||||
import { cv } from '../lynx-input.js';
|
||||
import { Icon } from '../Icon.js';
|
||||
|
||||
interface SkillsProps {
|
||||
state: AppState;
|
||||
onBack: () => void;
|
||||
onRefresh: () => Promise<void>;
|
||||
onSaveSecurity: (security: Security) => Promise<void>;
|
||||
}
|
||||
|
||||
interface ServerDraft {
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
transport: 'stdio' | 'http' | 'sse';
|
||||
command: string;
|
||||
argsText: string;
|
||||
envText: string;
|
||||
url: string;
|
||||
headersText: string;
|
||||
note?: string;
|
||||
}
|
||||
|
||||
function preview(value: unknown): string {
|
||||
const text = typeof value === 'string' ? value : JSON.stringify(value);
|
||||
return text.length > 600 ? `${text.slice(0, 600)}…` : text;
|
||||
}
|
||||
|
||||
function jsonOr(value: string, fallback: Record<string, string>): Record<string, string> {
|
||||
const raw = (value || '').trim();
|
||||
if (!raw) return fallback;
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return parsed && typeof parsed === 'object' ? parsed : fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function parseServers(text: string): ServerDraft[] {
|
||||
try {
|
||||
const json = JSON.parse(text);
|
||||
const servers = Array.isArray(json) ? json : json.servers || [];
|
||||
return servers.map((s: Record<string, unknown>) => ({
|
||||
name: String(s.name || ''),
|
||||
enabled: s.enabled !== false,
|
||||
transport: (s.transport as ServerDraft['transport']) || 'stdio',
|
||||
command: String(s.command || ''),
|
||||
argsText: Array.isArray(s.args) ? (s.args as string[]).join('\n') : '',
|
||||
envText: s.env && Object.keys(s.env as object).length ? JSON.stringify(s.env, null, 0) : '',
|
||||
url: String(s.url || ''),
|
||||
headersText: s.headers && Object.keys(s.headers as object).length ? JSON.stringify(s.headers, null, 0) : '',
|
||||
note: s.note ? String(s.note) : undefined,
|
||||
}));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function serializeServers(list: ServerDraft[]): string {
|
||||
const servers = list.map((s) => {
|
||||
const base: Record<string, unknown> = {
|
||||
name: s.name.trim(),
|
||||
enabled: s.enabled,
|
||||
transport: s.transport,
|
||||
};
|
||||
if (s.transport === 'stdio') {
|
||||
base.command = s.command.trim();
|
||||
base.args = s.argsText.split('\n').map((x) => x.trim()).filter(Boolean);
|
||||
const env = jsonOr(s.envText, {});
|
||||
if (Object.keys(env).length) base.env = env;
|
||||
} else {
|
||||
base.url = s.url.trim();
|
||||
const headers = jsonOr(s.headersText, {});
|
||||
if (Object.keys(headers).length) base.headers = headers;
|
||||
}
|
||||
if (s.note) base.note = s.note;
|
||||
return base;
|
||||
});
|
||||
return JSON.stringify({ servers }, null, 2);
|
||||
}
|
||||
|
||||
export function SkillsPage(props: SkillsProps) {
|
||||
const { state, onBack, onRefresh, onSaveSecurity } = props;
|
||||
|
||||
const [args, setArgs] = useState<Record<string, string>>({});
|
||||
const [results, setResults] = useState<Record<string, string>>({});
|
||||
const [busy, setBusy] = useState('');
|
||||
const [message, setMessage] = useState('');
|
||||
|
||||
const [mcpPath, setMcpPath] = useState('');
|
||||
const [canReveal, setCanReveal] = useState(false);
|
||||
const [mcpTab, setMcpTab] = useState<'gui' | 'json'>('gui');
|
||||
const [mcpText, setMcpText] = useState('');
|
||||
const [drafts, setDrafts] = useState<ServerDraft[]>([]);
|
||||
|
||||
const [security, setSecurity] = useState<Security>(state.settings.security || { mode: 'open', allow: [] });
|
||||
const [showTools, setShowTools] = useState(false);
|
||||
|
||||
const loadMcp = useCallback(async () => {
|
||||
try {
|
||||
const detail = await api.mcpDetail();
|
||||
setMcpPath(detail.path);
|
||||
setCanReveal(Boolean(detail.canReveal));
|
||||
setMcpText(detail.text);
|
||||
setDrafts(parseServers(detail.text));
|
||||
} catch (err) {
|
||||
setMessage(`读取 MCP 配置失败:${(err as Error).message}`);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadMcp();
|
||||
}, [loadMcp]);
|
||||
|
||||
/* -------------------- 工具试运行 -------------------- */
|
||||
const runTool = useCallback(async (name: string) => {
|
||||
setBusy(name);
|
||||
try {
|
||||
let parsed: Record<string, unknown> = {};
|
||||
const raw = (args[name] || '').trim();
|
||||
if (raw) {
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
setResults((prev) => ({ ...prev, [name]: '参数不是合法 JSON,已按空参数执行' }));
|
||||
}
|
||||
}
|
||||
const res = await api.runTool(name, parsed);
|
||||
setResults((prev) => ({
|
||||
...prev,
|
||||
[name]: res.ok ? preview(res.result ?? '(无输出)') : `调用失败:${res.error || '未知错误'}`,
|
||||
}));
|
||||
} catch (err) {
|
||||
setResults((prev) => ({ ...prev, [name]: `请求失败:${(err as Error).message}` }));
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
}, [args]);
|
||||
|
||||
/* -------------------- MCP -------------------- */
|
||||
const patchServer = useCallback((index: number, next: Partial<ServerDraft>) => {
|
||||
setDrafts((prev) => prev.map((item, i) => (i === index ? { ...item, ...next } : item)));
|
||||
}, []);
|
||||
|
||||
const saveMcp = useCallback(async () => {
|
||||
const text = mcpTab === 'json' ? mcpText : serializeServers(drafts);
|
||||
setBusy('save-mcp');
|
||||
setMessage('');
|
||||
try {
|
||||
const res = await api.saveMcpConfig(text);
|
||||
if (!res.ok) {
|
||||
setMessage(`保存失败:${res.error || '未知错误'}`);
|
||||
return;
|
||||
}
|
||||
const lines = (res.results || []).map((r) => (r.ok ? `✓ ${r.name}` : `✗ ${r.name}:${r.error || '连接失败'}`));
|
||||
setMessage(`已保存 ${res.count} 个服务\n${lines.join('\n')}`);
|
||||
await loadMcp();
|
||||
await onRefresh();
|
||||
} catch (err) {
|
||||
setMessage(`保存失败:${(err as Error).message}`);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
}, [mcpTab, mcpText, drafts, loadMcp, onRefresh]);
|
||||
|
||||
const toggleMcp = useCallback(async (name: string, connected: boolean) => {
|
||||
setBusy(`mcp:${name}`);
|
||||
try {
|
||||
if (connected) await api.disconnectMcp(name);
|
||||
else await api.connectMcp(name);
|
||||
await onRefresh();
|
||||
} catch (err) {
|
||||
setMessage(`操作失败:${(err as Error).message}`);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
}, [onRefresh]);
|
||||
|
||||
const reveal = useCallback(async () => {
|
||||
try {
|
||||
const res = await api.revealMcp();
|
||||
if (!res.ok) setMessage(res.error || `配置文件在:${res.path}`);
|
||||
} catch (err) {
|
||||
setMessage(`打开失败:${(err as Error).message}`);
|
||||
}
|
||||
}, []);
|
||||
|
||||
/* -------------------- 安全模式 -------------------- */
|
||||
const toggleAllow = useCallback((name: string) => {
|
||||
setSecurity((prev) => {
|
||||
const has = prev.allow.includes(name);
|
||||
return { ...prev, allow: has ? prev.allow.filter((x) => x !== name) : [...prev.allow, name] };
|
||||
});
|
||||
}, []);
|
||||
|
||||
const applySecurity = useCallback(async () => {
|
||||
setBusy('security');
|
||||
setMessage('');
|
||||
try {
|
||||
await onSaveSecurity(security);
|
||||
setMessage(security.mode === 'open' ? '已切到完全开放模式' : `已切到限制模式,授权 ${security.allow.length} 个工具`);
|
||||
} catch (err) {
|
||||
setMessage(`保存失败:${(err as Error).message}`);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
}, [security, onSaveSecurity]);
|
||||
|
||||
const restrictAll = useCallback(() => {
|
||||
setSecurity({ mode: 'restricted', allow: state.suggestedAllow });
|
||||
}, [state.suggestedAllow]);
|
||||
|
||||
return (
|
||||
<view className="page">
|
||||
<view className="sub-header">
|
||||
<view className="back-btn" bindtap={onBack}>
|
||||
<text style={{ fontSize: '24px', color: '#1f2329' }}>‹</text>
|
||||
</view>
|
||||
<text className="sub-header-title">技能 · 连接器</text>
|
||||
<view className="hdr-btn" bindtap={onRefresh}>
|
||||
<Icon name="gear" className="icon-sm" />
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<scroll-view className="form-scroll" scroll-orientation="vertical" scroll-y>
|
||||
<view className="form-inner">
|
||||
{/* ============ 安全模式 ============ */}
|
||||
<view className="form-card fade-in-up">
|
||||
<text className="form-label">工具权限</text>
|
||||
<view className="segment">
|
||||
<view
|
||||
className={security.mode === 'open' ? 'segment-item segment-item-active' : 'segment-item'}
|
||||
bindtap={() => setSecurity((prev) => ({ ...prev, mode: 'open' }))}
|
||||
>
|
||||
<text className={security.mode === 'open' ? 'segment-text segment-text-active' : 'segment-text'}>
|
||||
完全开放
|
||||
</text>
|
||||
</view>
|
||||
<view
|
||||
className={security.mode === 'restricted' ? 'segment-item segment-item-active' : 'segment-item'}
|
||||
bindtap={() => setSecurity((prev) => ({ ...prev, mode: 'restricted' }))}
|
||||
>
|
||||
<text className={security.mode === 'restricted' ? 'segment-text segment-text-active' : 'segment-text'}>
|
||||
限制模式
|
||||
</text>
|
||||
</view>
|
||||
</view>
|
||||
<text className="form-hint">
|
||||
{security.mode === 'open'
|
||||
? `完全开放:${state.toolNames.length} 个工具都交给模型自由调用。`
|
||||
: `限制模式:只有下面勾选的工具可用,其余即使模型点名也会被拦下。已选 ${security.allow.length} 个。`}
|
||||
</text>
|
||||
|
||||
{security.mode === 'restricted'
|
||||
? (
|
||||
<view style={{ display: 'flex', flexDirection: 'column', marginTop: '10px' }}>
|
||||
<view className="tool-actions" style={{ marginTop: '0px' }}>
|
||||
<view className="ghost-btn" bindtap={() => setShowTools(!showTools)}>
|
||||
<text className="ghost-btn-text">{showTools ? '收起工具列表' : `选择工具(${security.allow.length})`}</text>
|
||||
</view>
|
||||
<view className="ghost-btn" style={{ marginLeft: '8px' }} bindtap={restrictAll}>
|
||||
<text className="ghost-btn-text">只勾只读工具</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
{showTools
|
||||
? (
|
||||
<view className="tool-picker">
|
||||
{state.toolNames.map((name) => {
|
||||
const on = security.allow.includes(name);
|
||||
return (
|
||||
<view className="tool-pick-row" key={name} bindtap={() => toggleAllow(name)}>
|
||||
<view className={on ? 'checkbox checkbox-on' : 'checkbox'}>
|
||||
{on ? <text className="checkbox-tick">✓</text> : null}
|
||||
</view>
|
||||
<text className="tool-pick-name">{name}</text>
|
||||
{state.suggestedAllow.includes(name)
|
||||
? <text className="tool-pick-tag">只读</text>
|
||||
: null}
|
||||
</view>
|
||||
);
|
||||
})}
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
|
||||
<view className="primary-btn" style={{ marginTop: '12px' }} bindtap={applySecurity}>
|
||||
<text className="primary-btn-text">{busy === 'security' ? '保存中…' : '应用权限设置'}</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
{/* ============ Python 工具 ============ */}
|
||||
<view className="form-card">
|
||||
<text className="form-label">
|
||||
{`Python 工具 · ${state.python.tools.length} 个 · 解释器 ${state.python.interpreter || '未找到'}`}
|
||||
</text>
|
||||
{state.python.errors.map((err) => (
|
||||
<text className="form-hint" key={err.file}>{`⚠ ${err.file}:${err.error}`}</text>
|
||||
))}
|
||||
{state.python.tools.length === 0
|
||||
? <text className="empty-tip">没有发现工具。往 tools/ 里放一个 *.py,用 _protocol.serve() 暴露即可。</text>
|
||||
: null}
|
||||
{state.python.tools.map((tool) => (
|
||||
<view className="tool-item" key={tool.name}>
|
||||
<text className="tool-name">{tool.name}</text>
|
||||
<text className="tool-desc">{tool.description}</text>
|
||||
<text className="tool-meta">{tool.file}</text>
|
||||
<input
|
||||
className="form-input"
|
||||
style={{ marginTop: '8px', height: '36px', fontSize: '13px' }}
|
||||
placeholder='参数 JSON,例如 {"expression":"1+1"}'
|
||||
{...cv(args[tool.name] || '')}
|
||||
bindinput={(e: { detail: { value: string } }) =>
|
||||
setArgs((prev) => ({ ...prev, [tool.name]: e.detail.value }))}
|
||||
/>
|
||||
<view className="tool-actions">
|
||||
<view className="ghost-btn" bindtap={() => runTool(tool.name)}>
|
||||
<text className="ghost-btn-text">{busy === tool.name ? '执行中…' : '试运行'}</text>
|
||||
</view>
|
||||
</view>
|
||||
{results[tool.name]
|
||||
? (
|
||||
<view className="result-box">
|
||||
<text className="result-text">{results[tool.name]}</text>
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
</view>
|
||||
))}
|
||||
</view>
|
||||
|
||||
{/* ============ MCP ============ */}
|
||||
<view className="form-card">
|
||||
<text className="form-label">MCP 服务</text>
|
||||
<text className="tool-meta" style={{ marginTop: '0px' }}>
|
||||
{mcpPath ? `配置文件:${mcpPath}` : '配置文件:读取中…'}
|
||||
</text>
|
||||
|
||||
<view className="segment" style={{ marginTop: '10px' }}>
|
||||
<view
|
||||
className={mcpTab === 'gui' ? 'segment-item segment-item-active' : 'segment-item'}
|
||||
bindtap={() => {
|
||||
setDrafts(parseServers(mcpText));
|
||||
setMcpTab('gui');
|
||||
}}
|
||||
>
|
||||
<text className={mcpTab === 'gui' ? 'segment-text segment-text-active' : 'segment-text'}>图形化</text>
|
||||
</view>
|
||||
<view
|
||||
className={mcpTab === 'json' ? 'segment-item segment-item-active' : 'segment-item'}
|
||||
bindtap={() => {
|
||||
setMcpText(serializeServers(drafts));
|
||||
setMcpTab('json');
|
||||
}}
|
||||
>
|
||||
<text className={mcpTab === 'json' ? 'segment-text segment-text-active' : 'segment-text'}>原始 JSON</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
{mcpTab === 'gui'
|
||||
? (
|
||||
<view style={{ display: 'flex', flexDirection: 'column', marginTop: '10px' }}>
|
||||
{drafts.map((server, index) => (
|
||||
<view className="server-card" key={`${server.name}-${index}`}>
|
||||
<view className="server-head">
|
||||
<input
|
||||
className="form-input server-name"
|
||||
placeholder="服务名(唯一)"
|
||||
{...cv(server.name)}
|
||||
bindinput={(e: { detail: { value: string } }) => patchServer(index, { name: e.detail.value })}
|
||||
/>
|
||||
<view
|
||||
className={server.enabled ? 'switch switch-on' : 'switch'}
|
||||
bindtap={() => patchServer(index, { enabled: !server.enabled })}
|
||||
>
|
||||
<view className="switch-knob" />
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view className="segment" style={{ marginTop: '8px' }}>
|
||||
{(['stdio', 'http', 'sse'] as const).map((t) => (
|
||||
<view
|
||||
key={t}
|
||||
className={server.transport === t ? 'segment-item segment-item-active' : 'segment-item'}
|
||||
bindtap={() => patchServer(index, { transport: t })}
|
||||
>
|
||||
<text className={server.transport === t ? 'segment-text segment-text-active' : 'segment-text'}>
|
||||
{t}
|
||||
</text>
|
||||
</view>
|
||||
))}
|
||||
</view>
|
||||
|
||||
{server.transport === 'stdio'
|
||||
? (
|
||||
<>
|
||||
<text className="form-label" style={{ marginTop: '10px' }}>命令</text>
|
||||
<input
|
||||
className="form-input"
|
||||
placeholder="npx / python / node"
|
||||
{...cv(server.command)}
|
||||
bindinput={(e: { detail: { value: string } }) => patchServer(index, { command: e.detail.value })}
|
||||
/>
|
||||
<text className="form-label" style={{ marginTop: '10px' }}>参数(一行一个)</text>
|
||||
<textarea
|
||||
className="form-textarea"
|
||||
style={{ height: '86px', fontSize: '13px' }}
|
||||
placeholder={'-y\n@modelcontextprotocol/server-memory'}
|
||||
{...cv(server.argsText)}
|
||||
bindinput={(e: { detail: { value: string } }) => patchServer(index, { argsText: e.detail.value })}
|
||||
/>
|
||||
<text className="form-label" style={{ marginTop: '10px' }}>环境变量(JSON,可空)</text>
|
||||
<input
|
||||
className="form-input"
|
||||
placeholder='{"TOKEN":"xxx"}'
|
||||
{...cv(server.envText)}
|
||||
bindinput={(e: { detail: { value: string } }) => patchServer(index, { envText: e.detail.value })}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
: (
|
||||
<>
|
||||
<text className="form-label" style={{ marginTop: '10px' }}>URL</text>
|
||||
<input
|
||||
className="form-input"
|
||||
placeholder="https://your-host/mcp"
|
||||
{...cv(server.url)}
|
||||
bindinput={(e: { detail: { value: string } }) => patchServer(index, { url: e.detail.value })}
|
||||
/>
|
||||
<text className="form-label" style={{ marginTop: '10px' }}>请求头(JSON,可空)</text>
|
||||
<input
|
||||
className="form-input"
|
||||
placeholder='{"Authorization":"Bearer xxx"}'
|
||||
{...cv(server.headersText)}
|
||||
bindinput={(e: { detail: { value: string } }) => patchServer(index, { headersText: e.detail.value })}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<view className="tool-actions">
|
||||
<view
|
||||
className="ghost-btn"
|
||||
bindtap={() => setDrafts((prev) => prev.filter((_, i) => i !== index))}
|
||||
>
|
||||
<text className="ghost-btn-text">删除这个服务</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
))}
|
||||
|
||||
<view
|
||||
className="ghost-btn"
|
||||
style={{ alignSelf: 'flex-start' }}
|
||||
bindtap={() => setDrafts((prev) => [...prev, {
|
||||
name: `server-${prev.length + 1}`,
|
||||
enabled: false,
|
||||
transport: 'stdio',
|
||||
command: 'npx',
|
||||
argsText: '-y',
|
||||
envText: '',
|
||||
url: '',
|
||||
headersText: '',
|
||||
}])}
|
||||
>
|
||||
<text className="ghost-btn-text">+ 添加服务</text>
|
||||
</view>
|
||||
</view>
|
||||
)
|
||||
: (
|
||||
<view style={{ display: 'flex', flexDirection: 'column', marginTop: '10px' }}>
|
||||
<textarea
|
||||
className="form-textarea"
|
||||
style={{ height: '300px', fontSize: '12px', lineHeight: '18px' }}
|
||||
{...cv(mcpText)}
|
||||
bindinput={(e: { detail: { value: string } }) => setMcpText(e.detail.value)}
|
||||
/>
|
||||
<text className="form-hint">
|
||||
支持 stdio / http / sse。路径里可以写 {'${DOUBAO_DATA}'}、{'${APPDATA}'}、{'${USERPROFILE}'} 占位符;
|
||||
Windows 下 command 写 npx/npm/node 会自动包一层 cmd /c。
|
||||
</text>
|
||||
</view>
|
||||
)}
|
||||
|
||||
<view className="primary-btn" style={{ marginTop: '12px' }} bindtap={saveMcp}>
|
||||
<text className="primary-btn-text">{busy === 'save-mcp' ? '保存中…' : '保存并重连'}</text>
|
||||
</view>
|
||||
|
||||
<view className="tool-actions">
|
||||
<view className="ghost-btn" bindtap={loadMcp}>
|
||||
<text className="ghost-btn-text">重新读取</text>
|
||||
</view>
|
||||
{canReveal
|
||||
? (
|
||||
<view className="ghost-btn" style={{ marginLeft: '8px' }} bindtap={reveal}>
|
||||
<text className="ghost-btn-text">打开所在文件夹</text>
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
</view>
|
||||
|
||||
{message
|
||||
? (
|
||||
<view className="result-box">
|
||||
<text className="result-text">{message}</text>
|
||||
</view>
|
||||
)
|
||||
: null}
|
||||
</view>
|
||||
|
||||
<view className="form-card">
|
||||
<text className="form-label">已连接的服务</text>
|
||||
{state.mcp.length === 0
|
||||
? <text className="empty-tip">还没有配置 MCP 服务。</text>
|
||||
: null}
|
||||
{state.mcp.map((server) => (
|
||||
<view className="tool-item" key={server.name}>
|
||||
<view style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
|
||||
<text className="tool-name">{server.name}</text>
|
||||
<view className={server.connected ? 'badge badge-ok' : 'badge'}>
|
||||
<text className={server.connected ? 'badge-text badge-text-ok' : 'badge-text'}>
|
||||
{server.connected ? `已连接 · ${server.tools.length} 工具` : '未连接'}
|
||||
</text>
|
||||
</view>
|
||||
</view>
|
||||
<text className="tool-meta">{`${server.transport} · ${server.target}`}</text>
|
||||
{server.error ? <text className="tool-desc" style={{ color: '#d4380d' }}>{server.error}</text> : null}
|
||||
<view className="tool-actions">
|
||||
<view className="ghost-btn" bindtap={() => toggleMcp(server.name, server.connected)}>
|
||||
<text className="ghost-btn-text">
|
||||
{busy === `mcp:${server.name}` ? '处理中…' : server.connected ? '断开' : '连接'}
|
||||
</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
))}
|
||||
</view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
</view>
|
||||
);
|
||||
}
|
||||
181
app/src/pages/Terminal.tsx
Normal file
181
app/src/pages/Terminal.tsx
Normal file
@@ -0,0 +1,181 @@
|
||||
import { useCallback, useRef, useState } from '@lynx-js/react';
|
||||
|
||||
import { api } from '../api.js';
|
||||
import { Icon } from '../Icon.js';
|
||||
import { cv } from '../lynx-input.js';
|
||||
|
||||
interface TerminalProps {
|
||||
onBack: () => void;
|
||||
/** 当前是走 Termux 还是系统自带 shell(从 device 工具查询) */
|
||||
shellChannel: string;
|
||||
onRefreshChannel: () => void;
|
||||
/** win32 / linux / android —— 决定预设命令用哪套 */
|
||||
platform?: string;
|
||||
}
|
||||
|
||||
/** 按平台给几条常用命令,点一下就跑,省得在手机上打字 */
|
||||
const PRESETS_ANDROID = [
|
||||
{ label: '我是谁', command: 'getprop ro.product.model; uname -a' },
|
||||
{ label: 'Python', command: 'python -V' },
|
||||
{ label: '电池', command: 'dumpsys battery | head -8' },
|
||||
{ label: '存储', command: 'df -h /data /sdcard' },
|
||||
];
|
||||
|
||||
const PRESETS_DESKTOP = [
|
||||
{ label: '系统', command: 'ver' },
|
||||
{ label: 'Python', command: 'python -V' },
|
||||
{ label: '目录', command: 'dir' },
|
||||
{ label: '网络', command: 'ping -n 2 127.0.0.1' },
|
||||
];
|
||||
|
||||
const PRESETS_POSIX = [
|
||||
{ label: '我是谁', command: 'uname -a; whoami' },
|
||||
{ label: 'Python', command: 'python3 -V' },
|
||||
{ label: '目录', command: 'pwd; ls -la' },
|
||||
{ label: '网络', command: 'ping -c 2 127.0.0.1' },
|
||||
];
|
||||
|
||||
interface Line {
|
||||
kind: 'cmd' | 'out' | 'err' | 'note';
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** 内置几条常用命令,点一下就跑,省得在手机上打字 */
|
||||
const PRESETS = [
|
||||
{ label: '我是谁', command: 'getprop ro.product.model; uname -a' },
|
||||
{ label: 'Python', command: 'python -V; pip list 2>/dev/null | head -20' },
|
||||
{ label: '文件', command: 'ls -la /sdcard/Android/data/com.doubao.lynxclone/files/tools' },
|
||||
{ label: '网络', command: 'ping -c 2 8.8.8.8' },
|
||||
];
|
||||
/**
|
||||
* 应用内终端。
|
||||
*
|
||||
* 命令不是直接本地执行的,而是走内核的 shell 工具 —— 这样电脑/手机走的是同一条路:
|
||||
* 手机:内核优先交给 Termux(装了且开了 allow-external-apps),否则退回系统 toybox
|
||||
* 电脑:cmd /c 或 /bin/sh -c
|
||||
* 所以在手机上它其实就是"Termux 的另一个入口",还省得在两个 App 之间来回切。
|
||||
*/
|
||||
export function TerminalPage(props: TerminalProps) {
|
||||
const { onBack, shellChannel, onRefreshChannel, platform } = props;
|
||||
const presets = platform === 'android' ? PRESETS_ANDROID
|
||||
: platform === 'win32' ? PRESETS_DESKTOP
|
||||
: PRESETS_POSIX;
|
||||
const [lines, setLines] = useState<Line[]>([
|
||||
{ kind: 'note', text: '输入命令回车执行。装了 Termux 的话会自动走 Termux 的 bash。' },
|
||||
]);
|
||||
const [draft, setDraft] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [signal, setSignal] = useState(0);
|
||||
const history = useRef<string[]>([]);
|
||||
|
||||
const push = useCallback((line: Line) => {
|
||||
setLines((prev) => [...prev.slice(-200), line]);
|
||||
setSignal((n) => n + 1);
|
||||
}, []);
|
||||
|
||||
const runCommand = useCallback(async (command: string) => {
|
||||
const cmd = command.trim();
|
||||
if (!cmd || busy) return;
|
||||
history.current = [cmd, ...history.current.filter((c) => c !== cmd)].slice(0, 30);
|
||||
push({ kind: 'cmd', text: `$ ${cmd}` });
|
||||
setDraft('');
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await api.runTool('shell', { command: cmd, timeout: 60 });
|
||||
if (!res.ok) {
|
||||
push({ kind: 'err', text: res.error || '执行失败' });
|
||||
} else {
|
||||
const r = (res.result || {}) as { stdout?: string; stderr?: string; exit_code?: number; via?: string; termux_note?: string };
|
||||
if (r.stdout) push({ kind: 'out', text: r.stdout.replace(/\s+$/, '') });
|
||||
if (r.stderr) push({ kind: 'err', text: r.stderr.replace(/\s+$/, '') });
|
||||
push({
|
||||
kind: 'note',
|
||||
text: `[退出码 ${r.exit_code ?? '?'}|通道 ${
|
||||
r.via === 'termux' ? 'Termux'
|
||||
: r.via === 'toybox' ? '系统 shell (toybox)'
|
||||
: r.via === 'cmd' ? 'Windows cmd'
|
||||
: r.via === 'sh' ? '/bin/sh'
|
||||
: r.via || '未知'
|
||||
}]`,
|
||||
});
|
||||
if (r.termux_note) push({ kind: 'note', text: r.termux_note });
|
||||
if (r.via && !termuxReady) onRefreshChannel();
|
||||
}
|
||||
} catch (err) {
|
||||
push({ kind: 'err', text: `连不上内核:${(err as Error).message}` });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
onRefreshChannel();
|
||||
}
|
||||
}, [busy, push, onRefreshChannel]);
|
||||
|
||||
const handleInput = useCallback((e: { detail: { value: string } }) => setDraft(e.detail.value), []);
|
||||
const handleConfirm = useCallback(() => { runCommand(draft); }, [draft, runCommand]);
|
||||
|
||||
const termuxReady = shellChannel === 'termux';
|
||||
const channelText = termuxReady
|
||||
? '通道:Termux(完整 Linux:bash / apt / pip / node)'
|
||||
: shellChannel === 'cmd' ? '通道:Windows cmd'
|
||||
: shellChannel === 'sh' ? '通道:/bin/sh'
|
||||
: shellChannel === 'toybox' || shellChannel === 'android'
|
||||
? '通道:系统自带 shell(toybox)。装 Termux 并在其中执行一次 echo "allow-external-apps=true" >> ~/.termux/termux.properties 即可升级'
|
||||
: '通道:未知(内核可能没连上)';
|
||||
|
||||
return (
|
||||
<view className="page terminal-page">
|
||||
<view className="term-head">
|
||||
<view className="hdr-btn" bindtap={onBack}>
|
||||
<Icon name="chevron-right" className="icon back-flip" />
|
||||
</view>
|
||||
<text className="term-title">终端</text>
|
||||
<view className="hdr-btn" bindtap={() => setLines([])}>
|
||||
<Icon name="close" className="icon-sm" />
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view className={termuxReady ? 'term-chip term-chip-ok' : 'term-chip'}>
|
||||
<text className="term-chip-text">{channelText}</text>
|
||||
</view>
|
||||
|
||||
<view className="term-presets">
|
||||
{presets.map((preset) => (
|
||||
<view className="chip" key={preset.label} bindtap={() => runCommand(preset.command)}>
|
||||
<text className="chip-text">{preset.label}</text>
|
||||
</view>
|
||||
))}
|
||||
</view>
|
||||
|
||||
<scroll-view className="term-body" scroll-orientation="vertical" scroll-y scroll-top={900000 + signal}>
|
||||
<view>
|
||||
{lines.map((line, index) => (
|
||||
<text
|
||||
key={`l${index}`}
|
||||
className={
|
||||
line.kind === 'cmd' ? 'term-line term-cmd'
|
||||
: line.kind === 'err' ? 'term-line term-err'
|
||||
: line.kind === 'note' ? 'term-line term-note'
|
||||
: 'term-line'
|
||||
}
|
||||
>
|
||||
{line.text}
|
||||
</text>
|
||||
))}
|
||||
{busy ? <text className="term-line term-note">执行中…</text> : null}
|
||||
</view>
|
||||
</scroll-view>
|
||||
|
||||
<view className="term-input-bar">
|
||||
<input
|
||||
className="term-input"
|
||||
placeholder="输入命令,回车执行"
|
||||
{...cv(draft)}
|
||||
bindinput={handleInput}
|
||||
bindconfirm={handleConfirm}
|
||||
/>
|
||||
<view className="send-btn" bindtap={handleConfirm}>
|
||||
<Icon name="send" className="icon-sm" />
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user