用户四条要求,全部做完并实测:
1. "弹出的网页可再点进去" → 网页界面里链接在应用内打开,顶部有返回键
2. "支持 js" → javaScriptEnabled=true,同时把桥按页面收口
3. "你要单独开个按钮" → 消息操作栏加「打开网页」按钮 + 独立全屏网页界面
4. "是 ai 自己能写进网页里的" → ★ 本次核心:Doubao.sendToAi 真的把值送回模型
## ★★ 数据回流(本次最重要的一条)
以前 `Doubao.pick` 只是"关闭界面 + 弹个提示",**值根本到不了模型手里**。
现在是一条完整的链路:
AI 写的 HTML 里 Doubao.sendToAi('用户选了方案B')
→ JS 桥 AiWebHost.sendToAi
→ NativeBridge 的 ui_result action → POST /api/ui-result
→ store 里排队(内存,一次性的上下文,不落盘)
→ 下一轮 run_agent 取走,作为**一条 system 消息**插在历史前面
→ 模型真的看到"用户在界面上选了什么"
★ 为什么排队而不是"点了就起一轮对话":
用户可能连点几下、选好几项再确认。每点一下跑一轮模型又慢又费 token,
而且用户还没说完。语义上界面上的选择是**提问的一部分,不是提问本身**。
★ 为什么插成 system 而不是 user:它不是用户打的话。塞成 user 会让历史里
出现一条用户没说过的话,而且"重新生成"时会和真正那条用户消息混在一起。
★ 提示语如实写"已记下,下次对话会告诉 AI",不写"已发送" ——
后者会让用户以为模型马上回话,然后干等。
三个入口都收:`Doubao.sendToAi(v)` / `Doubao.pick(v)` / `<button data-doubao-result="v">`。
## 实测证据(不是"看代码应该没问题")
起了一个假的 OpenAI 兼容服务,把内核指过去,直接读它收到的请求体:
[system] 你是豆包,…(系统提示词)
[system] 用户在**你上一个弹出来的界面上**做了这些操作(这是实时回传的,不是猜测):
- 用户选了方案 B(蓝色按钮)
- 用户填写了:预算 3000 元
[user] 我刚才在界面上选了什么?
假服务是在**模拟器里**连宿主机的,用 `adb reverse tcp:18080 tcp:18080`;
`10.0.2.2` 在 LDPlayer 上不通(假服务一个请求都收不到,很容易误判成代码有问题)。
## 顺带修的第三个真 bug:清不掉 Base URL
`store.write_settings` 有一段"保险":空串一律当"没填、别动"
(防的是"前端草稿没初始化好,一次保存清空整份配置")。
这个保险是对的,但代价是**用户永远清不掉自定义 Base URL / 模型名** ——
删光输入框、保存,值一点没变,看起来就是"保存按钮坏了"。
(我是在测回流时踩到的:想把内核从假服务指回默认,传空串怎么也改不掉。)
修法:加一条**显式**的清除通路 —— 值传 `null` 就是"确实要清掉",
落到默认值上。空串仍然="没填、别动"。Python 和 Node 两端都改了。
## 网页点选(用在真实网页上)
全屏网页界面顶部有「点选」横条,打开后可以在页面上点选内容、填写的表单值,
攒够了一起发给 AI。实现上**没有挂 JS 桥** —— 用"注入脚本写队列 +
Kotlin 主动轮询取走",数据只从页面流向 App,外部站点没有任何办法调 App。
★ 改过一版:第一版只认"看着能点"的元素(a/button/[role=button]…),
实测在 example.com 上一个都标不出来(那页全是纯文本),
于是点选模式看起来完全没生效。用户想点的是**任意一段内容**,
所以改成 `elementFromPoint` 点哪儿抓哪儿。
## 其他
· 正文里的 markdown 链接以前**没绑点击**(蓝色下划线,点了没反应)
—— 用户问"网页在哪点开"时才查出来。现在用 withLink 绑上了。
★ withLink 带 @ExperimentalTextApi,不 opt-in 报的是
`Unresolved reference 'withLink'`(不是"需要 opt-in"),
很容易误判成"这个版本没这个 API"。我是把 aar 拆开 javap 看注解才确认的。
· 链接列表用**独立全屏界面**(项目约定:列表这种要滚动的东西不用弹窗)
## 验证
新增 `scripts/verify-web-pick.py`(28 项)守:外部浏览**没有桥**、
取数要"取走"不清空会重复上报、input 用冒泡旁听不拦页面、
输入要防抖、多条要能累积、关闭入口、show_ui 说明里有 sendToAi。
★ 这个验证脚本自己绊了自己三次,都记在文件注释里了:
去注释的正则截断了字符串里的 "http://"、光找 "Doubao" 会命中 `Doubao.Blue`、
查 "Doubao.close()" 因为源码里是转义的 `\n` 而对不上。
**验证脚本自己有 bug 比没有更坏** —— 它会让人去改本来对的代码。
真机实测(Android 14 x86_64,新建的 LDPlayer 实例):
打开网页按钮 → 全屏链接列表 → 点进 example.com
点选模式 → 点一段文字,虚线框选中
sendToAi/pick/data-result → 队列 ["方案B","方案C","方案D"]
发一句话 → 队列被取走,假服务收到的请求里带上了那些值 ✓
588 lines
23 KiB
Python
588 lines
23 KiB
Python
"""
|
||
持久化:设置 / 会话 / 智能体。
|
||
|
||
对应 Node 版的 config.mjs(设置)+ store.mjs(会话)+ agents.mjs(智能体),
|
||
文件名也保持一致(settings.json / conversations.json / agents.json),
|
||
这样安卓内核和桌面内核可以共用同一个数据目录。
|
||
|
||
为什么用 JSON 文件而不是 SQLite:
|
||
* 数据量极小(几条会话、几个智能体),前端还要能直接看到/改这些文件;
|
||
* 安卓上 Chaquopy 自带 sqlite3,但跨端"人肉可读"更重要;
|
||
* 写盘走"临时文件 + 原子替换",避免安卓被杀进程时留下半个 JSON。
|
||
"""
|
||
|
||
import json
|
||
import os
|
||
import re
|
||
import sys
|
||
import threading
|
||
from datetime import datetime, timezone
|
||
|
||
import paths
|
||
from defaults import DEFAULT_AGENTS, DEFAULT_SETTINGS, PROVIDER_PRESETS
|
||
|
||
_lock = threading.RLock()
|
||
_conv_state = None # 会话状态在内存里缓存(和 Node 版 store.mjs 一样只 load 一次)
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 通用小工具
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def now_iso() -> str:
|
||
"""
|
||
和 JS 的 new Date().toISOString() 完全一致的格式:
|
||
2025-01-01T12:00:00.000Z(毫秒精度 + Z 后缀)。
|
||
前端会把这些字符串直接排序/展示,格式不一致会出现"时间跳来跳去"。
|
||
"""
|
||
return datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z')
|
||
|
||
|
||
def _read_json(file_path: str):
|
||
"""读 JSON;文件不存在或坏掉都返回 None(调用方决定怎么兜底)。"""
|
||
if not os.path.isfile(file_path):
|
||
return None
|
||
try:
|
||
with open(file_path, 'r', encoding='utf-8') as fh:
|
||
return json.load(fh)
|
||
except (OSError, ValueError) as exc:
|
||
print(f'[store] {os.path.basename(file_path)} 解析失败:{exc}', file=sys.stderr)
|
||
return None
|
||
|
||
|
||
def _write_json(file_path: str, payload) -> None:
|
||
"""原子写:先写 .tmp 再 os.replace,避免掉电/被杀时留下半个文件。"""
|
||
os.makedirs(os.path.dirname(file_path), exist_ok=True)
|
||
tmp = f'{file_path}.tmp'
|
||
with open(tmp, 'w', encoding='utf-8') as fh:
|
||
json.dump(payload, fh, ensure_ascii=False, indent=2)
|
||
os.replace(tmp, file_path)
|
||
|
||
|
||
def _as_text(value) -> str:
|
||
"""JS 的 String(x):None 会变成空串而不是 'None'。"""
|
||
if value is None:
|
||
return ''
|
||
if isinstance(value, str):
|
||
return value
|
||
return str(value)
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 设置
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
_dotenv_loaded = False
|
||
|
||
|
||
def _load_dotenv() -> None:
|
||
"""
|
||
极简 .env 解析。Node 版读 server/.env;Python 版读数据目录和内核目录下的 .env,
|
||
这样安卓上把 key 放在数据目录里就能用,不需要动源码目录。
|
||
"""
|
||
global _dotenv_loaded
|
||
if _dotenv_loaded:
|
||
return
|
||
_dotenv_loaded = True
|
||
p = paths.get()
|
||
for folder in (p.data_dir, os.path.dirname(os.path.abspath(__file__))):
|
||
env_file = os.path.join(folder, '.env')
|
||
if not os.path.isfile(env_file):
|
||
continue
|
||
try:
|
||
with open(env_file, 'r', encoding='utf-8') as fh:
|
||
lines = fh.read().splitlines()
|
||
except OSError:
|
||
continue
|
||
for raw in lines:
|
||
line = raw.strip()
|
||
if not line or line.startswith('#') or '=' not in line:
|
||
continue
|
||
key, _, value = line.partition('=')
|
||
key = key.strip()
|
||
value = value.strip()
|
||
if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
|
||
value = value[1:-1]
|
||
if key and key not in os.environ:
|
||
os.environ[key] = value
|
||
|
||
|
||
def mask_settings(settings: dict) -> dict:
|
||
"""脱敏:apiKey / 语音 Token 只回掩码 + has* 标志(前端据此显示"已配置")。"""
|
||
out = dict(settings)
|
||
out['apiKey'] = '••••••••' if settings.get('apiKey') else ''
|
||
out['hasApiKey'] = bool(settings.get('apiKey'))
|
||
speech = dict(out.get('speech') or {})
|
||
speech['volcToken'] = '••••••••' if speech.get('volcToken') else ''
|
||
speech['volcApiKey'] = '••••••••' if speech.get('volcApiKey') else ''
|
||
speech['openaiApiKey'] = '••••••••' if speech.get('openaiApiKey') else ''
|
||
out['speech'] = speech
|
||
return out
|
||
|
||
|
||
def read_settings() -> dict:
|
||
"""读设置:默认值 + 文件 + 环境变量兜底(字段与 Node 版一致)。"""
|
||
_load_dotenv()
|
||
stored = _read_json(paths.get().settings_file) or {}
|
||
if not isinstance(stored, dict):
|
||
stored = {}
|
||
settings = dict(DEFAULT_SETTINGS)
|
||
settings.update(stored)
|
||
# 子对象要深合并,否则用户只改 security.allow 会把 security.mode 冲掉。
|
||
# ★ 而且必须防住"子对象被非字典值覆盖":曾经前端把嵌套 Map 序列化成了字符串
|
||
# ({"speech":"{autoRead=true}"}),存进去之后**每一次**读配置都会抛
|
||
# TypeError,/api/state 从此一直 500 —— 一个坏字段把整个 App 弄成空白。
|
||
# 所以:读的时候发现不是字典就回落默认值(自愈),写的时候也不让非字典覆盖。
|
||
for key in ('tools', 'security', 'speech'):
|
||
defaults = DEFAULT_SETTINGS.get(key) or {}
|
||
raw = stored.get(key)
|
||
if not isinstance(raw, dict):
|
||
if raw is not None:
|
||
print(f'[config] settings.json 里的 {key} 不是对象,已回落默认值', file=sys.stderr, flush=True)
|
||
raw = {}
|
||
settings[key] = {**defaults, **raw}
|
||
if not isinstance(settings['security'].get('allow'), list):
|
||
settings['security']['allow'] = []
|
||
settings.pop('hasApiKey', None)
|
||
|
||
# 环境变量兜底:没填 key 时用 .env / 系统环境变量里的
|
||
preset = _preset_of(settings)
|
||
if not settings.get('apiKey') and preset.get('apiKeyEnv'):
|
||
settings['apiKey'] = os.environ.get(preset['apiKeyEnv'], '')
|
||
return settings
|
||
|
||
|
||
def _preset_of(settings: dict) -> dict:
|
||
from defaults import PROVIDER_PRESETS # 局部导入,避免循环依赖
|
||
|
||
return PROVIDER_PRESETS.get(settings.get('provider')) or PROVIDER_PRESETS['ark']
|
||
|
||
|
||
def write_settings(patch: dict) -> dict:
|
||
"""写设置:浅合并 + 子对象深合并 + 掩码值表示"不修改"。"""
|
||
if not isinstance(patch, dict):
|
||
patch = {}
|
||
# ★★ 显式的"清除"通路:值传 None 就是"我要把它清掉"。
|
||
#
|
||
# 为什么需要它:下面那段"空串一律当没填"的保险是对的(它防的是
|
||
# "前端草稿没初始化好,一次保存清空整份配置"),但代价是
|
||
# **用户永远清不掉自定义 Base URL / 模型名** ——
|
||
# 他删光输入框、保存,值一点没变,看起来就是"保存按钮坏了"。
|
||
# (这是我在测 AI 界面回流时踩到的:想把内核从假模型服务指回默认,
|
||
# 传空串怎么也改不掉。)
|
||
#
|
||
# 所以给一条**显式**的路:传 null。空串仍然= "没填、别动",
|
||
# null = "确实要清掉"。两者语义不同,前端可以按需选。
|
||
explicit_clear = {k for k, v in patch.items() if v is None}
|
||
for key in explicit_clear:
|
||
patch.pop(key, None)
|
||
# ★ 保险:空的关键字段一律当"没填",不许拿它覆盖已有配置。
|
||
# 这些字段正常使用中永远不该是空串(空 = 前端草稿没初始化好),
|
||
# 前端曾经因为草稿没同步好而全量下发空值,一次保存就把整份配置清空了。
|
||
# systemPrompt / toolsDir 故意不在此列:它们"留空"是合理需求。
|
||
for key in ('baseUrl', 'model', 'apiKey', 'nickname', 'provider', 'thinkingLevel'):
|
||
if key in patch and isinstance(patch[key], str) and not patch[key].strip():
|
||
patch.pop(key)
|
||
current = read_settings()
|
||
nxt = {**current, **patch}
|
||
# 显式清除的落到默认值上(不是留着旧值,也不是变成空 —— 空会让
|
||
# "用哪个 provider 的默认 baseUrl"这套逻辑失效)
|
||
for key in explicit_clear:
|
||
nxt[key] = DEFAULT_SETTINGS.get(key, '')
|
||
# 这几个是子对象:整体替换会把没提到的开关抹掉,所以深合并。
|
||
# ★ 不是字典的直接丢掉:上游要是把嵌套对象发成了字符串(比如 JSON 序列化踩坑),
|
||
# 让它覆盖进去就会写出一个读不回来的配置 —— 宁可这次改动不生效。
|
||
for key in ('tools', 'security', 'speech'):
|
||
if key not in patch:
|
||
continue
|
||
if isinstance(patch[key], dict):
|
||
nxt[key] = {**(current.get(key) or {}), **patch[key]}
|
||
else:
|
||
nxt[key] = current.get(key) or {}
|
||
print(f'[config] 补丁里的 {key} 不是对象({type(patch[key]).__name__}),已忽略', file=sys.stderr, flush=True)
|
||
if patch.get('apiKey') == '••••••••':
|
||
nxt['apiKey'] = current.get('apiKey', '')
|
||
# ★ 掩码回写保护:界面读到的是 '••••••••',用户不改语音设置直接保存时,
|
||
# 这个掩码会跟着 patch 回来。不处理的话真 Token 就被这八个点覆盖了,
|
||
# 下次朗读直接报"缺 Token" —— 这类"看一眼就坏"的 bug 最难查。
|
||
speech_next = nxt.get('speech')
|
||
if isinstance(speech_next, dict):
|
||
speech_cur = current.get('speech') or {}
|
||
for secret in ('volcToken', 'volcApiKey', 'openaiApiKey'):
|
||
if speech_next.get(secret) == '••••••••':
|
||
speech_next[secret] = speech_cur.get(secret, '')
|
||
# ★ 语音里"空字符串就等于坏掉"的字段,同样不许被空值覆盖。
|
||
# 引擎名一空,界面上一张卡片都不会高亮(看起来就是"设置被清空了");
|
||
# 模型名一空,朗读/识别会直接调不通。
|
||
# 注意 ttsVoice / volcAppId / sttLanguage 不在此列 —— 它们留空是合理需求
|
||
# (留空 = 用引擎默认音色 / 还没填)。
|
||
for key in ('ttsEngine', 'sttEngine', 'sttModel', 'ttsModel', 'volcCluster', 'volcEncoding'):
|
||
if key in speech_next and isinstance(speech_next[key], str) and not speech_next[key].strip():
|
||
speech_next[key] = speech_cur.get(key) or DEFAULT_SETTINGS['speech'].get(key, '')
|
||
nxt['speech'] = speech_next
|
||
nxt.pop('hasApiKey', None)
|
||
_write_json(paths.get().settings_file, nxt)
|
||
return nxt
|
||
|
||
|
||
def provider_info(settings: dict, agent: dict = None) -> dict:
|
||
"""
|
||
当前提供商的完整信息(预设 + 生效的 baseUrl/model)。
|
||
|
||
★ agent 不为空时,智能体自己的 provider/model/baseUrl **优先**,留空则继承全局。
|
||
这样"某个智能体用 DeepSeek、其它还用方舟"是改一个智能体的事,
|
||
不用来回切全局设置 —— 而全局设置仍然是没配过的智能体的默认值。
|
||
"""
|
||
agent = agent or {}
|
||
provider_key = (agent.get('provider') or '').strip() or settings.get('provider')
|
||
preset = PROVIDER_PRESETS.get(provider_key) or _preset_of(settings)
|
||
return {
|
||
**preset,
|
||
'provider': provider_key,
|
||
# baseUrl 也是三层:智能体 > 全局 > 预设
|
||
'baseUrl': (agent.get('baseUrl') or '').strip() or settings.get('baseUrl') or preset.get('baseUrl', ''),
|
||
'model': (agent.get('model') or '').strip() or settings.get('model') or preset.get('defaultModel', ''),
|
||
}
|
||
|
||
|
||
def agent_or_empty(agent_id: str) -> dict:
|
||
"""按 id 找智能体;找不到返回空 dict(调用方按"没指定"处理)。
|
||
|
||
包一层是因为 get_agent 返回 None,而调用方(会议引擎、朗读路由)基本都是
|
||
"有就用、没有就继承全局"的语义,到处写 `or {}` 太啰嗦。
|
||
"""
|
||
return get_agent(agent_id) or {}
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 会话
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def _rid_conv() -> str:
|
||
# 和 Node 的 `c_${Date.now().toString(36)}_${random}` 同风格;不必逐字符相同
|
||
return f'c_{_ts36()}_{_rand36(5)}'
|
||
|
||
|
||
def _ts36() -> str:
|
||
return _base36(int(datetime.now(timezone.utc).timestamp() * 1000))
|
||
|
||
|
||
def _base36(num: int) -> str:
|
||
digits = '0123456789abcdefghijklmnopqrstuvwxyz'
|
||
if num == 0:
|
||
return '0'
|
||
out = ''
|
||
while num:
|
||
num, rem = divmod(num, 36)
|
||
out = digits[rem] + out
|
||
return out
|
||
|
||
|
||
def _rand36(length: int) -> str:
|
||
import random
|
||
|
||
return ''.join(random.choice('0123456789abcdefghijklmnopqrstuvwxyz') for _ in range(length))
|
||
|
||
|
||
def _fresh_state() -> dict:
|
||
stamp = now_iso()
|
||
return {
|
||
'conversations': [
|
||
{
|
||
'id': 'c_main',
|
||
'title': '主对话',
|
||
'agentId': 'a_doubao',
|
||
'pinned': True,
|
||
'createdAt': stamp,
|
||
'updatedAt': stamp,
|
||
'messages': [],
|
||
}
|
||
]
|
||
}
|
||
|
||
|
||
def _load_conversations() -> dict:
|
||
global _conv_state
|
||
with _lock:
|
||
if _conv_state is None:
|
||
state = _read_json(paths.get().conversations_file)
|
||
if state is None:
|
||
state = _fresh_state()
|
||
if not isinstance(state.get('conversations'), list) or not state['conversations']:
|
||
state = _fresh_state()
|
||
_conv_state = state
|
||
return _conv_state
|
||
|
||
|
||
def _persist_conversations() -> None:
|
||
_write_json(paths.get().conversations_file, _load_conversations())
|
||
|
||
|
||
def _preview_of(messages: list) -> str:
|
||
"""列表预览:取最后一条有内容的消息,用户消息加"我:"前缀。"""
|
||
for msg in reversed(messages or []):
|
||
content = msg.get('content')
|
||
if not content:
|
||
continue
|
||
text = re.sub(r'\s+', ' ', _as_text(content)).strip()
|
||
if not text:
|
||
continue
|
||
tag = '我:' if msg.get('role') == 'user' else ''
|
||
return f'{tag}{text[:30]}…' if len(text) > 30 else f'{tag}{text}'
|
||
return ''
|
||
|
||
|
||
def list_conversations() -> list:
|
||
"""列表:带最后一条消息预览,置顶优先 + 更新时间倒序。"""
|
||
items = list(_load_conversations()['conversations'])
|
||
items.sort(
|
||
key=lambda c: (1 if c.get('pinned') else 0, _as_text(c.get('updatedAt'))),
|
||
reverse=True,
|
||
)
|
||
out = []
|
||
for conv in items:
|
||
messages = conv.get('messages') or []
|
||
meta = {k: v for k, v in conv.items() if k != 'messages'}
|
||
meta['messageCount'] = len(messages)
|
||
meta['preview'] = _preview_of(messages)
|
||
out.append(meta)
|
||
return out
|
||
|
||
|
||
def get_conversation(conv_id: str):
|
||
for conv in _load_conversations()['conversations']:
|
||
if conv.get('id') == conv_id:
|
||
return conv
|
||
return None
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# AI 界面的数据回流
|
||
# --------------------------------------------------------------------------- #
|
||
#
|
||
# AI 用 show_ui 弹的 HTML 界面里可以调 `Doubao.sendToAi(值)`,
|
||
# 那个值先落到这里排队,下一轮对话开始时被取走、当作上下文交给模型。
|
||
#
|
||
# ★ 为什么单独存一份、而不是直接写进会话的消息列表:
|
||
# 写进消息列表的话它会**变成一条 user 消息** —— 用户会看到一条
|
||
# 自己没打过的消息,而且它会被当成"用户说的话"进历史。
|
||
# 语义上它更像**附件/上下文**,不是用户的一句话。
|
||
# 所以单独排队,由 agent_loop 拼进这一轮的上下文里。
|
||
#
|
||
# ★ 为什么不落盘:这是**一次性的上下文**,跨重启没有意义
|
||
# (用户重启 App 之后那个界面早就关了,界面的选择也就失效了)。
|
||
# 放内存里,进程重启自然清空,正合适。
|
||
_pending_ui: dict = {}
|
||
_pending_ui_lock = threading.Lock()
|
||
|
||
# 每个会话最多排多少条 —— 用户在界面上乱点不能把内存堆满
|
||
PENDING_UI_MAX = 20
|
||
# 单条最长多少字符 —— 界面可能回传一大段文本
|
||
PENDING_UI_ITEM_MAX = 4000
|
||
|
||
|
||
def add_pending_ui(conv_id: str, value: str) -> int:
|
||
"""把界面上回传的一个值排进队。返回队里现在有几条。"""
|
||
text = (value or '').strip()[:PENDING_UI_ITEM_MAX]
|
||
if not conv_id or not text:
|
||
return len(_pending_ui.get(conv_id) or [])
|
||
with _pending_ui_lock:
|
||
box = _pending_ui.setdefault(conv_id, [])
|
||
box.append(text)
|
||
# 超了就丢**最旧的**:用户最新点的那次最相关
|
||
while len(box) > PENDING_UI_MAX:
|
||
box.pop(0)
|
||
return len(box)
|
||
|
||
|
||
def peek_pending_ui(conv_id: str) -> list:
|
||
"""看一眼(不取走)—— 给调试用的 GET 接口"""
|
||
with _pending_ui_lock:
|
||
return list(_pending_ui.get(conv_id) or [])
|
||
|
||
|
||
def take_pending_ui(conv_id: str) -> list:
|
||
"""
|
||
取走并清空。
|
||
|
||
★ 必须"取走":不取走的话每轮对话都会把同一条又带上,
|
||
用户会看到模型反复提同一件事。
|
||
"""
|
||
with _pending_ui_lock:
|
||
return list(_pending_ui.pop(conv_id, []) or [])
|
||
|
||
|
||
def clear_pending_ui(conv_id: str) -> None:
|
||
with _pending_ui_lock:
|
||
_pending_ui.pop(conv_id, None)
|
||
|
||
|
||
def create_conversation(title: str = '新对话', agent_id: str | None = None) -> dict:
|
||
item = {
|
||
'id': _rid_conv(),
|
||
'title': title,
|
||
'agentId': agent_id or '',
|
||
'pinned': False,
|
||
'createdAt': now_iso(),
|
||
'updatedAt': now_iso(),
|
||
'messages': [],
|
||
}
|
||
with _lock:
|
||
_load_conversations()['conversations'].insert(0, item)
|
||
_persist_conversations()
|
||
return item
|
||
|
||
|
||
def update_conversation(conv_id: str, patch: dict):
|
||
item = get_conversation(conv_id)
|
||
if not item:
|
||
return None
|
||
with _lock:
|
||
if isinstance(patch, dict):
|
||
item.update(patch)
|
||
item['updatedAt'] = now_iso()
|
||
_persist_conversations()
|
||
return item
|
||
|
||
|
||
def delete_conversation(conv_id: str) -> bool:
|
||
with _lock:
|
||
state = _load_conversations()
|
||
index = next((i for i, c in enumerate(state['conversations']) if c.get('id') == conv_id), -1)
|
||
if index < 0:
|
||
return False
|
||
state['conversations'].pop(index)
|
||
# 删光了就把"主对话"补回来,界面上不能出现空列表
|
||
if not state['conversations']:
|
||
state['conversations'].extend(_fresh_state()['conversations'])
|
||
_persist_conversations()
|
||
return True
|
||
|
||
|
||
def append_messages(conv_id: str, messages: list):
|
||
item = get_conversation(conv_id)
|
||
if not item:
|
||
return None
|
||
with _lock:
|
||
item.setdefault('messages', []).extend(messages)
|
||
item['updatedAt'] = now_iso()
|
||
_persist_conversations()
|
||
return item
|
||
|
||
|
||
def auto_title(conv_id: str, text: str) -> None:
|
||
"""用首条用户消息自动起标题(只改还没起过名的会话)。"""
|
||
item = get_conversation(conv_id)
|
||
if not item or item.get('title') not in ('新对话', '主对话'):
|
||
return
|
||
title = re.sub(r'\s+', ' ', _as_text(text)).strip()[:18]
|
||
if title:
|
||
update_conversation(conv_id, {'title': title})
|
||
|
||
|
||
def store_file_path() -> str:
|
||
return paths.get().conversations_file
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 智能体
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 智能体
|
||
# --------------------------------------------------------------------------- #
|
||
#
|
||
# 智能体可以独立指定的字段。**留空一律表示"继承全局设置"** ——
|
||
# 这样"代码搭子走 DeepSeek、文案师用另一个音色"只改那一个智能体,
|
||
# 而全局设置仍然是没配过的智能体的默认值。
|
||
#
|
||
# 提成常量是为了 create / update 两边不会漂移:
|
||
# 之前这两个函数各写一份硬编码白名单,加字段时漏改一处,
|
||
# 表现就是"界面上填了、保存后再打开又变空了"。
|
||
AGENT_FIELDS = (
|
||
'provider', # 走哪家(留空 = 全局)
|
||
'model', # 用哪个模型
|
||
'baseUrl', # 自定义网关地址
|
||
'ttsEngine', # 朗读引擎:system / volcv3 / volc / openai
|
||
'ttsVoice', # 音色 —— 多人会议里靠它区分谁在说话
|
||
'ttsSpeed', # 语速
|
||
)
|
||
|
||
|
||
def _rid_agent() -> str:
|
||
return f'a_{_ts36()}_{_rand36(4)}'
|
||
|
||
|
||
def list_agents() -> list:
|
||
file_path = paths.get().agents_file
|
||
if not os.path.isfile(file_path):
|
||
_write_json(file_path, {'agents': DEFAULT_AGENTS})
|
||
return [dict(a) for a in DEFAULT_AGENTS]
|
||
data = _read_json(file_path)
|
||
if not isinstance(data, dict) or not isinstance(data.get('agents'), list) or not data['agents']:
|
||
print('[store] agents.json 损坏,重建内置智能体', file=sys.stderr)
|
||
_write_json(file_path, {'agents': DEFAULT_AGENTS})
|
||
return [dict(a) for a in DEFAULT_AGENTS]
|
||
return data['agents']
|
||
|
||
|
||
def get_agent(agent_id: str | None):
|
||
if not agent_id:
|
||
return None
|
||
for agent in list_agents():
|
||
if agent.get('id') == agent_id:
|
||
return agent
|
||
return None
|
||
|
||
|
||
def create_agent(payload: dict) -> dict:
|
||
payload = payload or {}
|
||
state = {'agents': list_agents()}
|
||
agent = {
|
||
'id': _rid_agent(),
|
||
'name': _as_text(payload.get('name') or '新智能体')[:24],
|
||
'avatar': payload.get('avatar') or 'custom',
|
||
'tagline': _as_text(payload.get('tagline'))[:40],
|
||
'systemPrompt': _as_text(payload.get('systemPrompt')),
|
||
'builtin': False,
|
||
'createdAt': now_iso(),
|
||
}
|
||
# 智能体自己的模型/语音(留空 = 继承全局)
|
||
for key in AGENT_FIELDS:
|
||
if payload.get(key) is not None:
|
||
agent[key] = _as_text(payload.get(key))
|
||
state['agents'].append(agent)
|
||
_write_json(paths.get().agents_file, state)
|
||
return agent
|
||
|
||
|
||
def update_agent(agent_id: str, patch: dict):
|
||
state = {'agents': list_agents()}
|
||
agent = next((a for a in state['agents'] if a.get('id') == agent_id), None)
|
||
if not agent:
|
||
return None
|
||
patch = patch or {}
|
||
for key in ('name', 'avatar', 'tagline', 'systemPrompt', *AGENT_FIELDS):
|
||
if patch.get(key) is not None:
|
||
agent[key] = patch[key]
|
||
_write_json(paths.get().agents_file, state)
|
||
return agent
|
||
|
||
|
||
def delete_agent(agent_id: str) -> bool:
|
||
state = {'agents': list_agents()}
|
||
index = next((i for i, a in enumerate(state['agents']) if a.get('id') == agent_id), -1)
|
||
if index < 0:
|
||
return False
|
||
state['agents'].pop(index)
|
||
_write_json(paths.get().agents_file, state)
|
||
return True
|
||
|
||
|
||
def reset_runtime_cache() -> None:
|
||
"""测试/热重载用:丢掉会话内存缓存(设置本来就不缓存)。"""
|
||
global _conv_state, _dotenv_loaded
|
||
with _lock:
|
||
_conv_state = None
|
||
_dotenv_loaded = False
|