test_group_topics_contract.py 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877
  1. from __future__ import annotations
  2. import asyncio
  3. import hashlib
  4. import importlib
  5. import json
  6. import sqlite3
  7. import sys
  8. import tempfile
  9. import unittest
  10. import uuid
  11. from io import BytesIO
  12. from pathlib import Path
  13. from unittest.mock import patch
  14. from fastapi import UploadFile
  15. from starlette.datastructures import Headers
  16. DASHBOARD_DIR = Path(__file__).resolve().parents[1]
  17. if str(DASHBOARD_DIR) not in sys.path:
  18. sys.path.insert(0, str(DASHBOARD_DIR))
  19. import group_plugin_api # noqa: E402
  20. PROTOCOL = importlib.import_module(f"{group_plugin_api._LOCAL_PACKAGE}.group_protocol")
  21. STORE_MODULE = importlib.import_module(f"{group_plugin_api._LOCAL_PACKAGE}.group_store")
  22. ORCHESTRATOR = importlib.import_module(
  23. f"{group_plugin_api._LOCAL_PACKAGE}.group_orchestrator"
  24. )
  25. SETTINGS_TESTS = importlib.import_module("dashboard.tests.test_group_settings_contract")
  26. GroupStore = STORE_MODULE.GroupStore
  27. def new_id() -> str:
  28. return str(uuid.uuid4())
  29. class GroupTopicsContractTests(unittest.TestCase):
  30. def test_protocol_and_router_advertise_topics(self) -> None:
  31. self.assertEqual(PROTOCOL.PROTOCOL_VERSION, 12)
  32. self.assertIn("topic.updated", PROTOCOL.EVENT_TYPES)
  33. self.assertIn("room.activity", PROTOCOL.EVENT_TYPES)
  34. request = PROTOCOL.SendMessageRequest.model_validate({
  35. "requestId": new_id(),
  36. "clientMessageId": new_id(),
  37. "topicId": new_id(),
  38. "content": "继续",
  39. "mentionAgentIds": [],
  40. })
  41. self.assertIsNotNone(request.topic_id)
  42. route_methods = {
  43. (route.path, tuple(sorted(route.methods or ())))
  44. for route in group_plugin_api.router.routes
  45. if hasattr(route, "methods")
  46. }
  47. self.assertIn(("/v1/rooms/{room_id}/topics", ("GET",)), route_methods)
  48. self.assertIn(
  49. ("/v1/rooms/{room_id}/topics/{topic_id}", ("PATCH",)),
  50. route_methods,
  51. )
  52. self.assertIn(
  53. ("/v1/rooms/{room_id}/topics/{topic_id}/read", ("PATCH",)),
  54. route_methods,
  55. )
  56. read_request = PROTOCOL.MarkTopicReadRequest.model_validate({
  57. "requestId": new_id(),
  58. "throughSeq": 12,
  59. })
  60. self.assertEqual(read_request.through_seq, 12)
  61. self.assertIn(
  62. ("/v1/rooms/{room_id}/uploads", ("POST",)), route_methods
  63. )
  64. def test_group_upload_persists_server_readable_attachment(self) -> None:
  65. with tempfile.TemporaryDirectory() as directory:
  66. store = GroupStore(Path(directory) / "group.db")
  67. store.initialize()
  68. room = store.create_room(
  69. {
  70. "requestId": new_id(),
  71. "name": "附件群",
  72. "cwd": "",
  73. "agents": [{"profile": "default"}],
  74. }
  75. )
  76. [agent] = room["agents"]
  77. room_id = room["id"]
  78. result = asyncio.run(
  79. group_plugin_api._persist_group_uploads(
  80. room_id,
  81. [
  82. UploadFile(
  83. filename="../photo.png",
  84. file=BytesIO(b"fixture-image"),
  85. headers=Headers({"content-type": "image/png"}),
  86. )
  87. ],
  88. root=Path(directory) / "uploads",
  89. )
  90. )
  91. [uploaded] = result
  92. path = Path(uploaded["path"])
  93. self.assertEqual(
  94. path.parent,
  95. Path(directory).resolve() / "uploads" / room_id,
  96. )
  97. self.assertEqual(path.suffix, ".png")
  98. self.assertEqual(path.read_bytes(), b"fixture-image")
  99. self.assertEqual(path.stat().st_mode & 0o777, 0o600)
  100. self.assertEqual(uploaded["name"], "photo.png")
  101. self.assertEqual(uploaded["mimeType"], "image/png")
  102. self.assertEqual(uploaded["size"], len(b"fixture-image"))
  103. created = store.create_human_message(
  104. room_id,
  105. request_id=new_id(),
  106. client_message_id=new_id(),
  107. topic_id=new_id(),
  108. content=f"请查看图片\n\n![photo.png](<{path}>)",
  109. mention_agent_ids=[agent["id"]],
  110. )
  111. [run] = created["runs"]
  112. self.assertEqual(store.claim_next_runnable_run()["id"], run["id"])
  113. projection = store.read_run_projection(run["id"])
  114. prompt = ORCHESTRATOR.build_run_prompt(
  115. projection,
  116. store.get_room(room_id)["agents"],
  117. )
  118. self.assertIn(str(path), prompt)
  119. self.assertTrue(path.is_file())
  120. def test_group_upload_rejects_oversize_and_removes_partial_files(self) -> None:
  121. room_id = new_id()
  122. with (
  123. tempfile.TemporaryDirectory() as directory,
  124. patch.object(group_plugin_api, "_MAX_GROUP_UPLOAD_FILE_BYTES", 4),
  125. ):
  126. with self.assertRaises(group_plugin_api.GroupAPIError) as raised:
  127. asyncio.run(
  128. group_plugin_api._persist_group_uploads(
  129. room_id,
  130. [
  131. UploadFile(
  132. filename="too-large.bin",
  133. file=BytesIO(b"12345"),
  134. headers=Headers(
  135. {"content-type": "application/octet-stream"}
  136. ),
  137. )
  138. ],
  139. root=Path(directory),
  140. )
  141. )
  142. self.assertEqual(raised.exception.status_code, 413)
  143. self.assertEqual(
  144. [path for path in Path(directory).rglob("*") if path.is_file()],
  145. [],
  146. )
  147. def test_room_settings_still_update_without_changing_agents(self) -> None:
  148. with tempfile.TemporaryDirectory() as directory:
  149. store = GroupStore(Path(directory) / "group.db")
  150. store.initialize()
  151. room = store.create_room({
  152. "requestId": new_id(),
  153. "name": "原房间",
  154. "cwd": "",
  155. "maxReplyRounds": 3,
  156. "agents": [{"profile": "default", "description": "保留职责"}],
  157. })
  158. before_agent = room["agents"][0]
  159. updated = store.update_room(
  160. room["id"],
  161. {
  162. "requestId": new_id(),
  163. "name": "新房间",
  164. "maxReplyRounds": 5,
  165. },
  166. )
  167. self.assertEqual(updated["name"], "新房间")
  168. self.assertEqual(updated["maxReplyRounds"], 5)
  169. self.assertEqual(updated["agents"], [before_agent])
  170. def test_topic_title_update_is_idempotent_and_emits_topic_event(self) -> None:
  171. with tempfile.TemporaryDirectory() as directory:
  172. store = GroupStore(Path(directory) / "group.db")
  173. store.initialize()
  174. room = store.create_room({
  175. "requestId": new_id(),
  176. "name": "话题群",
  177. "cwd": "",
  178. "agents": [{"profile": "default"}],
  179. })
  180. created = store.create_human_message(
  181. room["id"],
  182. request_id=new_id(),
  183. client_message_id=new_id(),
  184. topic_id=new_id(),
  185. content="原始标题",
  186. mention_agent_ids=[],
  187. )
  188. topic_id = created["message"]["topicId"]
  189. request_id = new_id()
  190. before = store.latest_cursor()
  191. renamed = store.update_topic(
  192. room["id"],
  193. topic_id,
  194. {"requestId": request_id, "title": " 新的\n话题标题 "},
  195. )
  196. repeated = store.update_topic(
  197. room["id"],
  198. topic_id,
  199. {"requestId": request_id, "title": " 新的\n话题标题 "},
  200. )
  201. self.assertEqual(renamed["title"], "新的 话题标题")
  202. self.assertEqual(repeated, renamed)
  203. events = store.events_after(before, 10)
  204. self.assertEqual(len(events), 1)
  205. self.assertEqual(events[0]["eventType"], "topic.updated")
  206. self.assertEqual(events[0]["payload"]["title"], "新的 话题标题")
  207. def test_schema_v7_migrates_topic_read_position_without_data_loss(self) -> None:
  208. with tempfile.TemporaryDirectory() as directory:
  209. path = Path(directory) / "group.db"
  210. store = GroupStore(path)
  211. store.initialize()
  212. room = store.create_room({
  213. "requestId": new_id(),
  214. "name": "迁移群",
  215. "cwd": "",
  216. "agents": [{"profile": "default"}],
  217. })
  218. created = store.create_human_message(
  219. room["id"],
  220. request_id=new_id(),
  221. client_message_id=new_id(),
  222. topic_id=new_id(),
  223. content="保留消息",
  224. mention_agent_ids=[],
  225. )
  226. topic_id = created["message"]["topicId"]
  227. with store.connection() as connection:
  228. original_message_count = connection.execute(
  229. "SELECT COUNT(*) FROM group_messages"
  230. ).fetchone()[0]
  231. original_latest_visible_seq = connection.execute(
  232. """SELECT COALESCE(MAX(seq), 0) FROM group_messages
  233. WHERE topic_id = ? AND visible = 1""",
  234. (topic_id,),
  235. ).fetchone()[0]
  236. with store.write_transaction() as connection:
  237. columns = {
  238. row["name"]
  239. for row in connection.execute("PRAGMA table_info(group_topics)")
  240. }
  241. if "last_read_message_seq" in columns:
  242. connection.execute(
  243. "ALTER TABLE group_topics DROP COLUMN last_read_message_seq"
  244. )
  245. connection.execute(
  246. "UPDATE group_meta SET value = '7' WHERE key = 'schema_version'"
  247. )
  248. migrated = GroupStore(path)
  249. migrated.initialize()
  250. self.assertEqual(migrated.schema_version(), 14)
  251. with migrated.connection() as connection:
  252. topic = connection.execute(
  253. "SELECT * FROM group_topics WHERE id = ?", (topic_id,)
  254. ).fetchone()
  255. message_count = connection.execute(
  256. "SELECT COUNT(*) FROM group_messages"
  257. ).fetchone()[0]
  258. self.assertEqual(
  259. topic["last_read_message_seq"],
  260. original_latest_visible_seq,
  261. )
  262. self.assertEqual(message_count, original_message_count)
  263. self.assertEqual(migrated.room_activity(room["id"])["unreadCount"], 0)
  264. def test_room_activity_counts_active_runs_and_unread_agent_messages(self) -> None:
  265. with tempfile.TemporaryDirectory() as directory:
  266. store = GroupStore(Path(directory) / "group.db")
  267. store.initialize()
  268. room = store.create_room({
  269. "requestId": new_id(),
  270. "name": "活动群",
  271. "cwd": "",
  272. "agents": [{"profile": "default"}],
  273. })
  274. agent = room["agents"][0]
  275. topic_id = new_id()
  276. created = store.create_human_message(
  277. room["id"],
  278. request_id=new_id(),
  279. client_message_id=new_id(),
  280. topic_id=topic_id,
  281. content="用户问题",
  282. mention_agent_ids=[agent["id"]],
  283. )
  284. trigger = created["message"]
  285. run = created["runs"][0]
  286. with store.write_transaction() as connection:
  287. connection.execute(
  288. "UPDATE group_agent_runs SET status = 'running' WHERE id = ?",
  289. (run["id"],),
  290. )
  291. visible_ids = [new_id(), new_id()]
  292. for index, message_id in enumerate(visible_ids, start=2):
  293. connection.execute(
  294. """INSERT INTO group_messages
  295. (id, room_id, topic_id, sender_kind, sender_id, sender_name,
  296. root_message_id, content, status, visible, created_at, updated_at)
  297. VALUES (?, ?, ?, 'agent', ?, '夭夭', ?, ?, 'completed', 1, ?, ?)""",
  298. (
  299. message_id,
  300. room["id"],
  301. topic_id,
  302. agent["id"],
  303. trigger["rootMessageId"],
  304. f"回复 {index}",
  305. index,
  306. index,
  307. ),
  308. )
  309. connection.execute(
  310. """INSERT INTO group_messages
  311. (id, room_id, topic_id, sender_kind, sender_id, sender_name,
  312. root_message_id, content, status, visible, created_at, updated_at)
  313. VALUES (?, ?, ?, 'agent', ?, '夭夭', ?, '隐藏', 'completed', 0, 4, 4)""",
  314. (
  315. new_id(), room["id"], topic_id, agent["id"],
  316. trigger["rootMessageId"],
  317. ),
  318. )
  319. activity = store.room_activity(room["id"])
  320. self.assertEqual(activity["activeRunCount"], 1)
  321. self.assertEqual(activity["unreadCount"], 2)
  322. self.assertEqual(activity["lastMessage"]["id"], visible_ids[-1])
  323. def test_mark_topic_read_is_monotonic_idempotent_and_emits_activity(self) -> None:
  324. with tempfile.TemporaryDirectory() as directory:
  325. store = GroupStore(Path(directory) / "group.db")
  326. store.initialize()
  327. room = store.create_room({
  328. "requestId": new_id(),
  329. "name": "已读群",
  330. "cwd": "",
  331. "agents": [{"profile": "default"}],
  332. })
  333. agent = room["agents"][0]
  334. topic_id = new_id()
  335. trigger = store.create_human_message(
  336. room["id"], request_id=new_id(), client_message_id=new_id(),
  337. topic_id=topic_id, content="问题", mention_agent_ids=[],
  338. )["message"]
  339. with store.write_transaction() as connection:
  340. connection.execute(
  341. """INSERT INTO group_messages
  342. (id, room_id, topic_id, sender_kind, sender_id, sender_name,
  343. root_message_id, content, status, visible, created_at, updated_at)
  344. VALUES (?, ?, ?, 'agent', ?, '夭夭', ?, '回复', 'completed', 1, 2, 2)""",
  345. (
  346. new_id(), room["id"], topic_id, agent["id"],
  347. trigger["rootMessageId"],
  348. ),
  349. )
  350. through_seq = connection.execute(
  351. "SELECT MAX(seq) FROM group_messages WHERE topic_id = ?",
  352. (topic_id,),
  353. ).fetchone()[0]
  354. request_id = new_id()
  355. before = store.latest_cursor()
  356. first = store.mark_topic_read(
  357. room["id"], topic_id,
  358. {"requestId": request_id, "throughSeq": through_seq},
  359. )
  360. repeated = store.mark_topic_read(
  361. room["id"], topic_id,
  362. {"requestId": request_id, "throughSeq": through_seq},
  363. )
  364. stale = store.mark_topic_read(
  365. room["id"], topic_id,
  366. {"requestId": new_id(), "throughSeq": through_seq - 1},
  367. )
  368. self.assertEqual(first, repeated)
  369. self.assertEqual(first["topic"]["lastReadMessageSeq"], through_seq)
  370. self.assertEqual(stale["room"]["unreadCount"], 0)
  371. events = store.events_after(before, 10)
  372. self.assertEqual(
  373. [event["eventType"] for event in events],
  374. ["topic.updated", "room.activity"],
  375. )
  376. with self.assertRaises(ValueError):
  377. store.mark_topic_read(
  378. room["id"], topic_id,
  379. {"requestId": new_id(), "throughSeq": through_seq + 100},
  380. )
  381. def test_topics_page_filter_compatibility_and_event_order(self) -> None:
  382. with tempfile.TemporaryDirectory() as directory:
  383. store = GroupStore(Path(directory) / "group.db")
  384. store.initialize()
  385. room = store.create_room({
  386. "requestId": new_id(),
  387. "name": "话题群",
  388. "cwd": "",
  389. "agents": [{"profile": "default"}],
  390. })
  391. topic_a, topic_b = new_id(), new_id()
  392. with self.assertRaises(STORE_MODULE.GroupNotFoundError):
  393. store.list_messages(room["id"], topic_id=new_id())
  394. before = store.latest_cursor()
  395. first = store.create_human_message(
  396. room["id"],
  397. request_id=new_id(),
  398. client_message_id=new_id(),
  399. topic_id=topic_a,
  400. content="第一个话题",
  401. mention_agent_ids=[],
  402. )
  403. events = store.events_after(before, 10)
  404. self.assertEqual(
  405. [event["eventType"] for event in events],
  406. [
  407. "message.upsert",
  408. "topic.updated",
  409. "room.activity",
  410. "message.upsert",
  411. "topic.updated",
  412. "run.updated",
  413. "room.activity",
  414. ],
  415. )
  416. self.assertEqual(events[0]["payload"]["topicId"], topic_a)
  417. self.assertEqual(
  418. set(events[1]["payload"]),
  419. {
  420. "id",
  421. "roomId",
  422. "title",
  423. "preview",
  424. "messageCount",
  425. "unreadCount",
  426. "latestMessageSeq",
  427. "lastReadMessageSeq",
  428. "archived",
  429. "pinned",
  430. "createdAt",
  431. "updatedAt",
  432. },
  433. )
  434. self.assertEqual(events[1]["payload"]["id"], topic_a)
  435. self.assertEqual(events[2]["payload"]["roomId"], room["id"])
  436. self.assertEqual(events[2]["payload"]["activeRunCount"], 0)
  437. self.assertEqual(events[-1]["payload"]["activeRunCount"], 1)
  438. second = store.create_human_message(
  439. room["id"],
  440. request_id=new_id(),
  441. client_message_id=new_id(),
  442. topic_id=topic_a,
  443. content="第一个话题的后续",
  444. mention_agent_ids=[],
  445. )
  446. store.create_human_message(
  447. room["id"],
  448. request_id=new_id(),
  449. client_message_id=new_id(),
  450. topic_id=topic_b,
  451. content="第二个话题",
  452. mention_agent_ids=[],
  453. )
  454. compatibility_first = store.create_human_message(
  455. room["id"],
  456. request_id=new_id(),
  457. client_message_id=new_id(),
  458. content="旧客户端消息",
  459. mention_agent_ids=[],
  460. )
  461. compatibility_second = store.create_human_message(
  462. room["id"],
  463. request_id=new_id(),
  464. client_message_id=new_id(),
  465. content="旧客户端继续",
  466. mention_agent_ids=[],
  467. )
  468. self.assertEqual(
  469. compatibility_first["message"]["topicId"],
  470. compatibility_second["message"]["topicId"],
  471. )
  472. self.assertEqual(
  473. compatibility_first["message"]["topicId"],
  474. store._compatibility_topic_id(room["id"]),
  475. )
  476. topic_a_messages = store.list_messages(room["id"], topic_id=topic_a)
  477. self.assertEqual(
  478. [
  479. message["id"]
  480. for message in topic_a_messages
  481. if message["senderKind"] == "human"
  482. ],
  483. [first["message"]["id"], second["message"]["id"]],
  484. )
  485. self.assertEqual(
  486. sum(
  487. message["senderKind"] == "human"
  488. for message in store.list_messages(room["id"])
  489. ),
  490. 5,
  491. )
  492. page_one = store.list_topics(room["id"], limit=2, cursor=None)
  493. page_two = store.list_topics(
  494. room["id"], limit=2, cursor=page_one.next_cursor
  495. )
  496. self.assertIsNotNone(page_one.next_cursor)
  497. summaries = [*page_one.items, *page_two.items]
  498. self.assertEqual(len(summaries), 3)
  499. summary_a = next(item for item in summaries if item["id"] == topic_a)
  500. self.assertEqual(summary_a["title"], "第一个话题")
  501. self.assertEqual(summary_a["preview"], "第一个话题的后续")
  502. self.assertEqual(summary_a["messageCount"], 4)
  503. other_room = store.create_room({
  504. "requestId": new_id(),
  505. "name": "另一个群",
  506. "cwd": "",
  507. "agents": [{"profile": "other"}],
  508. })
  509. with self.assertRaisesRegex(ValueError, "does not belong to room"):
  510. store.list_topics(
  511. other_room["id"], limit=2, cursor=page_one.next_cursor
  512. )
  513. with self.assertRaises(STORE_MODULE.GroupConflictError):
  514. store.create_human_message(
  515. other_room["id"],
  516. request_id=new_id(),
  517. client_message_id=new_id(),
  518. topic_id=topic_a,
  519. content="错误归属",
  520. mention_agent_ids=[],
  521. )
  522. def test_topic_context_watermarks_room_session_and_rotation(self) -> None:
  523. with tempfile.TemporaryDirectory() as directory:
  524. store = GroupStore(Path(directory) / "group.db")
  525. store.initialize()
  526. room = store.create_room({
  527. "requestId": new_id(),
  528. "name": "上下文群",
  529. "cwd": "",
  530. "agents": [{"profile": "default"}],
  531. })
  532. [agent] = room["agents"]
  533. topic_a, topic_b = new_id(), new_id()
  534. run_a = store.create_human_message(
  535. room["id"],
  536. request_id=new_id(),
  537. client_message_id=new_id(),
  538. topic_id=topic_a,
  539. content="A-1",
  540. mention_agent_ids=[agent["id"]],
  541. )["runs"][0]
  542. self.assertEqual(store.claim_next_runnable_run()["id"], run_a["id"])
  543. projection_a = store.read_run_projection(run_a["id"])
  544. self.assertEqual(
  545. [message["content"] for message in projection_a["messages"]], ["A-1"]
  546. )
  547. prompt_a = ORCHESTRATOR.build_run_prompt(
  548. projection_a, store.get_room(room["id"])["agents"]
  549. )
  550. envelope_a = json.loads(prompt_a.rsplit("GROUP_CONTEXT_JSON=", 1)[1])
  551. self.assertEqual(envelope_a["run"]["topicId"], topic_a)
  552. self._submit_and_settle(
  553. store, projection_a, runtime="runtime-a", stored="stored-room"
  554. )
  555. run_b = store.create_human_message(
  556. room["id"],
  557. request_id=new_id(),
  558. client_message_id=new_id(),
  559. topic_id=topic_b,
  560. content="B-1",
  561. mention_agent_ids=[agent["id"]],
  562. )["runs"][0]
  563. self.assertEqual(store.claim_next_runnable_run()["id"], run_b["id"])
  564. projection_b = store.read_run_projection(run_b["id"])
  565. self.assertFalse(projection_b["initial"])
  566. self.assertEqual(projection_b["agent"]["storedSessionId"], "stored-room")
  567. self.assertEqual(
  568. [message["content"] for message in projection_b["messages"]], ["B-1"]
  569. )
  570. prompt_b = ORCHESTRATOR.build_run_prompt(
  571. projection_b, store.get_room(room["id"])["agents"]
  572. )
  573. envelope_b = json.loads(prompt_b.rsplit("GROUP_CONTEXT_JSON=", 1)[1])
  574. self.assertEqual(envelope_b["run"]["topicId"], topic_b)
  575. self.assertNotEqual(
  576. envelope_a["run"]["topicId"], envelope_b["run"]["topicId"]
  577. )
  578. self._submit_and_settle(
  579. store, projection_b, runtime="runtime-b", stored="stored-room"
  580. )
  581. run_a2 = store.create_human_message(
  582. room["id"],
  583. request_id=new_id(),
  584. client_message_id=new_id(),
  585. topic_id=topic_a,
  586. content="A-2",
  587. mention_agent_ids=[agent["id"]],
  588. )["runs"][0]
  589. self.assertEqual(store.claim_next_runnable_run()["id"], run_a2["id"])
  590. incremental = store.read_run_projection(run_a2["id"])
  591. self.assertEqual(
  592. [message["content"] for message in incremental["messages"]], ["A-2"]
  593. )
  594. self.assertTrue(
  595. store.prepare_run_session_configuration(
  596. run_a2["id"],
  597. {
  598. "model": None,
  599. "provider": None,
  600. "reasoning_effort": None,
  601. "fast": None,
  602. },
  603. )
  604. )
  605. rebuilt = store.read_run_projection(run_a2["id"])
  606. self.assertTrue(rebuilt["initial"])
  607. rebuilt_contents = [message["content"] for message in rebuilt["messages"]]
  608. self.assertEqual(rebuilt_contents, ["A-1", "A-2"])
  609. self.assertNotIn("B-1", rebuilt_contents)
  610. with store.connection() as connection:
  611. watermarks = connection.execute(
  612. """SELECT topic_id, last_context_message_seq
  613. FROM group_agent_topic_state WHERE agent_id = ?""",
  614. (agent["id"],),
  615. ).fetchall()
  616. self.assertEqual(
  617. {
  618. row["topic_id"]: row["last_context_message_seq"]
  619. for row in watermarks
  620. },
  621. {topic_a: 0, topic_b: 0},
  622. )
  623. def test_cross_topic_runs_interactions_and_cascades_keep_topic(self) -> None:
  624. with tempfile.TemporaryDirectory() as directory:
  625. store = GroupStore(Path(directory) / "group.db")
  626. store.initialize()
  627. room = store.create_room({
  628. "requestId": new_id(),
  629. "name": "并发群",
  630. "cwd": "",
  631. "agents": [
  632. {"profile": "one", "displayName": "一号"},
  633. {"profile": "two", "displayName": "二号"},
  634. ],
  635. })
  636. first_agent, second_agent = room["agents"]
  637. topic_a, topic_b = new_id(), new_id()
  638. first_run = store.create_human_message(
  639. room["id"],
  640. request_id=new_id(),
  641. client_message_id=new_id(),
  642. topic_id=topic_a,
  643. content="请一号回复",
  644. mention_agent_ids=[first_agent["id"]],
  645. )["runs"][0]
  646. second_run = store.create_human_message(
  647. room["id"],
  648. request_id=new_id(),
  649. client_message_id=new_id(),
  650. topic_id=topic_b,
  651. content="请二号回复",
  652. mention_agent_ids=[second_agent["id"]],
  653. )["runs"][0]
  654. claimed = {
  655. store.claim_next_runnable_run()["id"],
  656. store.claim_next_runnable_run()["id"],
  657. }
  658. self.assertEqual(claimed, {first_run["id"], second_run["id"]})
  659. interaction = store.create_interaction(
  660. "approval-topic-test",
  661. first_run["id"],
  662. kind="approval",
  663. payload={"tool": "test"},
  664. )
  665. self.assertEqual(interaction["topicId"], topic_a)
  666. store.transition_run(first_run["id"], "running")
  667. store.upsert_agent_message(
  668. first_run["id"],
  669. content="@二号 继续",
  670. reasoning="",
  671. tool_state=[],
  672. status="completed",
  673. )
  674. store.transition_run(first_run["id"], "completed")
  675. cascade = store.enqueue_cascade_runs(
  676. first_run["id"], agent_ids=[second_agent["id"]], warnings=[]
  677. )
  678. [cascade_run] = cascade["runs"]
  679. self.assertEqual(cascade_run["topicId"], topic_a)
  680. def test_v2_stored_default_session_preserves_session_and_watermark(self) -> None:
  681. with tempfile.TemporaryDirectory() as directory:
  682. path = Path(directory) / "group.db"
  683. room_id, agent_id, topic_id = self._create_legacy_database(
  684. path, version=2, stored_session_id="stored-v2"
  685. )
  686. store = GroupStore(path)
  687. store.initialize()
  688. with store.connection() as connection:
  689. agent = connection.execute(
  690. "SELECT * FROM group_agents WHERE id = ?", (agent_id,)
  691. ).fetchone()
  692. self.assertEqual(
  693. agent["session_config_json"],
  694. '{"fast":null,"model":null,"provider":null,"reasoning_effort":null}',
  695. )
  696. run = self._claim_legacy_topic_continuation(
  697. store, room_id, agent_id, topic_id
  698. )
  699. self.assertFalse(
  700. store.prepare_run_session_configuration(
  701. run["id"], self._default_session_configuration()
  702. )
  703. )
  704. with store.connection() as connection:
  705. refreshed = connection.execute(
  706. "SELECT * FROM group_agents WHERE id = ?", (agent_id,)
  707. ).fetchone()
  708. state = connection.execute(
  709. """SELECT * FROM group_agent_topic_state
  710. WHERE agent_id = ? AND topic_id = ?""",
  711. (agent_id, topic_id),
  712. ).fetchone()
  713. self.assertEqual(refreshed["stored_session_id"], "stored-v2")
  714. self.assertEqual(state["last_context_message_seq"], 1)
  715. def test_v2_without_stored_session_rotates_default_generation(self) -> None:
  716. with tempfile.TemporaryDirectory() as directory:
  717. path = Path(directory) / "group.db"
  718. room_id, agent_id, topic_id = self._create_legacy_database(
  719. path, version=2, stored_session_id=None
  720. )
  721. store = GroupStore(path)
  722. store.initialize()
  723. with store.connection() as connection:
  724. agent = connection.execute(
  725. "SELECT * FROM group_agents WHERE id = ?", (agent_id,)
  726. ).fetchone()
  727. self.assertIsNone(agent["session_config_json"])
  728. run = self._claim_legacy_topic_continuation(
  729. store, room_id, agent_id, topic_id
  730. )
  731. self.assertTrue(
  732. store.prepare_run_session_configuration(
  733. run["id"], self._default_session_configuration()
  734. )
  735. )
  736. with store.connection() as connection:
  737. state = connection.execute(
  738. """SELECT * FROM group_agent_topic_state
  739. WHERE agent_id = ? AND topic_id = ?""",
  740. (agent_id, topic_id),
  741. ).fetchone()
  742. self.assertEqual(state["last_context_message_seq"], 0)
  743. def test_v3_dirty_null_session_configuration_still_rotates(self) -> None:
  744. with tempfile.TemporaryDirectory() as directory:
  745. path = Path(directory) / "group.db"
  746. room_id, agent_id, topic_id = self._create_legacy_database(
  747. path, version=3, stored_session_id="stored-dirty-v3"
  748. )
  749. store = GroupStore(path)
  750. store.initialize()
  751. with store.connection() as connection:
  752. agent = connection.execute(
  753. "SELECT * FROM group_agents WHERE id = ?", (agent_id,)
  754. ).fetchone()
  755. self.assertIsNone(agent["session_config_json"])
  756. run = self._claim_legacy_topic_continuation(
  757. store, room_id, agent_id, topic_id
  758. )
  759. self.assertTrue(
  760. store.prepare_run_session_configuration(
  761. run["id"], self._default_session_configuration()
  762. )
  763. )
  764. self.assertIsNone(store.get_room(room_id)["agents"][0]["storedSessionId"])
  765. def test_legacy_agent_status_and_failed_interaction_replay_shapes(self) -> None:
  766. with tempfile.TemporaryDirectory() as directory:
  767. store = GroupStore(Path(directory) / "group.db")
  768. store.initialize()
  769. room = store.create_room({
  770. "requestId": new_id(),
  771. "name": "兼容群",
  772. "cwd": "",
  773. "agents": [{"profile": "default"}],
  774. })
  775. [agent] = room["agents"]
  776. topic_id = new_id()
  777. run = store.create_human_message(
  778. room["id"],
  779. request_id=new_id(),
  780. client_message_id=new_id(),
  781. topic_id=topic_id,
  782. content="需要审批",
  783. mention_agent_ids=[agent["id"]],
  784. )["runs"][0]
  785. claimed = store.claim_next_runnable_run()
  786. self.assertEqual(claimed["id"], run["id"])
  787. status_events = [
  788. event
  789. for event in store.events_after(0, 100)
  790. if event["eventType"] == "agent.status"
  791. ]
  792. self.assertTrue(status_events)
  793. self.assertEqual(
  794. set(status_events[-1]["payload"]),
  795. {"roomId", "agentId", "status", "runId"},
  796. )
  797. store.bind_run_runtime(run["id"], "runtime-legacy-shape")
  798. interaction = store.create_interaction(
  799. "approval-legacy-shape",
  800. run["id"],
  801. kind="approval",
  802. payload={"choices": ["once"]},
  803. )
  804. response_request = new_id()
  805. response = {"choice": "once", "permanent": False}
  806. store.begin_interaction_response(
  807. room["id"],
  808. interaction["id"],
  809. request_id=response_request,
  810. kind="approval",
  811. response=response,
  812. )
  813. failed = store.fail_interaction_response(
  814. response_request,
  815. reason="Gateway outcome unknown",
  816. uncertain=True,
  817. )
  818. self.assertNotIn("topicId", failed["run"])
  819. self.assertEqual(
  820. set(failed["run"]),
  821. {
  822. "id",
  823. "roomId",
  824. "agentId",
  825. "triggerMessageId",
  826. "responseMessageId",
  827. "rootMessageId",
  828. "depth",
  829. "replyMode",
  830. "status",
  831. "runtimeSessionId",
  832. "error",
  833. "createdAt",
  834. "updatedAt",
  835. },
  836. )
  837. replay = store.begin_interaction_response(
  838. room["id"],
  839. interaction["id"],
  840. request_id=response_request,
  841. kind="approval",
  842. response=response,
  843. )
  844. self.assertEqual(replay, failed)
  845. run_events = [
  846. event
  847. for event in store.events_after(0, 200)
  848. if event["eventType"] == "run.updated"
  849. ]
  850. self.assertEqual(run_events[-1]["payload"]["topicId"], topic_id)
  851. def test_composite_topic_foreign_keys_reject_cross_room_rows(self) -> None:
  852. with tempfile.TemporaryDirectory() as directory:
  853. store = GroupStore(Path(directory) / "group.db")
  854. store.initialize()
  855. first_room = store.create_room({
  856. "requestId": new_id(),
  857. "name": "房间一",
  858. "cwd": "",
  859. "agents": [{"profile": "one"}],
  860. })
  861. second_room = store.create_room({
  862. "requestId": new_id(),
  863. "name": "房间二",
  864. "cwd": "",
  865. "agents": [{"profile": "two"}],
  866. })
  867. topic_id = new_id()
  868. first_message = store.create_human_message(
  869. first_room["id"],
  870. request_id=new_id(),
  871. client_message_id=new_id(),
  872. topic_id=topic_id,
  873. content="归属房间一",
  874. mention_agent_ids=[],
  875. )["message"]
  876. [second_agent] = second_room["agents"]
  877. invalid_statements = (
  878. (
  879. """INSERT INTO group_messages
  880. (id, room_id, topic_id, sender_kind, sender_id, sender_name,
  881. root_message_id, reply_to_message_id, client_message_id,
  882. content, reasoning, tool_state_json, status, error, visible,
  883. created_at, updated_at)
  884. VALUES (?, ?, ?, 'human', 'human', '你', ?, NULL, ?, '错误',
  885. '', '[]', 'completed', '', 1, 1, 1)""",
  886. (
  887. new_id(),
  888. second_room["id"],
  889. topic_id,
  890. new_id(),
  891. new_id(),
  892. ),
  893. ),
  894. (
  895. """INSERT INTO group_agent_runs
  896. (id, room_id, topic_id, agent_id, trigger_message_id,
  897. response_message_id, root_message_id, depth, reply_mode,
  898. status, runtime_session_id, error, created_at, updated_at)
  899. VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'mentioned', 'completed',
  900. NULL, '', 1, 1)""",
  901. (
  902. new_id(),
  903. second_room["id"],
  904. topic_id,
  905. second_agent["id"],
  906. first_message["id"],
  907. first_message["id"],
  908. first_message["rootMessageId"],
  909. ),
  910. ),
  911. (
  912. """INSERT INTO group_interactions
  913. (id, room_id, topic_id, agent_id, run_id, kind, payload_json,
  914. status, created_at, resolved_at)
  915. VALUES (?, ?, ?, ?, ?, 'approval', '{}', 'pending', 1, NULL)""",
  916. (
  917. "cross-room-interaction",
  918. second_room["id"],
  919. topic_id,
  920. second_agent["id"],
  921. new_id(),
  922. ),
  923. ),
  924. )
  925. for statement, parameters in invalid_statements:
  926. with self.subTest(table=statement.split()[2]):
  927. with self.assertRaises(sqlite3.IntegrityError):
  928. with store.write_transaction() as connection:
  929. connection.execute(statement, parameters)
  930. def test_v3_migration_topic_order_ignores_newer_hidden_messages(self) -> None:
  931. with tempfile.TemporaryDirectory() as directory:
  932. path = Path(directory) / "group.db"
  933. room_id, _agent_id, first_topic = self._create_legacy_database(
  934. path, version=3, stored_session_id=None
  935. )
  936. second_topic, hidden_topic = new_id(), new_id()
  937. connection = sqlite3.connect(path)
  938. connection.execute(
  939. """UPDATE group_messages
  940. SET visible = 1, created_at = 1, updated_at = 10
  941. WHERE root_message_id = ?""",
  942. (first_topic,),
  943. )
  944. connection.execute(
  945. """INSERT INTO group_messages
  946. (id, room_id, sender_kind, sender_id, sender_name, root_message_id,
  947. reply_to_message_id, client_message_id, content, reasoning,
  948. tool_state_json, status, error, visible, created_at, updated_at)
  949. VALUES (?, ?, 'agent', 'hidden', '隐藏', ?, NULL, NULL,
  950. '隐藏更新', '', '[]', 'completed', '', 0, 2, 100)""",
  951. (new_id(), room_id, first_topic),
  952. )
  953. connection.execute(
  954. """INSERT INTO group_messages
  955. (id, room_id, sender_kind, sender_id, sender_name, root_message_id,
  956. reply_to_message_id, client_message_id, content, reasoning,
  957. tool_state_json, status, error, visible, created_at, updated_at)
  958. VALUES (?, ?, 'human', 'human', '你', ?, NULL, ?,
  959. '第二可见话题', '', '[]', 'completed', '', 1, 3, 50)""",
  960. (second_topic, room_id, second_topic, new_id()),
  961. )
  962. connection.execute(
  963. """INSERT INTO group_messages
  964. (id, room_id, sender_kind, sender_id, sender_name, root_message_id,
  965. reply_to_message_id, client_message_id, content, reasoning,
  966. tool_state_json, status, error, visible, created_at, updated_at)
  967. VALUES (?, ?, 'agent', 'hidden', '隐藏', ?, NULL, NULL,
  968. '仅隐藏话题', '', '[]', 'completed', '', 0, 4, 75)""",
  969. (hidden_topic, room_id, hidden_topic),
  970. )
  971. connection.commit()
  972. connection.close()
  973. store = GroupStore(path)
  974. store.initialize()
  975. topics = store.list_topics(room_id, limit=10, cursor=None).items
  976. self.assertEqual(
  977. [topic["id"] for topic in topics],
  978. [hidden_topic, second_topic, first_topic],
  979. )
  980. self.assertEqual(
  981. {topic["id"]: topic["updatedAt"] for topic in topics},
  982. {hidden_topic: 75, second_topic: 50, first_topic: 10},
  983. )
  984. def test_v3_migration_rejects_orphan_run_messages_and_interactions(self) -> None:
  985. for column in ("trigger_message_id", "response_message_id"):
  986. with (
  987. self.subTest(orphan=column),
  988. tempfile.TemporaryDirectory() as directory,
  989. ):
  990. path = Path(directory) / "group.db"
  991. self._create_legacy_database(path, version=3, stored_session_id=None)
  992. connection = sqlite3.connect(path)
  993. connection.execute(
  994. f"UPDATE group_agent_runs SET {column} = ?", (new_id(),)
  995. )
  996. connection.commit()
  997. connection.close()
  998. with self.assertRaisesRegex(
  999. STORE_MODULE.GroupStoreError, "run messages are orphaned"
  1000. ):
  1001. GroupStore(path).initialize()
  1002. self._assert_legacy_schema_rolled_back(path)
  1003. with tempfile.TemporaryDirectory() as directory:
  1004. path = Path(directory) / "group.db"
  1005. room_id, agent_id, _topic_id = self._create_legacy_database(
  1006. path, version=3, stored_session_id=None
  1007. )
  1008. connection = sqlite3.connect(path)
  1009. connection.execute(
  1010. """INSERT INTO group_interactions
  1011. (id, room_id, agent_id, run_id, kind, payload_json, status,
  1012. created_at, resolved_at)
  1013. VALUES ('orphan-interaction', ?, ?, ?, 'approval', '{}',
  1014. 'pending', 1, NULL)""",
  1015. (room_id, agent_id, new_id()),
  1016. )
  1017. connection.commit()
  1018. connection.close()
  1019. with self.assertRaisesRegex(
  1020. STORE_MODULE.GroupStoreError, "interaction run is orphaned"
  1021. ):
  1022. GroupStore(path).initialize()
  1023. self._assert_legacy_schema_rolled_back(path)
  1024. def test_v4_validation_rejects_missing_run_trigger_or_response(self) -> None:
  1025. for column in ("trigger_message_id", "response_message_id"):
  1026. with (
  1027. self.subTest(orphan=column),
  1028. tempfile.TemporaryDirectory() as directory,
  1029. ):
  1030. path = Path(directory) / "group.db"
  1031. store = GroupStore(path)
  1032. store.initialize()
  1033. room = store.create_room({
  1034. "requestId": new_id(),
  1035. "name": "损坏群",
  1036. "cwd": "",
  1037. "agents": [{"profile": "default"}],
  1038. })
  1039. [agent] = room["agents"]
  1040. topic_id = new_id()
  1041. message = store.create_human_message(
  1042. room["id"],
  1043. request_id=new_id(),
  1044. client_message_id=new_id(),
  1045. topic_id=topic_id,
  1046. content="有效消息",
  1047. mention_agent_ids=[],
  1048. )["message"]
  1049. trigger_id = (
  1050. new_id() if column == "trigger_message_id" else message["id"]
  1051. )
  1052. response_id = (
  1053. new_id() if column == "response_message_id" else message["id"]
  1054. )
  1055. with store.connection() as connection:
  1056. connection.execute(
  1057. """INSERT INTO group_agent_runs
  1058. (id, room_id, topic_id, agent_id, trigger_message_id,
  1059. response_message_id, root_message_id, depth, reply_mode,
  1060. status, runtime_session_id, error, created_at, updated_at)
  1061. VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'mentioned', 'completed',
  1062. NULL, '', 1, 1)""",
  1063. (
  1064. new_id(),
  1065. room["id"],
  1066. topic_id,
  1067. agent["id"],
  1068. trigger_id,
  1069. response_id,
  1070. message["rootMessageId"],
  1071. ),
  1072. )
  1073. with self.assertRaisesRegex(
  1074. STORE_MODULE.GroupStoreError, "stored values are corrupt"
  1075. ):
  1076. GroupStore(path).initialize()
  1077. def test_early_v4_draft_repairs_losslessly_and_is_idempotent(self) -> None:
  1078. with tempfile.TemporaryDirectory() as directory:
  1079. path = Path(directory) / "group.db"
  1080. store = GroupStore(path)
  1081. store.initialize()
  1082. room = store.create_room({
  1083. "requestId": new_id(),
  1084. "name": "早期 v4 群",
  1085. "cwd": "",
  1086. "agents": [{"profile": "default", "description": "保留设置"}],
  1087. })
  1088. [agent] = room["agents"]
  1089. visible_topic, hidden_topic = new_id(), new_id()
  1090. created = store.create_human_message(
  1091. room["id"],
  1092. request_id=new_id(),
  1093. client_message_id=new_id(),
  1094. topic_id=visible_topic,
  1095. content="可见话题",
  1096. mention_agent_ids=[agent["id"]],
  1097. )
  1098. [run] = created["runs"]
  1099. self.assertEqual(store.claim_next_runnable_run()["id"], run["id"])
  1100. store.bind_run_runtime(run["id"], "runtime-early-v4")
  1101. interaction = store.create_interaction(
  1102. "approval-early-v4",
  1103. run["id"],
  1104. kind="approval",
  1105. payload={"choices": ["once"]},
  1106. )
  1107. failed_request = new_id()
  1108. with store.write_transaction() as connection:
  1109. connection.execute(
  1110. """UPDATE group_messages SET created_at = 1, updated_at = 10
  1111. WHERE topic_id = ?""",
  1112. (visible_topic,),
  1113. )
  1114. connection.execute(
  1115. """INSERT INTO group_messages
  1116. (id, room_id, topic_id, sender_kind, sender_id, sender_name,
  1117. root_message_id, reply_to_message_id, client_message_id,
  1118. content, reasoning, tool_state_json, status, error, visible,
  1119. created_at, updated_at)
  1120. VALUES (?, ?, ?, 'agent', ?, '隐藏', ?, NULL, NULL,
  1121. '隐藏更新', '', '[]', 'completed', '', 0, 2, 100)""",
  1122. (
  1123. new_id(),
  1124. room["id"],
  1125. visible_topic,
  1126. agent["id"],
  1127. created["message"]["rootMessageId"],
  1128. ),
  1129. )
  1130. store._ensure_topic(
  1131. connection, room["id"], hidden_topic, "仅隐藏话题", 4
  1132. )
  1133. connection.execute(
  1134. """INSERT INTO group_messages
  1135. (id, room_id, topic_id, sender_kind, sender_id, sender_name,
  1136. root_message_id, reply_to_message_id, client_message_id,
  1137. content, reasoning, tool_state_json, status, error, visible,
  1138. created_at, updated_at)
  1139. VALUES (?, ?, ?, 'agent', ?, '隐藏', ?, NULL, NULL,
  1140. '仅隐藏消息', '', '[]', 'completed', '', 0, 4, 75)""",
  1141. (hidden_topic, room["id"], hidden_topic, agent["id"], hidden_topic),
  1142. )
  1143. connection.execute("UPDATE group_topics SET updated_at = 999")
  1144. status_events = connection.execute(
  1145. """SELECT cursor, payload_json FROM group_events
  1146. WHERE event_type = 'agent.status'"""
  1147. ).fetchall()
  1148. for event in status_events:
  1149. payload = json.loads(event["payload_json"])
  1150. payload["topicId"] = visible_topic
  1151. connection.execute(
  1152. "UPDATE group_events SET payload_json = ? WHERE cursor = ?",
  1153. (GroupStore._canonical_json(payload), event["cursor"]),
  1154. )
  1155. failed_run = store._run_wire(store._run_row(connection, run["id"]))
  1156. connection.execute(
  1157. """INSERT INTO group_idempotency
  1158. (request_id, operation, request_hash, response_json, created_at)
  1159. VALUES (?, ?, 'early-v4-failed-hash', ?, 5)""",
  1160. (
  1161. failed_request,
  1162. f"interaction.approval.response:{interaction['id']}",
  1163. GroupStore._canonical_json({
  1164. "state": "failed",
  1165. "reason": "early failure",
  1166. "runtimeSessionIds": ["runtime-early-v4"],
  1167. "run": failed_run,
  1168. }),
  1169. ),
  1170. )
  1171. with store.connection() as connection:
  1172. expected_room = dict(
  1173. connection.execute(
  1174. "SELECT * FROM group_rooms WHERE id = ?", (room["id"],)
  1175. ).fetchone()
  1176. )
  1177. expected_agent = dict(
  1178. connection.execute(
  1179. "SELECT * FROM group_agents WHERE id = ?", (agent["id"],)
  1180. ).fetchone()
  1181. )
  1182. expected_counts = {
  1183. table: connection.execute(
  1184. f"SELECT COUNT(*) FROM {table}"
  1185. ).fetchone()[0]
  1186. for table in (
  1187. "group_messages",
  1188. "group_agent_runs",
  1189. "group_interactions",
  1190. "group_topics",
  1191. "group_agent_topic_state",
  1192. )
  1193. }
  1194. expected_states = [
  1195. tuple(row)
  1196. for row in connection.execute(
  1197. """SELECT * FROM group_agent_topic_state
  1198. ORDER BY agent_id, topic_id"""
  1199. )
  1200. ]
  1201. self._downgrade_to_early_v4(connection)
  1202. self.assertEqual(
  1203. {
  1204. table: GroupStore._topic_foreign_key_kind(connection, table)
  1205. for table in (
  1206. "group_messages",
  1207. "group_agent_runs",
  1208. "group_interactions",
  1209. )
  1210. },
  1211. {
  1212. "group_messages": "early",
  1213. "group_agent_runs": "early",
  1214. "group_interactions": "early",
  1215. },
  1216. )
  1217. repaired = GroupStore(path)
  1218. repaired.initialize()
  1219. with repaired.connection() as connection:
  1220. self.assertEqual(
  1221. {
  1222. table: GroupStore._topic_foreign_key_kind(connection, table)
  1223. for table in (
  1224. "group_messages",
  1225. "group_agent_runs",
  1226. "group_interactions",
  1227. )
  1228. },
  1229. {
  1230. "group_messages": "final",
  1231. "group_agent_runs": "final",
  1232. "group_interactions": "final",
  1233. },
  1234. )
  1235. self.assertEqual(
  1236. dict(
  1237. connection.execute(
  1238. "SELECT * FROM group_rooms WHERE id = ?", (room["id"],)
  1239. ).fetchone()
  1240. ),
  1241. expected_room,
  1242. )
  1243. self.assertEqual(
  1244. dict(
  1245. connection.execute(
  1246. "SELECT * FROM group_agents WHERE id = ?", (agent["id"],)
  1247. ).fetchone()
  1248. ),
  1249. expected_agent,
  1250. )
  1251. actual_counts = {
  1252. table: connection.execute(
  1253. f"SELECT COUNT(*) FROM {table}"
  1254. ).fetchone()[0]
  1255. for table in expected_counts
  1256. }
  1257. self.assertEqual(actual_counts, expected_counts)
  1258. max_message_seq = connection.execute(
  1259. "SELECT MAX(seq) FROM group_messages"
  1260. ).fetchone()[0]
  1261. message_sequence = connection.execute(
  1262. "SELECT seq FROM sqlite_sequence WHERE name = 'group_messages'"
  1263. ).fetchone()[0]
  1264. self.assertEqual(message_sequence, max_message_seq)
  1265. self.assertEqual(
  1266. [
  1267. tuple(row)
  1268. for row in connection.execute(
  1269. """SELECT * FROM group_agent_topic_state
  1270. ORDER BY agent_id, topic_id"""
  1271. )
  1272. ],
  1273. expected_states,
  1274. )
  1275. topics = {
  1276. row["id"]: dict(row)
  1277. for row in connection.execute(
  1278. "SELECT * FROM group_topics ORDER BY id"
  1279. )
  1280. }
  1281. self.assertEqual(topics[visible_topic]["updated_at"], 10)
  1282. self.assertEqual(topics[hidden_topic]["updated_at"], 75)
  1283. for event in connection.execute(
  1284. """SELECT payload_json FROM group_events
  1285. WHERE event_type = 'agent.status'"""
  1286. ):
  1287. self.assertNotIn("topicId", json.loads(event["payload_json"]))
  1288. failed = json.loads(
  1289. connection.execute(
  1290. """SELECT response_json FROM group_idempotency
  1291. WHERE request_id = ?""",
  1292. (failed_request,),
  1293. ).fetchone()[0]
  1294. )
  1295. self.assertNotIn("topicId", failed["run"])
  1296. first_snapshot = self._repair_snapshot(connection)
  1297. repaired.initialize()
  1298. with repaired.connection() as connection:
  1299. self.assertEqual(self._repair_snapshot(connection), first_snapshot)
  1300. def test_v3_migration_preserves_room_agent_and_rewrites_topic_wires(self) -> None:
  1301. with tempfile.TemporaryDirectory() as directory:
  1302. path = Path(directory) / "group.db"
  1303. SETTINGS_TESTS.GroupSettingsContractTests._create_v1_database(path)
  1304. connection = sqlite3.connect(path)
  1305. connection.row_factory = sqlite3.Row
  1306. GroupStore._migrate_v1_to_v2(connection)
  1307. GroupStore._migrate_v2_to_v3(connection)
  1308. room_id = connection.execute("SELECT id FROM group_rooms").fetchone()[0]
  1309. agent_id = connection.execute("SELECT id FROM group_agents").fetchone()[0]
  1310. first_message = connection.execute(
  1311. "SELECT * FROM group_messages ORDER BY seq LIMIT 1"
  1312. ).fetchone()
  1313. connection.execute(
  1314. """UPDATE group_rooms SET name = '保留群', max_reply_rounds = 7,
  1315. archived = 1 WHERE id = ?""",
  1316. (room_id,),
  1317. )
  1318. connection.execute(
  1319. """UPDATE group_agents
  1320. SET display_name = '保留名', display_name_key = '保留名',
  1321. description = '保留职责', stored_session_id = 'stored-old',
  1322. last_context_message_seq = 2, enabled = 0,
  1323. reply_without_mention = 1, model_override = 'model-old',
  1324. provider_override = 'provider-old',
  1325. reasoning_effort_override = 'high', fast_mode_override = 1,
  1326. session_config_json = '{"fast":true}'
  1327. WHERE id = ?""",
  1328. (agent_id,),
  1329. )
  1330. expected_room = dict(
  1331. connection.execute(
  1332. "SELECT * FROM group_rooms WHERE id = ?", (room_id,)
  1333. ).fetchone()
  1334. )
  1335. expected_agent = dict(
  1336. connection.execute(
  1337. "SELECT * FROM group_agents WHERE id = ?", (agent_id,)
  1338. ).fetchone()
  1339. )
  1340. second_message, second_run = new_id(), new_id()
  1341. connection.execute(
  1342. """INSERT INTO group_messages
  1343. (id, room_id, sender_kind, sender_id, sender_name, root_message_id,
  1344. reply_to_message_id, client_message_id, content, reasoning,
  1345. tool_state_json, status, error, visible, created_at, updated_at)
  1346. VALUES (?, ?, 'human', 'human', '你', ?, NULL, ?, '第二话题', '',
  1347. '[]', 'completed', '', 1, 2, 2)""",
  1348. (second_message, room_id, second_message, new_id()),
  1349. )
  1350. connection.execute(
  1351. """INSERT INTO group_agent_runs
  1352. (id, room_id, agent_id, trigger_message_id, response_message_id,
  1353. root_message_id, depth, reply_mode, status, runtime_session_id,
  1354. error, created_at, updated_at)
  1355. VALUES (?, ?, ?, ?, ?, ?, 0, 'mentioned', 'running',
  1356. 'runtime-old', '', 2, 2)""",
  1357. (
  1358. second_run,
  1359. room_id,
  1360. agent_id,
  1361. second_message,
  1362. second_message,
  1363. second_message,
  1364. ),
  1365. )
  1366. connection.execute(
  1367. """INSERT INTO group_interactions
  1368. (id, room_id, agent_id, run_id, kind, payload_json, status,
  1369. created_at, resolved_at)
  1370. VALUES ('legacy-interaction', ?, ?, ?, 'approval', '{}',
  1371. 'pending', 2, NULL)""",
  1372. (room_id, agent_id, second_run),
  1373. )
  1374. failed_interaction_request = new_id()
  1375. connection.execute(
  1376. """INSERT INTO group_idempotency
  1377. (request_id, operation, request_hash, response_json, created_at)
  1378. VALUES (?, 'interaction.approval.response:legacy-interaction',
  1379. 'legacy-failed-hash', ?, 2)""",
  1380. (
  1381. failed_interaction_request,
  1382. GroupStore._canonical_json({
  1383. "state": "failed",
  1384. "reason": "legacy failure",
  1385. "runtimeSessionIds": [],
  1386. "run": {
  1387. "id": second_run,
  1388. "triggerMessageId": second_message,
  1389. },
  1390. }),
  1391. ),
  1392. )
  1393. replay_request = new_id()
  1394. old_payload = {
  1395. "roomId": room_id,
  1396. "clientMessageId": first_message["client_message_id"],
  1397. "content": first_message["content"],
  1398. "mentionAgentIds": [],
  1399. }
  1400. old_response = {
  1401. "message": {"id": first_message["id"], "senderKind": "human"},
  1402. "runs": [],
  1403. }
  1404. connection.execute(
  1405. """INSERT INTO group_idempotency
  1406. (request_id, operation, request_hash, response_json, created_at)
  1407. VALUES (?, 'message.create', ?, ?, 1)""",
  1408. (
  1409. replay_request,
  1410. hashlib.sha256(
  1411. GroupStore._canonical_json(old_payload).encode()
  1412. ).hexdigest(),
  1413. GroupStore._canonical_json(old_response),
  1414. ),
  1415. )
  1416. connection.execute(
  1417. """INSERT INTO group_events
  1418. (epoch, room_id, event_type, payload_json, created_at)
  1419. VALUES ('11111111-1111-4111-8111-111111111111', ?,
  1420. 'message.upsert', ?, 1)""",
  1421. (room_id, GroupStore._canonical_json(old_response["message"])),
  1422. )
  1423. connection.execute(
  1424. """INSERT INTO group_events
  1425. (epoch, room_id, event_type, payload_json, created_at)
  1426. VALUES ('11111111-1111-4111-8111-111111111111', ?,
  1427. 'run.updated', ?, 2)""",
  1428. (
  1429. room_id,
  1430. GroupStore._canonical_json({
  1431. "id": second_run,
  1432. "triggerMessageId": second_message,
  1433. }),
  1434. ),
  1435. )
  1436. connection.execute(
  1437. """INSERT INTO group_events
  1438. (epoch, room_id, event_type, payload_json, created_at)
  1439. VALUES ('11111111-1111-4111-8111-111111111111', ?,
  1440. 'interaction.requested', ?, 2)""",
  1441. (
  1442. room_id,
  1443. GroupStore._canonical_json({
  1444. "id": "legacy-interaction",
  1445. "runId": second_run,
  1446. "kind": "approval",
  1447. }),
  1448. ),
  1449. )
  1450. connection.commit()
  1451. connection.close()
  1452. store = GroupStore(path)
  1453. store.initialize()
  1454. self.assertEqual(store.schema_version(), 14)
  1455. with store.connection() as migrated:
  1456. room = migrated.execute("SELECT * FROM group_rooms").fetchone()
  1457. agent = migrated.execute("SELECT * FROM group_agents").fetchone()
  1458. topics = migrated.execute(
  1459. "SELECT * FROM group_topics ORDER BY created_at, id"
  1460. ).fetchall()
  1461. states = migrated.execute(
  1462. """SELECT * FROM group_agent_topic_state
  1463. WHERE agent_id = ? ORDER BY topic_id""",
  1464. (agent_id,),
  1465. ).fetchall()
  1466. interaction = migrated.execute(
  1467. "SELECT * FROM group_interactions WHERE id = 'legacy-interaction'"
  1468. ).fetchone()
  1469. active_run = migrated.execute(
  1470. "SELECT * FROM group_agent_runs WHERE id = ?", (second_run,)
  1471. ).fetchone()
  1472. failed_interaction_replay = json.loads(
  1473. migrated.execute(
  1474. """SELECT response_json FROM group_idempotency
  1475. WHERE request_id = ?""",
  1476. (failed_interaction_request,),
  1477. ).fetchone()[0]
  1478. )
  1479. self.assertEqual(
  1480. dict(room), {
  1481. **expected_room,
  1482. "orchestration_mode": "free",
  1483. "instructions": "",
  1484. "avatar_data_url": "",
  1485. }
  1486. )
  1487. self.assertEqual(
  1488. dict(agent),
  1489. {
  1490. **expected_agent,
  1491. "is_host": 1,
  1492. "node_id": "local",
  1493. "node_label": "",
  1494. "execution_profile": None,
  1495. },
  1496. )
  1497. self.assertEqual(
  1498. (room["name"], room["max_reply_rounds"], room["archived"]),
  1499. ("保留群", 7, 1),
  1500. )
  1501. self.assertEqual(
  1502. (
  1503. agent["profile"],
  1504. agent["display_name"],
  1505. agent["description"],
  1506. agent["stored_session_id"],
  1507. agent["last_context_message_seq"],
  1508. agent["enabled"],
  1509. agent["reply_without_mention"],
  1510. agent["model_override"],
  1511. agent["provider_override"],
  1512. agent["reasoning_effort_override"],
  1513. agent["fast_mode_override"],
  1514. agent["session_config_json"],
  1515. ),
  1516. (
  1517. "default",
  1518. "保留名",
  1519. "保留职责",
  1520. "stored-old",
  1521. 2,
  1522. 0,
  1523. 1,
  1524. "model-old",
  1525. "provider-old",
  1526. "high",
  1527. 1,
  1528. '{"fast":true}',
  1529. ),
  1530. )
  1531. self.assertEqual(
  1532. {topic["id"] for topic in topics},
  1533. {first_message["root_message_id"], second_message},
  1534. )
  1535. self.assertEqual(
  1536. {
  1537. state["topic_id"]: state["last_context_message_seq"]
  1538. for state in states
  1539. },
  1540. {first_message["root_message_id"]: 1, second_message: 2},
  1541. )
  1542. self.assertEqual(interaction["topic_id"], second_message)
  1543. self.assertEqual(active_run["topic_id"], second_message)
  1544. self.assertEqual(active_run["runtime_session_id"], "runtime-old")
  1545. self.assertNotIn("topicId", failed_interaction_replay["run"])
  1546. replay = store.create_human_message(
  1547. room_id,
  1548. request_id=replay_request,
  1549. client_message_id=first_message["client_message_id"],
  1550. content=first_message["content"],
  1551. mention_agent_ids=[],
  1552. )
  1553. self.assertEqual(
  1554. replay["message"]["topicId"], first_message["root_message_id"]
  1555. )
  1556. historical_events = store.events_after(0, 3)
  1557. self.assertEqual(
  1558. [event["payload"]["topicId"] for event in historical_events],
  1559. [
  1560. first_message["root_message_id"],
  1561. second_message,
  1562. second_message,
  1563. ],
  1564. )
  1565. def test_v3_migration_rolls_back_atomically_on_invalid_topic_identity(self) -> None:
  1566. with tempfile.TemporaryDirectory() as directory:
  1567. path = Path(directory) / "group.db"
  1568. SETTINGS_TESTS.GroupSettingsContractTests._create_v1_database(path)
  1569. connection = sqlite3.connect(path)
  1570. connection.row_factory = sqlite3.Row
  1571. GroupStore._migrate_v1_to_v2(connection)
  1572. GroupStore._migrate_v2_to_v3(connection)
  1573. connection.execute(
  1574. "UPDATE group_messages SET root_message_id = 'invalid-topic'"
  1575. )
  1576. connection.execute(
  1577. "UPDATE group_agent_runs SET root_message_id = 'invalid-topic'"
  1578. )
  1579. connection.commit()
  1580. connection.close()
  1581. with self.assertRaises(STORE_MODULE.GroupStoreError):
  1582. GroupStore(path).initialize()
  1583. verification = sqlite3.connect(path)
  1584. version = verification.execute(
  1585. "SELECT value FROM group_meta WHERE key = 'schema_version'"
  1586. ).fetchone()[0]
  1587. tables = {
  1588. row[0]
  1589. for row in verification.execute(
  1590. """SELECT name FROM sqlite_master
  1591. WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"""
  1592. )
  1593. }
  1594. verification.close()
  1595. self.assertEqual(version, "3")
  1596. self.assertNotIn("group_topics", tables)
  1597. self.assertNotIn("group_agent_topic_state", tables)
  1598. @staticmethod
  1599. def _downgrade_to_early_v4(connection: sqlite3.Connection) -> None:
  1600. connection.execute(
  1601. """CREATE TABLE group_messages_early_fixture (
  1602. seq INTEGER PRIMARY KEY AUTOINCREMENT,
  1603. id TEXT NOT NULL UNIQUE,
  1604. room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
  1605. topic_id TEXT NOT NULL REFERENCES group_topics(id) ON DELETE CASCADE,
  1606. sender_kind TEXT NOT NULL,
  1607. sender_id TEXT NOT NULL,
  1608. sender_name TEXT NOT NULL,
  1609. root_message_id TEXT NOT NULL,
  1610. reply_to_message_id TEXT,
  1611. client_message_id TEXT UNIQUE,
  1612. content TEXT NOT NULL DEFAULT '',
  1613. reasoning TEXT NOT NULL DEFAULT '',
  1614. tool_state_json TEXT NOT NULL DEFAULT '[]',
  1615. status TEXT NOT NULL,
  1616. error TEXT NOT NULL DEFAULT '',
  1617. visible INTEGER NOT NULL DEFAULT 1,
  1618. created_at REAL NOT NULL,
  1619. updated_at REAL NOT NULL
  1620. )"""
  1621. )
  1622. connection.execute(
  1623. """INSERT INTO group_messages_early_fixture
  1624. SELECT * FROM group_messages ORDER BY seq"""
  1625. )
  1626. connection.execute(
  1627. """CREATE TABLE group_agent_runs_early_fixture (
  1628. id TEXT PRIMARY KEY,
  1629. room_id TEXT NOT NULL,
  1630. topic_id TEXT NOT NULL REFERENCES group_topics(id) ON DELETE CASCADE,
  1631. agent_id TEXT NOT NULL,
  1632. trigger_message_id TEXT NOT NULL,
  1633. response_message_id TEXT NOT NULL,
  1634. root_message_id TEXT NOT NULL,
  1635. depth INTEGER NOT NULL,
  1636. reply_mode TEXT NOT NULL DEFAULT 'mentioned',
  1637. status TEXT NOT NULL,
  1638. runtime_session_id TEXT,
  1639. error TEXT NOT NULL DEFAULT '',
  1640. created_at REAL NOT NULL,
  1641. updated_at REAL NOT NULL
  1642. )"""
  1643. )
  1644. connection.execute(
  1645. """INSERT INTO group_agent_runs_early_fixture
  1646. SELECT id, room_id, topic_id, agent_id, trigger_message_id,
  1647. response_message_id, root_message_id, depth, reply_mode,
  1648. status, runtime_session_id, error, created_at, updated_at
  1649. FROM group_agent_runs"""
  1650. )
  1651. connection.execute(
  1652. """CREATE TABLE group_interactions_early_fixture (
  1653. id TEXT PRIMARY KEY,
  1654. room_id TEXT NOT NULL,
  1655. topic_id TEXT NOT NULL REFERENCES group_topics(id) ON DELETE CASCADE,
  1656. agent_id TEXT NOT NULL,
  1657. run_id TEXT NOT NULL,
  1658. kind TEXT NOT NULL,
  1659. payload_json TEXT NOT NULL,
  1660. status TEXT NOT NULL,
  1661. created_at REAL NOT NULL,
  1662. resolved_at REAL
  1663. )"""
  1664. )
  1665. connection.execute(
  1666. """INSERT INTO group_interactions_early_fixture
  1667. SELECT * FROM group_interactions"""
  1668. )
  1669. connection.execute("DROP TABLE group_interactions")
  1670. connection.execute("DROP TABLE group_agent_runs")
  1671. connection.execute("DROP TABLE group_messages")
  1672. connection.execute(
  1673. "ALTER TABLE group_messages_early_fixture RENAME TO group_messages"
  1674. )
  1675. connection.execute(
  1676. "ALTER TABLE group_agent_runs_early_fixture RENAME TO group_agent_runs"
  1677. )
  1678. connection.execute(
  1679. "ALTER TABLE group_interactions_early_fixture RENAME TO group_interactions"
  1680. )
  1681. connection.execute("DROP INDEX IF EXISTS idx_group_agents_room_host")
  1682. connection.execute("ALTER TABLE group_agents DROP COLUMN is_host")
  1683. connection.execute(
  1684. "UPDATE group_meta SET value = '4' WHERE key = 'schema_version'"
  1685. )
  1686. @staticmethod
  1687. def _repair_snapshot(connection: sqlite3.Connection) -> dict[str, object]:
  1688. ordering = {
  1689. "group_meta": "key",
  1690. "group_rooms": "id",
  1691. "group_topics": "id",
  1692. "group_agents": "id",
  1693. "group_agent_topic_state": "agent_id, topic_id",
  1694. "group_messages": "seq",
  1695. "group_agent_runs": "id",
  1696. "group_interactions": "id",
  1697. "group_events": "cursor",
  1698. "group_idempotency": "request_id",
  1699. }
  1700. return {
  1701. table: [
  1702. tuple(row)
  1703. for row in connection.execute(
  1704. f"SELECT * FROM {table} ORDER BY {order_by}"
  1705. )
  1706. ]
  1707. for table, order_by in ordering.items()
  1708. }
  1709. @staticmethod
  1710. def _create_legacy_database(
  1711. path: Path, *, version: int, stored_session_id: str | None
  1712. ) -> tuple[str, str, str]:
  1713. if version not in {2, 3}:
  1714. raise ValueError("legacy test version must be 2 or 3")
  1715. SETTINGS_TESTS.GroupSettingsContractTests._create_v1_database(path)
  1716. connection = sqlite3.connect(path)
  1717. connection.row_factory = sqlite3.Row
  1718. GroupStore._migrate_v1_to_v2(connection)
  1719. room_id = connection.execute("SELECT id FROM group_rooms").fetchone()[0]
  1720. agent_id = connection.execute("SELECT id FROM group_agents").fetchone()[0]
  1721. topic_id = connection.execute(
  1722. "SELECT root_message_id FROM group_messages ORDER BY seq LIMIT 1"
  1723. ).fetchone()[0]
  1724. connection.execute(
  1725. """UPDATE group_agents
  1726. SET stored_session_id = ?, last_context_message_seq = 1
  1727. WHERE id = ?""",
  1728. (stored_session_id, agent_id),
  1729. )
  1730. if version == 3:
  1731. GroupStore._migrate_v2_to_v3(connection)
  1732. connection.execute(
  1733. "UPDATE group_agents SET session_config_json = NULL WHERE id = ?",
  1734. (agent_id,),
  1735. )
  1736. connection.commit()
  1737. connection.close()
  1738. return room_id, agent_id, topic_id
  1739. @staticmethod
  1740. def _default_session_configuration() -> dict[str, object]:
  1741. return {
  1742. "model": None,
  1743. "provider": None,
  1744. "reasoning_effort": None,
  1745. "fast": None,
  1746. }
  1747. @staticmethod
  1748. def _claim_legacy_topic_continuation(
  1749. store: GroupStore, room_id: str, agent_id: str, topic_id: str
  1750. ) -> dict[str, object]:
  1751. [run] = store.create_human_message(
  1752. room_id,
  1753. request_id=new_id(),
  1754. client_message_id=new_id(),
  1755. topic_id=topic_id,
  1756. content="继续旧话题",
  1757. mention_agent_ids=[agent_id],
  1758. )["runs"]
  1759. claimed = store.claim_next_runnable_run()
  1760. if claimed is None or claimed["id"] != run["id"]:
  1761. raise AssertionError("legacy continuation was not claimed")
  1762. return claimed
  1763. @staticmethod
  1764. def _assert_legacy_schema_rolled_back(path: Path) -> None:
  1765. connection = sqlite3.connect(path)
  1766. version = connection.execute(
  1767. "SELECT value FROM group_meta WHERE key = 'schema_version'"
  1768. ).fetchone()[0]
  1769. tables = {
  1770. row[0]
  1771. for row in connection.execute(
  1772. """SELECT name FROM sqlite_master
  1773. WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"""
  1774. )
  1775. }
  1776. connection.close()
  1777. if version != "3" or "group_topics" in tables:
  1778. raise AssertionError("failed migration was not rolled back")
  1779. def _submit_and_settle(
  1780. self,
  1781. store: GroupStore,
  1782. projection: dict[str, object],
  1783. *,
  1784. runtime: str,
  1785. stored: str,
  1786. ) -> None:
  1787. run = projection["run"]
  1788. agent = projection["agent"]
  1789. store.bind_run_runtime(run["id"], runtime)
  1790. store.commit_prompt_submission(
  1791. run["id"],
  1792. expected_stored_session_id=agent["storedSessionId"],
  1793. stored_session_id=stored,
  1794. runtime_session_id=runtime,
  1795. expected_context_seq=agent["lastContextMessageSeq"],
  1796. through_seq=projection["throughSeq"],
  1797. )
  1798. store.upsert_agent_message(
  1799. run["id"],
  1800. content="完成",
  1801. reasoning="",
  1802. tool_state=[],
  1803. status="completed",
  1804. )
  1805. store.settle_run(
  1806. run["id"],
  1807. runtime_session_id=runtime,
  1808. expected_stored_session_id=stored,
  1809. stored_session_id=stored,
  1810. outcome="completed",
  1811. )
  1812. if __name__ == "__main__":
  1813. unittest.main()