Files
doubao-clone/android/kernel/meeting.py
l 24181cd6b6 会议模式:一手势分工、节点可重复/无限循环、停止按钮、结果单开一屏
用户反馈的四条。

【1. 节点拖不动 → 改成"一指拖节点 / 两指移画布"】
复现出来是"拖节点变成了平移画布"。查的过程比较绕,值得记:

  先后试过两种写法都不行:
    a) 节点自己 detectDragGestures + 父级平移  → 父级总是赢
    b) 节点按下就 consume 抢手势              → 还是父级赢
  最后按用户提的**手指数分工**来做,才彻底没有争抢:
    一指 → 拖手指底下那个节点(空白处则什么都不做)
    两指 → 平移画布(按在哪都行)

  ★ 中途我一度以为"拖拽根本没生效",其实是**验证方法错了**:
    测试点 (240,648) 落在空白处 —— 那个会议的节点早被拖到画布角落
    (784,712)(784=CANVAS_W-NODE_W、712=CANVAS_H-NODE_H,正是四角限位),
    跑出屏幕了。日志一打就清楚了。
    所以测试脚本现在**先删掉旧会议、新建一个**,坐标才可预测。

【2. 停止按钮】
跑起来时"运行"变红色"停止"。一场会议可能跑好几分钟(每个智能体都是一次
完整模型调用),发现配错了却停不下来最让人抓狂。
点了停止会把还在"跑"的节点标成中断,不让界面上一直转圈。

【3. 节点可重复 / 无限循环】
原来引擎用 visited 集合(跑过就不再跑),环只转一圈 —— 用户要的是
"n1 → n2 → n1 只有一轮,但**能重复,可以无限循环**"。
改成**每个节点一个「最多执行次数」**:
    1(默认)  只跑一次,有环也只转一圈 —— 和以前一样
    2~20      环来回跑对应轮数
    **0        无限循环**,靠「停止」收尾(两个智能体互相点评的用法)
节点卡片上会标 ×N / ∞,不然跑起来发现它转了三轮会很意外。

★ 敢开无限是有前提的:引擎每一轮都检查 should_stop(客户端断开或用户点停止),
  所以"无限"实际是"跑到你喊停为止"。另外兜了个很大的硬上限,
  防止用户忘了停或客户端异常断开时把额度烧光。

【4. 结果单开一屏】
节点卡片就那么点大,长回答只能看两行。新增「结果」:最终输出放最上面
(那才是用户要的),下面按**节点在图上从左到右的顺序**列各自的产出,
带「复制」按钮。按 x 坐标排而不是按事件到达顺序 —— 用户脑子里的顺序是
图上那个顺序。

【测试抓到的】
- 引擎改完漏了 `final_output = ''` 的初始化 → UnboundLocalError
- Kotlin `awaitPointerEvent` 是 AwaitPointerEventScope 的方法,不用 import
- 环用例的测试图**没有入口节点**(n1、n2 都有入边)→ 引擎直接报"没有入口节点",
  跑不起来。真实的环一定是从某个起点进去的,测试图也得有

【验证】
- verify-meeting.mjs:新增 4 个环用例(1 轮 / 3 轮 / 无限+停止 / 第二轮拿到上一轮输出),
  Node 与 Python **11/11 逐用例一致**,总共 29/29
- 模拟器实测:一指拖节点 → 节点移动、**连线跟着走**;一指拖空白 → 不动
- 全部回归:Markdown 19/19、语音 41/41 ×2、会议引擎 29/29、会议 HTTP 12/12 ×2
2026-10-10 13:58:51 +08:00

467 lines
19 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""会议模式:用「节点 + 连线」把多个智能体串成一条流水线。
和普通对话的区别:
普通对话是"一个智能体回答一个问题";
会议模式是一张有向图 —— 初始输入进去,经过若干智能体节点各自加工,
中间可以按条件分叉,最后汇到最终输出节点。
为什么放在内核而不是界面上:
执行要走模型、要调工具、要按智能体各自的模型和音色去请求 ——
这些能力都已经在内核里了。界面只负责画图和收事件。
和 Node 版 server/src/meeting.mjs 是镜像实现,字段和事件名必须逐字一致
(两边不一致的话,同一个会议在手机和电脑上跑出来不一样)。
--------------------------------------------------------------------------
节点类型
--------------------------------------------------------------------------
start 初始输入:整个图的入口。文本可以写死,也可以留空表示"用用户发的那句"。
agent 智能体:带一个 agentId,外加**本节点专属**的附加提示词和输出控制。
这是"每个智能体都是一个节点、都能控制输出内容"的落点。
judge 判断:按条件把流分到 true / false 两条出边。
end 最终输出:汇总上游内容作为结果。
--------------------------------------------------------------------------
关于判断节点的"规则"模式为什么不用 eval
--------------------------------------------------------------------------
判断节点要支持"上游输出里有没有某个词""长度是否超过 N"这类条件。
最省事的做法是让用户写一段 Python 表达式然后 eval —— **绝对不行**:
配置能被任意改写(界面上可编辑、文件可手改),eval 就等于把任意代码
执行权交出去。所以这里用**结构化规则**(kind + value),
能表达的就那几种,多一种就多一个分支,而不是多一分风险。
"""
import json
import os
import sys
import threading
import uuid
from datetime import datetime, timezone
import paths
_lock = threading.Lock()
NODE_TYPES = ('start', 'agent', 'judge', 'end')
# 判断节点支持的条件。**结构化而不是表达式**,理由见文件头。
JUDGE_KINDS = (
('contains', '包含关键词'),
('not_contains', '不包含关键词'),
('longer_than', '字数多于'),
('shorter_than', '字数少于'),
('empty', '为空'),
('not_empty', '不为空'),
('ai', '让模型判断'),
)
def _ts36() -> str:
num = int(datetime.now(timezone.utc).timestamp() * 1000)
digits = '0123456789abcdefghijklmnopqrstuvwxyz'
out = ''
while num:
num, rem = divmod(num, 36)
out = digits[rem] + out
return out or '0'
def _rid(prefix: str) -> str:
return f'{prefix}_{_ts36()}_{uuid.uuid4().hex[:4]}'
def now_iso() -> str:
return datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
# --------------------------------------------------------------------------- #
# 默认会议:一个能直接跑的最小图(初始输入 → 智能体 → 最终输出)
# --------------------------------------------------------------------------- #
def new_meeting(name: str = '新会议') -> dict:
"""
给一张能直接跑的初始图,而不是空白画布。
空白画布对着干瞪眼是最差的新手体验;放一个"输入 → 一个智能体 → 输出"
的最小闭环,用户改改就能用,也能一眼看懂节点和连线是怎么连的。
★ 坐标要**一屏放得下**:x 按 120 递增、节点宽 116,所以 12→132→252,
最右边 252+116=368。手机竖屏大约 360dp 宽,会稍微超一点点,
但主体都在视野里;早先按 60/300/540 摆,默认图直接摊到两屏外,
用户一进来看到的是空画布加一个孤零零的节点,以为坏了。
"""
return {
'id': _rid('m'),
'name': name,
'nodes': [
{'id': 'n_start', 'type': 'start', 'x': 12, 'y': 120,
'title': '初始输入', 'text': ''},
{'id': 'n_agent1', 'type': 'agent', 'x': 132, 'y': 120,
'title': '智能体', 'agentId': '', 'extraPrompt': '', 'outputControl': ''},
{'id': 'n_end', 'type': 'end', 'x': 252, 'y': 120,
'title': '最终输出', 'text': ''},
],
'edges': [
{'from': 'n_start', 'to': 'n_agent1', 'branch': ''},
{'from': 'n_agent1', 'to': 'n_end', 'branch': ''},
],
'createdAt': now_iso(),
'updatedAt': now_iso(),
}
# --------------------------------------------------------------------------- #
# 存取
# --------------------------------------------------------------------------- #
def _file() -> str:
return os.path.join(paths.get().data_dir, 'meetings.json')
def _read() -> list:
file_path = _file()
if not os.path.isfile(file_path):
return []
try:
with open(file_path, encoding='utf-8') as fh:
data = json.load(fh)
except (OSError, ValueError) as exc:
print(f'[meeting] meetings.json 读不了:{exc}', file=sys.stderr)
return []
items = data.get('meetings') if isinstance(data, dict) else None
return items if isinstance(items, list) else []
def _write(items: list) -> None:
os.makedirs(paths.get().data_dir, exist_ok=True)
with open(_file(), 'w', encoding='utf-8') as fh:
json.dump({'meetings': items}, fh, ensure_ascii=False, indent=2)
def list_meetings() -> list:
"""列表只给摘要:节点连线可能很大,列表页用不上"""
return [
{
'id': m.get('id'),
'name': m.get('name') or '未命名会议',
'nodeCount': len(m.get('nodes') or []),
'edgeCount': len(m.get('edges') or []),
'updatedAt': m.get('updatedAt'),
}
for m in _read()
]
def get_meeting(meeting_id: str):
return next((m for m in _read() if m.get('id') == meeting_id), None)
def create_meeting(payload: dict) -> dict:
payload = payload or {}
item = new_meeting(str(payload.get('name') or '新会议')[:40])
with _lock:
items = _read()
items.append(item)
_write(items)
return item
def save_meeting(meeting_id: str, payload: dict):
"""整份覆盖。图这种东西局部改很容易改出坏结构(悬空连线、重复 id)。"""
payload = payload or {}
with _lock:
items = _read()
for i, item in enumerate(items):
if item.get('id') != meeting_id:
continue
merged = {**item, **payload, 'id': meeting_id, 'updatedAt': now_iso()}
merged['nodes'] = _sanitize_nodes(merged.get('nodes') or [])
merged['edges'] = _sanitize_edges(merged.get('edges') or [], merged['nodes'])
items[i] = merged
_write(items)
return merged
return None
def delete_meeting(meeting_id: str) -> bool:
with _lock:
items = _read()
left = [m for m in items if m.get('id') != meeting_id]
if len(left) == len(items):
return False
_write(left)
return True
def _sanitize_nodes(nodes: list) -> list:
"""丢掉类型不认识、或者 id 重复的节点 —— 坏节点会让整张图跑不起来"""
out = []
seen = set()
for n in nodes:
if not isinstance(n, dict):
continue
nid = str(n.get('id') or '')
ntype = str(n.get('type') or '')
if not nid or nid in seen or ntype not in NODE_TYPES:
continue
seen.add(nid)
try:
max_runs = int(n.get('maxRuns')) if n.get('maxRuns') is not None else 1
except (TypeError, ValueError):
max_runs = 1
out.append({
**n,
'id': nid,
'type': ntype,
'x': float(n.get('x') or 0),
'y': float(n.get('y') or 0),
# 夹在 0~20:**0 = 无限循环**(两个智能体互相点评那种用法),
# 1~20 是有限次。负数或大于 20 的值都不认,退回 1 ——
# 不然用户手改文件写成 99999 会一直烧额度。
'maxRuns': 0 if max_runs <= 0 else min(max_runs, 20),
})
return out
def _sanitize_edges(edges: list, nodes: list) -> list:
"""丢掉指向不存在节点的连线 —— 悬空连线是崩溃的常见来源"""
ids = {n['id'] for n in nodes}
out = []
for e in edges:
if not isinstance(e, dict):
continue
src, dst = str(e.get('from') or ''), str(e.get('to') or '')
if src in ids and dst in ids and src != dst:
out.append({'from': src, 'to': dst, 'branch': str(e.get('branch') or '')})
return out
# --------------------------------------------------------------------------- #
# 执行引擎
# --------------------------------------------------------------------------- #
def _incoming(edges: list, node_id: str) -> list:
return [e for e in edges if e.get('to') == node_id]
def _outgoing(edges: list, node_id: str) -> list:
return [e for e in edges if e.get('from') == node_id]
def _collect_input(node_id: str, edges: list, outputs: dict) -> str:
"""一个节点的输入 = 它所有上游节点的输出拼起来。
多条入边就按连线顺序拼 —— 这样"多个智能体的意见汇总给判断节点"
不需要额外的合并节点。
"""
parts = []
for e in _incoming(edges, node_id):
text = outputs.get(e.get('from'))
if text:
parts.append(str(text))
return '\n\n'.join(parts).strip()
def _judge_rule(node: dict, text: str) -> bool:
"""结构化条件判断(不用 eval,理由见文件头)"""
kind = str(node.get('judgeKind') or 'not_empty')
value = str(node.get('judgeValue') or '')
if kind == 'contains':
return value in text
if kind == 'not_contains':
return value not in text
if kind == 'longer_than':
try:
return len(text) > int(value or 0)
except ValueError:
return False
if kind == 'shorter_than':
try:
return len(text) < int(value or 0)
except ValueError:
return False
if kind == 'empty':
return not text.strip()
if kind == 'not_empty':
return bool(text.strip())
return True
def run_meeting(*, meeting: dict, settings: dict, user_input: str,
emit, run_agent_fn, should_stop=None) -> dict:
"""
跑完一整张图。
meeting 会议的节点与连线
settings 全局设置(智能体没配的模型/语音从这里继承)
user_input 用户在会议页发的那句话(start 节点文本为空时用它)
emit 事件回调,直接往 SSE 里写
run_agent_fn 实际调用模型的那个函数(由 app.py 注入,避免这里 import 一堆东西)
事件:
{'type':'meeting_start', 'nodes': n, 'edges': n}
{'type':'node_start', 'nodeId', 'nodeType', 'title'}
{'type':'node_delta', 'nodeId', 'text'} ← 流式增量
{'type':'node_done', 'nodeId', 'output'}
{'type':'node_error', 'nodeId', 'error'}
{'type':'meeting_done', 'output'}
为什么用拓扑序 + 访问计数而不是递归:图里可能有环(用户画错了),
递归会直接爆栈。这里每个节点最多跑一次、总步数有上限,
画错了也只是"少跑几个节点",不会把 App 拖死。
"""
nodes = meeting.get('nodes') or []
edges = meeting.get('edges') or []
by_id = {n['id']: n for n in nodes}
outputs = {}
emit({'type': 'meeting_start', 'nodes': len(nodes), 'edges': len(edges)})
# 入口:优先 start 节点;没有就从"没有入边"的节点开始
starts = [n for n in nodes if n['type'] == 'start']
if not starts:
starts = [n for n in nodes if not _incoming(edges, n['id'])]
if not starts:
emit({'type': 'meeting_done', 'output': '', 'error': '这张图没有入口节点'})
return {'output': '', 'error': '这张图没有入口节点'}
queue = [n['id'] for n in starts]
# ★ 每个节点跑了几次(不是"跑没跑过")。
#
# 用户要的是"n1 → n2 → n1 只有一轮,但**能重复**":
# 默认每节点 1 次(= 不重复,和以前一样),把节点上的「最多执行次数」
# 调大就能来回跑 —— 比如两个节点都设 3,就是 n1/n2 各跑三轮。
#
# 以前用的是 visited 集合(跑过就不再跑),环永远只转一圈,没法重复。
runs = {}
steps = 0
def limit_of(node: dict) -> int:
"""
节点的执行次数上限。**0 表示无限**。
为什么要支持无限:两个智能体互相点评(甲评乙、乙再评甲)是常见用法,
用户希望一直怼下去,自己觉得够了再按停止。
为什么敢开无限:引擎每一轮都会检查 should_stop(客户端断开或用户点了停止),
所以"无限"实际是"跑到你喊停为止",不是真的停不下来。
另外还兜了一个很大的硬上限 MAX_STEPS_HARD,防止用户忘了停、
或者客户端异常断开时把额度烧光。
"""
raw = node.get('maxRuns')
try:
value = int(raw) if raw is not None else 1
except (TypeError, ValueError):
value = 1
return 0 if value <= 0 else min(value, 20)
budget = sum((limit_of(n) or 200) for n in nodes)
# 硬上限:无限循环时预算按每节点 200 次估,再乘 2 留余量。
# 这不是"限制用户",是**防止客户端异常断开时把额度烧光** ——
# 正常用停止按钮就能收尾,根本碰不到这个数。
max_steps = max(20, budget * 2 + len(nodes))
final_output = ''
def can_run(node_id: str) -> bool:
node = by_id.get(node_id)
if not node:
return False
limit = limit_of(node)
# 0 = 无限:永远还能再跑一次
return limit == 0 or runs.get(node_id, 0) < limit
while queue and steps < max_steps:
if should_stop and should_stop():
emit({'type': 'meeting_done', 'output': final_output, 'aborted': True})
return {'output': final_output, 'aborted': True}
node_id = queue.pop(0)
steps += 1
if not can_run(node_id):
continue
node = by_id.get(node_id)
if not node:
continue
run_index = runs.get(node_id, 0) + 1
runs[node_id] = run_index
node_type = node['type']
title = node.get('title') or {'start': '初始输入', 'agent': '智能体',
'judge': '判断', 'end': '最终输出'}.get(node_type, node_type)
emit({'type': 'node_start', 'nodeId': node_id, 'nodeType': node_type,
'title': title, 'run': run_index, 'maxRuns': limit_of(node)})
incoming = _collect_input(node_id, edges, outputs)
try:
if node_type == 'start':
# 第二轮开始,"初始输入"要把**自己上一轮的输出**当输入,
# 否则循环回来的内容会被起点覆盖掉,重复就没意义了
text = incoming or (node.get('text') or '').strip() or (user_input or '')
outputs[node_id] = text
emit({'type': 'node_done', 'nodeId': node_id, 'output': text,
'run': run_index, 'note': '用的初始输入'})
next_ids = [e['to'] for e in _outgoing(edges, node_id)]
elif node_type == 'agent':
out = run_agent_fn(node, incoming, settings, emit, node_id)
outputs[node_id] = out
emit({'type': 'node_done', 'nodeId': node_id, 'output': out, 'run': run_index})
next_ids = [e['to'] for e in _outgoing(edges, node_id)]
elif node_type == 'judge':
kind = str(node.get('judgeKind') or 'not_empty')
if kind == 'ai':
verdict = run_agent_fn({**node, '_judgeOnly': True}, incoming, settings, emit, node_id)
passed = 'YES' in verdict.upper()[:40] or '是' in verdict[:20]
else:
passed = _judge_rule(node, incoming)
# ★ 判断节点必须**透传上游内容**,不能把自己的输出改成 "true"/"false"。
# 否则下游智能体收到的输入就变成字符串 "true" 了,完全没法用 ——
# 这个错误是验证脚本抓到的(输出是"真 收到[true]")。
# 判断结论走 verdict 字段,不占 output。
outputs[node_id] = incoming
emit({'type': 'node_done', 'nodeId': node_id,
'output': incoming,
'run': run_index,
'verdict': passed,
'branch': 'true' if passed else 'false',
'note': f'判断结果:{passed}'})
# 判断节点走 true / false 两条出边;没标分支的那条当默认(true)
outs = _outgoing(edges, node_id)
next_ids = [
e['to'] for e in outs
if (e.get('branch') or 'true') == ('true' if passed else 'false')
]
if not next_ids:
# 没连对应的分支就顺走第一条,免得图直接断在这儿
next_ids = [e['to'] for e in outs][:1]
elif node_type == 'end':
outputs[node_id] = (node.get('text') or '').strip() or incoming
final_output = outputs[node_id]
emit({'type': 'node_done', 'nodeId': node_id, 'output': final_output, 'run': run_index})
next_ids = []
else:
emit({'type': 'node_error', 'nodeId': node_id, 'error': f'不认识的节点类型:{node_type}'})
next_ids = []
except Exception as exc: # noqa: BLE001
# 单个节点出错不该让整场会议停摆:记下来,继续跑下游
emit({'type': 'node_error', 'nodeId': node_id, 'error': str(exc), 'run': run_index})
outputs[node_id] = ''
next_ids = [e['to'] for e in _outgoing(edges, node_id)]
# ★ 只有"还能再跑"的节点才重新入队。
# 这就是"重复"的开关:maxRuns=1(默认)时,跑过的节点不会再进来,
# 环也只转一圈;把它调大,环就会来回转到次数用完为止。
for nid in next_ids:
if can_run(nid):
queue.append(nid)
emit({'type': 'meeting_done', 'output': final_output})
return {'output': final_output}