transcript-hydration.test.ts 137 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941
  1. // M4 transcript→event 合成 golden(13 §9 reduce(transcript) ≡ reduce(events) 的子集)。
  2. import { describe, expect, it } from "vitest";
  3. import {
  4. CompactTimelineStatus,
  5. CompactTrigger,
  6. ModelErrorCode,
  7. SessionEventType,
  8. STREAM_RECOVERY_DISCARDED_ERROR_NAME,
  9. STREAM_RECOVERY_DISCARDED_FINISH,
  10. type MessagePart,
  11. type MessageWithParts,
  12. type SessionEvent,
  13. } from "@zcode/contracts";
  14. import {
  15. toolCallGetWorkflowRunDisplaySchema,
  16. type CommandEnvelope,
  17. } from "@zcode/shared/zcode-protocol-v4";
  18. import { ProductProjection } from "../src/zcode-protocol-v4/index.js";
  19. import { inputIntentMetadata } from "../src/zcode-protocol-v4/commands/input-intent.js";
  20. import {
  21. eventsCoverTranscript,
  22. synthesizeEventsFromMessages,
  23. } from "../src/zcode-protocol-v4/transcript-hydration.js";
  24. function userMessage(id: string, text: string, created: number): MessageWithParts {
  25. return {
  26. info: {
  27. id: id as never,
  28. sessionID: "s1" as never,
  29. role: "user",
  30. time: { created },
  31. agent: "default",
  32. modelSelection: { providerId: "p" as never, modelId: "m" as never },
  33. },
  34. parts: [
  35. {
  36. id: `${id}-t` as never,
  37. sessionID: "s1" as never,
  38. messageID: id as never,
  39. type: "text",
  40. text,
  41. },
  42. ],
  43. };
  44. }
  45. function syntheticUserMessage(
  46. id: string,
  47. text: string,
  48. created: number,
  49. options: {
  50. metadata?: Record<string, unknown>;
  51. semantics?: MessageWithParts["info"]["semantics"];
  52. source?: string;
  53. visibility?: string;
  54. } = {},
  55. ): MessageWithParts {
  56. return {
  57. info: {
  58. id: id as never,
  59. sessionID: "s1" as never,
  60. role: "user",
  61. time: { created },
  62. agent: "default",
  63. modelSelection: { providerId: "p" as never, modelId: "m" as never },
  64. metadata: options.metadata,
  65. semantics: options.semantics,
  66. source: options.source as never,
  67. synthetic: true,
  68. visibility: options.visibility as never,
  69. },
  70. parts: [
  71. {
  72. id: `${id}-t` as never,
  73. sessionID: "s1" as never,
  74. messageID: id as never,
  75. type: "text",
  76. text,
  77. metadata: options.metadata,
  78. synthetic: true,
  79. },
  80. ],
  81. };
  82. }
  83. function assistantMessage(
  84. id: string,
  85. parentId: string,
  86. text: string,
  87. created: number,
  88. completed = created + 1,
  89. ): MessageWithParts {
  90. return {
  91. info: {
  92. id: id as never,
  93. sessionID: "s1" as never,
  94. role: "assistant",
  95. time: { created, completed },
  96. parentID: parentId as never,
  97. modelId: "m" as never,
  98. providerId: "p" as never,
  99. mode: "default",
  100. agent: "default",
  101. path: { cwd: "/", root: "/" },
  102. cost: 0,
  103. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  104. },
  105. parts: [
  106. {
  107. id: `${id}-t` as never,
  108. sessionID: "s1" as never,
  109. messageID: id as never,
  110. type: "text",
  111. text,
  112. },
  113. ],
  114. };
  115. }
  116. function assistantMessageWithParts(
  117. id: string,
  118. parentId: string,
  119. parts: MessagePart[],
  120. created: number,
  121. ): MessageWithParts {
  122. return {
  123. ...assistantMessage(id, parentId, "", created),
  124. parts,
  125. };
  126. }
  127. function reduce(messages: MessageWithParts[]) {
  128. const events = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  129. const projection = new ProductProjection("s1", "epoch");
  130. for (const event of events) projection.applyEvent(event);
  131. return { events, projection };
  132. }
  133. describe("transcript→event 合成", () => {
  134. it.each([
  135. { output: "任务完成", expectedType: "frontend-demo" },
  136. { output: JSON.stringify({ agentType: "Explore" }), expectedType: "Explore" },
  137. ])(
  138. "冷恢复从 subagent_type 保留名称且输出显式名称优先: $expectedType",
  139. ({ output, expectedType }) => {
  140. const { projection } = reduce([
  141. userMessage("u-agent-name", "执行任务", 1000),
  142. assistantMessageWithParts(
  143. "a-agent-name",
  144. "u-agent-name",
  145. [
  146. {
  147. id: "part-agent-name" as never,
  148. sessionID: "s1" as never,
  149. messageID: "a-agent-name" as never,
  150. type: "tool",
  151. callID: "call-agent-name",
  152. tool: "Agent",
  153. metadata: {},
  154. state: {
  155. status: "completed",
  156. input: { subagent_type: "frontend-demo", description: "创建示例项目" },
  157. output,
  158. title: "创建示例项目",
  159. metadata: {},
  160. time: { start: 1001, end: 1002 },
  161. },
  162. },
  163. ],
  164. 1001,
  165. ),
  166. ]);
  167. expect(
  168. projection.getSnapshot().rows.window.find((row) => row.kind === "subagent"),
  169. ).toMatchObject({
  170. parentToolCallId: "call-agent-name",
  171. subagentType: expectedType,
  172. status: "success",
  173. });
  174. },
  175. );
  176. it("冷恢复把缺少完成时间的 orphan assistant 收口为 completedInterrupted", () => {
  177. const user = userMessage("u-orphan", "执行任务", 1000);
  178. const orphan = assistantMessage("a-orphan", "u-orphan", "未完成的部分结果", 1001);
  179. delete orphan.info.time.completed;
  180. const { events, projection } = reduce([user, orphan]);
  181. expect(events).toContainEqual(
  182. expect.objectContaining({
  183. type: SessionEventType.TurnComplete,
  184. payload: expect.objectContaining({ resultType: "cancelled" }),
  185. }),
  186. );
  187. expect(projection.getSnapshot().control.phase).toBe("completedInterrupted");
  188. expect(projection.getSnapshot().rows.window).toContainEqual(
  189. expect.objectContaining({ kind: "turnHeader", state: "completedInterrupted" }),
  190. );
  191. });
  192. it("冷恢复从最终 assistant anchor 恢复 query 历史轮次数", () => {
  193. const user = userMessage("u-round", "问题", 1000);
  194. user.info.anchor = { sourceCommandId: "query-round" };
  195. const assistant = assistantMessage("a-round", "u-round", "回答", 1001);
  196. assistant.info.anchor = { historyRoundCount: 3 };
  197. const { projection } = reduce([user, assistant]);
  198. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  199. expect(header).toMatchObject({
  200. kind: "turnHeader",
  201. sourceCommandId: "query-round",
  202. historyRoundCount: 3,
  203. state: "completedSuccess",
  204. });
  205. });
  206. it("OTC08 cold:持久化 finish=length 的连续正文恢复为一条 assistantText", () => {
  207. const user = userMessage("u-output-continue", "写一段长回复", 1000);
  208. const first = assistantMessage("a-output-p1", user.info.id, "即使底层已经", 1001);
  209. first.info.finish = "length";
  210. const second = assistantMessage("a-output-p2", user.info.id, "发起新的请求并停在", 1002);
  211. second.info.finish = "length";
  212. const final = assistantMessage("a-output-p3", user.info.id, "一个尚未完成的位置。", 1003);
  213. final.info.finish = "end_turn";
  214. const { projection } = reduce([user, first, second, final]);
  215. const snapshot = projection.getSnapshot();
  216. const assistantRows = snapshot.rows.window.filter((row) => row.kind === "assistantText");
  217. expect(assistantRows).toHaveLength(1);
  218. expect(assistantRows[0]).toMatchObject({
  219. text: "即使底层已经发起新的请求并停在一个尚未完成的位置。",
  220. assistantResponseId: "a-output-p3",
  221. entityId: "a-output-p3",
  222. state: "complete",
  223. });
  224. expect(projection.getMessageIdForRow(assistantRows[0]!.rowId)).toBe("a-output-p3");
  225. const header = snapshot.rows.window.find((row) => row.kind === "turnHeader");
  226. expect(projection.getMessageIdsForTurnRow(header!.rowId)).toEqual(
  227. expect.arrayContaining(["u-output-continue", "a-output-p1", "a-output-p2", "a-output-p3"]),
  228. );
  229. });
  230. it("冷恢复使用调用方注入的当前模型上下文窗口", () => {
  231. const events = synthesizeEventsFromMessages(
  232. [
  233. userMessage("u-context-window", "问题", 1000),
  234. assistantMessage("a-context-window", "u-context-window", "回答", 1001),
  235. ],
  236. { sessionId: "s1", contextWindow: 1_000_000 },
  237. );
  238. expect(events.find((event) => event.type === SessionEventType.SessionCreated)?.payload).toEqual(
  239. {
  240. mode: "default",
  241. contextWindow: 1_000_000,
  242. },
  243. );
  244. expect(
  245. events.find((event) => event.type === SessionEventType.ModelComplete)?.payload,
  246. ).toMatchObject({ contextWindow: 1_000_000 });
  247. });
  248. it("assistant feedback 从 transcript metadata 恢复为权威 row 字段", () => {
  249. const assistant = assistantMessage("a-feedback", "u-feedback", "回复", 1001);
  250. assistant.info.metadata = { assistantFeedback: "like" };
  251. const { events, projection } = reduce([userMessage("u-feedback", "问题", 1000), assistant]);
  252. expect(events).toContainEqual(
  253. expect.objectContaining({
  254. type: SessionEventType.AssistantFeedbackUpdated,
  255. payload: { entityId: "a-feedback", feedback: "like" },
  256. }),
  257. );
  258. expect(
  259. projection
  260. .getSnapshot()
  261. .rows.window.find((row) => row.kind === "assistantText" && row.entityId === "a-feedback"),
  262. ).toMatchObject({ feedback: "like" });
  263. projection.applyEvent({
  264. id: "feedback-clear" as never,
  265. sessionId: "s1" as never,
  266. turnId: events.find((event) => event.type === SessionEventType.TurnStarted)?.turnId,
  267. type: SessionEventType.AssistantFeedbackUpdated,
  268. timestamp: new Date(2000),
  269. traceId: "trace-feedback" as never,
  270. sequenceNumber: (events.at(-1)?.sequenceNumber ?? 0) + 1,
  271. payload: { entityId: "a-feedback", feedback: null },
  272. });
  273. expect(
  274. projection
  275. .getSnapshot()
  276. .rows.window.find((row) => row.kind === "assistantText" && row.entityId === "a-feedback"),
  277. ).not.toHaveProperty("feedback");
  278. });
  279. it("多个文字 part 冷恢复成多行,反馈落在最后一个文字行", () => {
  280. const assistant = assistantMessage("a-blocks", "u-blocks", "第一段", 1001);
  281. const firstPart = assistant.parts.find((part) => part.type === "text")!;
  282. assistant.parts = [
  283. ...assistant.parts,
  284. { ...firstPart, id: "a-blocks-second" as never, text: "第二段" },
  285. ];
  286. assistant.info.metadata = { assistantFeedback: "like" };
  287. const { projection } = reduce([userMessage("u-blocks", "问题", 1000), assistant]);
  288. const rows = projection
  289. .getSnapshot()
  290. .rows.window.filter((row) => row.kind === "assistantText" && row.entityId === "a-blocks");
  291. expect(rows.map((row) => (row as { text: string }).text)).toEqual(["第一段", "第二段"]);
  292. expect(rows[0]).not.toHaveProperty("feedback");
  293. expect(rows[1]).toMatchObject({ feedback: "like" });
  294. });
  295. it("首订阅晚于完成时仍从真实持久化语义恢复 assistant 正文", () => {
  296. const persistedAssistant = assistantMessage("a1", "u1", "快速首轮回复", 1001);
  297. const messages = [
  298. userMessage("u1", "开始", 1000),
  299. {
  300. ...persistedAssistant,
  301. info: {
  302. ...persistedAssistant.info,
  303. semantics: {
  304. origin: "agent_runtime",
  305. kind: "assistant_response",
  306. uiVisibility: "visible",
  307. providerVisibility: "visible",
  308. transcriptVisibility: "visible",
  309. },
  310. } as MessageWithParts["info"],
  311. },
  312. ];
  313. const { events, projection } = reduce(messages);
  314. const visibleTexts = projection
  315. .getSnapshot()
  316. .rows.window.filter((row) => row.kind === "userInput" || row.kind === "assistantText")
  317. .map((row) => row.text);
  318. expect(visibleTexts).toEqual(["开始", "快速首轮回复"]);
  319. expect(eventsCoverTranscript(events, messages)).toBe(true);
  320. });
  321. it("user+assistant 文本轮 → userInput + assistantText rows", () => {
  322. const messages = [
  323. userMessage("u1", "问题一", 1000),
  324. assistantMessage("a1", "u1", "回答一", 1001),
  325. userMessage("u2", "问题二", 2000),
  326. assistantMessage("a2", "u2", "回答二", 2001),
  327. ];
  328. const { events, projection } = reduce(messages);
  329. const rows = projection.getSnapshot().rows.window;
  330. const texts = rows
  331. .filter((r) => r.kind === "userInput" || r.kind === "assistantText")
  332. .map((r) => (r.kind === "userInput" || r.kind === "assistantText" ? r.text : ""));
  333. expect(texts).toEqual(["问题一", "回答一", "问题二", "回答二"]);
  334. // 两轮都 completedSuccess。
  335. const turnHeaders = rows.filter((r) => r.kind === "turnHeader");
  336. expect(turnHeaders).toHaveLength(2);
  337. expect(
  338. turnHeaders.every((r) => r.kind === "turnHeader" && r.state === "completedSuccess"),
  339. ).toBe(true);
  340. const starts = events.filter((event) => event.type === SessionEventType.TurnStarted);
  341. expect(starts.map((event) => (event.payload as { messageId?: string }).messageId)).toEqual([
  342. "u1",
  343. "u2",
  344. ]);
  345. const userRows = rows.filter((row) => row.kind === "userInput");
  346. const assistantRows = rows.filter((row) => row.kind === "assistantText");
  347. // Bugfix 回归:cold 合成必须保留各 assistant message 的真实创建时间,不能全部
  348. // 退化成首条 transcript 时间附近的合成序号。
  349. expect(assistantRows.map((row) => row.createdAt)).toEqual([1001, 2001]);
  350. expect(userRows[0]?.actions?.canEdit).not.toBe(true);
  351. expect(userRows[1]?.actions?.canEdit).toBe(true);
  352. expect(projection.getMessageIdForRow(userRows[1]!.rowId)).toBe("u2");
  353. expect(projection.getTurnRewindAnchor(userRows[1]!.rowId)).toBe("u2");
  354. });
  355. it("canonical assistant 与 interrupted ExitPlanMode 冷恢复后仍保留可见行", () => {
  356. const assistant = assistantMessageWithParts(
  357. "a-plan",
  358. "u-plan",
  359. [
  360. {
  361. id: "a-plan-text" as never,
  362. sessionID: "s1" as never,
  363. messageID: "a-plan" as never,
  364. type: "text",
  365. text: "计划如下",
  366. },
  367. {
  368. id: "a-plan-tool" as never,
  369. sessionID: "s1" as never,
  370. messageID: "a-plan" as never,
  371. type: "tool",
  372. callID: "call-plan",
  373. tool: "ExitPlanMode",
  374. state: {
  375. status: "running",
  376. input: { plan: "# 实施计划\n\n第一步\n第二步" },
  377. title: "ExitPlanMode",
  378. time: { start: 1001 },
  379. },
  380. },
  381. ],
  382. 1001,
  383. );
  384. assistant.info.semantics = {
  385. kind: "assistant_response",
  386. origin: "agent_runtime",
  387. providerVisibility: "visible",
  388. transcriptVisibility: "visible",
  389. uiVisibility: "visible",
  390. };
  391. const { projection } = reduce([userMessage("u-plan", "写计划", 1000), assistant]);
  392. const rows = projection.getSnapshot().rows.window;
  393. expect(rows.find((row) => row.kind === "assistantText")).toMatchObject({
  394. text: "计划如下",
  395. state: "complete",
  396. });
  397. expect(rows.find((row) => row.kind === "toolCall")).toMatchObject({
  398. input: { plan: "# 实施计划\n\n第一步\n第二步" },
  399. status: "cancelled",
  400. toolCallId: "call-plan",
  401. toolName: "ExitPlanMode",
  402. });
  403. });
  404. it("冷恢复为同一 assistant response 的 reasoning、text 与 CUA tool 投影关联 ID", () => {
  405. const assistant = assistantMessageWithParts(
  406. "a-cua",
  407. "u-cua",
  408. [
  409. {
  410. id: "a-cua-reasoning" as never,
  411. sessionID: "s1" as never,
  412. messageID: "a-cua" as never,
  413. type: "reasoning",
  414. text: "先确认电脑操作权限。",
  415. time: { start: 1001, end: 1002 },
  416. },
  417. {
  418. id: "a-cua-text" as never,
  419. sessionID: "s1" as never,
  420. messageID: "a-cua" as never,
  421. type: "text",
  422. text: "我先检查电脑操作权限与应用列表。",
  423. },
  424. {
  425. id: "a-cua-tool" as never,
  426. sessionID: "s1" as never,
  427. messageID: "a-cua" as never,
  428. type: "tool",
  429. callID: "call-cua",
  430. tool: "mcp__computer-use__request_access",
  431. state: {
  432. status: "running",
  433. input: {},
  434. title: "request_access",
  435. time: { start: 1001 },
  436. },
  437. },
  438. ],
  439. 1001,
  440. );
  441. const rows = reduce([
  442. userMessage("u-cua", "检查权限", 1000),
  443. assistant,
  444. ]).projection.getSnapshot().rows.window;
  445. expect(rows.find((row) => row.kind === "reasoning")?.assistantResponseId).toBe("a-cua");
  446. expect(rows.find((row) => row.kind === "assistantText")?.assistantResponseId).toBe("a-cua");
  447. expect(rows.find((row) => row.kind === "toolCall")?.assistantResponseId).toBe("a-cua");
  448. });
  449. it("legacy /compact 缺 visibility 时由 CLI hydration 归一化,不下发 visible user row", () => {
  450. const compactHost = assistantMessageWithParts(
  451. "a-compact-legacy",
  452. "u-compact-legacy",
  453. [
  454. {
  455. id: "a-compact-legacy-part" as never,
  456. sessionID: "s1" as never,
  457. messageID: "a-compact-legacy" as never,
  458. type: "timeline",
  459. timelineType: "context_compaction",
  460. display: "separator",
  461. status: CompactTimelineStatus.Completed,
  462. operationId: "cmp-legacy",
  463. trigger: CompactTrigger.Manual,
  464. },
  465. ],
  466. 1001,
  467. );
  468. const { projection } = reduce([
  469. userMessage("u-compact-legacy", "/compact keep recent files", 1000),
  470. compactHost,
  471. ]);
  472. const rows = projection.getSnapshot().rows.window;
  473. expect(rows.some((row) => row.kind === "userInput")).toBe(false);
  474. expect(rows.some((row) => row.kind === "timelineMarker" && row.marker.type === "compact")).toBe(
  475. true,
  476. );
  477. });
  478. it.each([
  479. {
  480. name: "tool-only",
  481. assistant: assistantMessageWithParts(
  482. "a-tool",
  483. "u-latest",
  484. [
  485. {
  486. id: "a-tool-part" as never,
  487. sessionID: "s1" as never,
  488. messageID: "a-tool" as never,
  489. type: "tool" as const,
  490. callID: "call-read",
  491. tool: "Read",
  492. state: {
  493. status: "completed" as const,
  494. input: { file_path: "README.md" },
  495. output: "ok",
  496. title: "Read README.md",
  497. metadata: {},
  498. time: { start: 1001, end: 1002 },
  499. },
  500. },
  501. ],
  502. 1001,
  503. ),
  504. },
  505. {
  506. name: "empty assistant",
  507. assistant: assistantMessage("a-empty", "u-latest", "", 1001),
  508. },
  509. {
  510. name: "failed before first token",
  511. assistant: {
  512. ...assistantMessage("a-failed", "u-latest", "", 1001),
  513. info: {
  514. ...assistantMessage("a-failed", "u-latest", "", 1001).info,
  515. error: { name: "ProviderError" },
  516. },
  517. } satisfies MessageWithParts,
  518. },
  519. ])("cold $name:latest real user 保持可编辑且 target 可解析", ({ assistant }) => {
  520. const { projection } = reduce([userMessage("u-latest", "继续", 1000), assistant]);
  521. const rows = projection.getSnapshot().rows.window;
  522. const userRow = rows.find((row) => row.kind === "userInput");
  523. expect(userRow?.actions?.canEdit).toBe(true);
  524. expect(projection.isLatestEditableUserRow(userRow!.rowId)).toBe(true);
  525. expect(projection.getMessageIdForRow(userRow!.rowId)).toBe("u-latest");
  526. expect(projection.getTurnRewindAnchor(userRow!.rowId)).toBe("u-latest");
  527. expect(rows.some((row) => row.actions?.canRetry === true)).toBe(false);
  528. });
  529. it.each([true, false])(
  530. "cold first-token failure restores retryable=%s from the structured runtime error",
  531. (retryable) => {
  532. const failed = assistantMessage("a-failed-structured", "u-failed", "", 1001);
  533. const { projection } = reduce([
  534. userMessage("u-failed", "trigger failure", 1000),
  535. {
  536. ...failed,
  537. info: {
  538. ...failed.info,
  539. error: {
  540. name: "ProviderError",
  541. data: { message: "rate limited before first token", retryable },
  542. },
  543. },
  544. } satisfies MessageWithParts,
  545. ]);
  546. expect(projection.getSnapshot().control.lastError).toMatchObject({
  547. code: "ProviderError",
  548. message: "rate limited before first token",
  549. recoverable: retryable,
  550. source: "runtime",
  551. });
  552. },
  553. );
  554. it("cold first-token failure restores the same structured attribution as live TurnError", () => {
  555. const failed = assistantMessage("a-failed-attribution", "u-failed-attribution", "", 1001);
  556. const { events, projection } = reduce([
  557. userMessage("u-failed-attribution", "trigger network failure", 1000),
  558. {
  559. ...failed,
  560. info: {
  561. ...failed.info,
  562. error: {
  563. name: "AiSdkModelAdapterError",
  564. data: {
  565. message: "Provider stream failed",
  566. attribution: {
  567. source: "network",
  568. reason: "network_error",
  569. errorPhase: "stream",
  570. exceptionKind: "transport",
  571. providerId: "default-deepseek",
  572. modelId: "deepseek-v4-flash",
  573. providerKind: "anthropic",
  574. transport: "sse",
  575. statusCode: 503,
  576. retryable: true,
  577. },
  578. },
  579. },
  580. },
  581. } satisfies MessageWithParts,
  582. ]);
  583. expect(events).toContainEqual(
  584. expect.objectContaining({
  585. type: SessionEventType.TurnError,
  586. payload: expect.objectContaining({
  587. error: expect.objectContaining({
  588. attribution: expect.objectContaining({
  589. source: "network",
  590. reason: "network_error",
  591. errorPhase: "stream",
  592. exceptionKind: "transport",
  593. transport: "sse",
  594. }),
  595. }),
  596. }),
  597. }),
  598. );
  599. expect(projection.getSnapshot().control.lastError).toMatchObject({
  600. source: "network",
  601. attribution: {
  602. source: "network",
  603. reason: "network_error",
  604. errorPhase: "stream",
  605. exceptionKind: "transport",
  606. providerId: "default-deepseek",
  607. modelId: "deepseek-v4-flash",
  608. providerKind: "anthropic",
  609. transport: "sse",
  610. statusCode: 503,
  611. retryable: true,
  612. },
  613. });
  614. });
  615. it("cold empty output-limit exhaustion restores only its error state", () => {
  616. const failed = assistantMessage("a-output-limit", "u-output-limit", "", 1001);
  617. const { events, projection } = reduce([
  618. userMessage("u-output-limit", "exhaust output continuation", 1000),
  619. {
  620. ...failed,
  621. info: {
  622. ...failed.info,
  623. error: {
  624. name: "model_output_limit_exceeded",
  625. data: {
  626. code: "model_output_limit_exceeded",
  627. message: "The model's response exceeded the output token maximum.",
  628. retryable: true,
  629. attribution: {
  630. source: "provider",
  631. reason: "model_output_limit_exceeded",
  632. providerErrorCode: "model_output_limit_exceeded",
  633. },
  634. },
  635. },
  636. },
  637. } satisfies MessageWithParts,
  638. ]);
  639. expect(events).toContainEqual(
  640. expect.objectContaining({
  641. type: SessionEventType.TurnError,
  642. payload: expect.objectContaining({
  643. error: expect.objectContaining({
  644. type: "model_output_limit_exceeded",
  645. message: "The model's response exceeded the output token maximum.",
  646. retryable: true,
  647. attribution: expect.objectContaining({ source: "provider" }),
  648. }),
  649. }),
  650. }),
  651. );
  652. const snapshot = projection.getSnapshot();
  653. expect(snapshot.rows.window.some((row) => row.kind === "assistantText")).toBe(false);
  654. expect(snapshot.control.lastError).toMatchObject({
  655. code: "model_output_limit_exceeded",
  656. message: "The model's response exceeded the output token maximum.",
  657. recoverable: true,
  658. source: "provider",
  659. });
  660. });
  661. it.each([
  662. {
  663. name: "typed cancellation",
  664. error: {
  665. name: "AiSdkModelAdapterError",
  666. data: {
  667. code: ModelErrorCode.ModelRequestCancelled,
  668. message: "Model request was cancelled.",
  669. turnResult: "cancelled",
  670. },
  671. },
  672. },
  673. {
  674. name: "legacy canonical cancellation",
  675. error: {
  676. name: "AiSdkModelAdapterError",
  677. data: { message: "Model request was cancelled." },
  678. },
  679. },
  680. {
  681. name: "legacy protocol session stop",
  682. error: {
  683. name: "Error",
  684. data: { message: "ZCode Protocol session stopped" },
  685. },
  686. },
  687. ])("cold $name restores interrupted completion instead of TurnError", ({ error }) => {
  688. const cancelled = assistantMessage("a-cancelled", "u-cancelled", "partial", 1001);
  689. const { events, projection } = reduce([
  690. userMessage("u-cancelled", "stop this turn", 1000),
  691. {
  692. ...cancelled,
  693. info: { ...cancelled.info, error },
  694. } satisfies MessageWithParts,
  695. ]);
  696. expect(events.some((event) => event.type === SessionEventType.TurnError)).toBe(false);
  697. expect(events).toContainEqual(
  698. expect.objectContaining({
  699. type: SessionEventType.TurnComplete,
  700. payload: expect.objectContaining({ resultType: "cancelled", historyRoundCount: 1 }),
  701. }),
  702. );
  703. expect(projection.getSnapshot().control).toMatchObject({
  704. phase: "completedInterrupted",
  705. lastError: null,
  706. });
  707. expect(projection.getSnapshot().rows.window).toContainEqual(
  708. expect.objectContaining({ kind: "turnHeader", state: "completedInterrupted" }),
  709. );
  710. });
  711. it("cold restores a stop after the final text as cancelled when the interrupt marker follows", () => {
  712. // 最终文本已完整输出后再停止:assistant 是 finish=stop、没有 error,只有中断标记记录停止事实。
  713. const answer = assistantMessage("a-final", "u-final", "complete final answer", 1001);
  714. const runtimeMessage = { source: "interrupt_marker" };
  715. const { events, projection } = reduce([
  716. userMessage("u-final", "question", 1000),
  717. { ...answer, info: { ...answer.info, finish: "stop" } } satisfies MessageWithParts,
  718. syntheticUserMessage("m-interrupt", "[Request interrupted by user]", 1003, {
  719. metadata: { runtimeMessage, source: "interrupt_marker", visibility: "model-only" },
  720. semantics: {
  721. origin: "agent_runtime",
  722. kind: "system_reminder",
  723. source: "interrupt_marker",
  724. uiVisibility: "hidden",
  725. providerVisibility: "visible",
  726. transcriptVisibility: "hidden",
  727. },
  728. visibility: "model-only",
  729. }),
  730. ]);
  731. expect(events.some((event) => event.type === SessionEventType.TurnError)).toBe(false);
  732. expect(events).toContainEqual(
  733. expect.objectContaining({
  734. type: SessionEventType.TurnComplete,
  735. payload: expect.objectContaining({ resultType: "cancelled" }),
  736. }),
  737. );
  738. expect(projection.getSnapshot().control.phase).toBe("completedInterrupted");
  739. });
  740. function streamRecoveryDiscardedMessage(id: string, parentId: string, created: number) {
  741. const discarded = assistantMessage(id, parentId, "partial output", created);
  742. return {
  743. ...discarded,
  744. info: {
  745. ...discarded.info,
  746. finish: STREAM_RECOVERY_DISCARDED_FINISH,
  747. error: {
  748. name: STREAM_RECOVERY_DISCARDED_ERROR_NAME,
  749. data: {
  750. message: "Partial assistant output was discarded before a streaming retry.",
  751. retryNumber: 1,
  752. },
  753. },
  754. },
  755. } satisfies MessageWithParts;
  756. }
  757. it("cold stream recovery discard followed by a recovered answer restores success, not TurnError", () => {
  758. const { events, projection } = reduce([
  759. userMessage("u-recover", "keep going", 1000),
  760. streamRecoveryDiscardedMessage("a-discarded", "u-recover", 1001),
  761. assistantMessage("a-recovered", "u-recover", "final answer", 1003),
  762. ]);
  763. expect(events.some((event) => event.type === SessionEventType.TurnError)).toBe(false);
  764. expect(events).toContainEqual(
  765. expect.objectContaining({
  766. type: SessionEventType.TurnComplete,
  767. payload: expect.objectContaining({ resultType: "success", historyRoundCount: 2 }),
  768. }),
  769. );
  770. const control = projection.getSnapshot().control;
  771. expect(control.lastError).toBeNull();
  772. expect(control.phase).not.toBe("error");
  773. expect(projection.getSnapshot().rows.window).toContainEqual(
  774. expect.objectContaining({ kind: "assistantText", text: "final answer" }),
  775. );
  776. });
  777. it("cold stream recovery discard without a recovered answer restores interrupted completion", () => {
  778. const { events, projection } = reduce([
  779. userMessage("u-recover-lost", "keep going", 1000),
  780. streamRecoveryDiscardedMessage("a-discarded-last", "u-recover-lost", 1001),
  781. ]);
  782. expect(events.some((event) => event.type === SessionEventType.TurnError)).toBe(false);
  783. expect(events).toContainEqual(
  784. expect.objectContaining({
  785. type: SessionEventType.TurnComplete,
  786. payload: expect.objectContaining({ resultType: "cancelled" }),
  787. }),
  788. );
  789. expect(projection.getSnapshot().control).toMatchObject({
  790. phase: "completedInterrupted",
  791. lastError: null,
  792. });
  793. });
  794. it("does not suppress a typed provider failure that reuses the cancellation message", () => {
  795. const failed = assistantMessage("a-failed-cancel-text", "u-failed-cancel-text", "", 1001);
  796. const { events, projection } = reduce([
  797. userMessage("u-failed-cancel-text", "trigger provider failure", 1000),
  798. {
  799. ...failed,
  800. info: {
  801. ...failed.info,
  802. error: {
  803. name: "AiSdkModelAdapterError",
  804. data: {
  805. code: ModelErrorCode.ModelRequestFailed,
  806. message: "Model request was cancelled.",
  807. },
  808. },
  809. },
  810. } satisfies MessageWithParts,
  811. ]);
  812. expect(events.some((event) => event.type === SessionEventType.TurnError)).toBe(true);
  813. expect(projection.getSnapshot().control).toMatchObject({
  814. phase: "error",
  815. lastError: {
  816. code: "AiSdkModelAdapterError",
  817. message: "Model request was cancelled.",
  818. },
  819. });
  820. });
  821. it("live/cold goal use persisted canonical intent text instead of visible command text", () => {
  822. const goalInput = userMessage("u-goal", "/GoAl replace X", 1000);
  823. goalInput.info.anchor = { sourceCommandId: "command-goal" };
  824. goalInput.info.metadata = {
  825. conversationInputIntent: {
  826. sourceCommandId: "command-goal",
  827. queueItemId: "queue_command-goal",
  828. clientId: "desktop-goal",
  829. kind: "sendGoalCommand",
  830. text: "X",
  831. attachments: [],
  832. delivery: { requested: "startNow", admitted: "startNow" },
  833. order: { admissionSeq: 3 },
  834. steer: { state: "notRequested" },
  835. dispatch: { state: "drained" },
  836. admittedAt: 999,
  837. },
  838. };
  839. const { projection: cold } = reduce([
  840. goalInput,
  841. assistantMessage("a-goal", "u-goal", "working on it", 1001),
  842. ]);
  843. const row = cold.getSnapshot().rows.window.find((candidate) => candidate.kind === "userInput");
  844. const envelope = {
  845. type: "sendGoalCommand",
  846. payload: { text: "X", displayText: "/GoAl replace X" },
  847. sessionId: "s1",
  848. commandId: "command-goal",
  849. clientId: "desktop-goal",
  850. baseRevision: 0,
  851. __v4Admission: {
  852. admissionSeq: 3,
  853. admittedAt: 999,
  854. queueItemId: "queue_command-goal",
  855. },
  856. } as unknown as CommandEnvelope;
  857. const liveIntent = inputIntentMetadata(envelope, {
  858. requestedDelivery: "startNow",
  859. text: "X",
  860. });
  861. const live = new ProductProjection("s1", "epoch-live");
  862. live.applyEvent({
  863. id: "live-goal" as never,
  864. sessionId: "s1" as never,
  865. turnId: "runtime-goal" as never,
  866. type: SessionEventType.TurnStarted,
  867. timestamp: new Date(1000),
  868. traceId: "live-goal-trace" as never,
  869. sequenceNumber: 1,
  870. payload: {
  871. turnNumber: 1,
  872. input: "/GoAl replace X",
  873. messageId: "u-goal",
  874. inputId: "command-goal",
  875. intent: liveIntent,
  876. },
  877. });
  878. expect(row).toMatchObject({
  879. entityId: "u-goal",
  880. productTurnId: "u-goal",
  881. sourceCommandId: "command-goal",
  882. actions: { canEdit: true },
  883. });
  884. const coldTarget = cold.resolveEditTargetByEntityId("u-goal");
  885. const liveTarget = live.resolveEditTargetByEntityId("u-goal");
  886. expect(liveTarget).toEqual(coldTarget);
  887. expect(liveTarget).toMatchObject({
  888. coveredByStableCompact: false,
  889. entityId: "u-goal",
  890. productTurnId: "u-goal",
  891. transcriptMessageId: "u-goal",
  892. intent: {
  893. clientId: "desktop-goal",
  894. kind: "sendGoalCommand",
  895. sourceCommandId: "command-goal",
  896. text: "X",
  897. },
  898. });
  899. });
  900. it("cold hydration preserves the canonical sending session source without parsing message text", () => {
  901. const input = userMessage("u-session-source", "普通正文,不含来源提示", 1000);
  902. const source = { kind: "session", sessionId: "source-session", title: "来源会话" } as const;
  903. input.info.metadata = {
  904. conversationInputIntent: {
  905. sourceCommandId: "command-session-source",
  906. queueItemId: "queue-session-source",
  907. clientId: "host-caller",
  908. kind: "sendText",
  909. text: input.parts[0]!.type === "text" ? input.parts[0]!.text : "",
  910. attachments: [],
  911. delivery: { requested: "queue", admitted: "startNow" },
  912. order: { admissionSeq: 1 },
  913. steer: { state: "notRequested" },
  914. dispatch: { state: "drained" },
  915. admittedAt: 999,
  916. source,
  917. },
  918. };
  919. const { projection } = reduce([
  920. input,
  921. assistantMessage("a-session-source", "u-session-source", "收到", 1001),
  922. ]);
  923. expect(projection.getSnapshot().rows.window).toContainEqual(
  924. expect.objectContaining({ kind: "userInput", text: "普通正文,不含来源提示", source }),
  925. );
  926. });
  927. it("cold hydration projects persisted highspeed metadata onto the user input row", () => {
  928. const input = userMessage("u-highspeed", "accelerated prompt", 1000);
  929. input.info.metadata = {
  930. conversationInputIntent: {
  931. sourceCommandId: "command-highspeed",
  932. queueItemId: "queue-highspeed",
  933. clientId: "desktop-highspeed",
  934. kind: "sendText",
  935. text: "accelerated prompt",
  936. attachments: [],
  937. delivery: { requested: "startNow", admitted: "startNow" },
  938. order: { admissionSeq: 5 },
  939. steer: { state: "notRequested" },
  940. dispatch: { state: "drained" },
  941. admittedAt: 1000,
  942. highspeed: {
  943. schemaVersion: 1,
  944. ownerKey: `v1:${"a".repeat(64)}`,
  945. cardId: "hsc-persisted",
  946. taskId: "s1",
  947. provider: "zai",
  948. model: "glm-5",
  949. issuedAt: 900,
  950. expiresAt: 1900,
  951. regularTps: 73,
  952. outputTokens: 120_000,
  953. durationMs: 881_000,
  954. savedDurationMs: 762_836,
  955. // CR-02:fallbackAt 是权威 metadata 字段,cold hydration 必须原样恢复。
  956. fallbackAt: 1500,
  957. },
  958. },
  959. };
  960. const { projection } = reduce([
  961. input,
  962. assistantMessage("a-highspeed", "u-highspeed", "accelerated answer", 1001),
  963. ]);
  964. expect(
  965. projection.getSnapshot().rows.window.find((row) => row.kind === "userInput"),
  966. ).toMatchObject({
  967. sourceCommandId: "command-highspeed",
  968. highspeed: {
  969. schemaVersion: 1,
  970. ownerKey: `v1:${"a".repeat(64)}`,
  971. cardId: "hsc-persisted",
  972. taskId: "s1",
  973. provider: "zai",
  974. model: "glm-5",
  975. issuedAt: 900,
  976. expiresAt: 1900,
  977. regularTps: 73,
  978. outputTokens: 120_000,
  979. durationMs: 881_000,
  980. savedDurationMs: 762_836,
  981. fallbackAt: 1500,
  982. },
  983. });
  984. const turnId = projection
  985. .getSnapshot()
  986. .rows.window.find((row) => row.kind === "turnHeader")?.turnId;
  987. projection.applyEvent({
  988. id: "highspeed-metrics-update" as never,
  989. sessionId: "s1" as never,
  990. turnId,
  991. type: SessionEventType.HighspeedMetricsUpdated,
  992. timestamp: new Date(2000),
  993. traceId: "trace-highspeed" as never,
  994. sequenceNumber: 99,
  995. payload: {
  996. entityId: "u-highspeed",
  997. highspeed: {
  998. schemaVersion: 1,
  999. cardId: "hsc-persisted",
  1000. taskId: "s1",
  1001. provider: "zai",
  1002. model: "glm-5",
  1003. issuedAt: 900,
  1004. expiresAt: 1900,
  1005. regularTps: 73,
  1006. outputTokens: 130_000,
  1007. durationMs: 900_000,
  1008. savedDurationMs: 880_822,
  1009. },
  1010. },
  1011. });
  1012. expect(
  1013. projection.getSnapshot().rows.window.find((row) => row.kind === "userInput"),
  1014. ).toMatchObject({
  1015. // CR-02:终态指标更新是字段级合并,不含 fallbackAt 的 payload 不得清掉已持久化的 fallbackAt。
  1016. highspeed: { outputTokens: 130_000, savedDurationMs: 880_822, fallbackAt: 1500 },
  1017. });
  1018. });
  1019. it("cold retry intent preserves original cause provenance", () => {
  1020. const retried = userMessage("u-retry", "original text", 1000);
  1021. retried.info.metadata = {
  1022. conversationInputIntent: {
  1023. sourceCommandId: "command-retry",
  1024. queueItemId: "queue-retry",
  1025. clientId: "desktop-new",
  1026. kind: "sendText",
  1027. text: "original text",
  1028. attachments: [],
  1029. delivery: { requested: "guide", admitted: "queue" },
  1030. order: { admissionSeq: 4 },
  1031. steer: {
  1032. state: "fellBack",
  1033. reasonCode: "guide.attachmentsUnsupported",
  1034. },
  1035. dispatch: { state: "drained" },
  1036. admittedAt: 1000,
  1037. provenance: {
  1038. sourceCommandId: "command-original",
  1039. queueItemId: "queue-original",
  1040. clientId: "desktop-original",
  1041. },
  1042. },
  1043. };
  1044. const { projection } = reduce([
  1045. retried,
  1046. assistantMessage("a-retry", "u-retry", "answer", 1001),
  1047. ]);
  1048. expect(
  1049. projection.getSnapshot().rows.window.find((row) => row.kind === "userInput"),
  1050. ).toMatchObject({
  1051. sourceCommandId: "command-retry",
  1052. rootSourceCommandId: "command-original",
  1053. });
  1054. expect(projection.resolveEditTargetByEntityId("u-retry")).toMatchObject({
  1055. intent: {
  1056. sourceCommandId: "command-retry",
  1057. provenance: {
  1058. sourceCommandId: "command-original",
  1059. queueItemId: "queue-original",
  1060. clientId: "desktop-original",
  1061. },
  1062. },
  1063. });
  1064. });
  1065. it("cold compact boundary marks only its stable message coverage in the edit target", () => {
  1066. const compactHost = assistantMessageWithParts(
  1067. "a-compact",
  1068. "u-compact",
  1069. [
  1070. {
  1071. id: "compact-boundary-part" as never,
  1072. sessionID: "s1" as never,
  1073. messageID: "a-compact" as never,
  1074. type: "compaction",
  1075. auto: false,
  1076. operationId: "compact-operation",
  1077. timelineStatus: CompactTimelineStatus.Completed,
  1078. tail_start_id: "u-compact" as never,
  1079. },
  1080. ],
  1081. 1001,
  1082. );
  1083. const { projection } = reduce([userMessage("u-compact", "covered input", 1000), compactHost]);
  1084. const row = projection
  1085. .getSnapshot()
  1086. .rows.window.find((candidate) => candidate.kind === "userInput");
  1087. expect(projection.resolveEditTarget(row!.rowId)).toMatchObject({
  1088. transcriptMessageId: "u-compact",
  1089. coveredByStableCompact: true,
  1090. });
  1091. });
  1092. it("cold compact prefers the durable coverage boundary over an earlier timeline part", () => {
  1093. const compactHost = assistantMessageWithParts(
  1094. "a-compact-durable",
  1095. "u-compact-durable",
  1096. [
  1097. {
  1098. id: "compact-timeline-first" as never,
  1099. sessionID: "s1" as never,
  1100. messageID: "a-compact-durable" as never,
  1101. type: "timeline",
  1102. timelineType: "context_compaction",
  1103. display: "separator",
  1104. status: CompactTimelineStatus.Completed,
  1105. operationId: "compact-operation-durable",
  1106. trigger: CompactTrigger.Manual,
  1107. },
  1108. {
  1109. id: "compact-durable-second" as never,
  1110. sessionID: "s1" as never,
  1111. messageID: "a-compact-durable" as never,
  1112. type: "compaction",
  1113. auto: false,
  1114. operationId: "compact-operation-durable",
  1115. tail_start_id: "u-compact-durable" as never,
  1116. },
  1117. ],
  1118. 1001,
  1119. );
  1120. const { events } = reduce([
  1121. userMessage("u-compact-durable", "covered input", 1000),
  1122. compactHost,
  1123. ]);
  1124. const completed = events.find((event) => event.type === SessionEventType.CompactCompleted);
  1125. expect(completed?.payload).toMatchObject({
  1126. operationId: "compact-operation-durable",
  1127. tailStartMessageId: "u-compact-durable",
  1128. });
  1129. });
  1130. it("live/cold 的 edit/retry action 与 command target 逐行等价", () => {
  1131. const messages = [
  1132. userMessage("u-live-cold", "问题", 1000),
  1133. assistantMessage("a-live-cold", "u-live-cold", "回答", 1001),
  1134. ];
  1135. const cold = reduce(messages).projection;
  1136. const live = new ProductProjection("s1", "epoch");
  1137. const liveEvents = [
  1138. {
  1139. type: SessionEventType.SessionCreated,
  1140. payload: { mode: "default", contextWindow: 200_000 },
  1141. },
  1142. {
  1143. type: SessionEventType.TurnStarted,
  1144. payload: { turnNumber: 1, input: "问题", messageId: "u-live-cold" },
  1145. turnId: "hydrate-turn-1",
  1146. },
  1147. {
  1148. type: SessionEventType.ModelStreaming,
  1149. payload: {
  1150. kind: "text_start",
  1151. delta: "",
  1152. done: false,
  1153. assistantMessageId: "a-live-cold",
  1154. },
  1155. turnId: "hydrate-turn-1",
  1156. },
  1157. {
  1158. type: SessionEventType.ModelStreaming,
  1159. payload: { kind: "text_delta", delta: "回答", done: false },
  1160. turnId: "hydrate-turn-1",
  1161. },
  1162. {
  1163. type: SessionEventType.ModelStreaming,
  1164. payload: { kind: "text_end", delta: "", done: false },
  1165. turnId: "hydrate-turn-1",
  1166. },
  1167. {
  1168. type: SessionEventType.TurnComplete,
  1169. payload: {
  1170. response: "回答",
  1171. tokenCount: 0,
  1172. toolCallCount: 0,
  1173. duration: 1,
  1174. resultType: "success",
  1175. },
  1176. turnId: "hydrate-turn-1",
  1177. },
  1178. ].map(
  1179. (event, index) =>
  1180. ({
  1181. id: `live-${index + 1}`,
  1182. sessionId: "s1",
  1183. timestamp: new Date(1000 + index),
  1184. traceId: "live-trace",
  1185. sequenceNumber: index + 1,
  1186. ...event,
  1187. }) as unknown as SessionEvent,
  1188. );
  1189. for (const event of liveEvents) live.applyEvent(event);
  1190. const coldEntityResolver = cold.resolveEditTargetByEntityId;
  1191. const liveEntityResolver = live.resolveEditTargetByEntityId;
  1192. const commandFacts = (
  1193. projection: ProductProjection,
  1194. resolveByEntityId: (entityId: string) => unknown,
  1195. ) =>
  1196. projection
  1197. .getSnapshot()
  1198. .rows.window.filter((row) => row.kind === "userInput" || row.kind === "assistantText")
  1199. .map((row) => {
  1200. const entityId = projection.getEntityIdForRow(row.rowId);
  1201. return {
  1202. actions: row.actions,
  1203. entityId,
  1204. kind: row.kind,
  1205. messageId: projection.getMessageIdForRow(row.rowId),
  1206. rewindAnchor: projection.getTurnRewindAnchor(row.rowId),
  1207. target: entityId ? resolveByEntityId.call(projection, entityId) : null,
  1208. text: row.text,
  1209. };
  1210. });
  1211. expect(commandFacts(cold, coldEntityResolver)).toEqual(commandFacts(live, liveEntityResolver));
  1212. expect(commandFacts(cold, coldEntityResolver)).toEqual(
  1213. expect.arrayContaining([
  1214. expect.objectContaining({
  1215. entityId: "u-live-cold",
  1216. target: {
  1217. coveredByStableCompact: false,
  1218. entityId: "u-live-cold",
  1219. intent: { kind: "sendText", text: "问题" },
  1220. productTurnId: "u-live-cold",
  1221. transcriptMessageId: "u-live-cold",
  1222. },
  1223. }),
  1224. ]),
  1225. );
  1226. for (const row of cold.getSnapshot().rows.window) {
  1227. if (row.actions?.canEdit) {
  1228. expect(cold.getMessageIdForRow(row.rowId)).not.toBeNull();
  1229. expect(cold.getTurnRewindAnchor(row.rowId)).not.toBeNull();
  1230. }
  1231. if (row.actions?.canRetry) expect(cold.getMessageIdForRow(row.rowId)).not.toBeNull();
  1232. }
  1233. });
  1234. it("冷恢复用同一轮历史消息跨度合成 turnHeader activeMs", () => {
  1235. const messages = [
  1236. userMessage("u1", "排查一个慢任务", 1000),
  1237. assistantMessage("a1", "u1", "先读文件", 1200, 3400),
  1238. assistantMessage("a2", "u1", "再跑命令", 5000, 61_000),
  1239. ];
  1240. const { events, projection } = reduce(messages);
  1241. const turnComplete = events.find((event) => event.type === SessionEventType.TurnComplete);
  1242. expect(turnComplete?.payload).toMatchObject({ duration: 60_000 });
  1243. const turnHeader = projection
  1244. .getSnapshot()
  1245. .rows.window.find((row) => row.kind === "turnHeader");
  1246. expect(turnHeader).toMatchObject({
  1247. activeMs: 60_000,
  1248. state: "completedSuccess",
  1249. });
  1250. });
  1251. it("assistant 行携带 assistantMessageId → fork-of-fork 可解析", () => {
  1252. const messages = [userMessage("u1", "hi", 1000), assistantMessage("a1", "u1", "yo", 1001)];
  1253. const { projection } = reduce(messages);
  1254. const assistantRow = projection
  1255. .getSnapshot()
  1256. .rows.window.find((r) => r.kind === "assistantText");
  1257. // messageId 侧表用合成时的 assistant message id。
  1258. expect(projection.getMessageIdForRow(assistantRow!.rowId)).toBe("a1");
  1259. });
  1260. it("eventsCoverTranscript:事件日志缺 user 轮 → false(应改走合成)", () => {
  1261. const messages = [userMessage("u1", "a", 1000), assistantMessage("a1", "u1", "b", 1001)];
  1262. // 空事件日志 vs 有 1 个 user 消息 → 不覆盖。
  1263. expect(eventsCoverTranscript([], messages)).toBe(false);
  1264. // 合成出的事件 → 覆盖。
  1265. const { events } = reduce(messages);
  1266. expect(eventsCoverTranscript(events, messages)).toBe(true);
  1267. });
  1268. it("model-only 唤醒(goal continuation)开独立 model-only 轮,无可见气泡(S11/BG-wake-cold)", () => {
  1269. // 16-plan P2 语义变更(2026-07-08):wake/continuation 触发的 synthetic user
  1270. // 与 live 一致开 model-only 轮(旧冷路径把其后 assistant 并进上一轮——前审 F2 分叉)。
  1271. const messages = [
  1272. userMessage("u1", "a", 1000),
  1273. assistantMessage("a1", "u1", "b", 1002),
  1274. syntheticUserMessage("u_goal", "continue goal", 2000, {
  1275. metadata: { source: "goal-continuation", visibility: "model-only" },
  1276. source: "goal-continuation",
  1277. visibility: "model-only",
  1278. }),
  1279. assistantMessage("a2", "u_goal", "续跑产出", 2001),
  1280. ];
  1281. const { events, projection } = reduce(messages);
  1282. const turnStarts = events.filter((event) => event.type === SessionEventType.TurnStarted);
  1283. expect(turnStarts).toHaveLength(2);
  1284. expect(turnStarts[1]?.payload).toMatchObject({
  1285. inputVisibility: "model-only",
  1286. inputSource: "goal-continuation",
  1287. messageId: "u_goal",
  1288. });
  1289. expect(eventsCoverTranscript(events, messages)).toBe(true);
  1290. const rows = projection.getSnapshot().rows.window;
  1291. // 唤醒轮无可见 user 气泡;两轮 assistant 内容都在、各归自己的轮。
  1292. const userRows = rows.filter((row) => row.kind === "userInput");
  1293. expect(userRows).toHaveLength(1);
  1294. expect(userRows[0]?.kind === "userInput" ? userRows[0].text : "").toBe("a");
  1295. const assistantRows = rows.filter((row) => row.kind === "assistantText");
  1296. expect(assistantRows.map((row) => row.turnId)).toEqual(["u1", "u_goal"]);
  1297. expect(rows.filter((row) => row.kind === "turnHeader")).toHaveLength(2);
  1298. });
  1299. it("H17 cold:切模型后的 controlOnly goal query 与 continuation 保持独立执行语义", () => {
  1300. const previousUser = userMessageWithModel("u-before-goal", "上一轮", 1000, {
  1301. providerId: "p1",
  1302. modelId: "m1",
  1303. });
  1304. const previousAssistant = assistantMessage("a-before-goal", "u-before-goal", "完成", 1001);
  1305. previousAssistant.info.providerId = "p1" as never;
  1306. previousAssistant.info.modelId = "m1" as never;
  1307. const goalInput = userMessageWithModel("u-goal", "/Goal 开发招投标系统", 2000, {
  1308. providerId: "p2",
  1309. modelId: "m2",
  1310. });
  1311. goalInput.info.metadata = { executionKind: "controlOnly" };
  1312. const continuation = syntheticUserMessage("u-goal-continuation", "继续目标", 2001, {
  1313. metadata: { source: "goal-continuation", visibility: "model-only" },
  1314. source: "goal-continuation",
  1315. visibility: "model-only",
  1316. });
  1317. continuation.info.modelSelection = { providerId: "p2" as never, modelId: "m2" as never };
  1318. const continuationAssistant = assistantMessage(
  1319. "a-goal-continuation",
  1320. "u-goal-continuation",
  1321. "执行中",
  1322. 2002,
  1323. );
  1324. continuationAssistant.info.providerId = "p2" as never;
  1325. continuationAssistant.info.modelId = "m2" as never;
  1326. const messages = [
  1327. previousUser,
  1328. previousAssistant,
  1329. goalInput,
  1330. continuation,
  1331. continuationAssistant,
  1332. ];
  1333. const events = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  1334. const goalStart = events.find(
  1335. (event) =>
  1336. event.type === SessionEventType.TurnStarted &&
  1337. (event.payload as { messageId?: string }).messageId === "u-goal",
  1338. );
  1339. expect(goalStart?.payload).toMatchObject({ executionKind: "controlOnly" });
  1340. const projection = new ProductProjection("s1", "epoch");
  1341. let activeMessageId: string | undefined;
  1342. for (const event of events) {
  1343. if (event.type === SessionEventType.TurnStarted) {
  1344. activeMessageId = (event.payload as { messageId?: string }).messageId;
  1345. }
  1346. projection.applyEvent(event);
  1347. if (event.type === SessionEventType.TurnComplete && activeMessageId === "u-goal") {
  1348. expect(projection.getSnapshot().control).toMatchObject({
  1349. phase: "completedSuccess",
  1350. activeWorks: [],
  1351. });
  1352. }
  1353. }
  1354. const rows = projection.getSnapshot().rows.window;
  1355. const headers = rows.filter((row) => row.kind === "turnHeader");
  1356. expect(headers.find((row) => row.turnId === "u-goal")).toMatchObject({
  1357. executionKind: "controlOnly",
  1358. state: "completedSuccess",
  1359. });
  1360. expect(headers.find((row) => row.turnId === "u-goal")).not.toHaveProperty("activeMs");
  1361. expect(headers.find((row) => row.turnId === "u-goal-continuation")).toMatchObject({
  1362. executionKind: "agent",
  1363. state: "completedSuccess",
  1364. });
  1365. expect(
  1366. rows.filter((row) => row.kind === "timelineMarker" && row.marker.type === "modelChange"),
  1367. ).toHaveLength(1);
  1368. expect(eventsCoverTranscript(events, messages)).toBe(true);
  1369. });
  1370. it("cold hydration strips the withdrawn refined names from a persisted CreateWorkflow display", () => {
  1371. // docs/dynamic-workflow/presentation.md:旧 part 的 display 里还带着
  1372. // `refinedName` / `refinedLabel`,而渲染端按严格 schema 校验每一帧。三个携带 display 的
  1373. // 事件都必须拿到剥离后的同一份,否则旧会话在订阅时整帧被拒。
  1374. const plainGraph = {
  1375. steps: [{ id: "ask#1", kind: "ask", label: "planner", lane: "actor#1", phase: "phase#1" }],
  1376. lanes: [{ id: "actor#1", name: "planner" }],
  1377. participants: [
  1378. { id: "phase#1:actor#1", phase: "phase#1", lane: "actor#1", steps: ["ask#1"] },
  1379. ],
  1380. handoffs: [],
  1381. phases: [{ id: "phase#1", name: "plan" }],
  1382. };
  1383. const refinedGraph = {
  1384. ...plainGraph,
  1385. steps: [{ ...plainGraph.steps[0], refinedLabel: "拟定计划" }],
  1386. lanes: [{ ...plainGraph.lanes[0], refinedName: "规划者" }],
  1387. phases: [{ ...plainGraph.phases[0], refinedName: "规划" }],
  1388. };
  1389. const displayOf = (causalityGraph: unknown) => ({
  1390. kind: "create_workflow",
  1391. ok: true,
  1392. errorCount: 0,
  1393. diagnostics: [],
  1394. causalityGraph,
  1395. });
  1396. const messages = [
  1397. userMessage("u1", "run the workflow", 1000),
  1398. assistantMessageWithParts(
  1399. "a1",
  1400. "u1",
  1401. [
  1402. {
  1403. id: "a1-tool-create-workflow" as never,
  1404. sessionID: "s1" as never,
  1405. messageID: "a1" as never,
  1406. type: "tool",
  1407. callID: "call-create-workflow",
  1408. tool: "CreateWorkflow",
  1409. state: {
  1410. status: "completed",
  1411. input: { script: "phase('plan'); return await agent('planner').ask('plan');" },
  1412. output: "started",
  1413. title: "CreateWorkflow",
  1414. metadata: { schemaVersion: 1, display: displayOf(refinedGraph) },
  1415. time: { start: 1001, end: 1002 },
  1416. },
  1417. },
  1418. ],
  1419. 1001,
  1420. ),
  1421. ];
  1422. const { events } = reduce(messages);
  1423. const displays = events
  1424. .filter(
  1425. (event) =>
  1426. event.type === SessionEventType.ToolCallScheduled ||
  1427. event.type === SessionEventType.ToolCallStarted ||
  1428. event.type === SessionEventType.ToolCallResult,
  1429. )
  1430. .map((event) => {
  1431. const payload = event.payload as { display?: unknown; result?: { display?: unknown } };
  1432. return payload.display ?? payload.result?.display;
  1433. });
  1434. expect(displays).toHaveLength(3);
  1435. for (const display of displays) expect(display).toEqual(displayOf(plainGraph));
  1436. });
  1437. it("cold hydration strips providerStop from a persisted GetWorkflowRun display", () => {
  1438. // docs/dynamic-workflow/launch.md「Their cards」:旧 part 的 display 里还带着工具输出
  1439. // 那份 `error.providerStop`,而渲染端按镜像 schema 校验每一帧。三个携带 display
  1440. // 的事件都必须拿到剥离后的同一份,否则这个会话一订阅就整帧被拒。
  1441. const plainDisplay = {
  1442. kind: "get_workflow_run",
  1443. runId: "dwfrun_stopped",
  1444. label: "nightly-sync",
  1445. status: "stopped",
  1446. stopReason: "provider",
  1447. usage: {
  1448. spentTokens: 12_345,
  1449. nodesObserved: 7,
  1450. nodesRunning: 0,
  1451. nodesCompleted: 4,
  1452. nodesFailed: 1,
  1453. },
  1454. actors: [{ siteId: "agent#1", ordinal: 1, name: "scout" }],
  1455. logTail: [{ sequence: 1, message: "started" }],
  1456. error: { code: "ProviderStop", message: "The provider stopped the run: rate limited." },
  1457. };
  1458. const persistedDisplay = {
  1459. ...plainDisplay,
  1460. error: {
  1461. ...plainDisplay.error,
  1462. providerStop: { kind: "quota", reason: "rate_limited", providerCode: "1308" },
  1463. },
  1464. };
  1465. const messages = [
  1466. userMessage("u1", "how is the run doing", 1000),
  1467. assistantMessageWithParts(
  1468. "a1",
  1469. "u1",
  1470. [
  1471. {
  1472. id: "a1-tool-get-workflow-run" as never,
  1473. sessionID: "s1" as never,
  1474. messageID: "a1" as never,
  1475. type: "tool",
  1476. callID: "call-get-workflow-run",
  1477. tool: "GetWorkflowRun",
  1478. state: {
  1479. status: "completed",
  1480. input: { run_id: "dwfrun_stopped" },
  1481. output: "stopped",
  1482. title: "GetWorkflowRun",
  1483. metadata: { schemaVersion: 1, display: persistedDisplay },
  1484. time: { start: 1001, end: 1002 },
  1485. },
  1486. },
  1487. ],
  1488. 1001,
  1489. ),
  1490. ];
  1491. const { events } = reduce(messages);
  1492. const displays = events
  1493. .filter(
  1494. (event) =>
  1495. event.type === SessionEventType.ToolCallScheduled ||
  1496. event.type === SessionEventType.ToolCallStarted ||
  1497. event.type === SessionEventType.ToolCallResult,
  1498. )
  1499. .map((event) => {
  1500. const payload = event.payload as { display?: unknown; result?: { display?: unknown } };
  1501. return payload.display ?? payload.result?.display;
  1502. });
  1503. expect(displays).toHaveLength(3);
  1504. for (const display of displays) {
  1505. expect(display).toEqual(plainDisplay);
  1506. // 水合出来的每一帧都要过渲染端那把尺。
  1507. const mirrored = toolCallGetWorkflowRunDisplaySchema.strict().safeParse(display);
  1508. expect(mirrored.success ? [] : mirrored.error.issues).toEqual([]);
  1509. }
  1510. });
  1511. it("BG26:cold hydration 保留 background notification 原文并恢复 Agent 失败终态", () => {
  1512. const toolCallId = "call-agent-rate-limit";
  1513. const error = "Requests are too frequent. Request id: bg26-cold";
  1514. const result = `Agent general-purpose task \"分析世界杯\" failed. ${error}`;
  1515. const launchOutput = [
  1516. "Async agent launched successfully.",
  1517. "agentId: agent-bg26 (internal ID - do not mention to user.)",
  1518. "The agent is working in the background.",
  1519. ].join("\n");
  1520. const messages = [
  1521. userMessage("u1", "launch agent", 1000),
  1522. assistantMessageWithParts(
  1523. "a1",
  1524. "u1",
  1525. [
  1526. {
  1527. id: "a1-tool-agent-bg26" as never,
  1528. sessionID: "s1" as never,
  1529. messageID: "a1" as never,
  1530. type: "tool",
  1531. callID: toolCallId,
  1532. tool: "Agent",
  1533. state: {
  1534. status: "completed",
  1535. input: {
  1536. description: "分析世界杯",
  1537. run_in_background: true,
  1538. subagent_type: "general-purpose",
  1539. },
  1540. output: launchOutput,
  1541. title: "Agent 分析世界杯",
  1542. metadata: {},
  1543. time: { start: 1001, end: 1002 },
  1544. },
  1545. },
  1546. ],
  1547. 1001,
  1548. ),
  1549. syntheticUserMessage(
  1550. "u-agent-notification",
  1551. [
  1552. "<task-notification>",
  1553. `<tool-use-id>${toolCallId}</tool-use-id>`,
  1554. "<status>failed</status>",
  1555. `<result>${result}</result>`,
  1556. `<error>${error}</error>`,
  1557. "</task-notification>",
  1558. ].join("\n"),
  1559. 2000,
  1560. {
  1561. metadata: { source: "background_task", visibility: "model-only" },
  1562. source: "background_task",
  1563. visibility: "model-only",
  1564. },
  1565. ),
  1566. assistantMessage("a2", "u-agent-notification", "父会话已处理失败", 2001),
  1567. ];
  1568. const { events, projection } = reduce(messages);
  1569. const notificationStart = events
  1570. .filter((event) => event.type === SessionEventType.TurnStarted)
  1571. .find(
  1572. (event) => (event.payload as { messageId?: string }).messageId === "u-agent-notification",
  1573. );
  1574. expect(notificationStart?.payload).toMatchObject({
  1575. inputVisibility: "model-only",
  1576. inputSource: "background_task",
  1577. input: expect.stringContaining(`<tool-use-id>${toolCallId}</tool-use-id>`),
  1578. });
  1579. expect(
  1580. projection.getSnapshot().rows.window.filter((row) => row.kind === "userInput"),
  1581. ).toHaveLength(1);
  1582. expect(
  1583. projection
  1584. .getSnapshot()
  1585. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1586. ).toMatchObject({
  1587. error: {
  1588. code: "fault.runtime.backgroundTaskFailed",
  1589. message: error,
  1590. },
  1591. output: { text: result },
  1592. status: "error",
  1593. });
  1594. expect(
  1595. projection
  1596. .getSnapshot()
  1597. .rows.window.find((row) => row.kind === "subagent" && row.parentToolCallId === toolCallId),
  1598. ).toMatchObject({
  1599. childSessionId: "sess_subagent_agent-bg26",
  1600. });
  1601. });
  1602. it("BG26:cold hydration 从通知消息 metadata 的 originMeta 恢复结构化失败原因", () => {
  1603. const toolCallId = "call-agent-rate-limit";
  1604. const error = "Requests are too frequent. Request id: bg26-cold";
  1605. const summary = `Agent "分析世界杯" failed: ${error}`;
  1606. const messages = [
  1607. userMessage("u1", "launch agent", 1000),
  1608. assistantMessageWithParts(
  1609. "a1",
  1610. "u1",
  1611. [
  1612. {
  1613. id: "a1-tool-agent-bg26" as never,
  1614. sessionID: "s1" as never,
  1615. messageID: "a1" as never,
  1616. type: "tool",
  1617. callID: toolCallId,
  1618. tool: "Agent",
  1619. state: {
  1620. status: "completed",
  1621. input: { description: "分析世界杯", run_in_background: true },
  1622. output: "Async agent launched successfully.",
  1623. title: "Agent 分析世界杯",
  1624. metadata: {},
  1625. time: { start: 1001, end: 1002 },
  1626. },
  1627. },
  1628. ],
  1629. 1001,
  1630. ),
  1631. syntheticUserMessage(
  1632. "u-agent-notification",
  1633. [
  1634. "<task-notification>",
  1635. "<task-id>agent-bg26</task-id>",
  1636. `<tool-use-id>${toolCallId}</tool-use-id>`,
  1637. "<status>failed</status>",
  1638. `<summary>${summary}</summary>`,
  1639. "</task-notification>",
  1640. ].join("\n"),
  1641. 2000,
  1642. {
  1643. metadata: {
  1644. source: "background_task",
  1645. visibility: "model-only",
  1646. originMeta: {
  1647. backgroundSource: "subagent",
  1648. workId: "agent-bg26",
  1649. title: "分析世界杯",
  1650. subagentResult: { status: "failed", error },
  1651. },
  1652. },
  1653. source: "background_task",
  1654. visibility: "model-only",
  1655. },
  1656. ),
  1657. assistantMessage("a2", "u-agent-notification", "父会话已处理失败", 2001),
  1658. ];
  1659. const { projection } = reduce(messages);
  1660. expect(
  1661. projection
  1662. .getSnapshot()
  1663. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1664. ).toMatchObject({
  1665. error: { code: "fault.runtime.backgroundTaskFailed", message: error },
  1666. output: { text: summary },
  1667. status: "error",
  1668. });
  1669. });
  1670. it("BG26:cold hydration 按块恢复合并通知,失败任务不读下一条通知的结果", () => {
  1671. const failedSummary = 'Agent "A" failed: Permission denied';
  1672. const agentTool = (callID: string) => ({
  1673. id: `a1-${callID}` as never,
  1674. sessionID: "s1" as never,
  1675. messageID: "a1" as never,
  1676. type: "tool" as const,
  1677. callID,
  1678. tool: "Agent",
  1679. state: {
  1680. status: "completed" as const,
  1681. input: { description: callID, run_in_background: true },
  1682. output: "Async agent launched successfully.",
  1683. title: `Agent ${callID}`,
  1684. metadata: {},
  1685. time: { start: 1001, end: 1002 },
  1686. },
  1687. });
  1688. const messages = [
  1689. userMessage("u1", "launch agents", 1000),
  1690. assistantMessageWithParts(
  1691. "a1",
  1692. "u1",
  1693. [agentTool("call-agent-a"), agentTool("call-agent-b")],
  1694. 1001,
  1695. ),
  1696. syntheticUserMessage(
  1697. "u-merged-notification",
  1698. [
  1699. [
  1700. "<task-notification>",
  1701. "<tool-use-id>call-agent-a</tool-use-id>",
  1702. "<status>failed</status>",
  1703. `<summary>${failedSummary}</summary>`,
  1704. "</task-notification>",
  1705. ].join("\n"),
  1706. [
  1707. "<task-notification>",
  1708. "<tool-use-id>call-agent-b</tool-use-id>",
  1709. "<status>completed</status>",
  1710. '<summary>Agent "B" finished</summary>',
  1711. "<result>Tests passed</result>",
  1712. "</task-notification>",
  1713. ].join("\n"),
  1714. ].join("\n\n"),
  1715. 2000,
  1716. {
  1717. metadata: {
  1718. source: "background_task",
  1719. visibility: "model-only",
  1720. originMeta: { backgroundSource: "subagent", workId: "agent-a", title: "A · B" },
  1721. },
  1722. source: "background_task",
  1723. visibility: "model-only",
  1724. },
  1725. ),
  1726. assistantMessage("a2", "u-merged-notification", "父会话已处理", 2001),
  1727. ];
  1728. const rows = reduce(messages).projection.getSnapshot().rows.window;
  1729. const toolRow = (toolCallId: string) =>
  1730. rows.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId);
  1731. expect(toolRow("call-agent-a")).toMatchObject({
  1732. error: { code: "fault.runtime.backgroundTaskFailed", message: failedSummary },
  1733. output: { text: failedSummary },
  1734. status: "error",
  1735. });
  1736. expect(toolRow("call-agent-b")).toMatchObject({
  1737. output: { text: "Tests passed" },
  1738. status: "success",
  1739. });
  1740. });
  1741. it("selection side chat 的继承历史只进 provider context,冷恢复时间线从新问题开始", () => {
  1742. const inheritedUser = userMessage("u_selection_parent", "父任务问题", 1000);
  1743. const inheritedAssistant = assistantMessage(
  1744. "a_selection_parent",
  1745. inheritedUser.info.id,
  1746. "父任务回答",
  1747. 1001,
  1748. );
  1749. const hideInheritedMessage = (message: MessageWithParts): MessageWithParts => ({
  1750. ...message,
  1751. info: {
  1752. ...message.info,
  1753. visibility: "model-only",
  1754. semantics: {
  1755. kind: "system_reminder",
  1756. origin: "migration",
  1757. providerVisibility: "visible",
  1758. transcriptVisibility: "hidden",
  1759. uiVisibility: "hidden",
  1760. },
  1761. },
  1762. });
  1763. const boundary = syntheticUserMessage("u_selection_boundary", "side chat boundary", 1002, {
  1764. source: "selection_side_chat",
  1765. visibility: "model-only",
  1766. semantics: {
  1767. kind: "system_reminder",
  1768. origin: "system",
  1769. providerVisibility: "visible",
  1770. source: "selection_side_chat",
  1771. transcriptVisibility: "hidden",
  1772. uiVisibility: "hidden",
  1773. },
  1774. });
  1775. const sideUser = userMessage("u_selection_visible", "解释这个片段", 2000);
  1776. const sideAssistant = assistantMessage(
  1777. "a_selection_visible",
  1778. sideUser.info.id,
  1779. "这是副屏回答",
  1780. 2001,
  1781. );
  1782. const messages = [
  1783. hideInheritedMessage(inheritedUser),
  1784. hideInheritedMessage(inheritedAssistant),
  1785. boundary,
  1786. sideUser,
  1787. sideAssistant,
  1788. ];
  1789. const { events, projection } = reduce(messages);
  1790. const snapshot = projection.getSnapshot();
  1791. const visibleTexts = snapshot.rows.window
  1792. .filter((row) => row.kind === "userInput" || row.kind === "assistantText")
  1793. .map((row) => row.text);
  1794. expect(eventsCoverTranscript(events, messages)).toBe(true);
  1795. expect(visibleTexts).toEqual(["解释这个片段", "这是副屏回答"]);
  1796. expect(JSON.stringify(snapshot.rows.window)).not.toContain("父任务");
  1797. expect(snapshot.rows.totalCount).toBe(snapshot.rows.window.length);
  1798. });
  1799. it("subagent_message idle carrier 的 live/cold identity 与 fork target 完全一致", () => {
  1800. const carrierId = "u-subagent-message-idle";
  1801. const assistantId = "a-subagent-message-idle";
  1802. const carrier = syntheticUserMessage(carrierId, "internal coordinator response", 1000, {
  1803. metadata: { source: "subagent_message", visibility: "model-only" },
  1804. source: "subagent_message",
  1805. visibility: "model-only",
  1806. });
  1807. const cold = reduce([
  1808. carrier,
  1809. assistantMessage(assistantId, carrierId, "subagent follow-up", 1001),
  1810. ]).projection;
  1811. const live = new ProductProjection("s1", "epoch-live-subagent-message");
  1812. const liveEvents = [
  1813. {
  1814. type: SessionEventType.SessionCreated,
  1815. payload: { mode: "default", contextWindow: 200_000 },
  1816. },
  1817. {
  1818. type: SessionEventType.TurnStarted,
  1819. payload: {
  1820. turnNumber: 1,
  1821. input: "",
  1822. inputVisibility: "model-only",
  1823. inputSource: "subagent_message",
  1824. messageId: carrierId,
  1825. },
  1826. turnId: "runtime-subagent-message-turn",
  1827. },
  1828. {
  1829. type: SessionEventType.ModelStreaming,
  1830. payload: {
  1831. kind: "text_start",
  1832. delta: "",
  1833. done: false,
  1834. assistantMessageId: assistantId,
  1835. },
  1836. turnId: "runtime-subagent-message-turn",
  1837. },
  1838. {
  1839. type: SessionEventType.ModelStreaming,
  1840. payload: { kind: "text_delta", delta: "subagent follow-up", done: false },
  1841. turnId: "runtime-subagent-message-turn",
  1842. },
  1843. {
  1844. type: SessionEventType.ModelStreaming,
  1845. payload: { kind: "text_end", delta: "", done: false },
  1846. turnId: "runtime-subagent-message-turn",
  1847. },
  1848. {
  1849. type: SessionEventType.TurnComplete,
  1850. payload: {
  1851. response: "subagent follow-up",
  1852. tokenCount: 0,
  1853. toolCallCount: 0,
  1854. duration: 1,
  1855. resultType: "success",
  1856. },
  1857. turnId: "runtime-subagent-message-turn",
  1858. },
  1859. ].map(
  1860. (event, index) =>
  1861. ({
  1862. id: `live-subagent-message-${index + 1}`,
  1863. sessionId: "s1",
  1864. timestamp: new Date(1000 + index),
  1865. traceId: "live-subagent-message-trace",
  1866. sequenceNumber: index + 1,
  1867. ...event,
  1868. }) as unknown as SessionEvent,
  1869. );
  1870. for (const event of liveEvents) live.applyEvent(event);
  1871. const identity = (projection: ProductProjection) => {
  1872. const row = projection
  1873. .getSnapshot()
  1874. .rows.window.find((candidate) => candidate.kind === "assistantText");
  1875. expect(row).toBeDefined();
  1876. if (!row) return null;
  1877. const entityId = projection.getEntityIdForRow(row.rowId);
  1878. expect(entityId).toBeTruthy();
  1879. const target = projection.resolveRowActionTarget(
  1880. { rowId: row.rowId, entityId: entityId! },
  1881. "forkAssistant",
  1882. );
  1883. return {
  1884. actionTarget:
  1885. target.ok && target.action === "forkAssistant"
  1886. ? {
  1887. entityId: target.row.entityId,
  1888. messageId: target.messageId,
  1889. productTurnId: target.row.productTurnId,
  1890. }
  1891. : target,
  1892. actions: row.actions,
  1893. entityId,
  1894. messageId: projection.getMessageIdForRow(row.rowId),
  1895. productTurnId: row.productTurnId,
  1896. turnId: row.turnId,
  1897. };
  1898. };
  1899. expect(identity(cold)).toEqual(identity(live));
  1900. expect(identity(cold)).toMatchObject({
  1901. actionTarget: {
  1902. entityId: assistantId,
  1903. messageId: assistantId,
  1904. productTurnId: carrierId,
  1905. },
  1906. entityId: assistantId,
  1907. messageId: assistantId,
  1908. productTurnId: carrierId,
  1909. turnId: carrierId,
  1910. });
  1911. });
  1912. // 新版本每条通知存为一个文本 part;旧版本存为一个 "\n\n" 连接的 part。两种冷恢复的轮输入都与 live 相同。
  1913. it.each([
  1914. ["one part per notification", true],
  1915. ["one joined part", false],
  1916. ])("BG36:multi-notification batch 冷恢复只生成一个 background result turn(%s)", (_, split) => {
  1917. const originMeta = {
  1918. backgroundSource: "subagent" as const,
  1919. title: "Inspect renderer state · Inspect service state",
  1920. workId: "batch-agent-1",
  1921. };
  1922. const notifications = [
  1923. "<task-notification><task-id>batch-agent-1</task-id><status>completed</status></task-notification>",
  1924. "<task-notification><task-id>batch-agent-2</task-id><status>completed</status></task-notification>",
  1925. ];
  1926. const batchText = notifications.join("\n\n");
  1927. const batch = syntheticUserMessage("wake-batch", split ? notifications[0]! : batchText, 2000, {
  1928. metadata: { originMeta, source: "background_task", visibility: "model-only" },
  1929. source: "background_task",
  1930. visibility: "model-only",
  1931. });
  1932. if (split) {
  1933. batch.parts.push({
  1934. ...batch.parts[0]!,
  1935. id: "wake-batch-t2" as never,
  1936. text: notifications[1]!,
  1937. });
  1938. }
  1939. const { events, projection } = reduce([
  1940. batch,
  1941. assistantMessage("a-wake-batch", "wake-batch", "processed batch", 2001),
  1942. ]);
  1943. const turnStarts = events.filter((event) => event.type === SessionEventType.TurnStarted);
  1944. const rows = projection.getSnapshot().rows.window;
  1945. expect(turnStarts).toHaveLength(1);
  1946. expect(turnStarts[0]?.payload).toMatchObject({
  1947. input: batchText,
  1948. inputSource: "background_task",
  1949. inputVisibility: "model-only",
  1950. messageId: "wake-batch",
  1951. originMeta,
  1952. });
  1953. expect(rows.filter((row) => row.kind === "userInput")).toHaveLength(0);
  1954. const turnHeaders = rows.filter((row) => row.kind === "turnHeader");
  1955. expect(turnHeaders).toHaveLength(1);
  1956. expect(turnHeaders[0]).toMatchObject({
  1957. origin: "backgroundResult",
  1958. originMeta,
  1959. });
  1960. const assistantRows = rows.filter((row) => row.kind === "assistantText");
  1961. expect(assistantRows).toHaveLength(1);
  1962. expect(assistantRows[0]).toMatchObject({
  1963. productTurnId: "wake-batch",
  1964. turnId: "wake-batch",
  1965. });
  1966. });
  1967. it("multiple background wakes each keep an independent stable productTurnId", () => {
  1968. const background = (id: string, created: number) =>
  1969. syntheticUserMessage(id, "background result", created, {
  1970. metadata: { source: "background_task", visibility: "model-only" },
  1971. source: "background_task",
  1972. visibility: "model-only",
  1973. });
  1974. const { projection } = reduce([
  1975. userMessage("u1", "start", 1000),
  1976. assistantMessage("a1", "u1", "initial", 1001),
  1977. background("wake-1", 2000),
  1978. assistantMessage("a-wake-1", "wake-1", "wake answer 1", 2001),
  1979. background("wake-2", 3000),
  1980. assistantMessage("a-wake-2", "wake-2", "wake answer 2", 3001),
  1981. ]);
  1982. const rows = projection.getSnapshot().rows.window;
  1983. const answers = rows.filter((row) => row.kind === "assistantText");
  1984. expect(answers.map((row) => row.turnId)).toEqual(["u1", "wake-1", "wake-2"]);
  1985. expect(new Set(answers.map((row) => row.productTurnId)).size).toBe(3);
  1986. expect(rows.filter((row) => row.kind === "userInput")).toHaveLength(1);
  1987. expect(answers.map((row) => row.actions?.canRetry === true)).toEqual([false, false, false]);
  1988. expect(answers[2]!.actions?.canFork).toBe(true);
  1989. const withNextRealUserTurn = reduce([
  1990. userMessage("u1", "start", 1000),
  1991. assistantMessage("a1", "u1", "initial", 1001),
  1992. background("wake-1", 2000),
  1993. assistantMessage("a-wake-1", "wake-1", "wake answer 1", 2001),
  1994. background("wake-2", 3000),
  1995. assistantMessage("a-wake-2", "wake-2", "wake answer 2", 3001),
  1996. userMessage("u2", "continue", 4000),
  1997. assistantMessage("a2", "u2", "latest real-user answer", 4001),
  1998. ]).projection;
  1999. const hydratedAnswers = withNextRealUserTurn
  2000. .getSnapshot()
  2001. .rows.window.filter((row) => row.kind === "assistantText");
  2002. expect(hydratedAnswers.map((row) => row.actions?.canRetry === true)).toEqual([
  2003. false,
  2004. false,
  2005. false,
  2006. true,
  2007. ]);
  2008. });
  2009. it("BG27/BG28:cold hydration 只从结构化 metadata 恢复后台结果标题", () => {
  2010. const background = syntheticUserMessage("wake-title", "background result", 2000, {
  2011. metadata: {
  2012. originMeta: {
  2013. backgroundSource: "bash",
  2014. title: "pnpm typecheck",
  2015. workId: "bash-typecheck",
  2016. },
  2017. source: "background_task",
  2018. visibility: "model-only",
  2019. },
  2020. source: "background_task",
  2021. visibility: "model-only",
  2022. });
  2023. const { projection } = reduce([
  2024. background,
  2025. assistantMessage("a-wake-title", "wake-title", "typecheck complete", 2001),
  2026. ]);
  2027. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  2028. expect(header).toMatchObject({
  2029. origin: "backgroundResult",
  2030. originMeta: {
  2031. backgroundSource: "bash",
  2032. title: "pnpm typecheck",
  2033. workId: "bash-typecheck",
  2034. },
  2035. });
  2036. });
  2037. // dwf run 的完成通知走同一条后台管线,backgroundSource 是第三个取值 "workflow"。
  2038. // 冷恢复的 originMeta 过滤器此前只放行 bash|subagent,漏掉它会让 workflow 的后台结果轮
  2039. // 静默退化成一条无标题的 model-only 消息(工具卡→详情页的关联键 workId 一起丢掉)。
  2040. it("cold hydration 恢复 workflow 后台结果的 originMeta", () => {
  2041. const background = syntheticUserMessage("wake-workflow", "workflow result", 2000, {
  2042. metadata: {
  2043. originMeta: {
  2044. backgroundSource: "workflow",
  2045. title: "review the diff",
  2046. workId: "dwfrun-abc",
  2047. },
  2048. source: "background_task",
  2049. visibility: "model-only",
  2050. },
  2051. source: "background_task",
  2052. visibility: "model-only",
  2053. });
  2054. const { projection } = reduce([
  2055. background,
  2056. assistantMessage("a-wake-workflow", "wake-workflow", "workflow done", 2001),
  2057. ]);
  2058. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  2059. expect(header).toMatchObject({
  2060. origin: "backgroundResult",
  2061. originMeta: {
  2062. backgroundSource: "workflow",
  2063. title: "review the diff",
  2064. workId: "dwfrun-abc",
  2065. },
  2066. });
  2067. });
  2068. // manifest 载荷(workflowNotification)也要过冷恢复:读取器此前只回读三基字段,
  2069. // 载荷会在冷恢复后静默丢失,manifest 条目退回裸标题行(本特性最隐蔽的坑)。
  2070. it("cold hydration 恢复 workflow originMeta 的 manifest 载荷(terminal)", () => {
  2071. const workflowNotification = {
  2072. kind: "terminal",
  2073. status: "completed",
  2074. summary: "review the diff",
  2075. result: "final artifact",
  2076. resultForm: "prose",
  2077. reports: { count: 3, shown: 1, preview: ["第一步"] },
  2078. durationMs: 4200,
  2079. };
  2080. const background = syntheticUserMessage("wake-workflow-meta", "workflow result", 2000, {
  2081. metadata: {
  2082. originMeta: {
  2083. backgroundSource: "workflow",
  2084. title: "review the diff",
  2085. workId: "dwfrun-meta",
  2086. workflowNotification,
  2087. },
  2088. source: "background_task",
  2089. visibility: "model-only",
  2090. },
  2091. source: "background_task",
  2092. visibility: "model-only",
  2093. });
  2094. const { projection } = reduce([
  2095. background,
  2096. assistantMessage("a-wake-meta", "wake-workflow-meta", "workflow done", 2001),
  2097. ]);
  2098. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  2099. expect(header).toMatchObject({
  2100. origin: "backgroundResult",
  2101. originMeta: { backgroundSource: "workflow", workId: "dwfrun-meta", workflowNotification },
  2102. });
  2103. });
  2104. // 「主代理闲着、run 还欠着决定」的提醒走同一条读取器,载荷在它自己的键 `workflowBlocked` 上
  2105. // (docs/dynamic-workflow/transcript-and-notifications.md「The payload」):冷恢复后仍是那一行,
  2106. // 而不是退回裸标题行。
  2107. it("cold hydration 恢复 workflow originMeta 的提醒载荷(workflowBlocked)", () => {
  2108. const workflowBlocked = { questions: 2, holes: 1, sinceMs: 1_020_000 };
  2109. const background = syntheticUserMessage("wake-workflow-blocked", "workflow reminder", 2000, {
  2110. metadata: {
  2111. originMeta: {
  2112. backgroundSource: "workflow",
  2113. title: "review the diff",
  2114. workId: "dwfrun-blocked",
  2115. workflowBlocked,
  2116. },
  2117. source: "background_task",
  2118. visibility: "model-only",
  2119. },
  2120. source: "background_task",
  2121. visibility: "model-only",
  2122. });
  2123. const { projection } = reduce([
  2124. background,
  2125. assistantMessage("a-wake-blocked", "wake-workflow-blocked", "answered", 2001),
  2126. ]);
  2127. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  2128. expect(header).toMatchObject({
  2129. origin: "backgroundResult",
  2130. originMeta: { backgroundSource: "workflow", workId: "dwfrun-blocked", workflowBlocked },
  2131. });
  2132. expect(header).not.toHaveProperty("originMeta.workflowNotification");
  2133. });
  2134. // 提醒曾短暂地作为 `workflowNotification` 的一个 kind 落过盘(闭集多一个成员会让老客户端拒掉整帧)。
  2135. // 那样的行冷恢复时只丢载荷:绝不把闭集之外的 kind 再发上线。
  2136. it("cold hydration 不把闭集之外的 workflowNotification kind 发上线", () => {
  2137. const background = syntheticUserMessage("wake-workflow-legacy", "workflow reminder", 2000, {
  2138. metadata: {
  2139. originMeta: {
  2140. backgroundSource: "workflow",
  2141. title: "review the diff",
  2142. workId: "dwfrun-legacy",
  2143. workflowNotification: { kind: "blocked", questions: 2, holes: 1, sinceMs: 1_020_000 },
  2144. },
  2145. source: "background_task",
  2146. visibility: "model-only",
  2147. },
  2148. source: "background_task",
  2149. visibility: "model-only",
  2150. });
  2151. const { projection } = reduce([
  2152. background,
  2153. assistantMessage("a-wake-legacy", "wake-workflow-legacy", "answered", 2001),
  2154. ]);
  2155. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  2156. expect(header).toMatchObject({
  2157. origin: "backgroundResult",
  2158. originMeta: { backgroundSource: "workflow", workId: "dwfrun-legacy" },
  2159. });
  2160. expect(header).not.toHaveProperty("originMeta.workflowNotification");
  2161. expect(header).not.toHaveProperty("originMeta.workflowBlocked");
  2162. });
  2163. // 防御性读取:畸形载荷(status 不在枚举内)只丢载荷、保三基字段,绝不打挂整条冷恢复。
  2164. it("cold hydration 丢弃畸形 manifest 载荷但保留三基字段", () => {
  2165. const background = syntheticUserMessage("wake-workflow-bad", "workflow result", 2000, {
  2166. metadata: {
  2167. originMeta: {
  2168. backgroundSource: "workflow",
  2169. title: "review the diff",
  2170. workId: "dwfrun-bad",
  2171. // status 非法(不在 completed/failed/cancelled 内)→ zod 拒收 → 只丢载荷。
  2172. workflowNotification: { kind: "terminal", status: "running", summary: "x" },
  2173. },
  2174. source: "background_task",
  2175. visibility: "model-only",
  2176. },
  2177. source: "background_task",
  2178. visibility: "model-only",
  2179. });
  2180. const { projection } = reduce([
  2181. background,
  2182. assistantMessage("a-wake-bad", "wake-workflow-bad", "workflow done", 2001),
  2183. ]);
  2184. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  2185. expect(header).toMatchObject({
  2186. origin: "backgroundResult",
  2187. originMeta: { backgroundSource: "workflow", title: "review the diff", workId: "dwfrun-bad" },
  2188. });
  2189. // 载荷被丢弃,不带进投影。
  2190. expect(
  2191. (header as { originMeta?: { workflowNotification?: unknown } }).originMeta
  2192. ?.workflowNotification,
  2193. ).toBeUndefined();
  2194. });
  2195. // 用户面产物的 chips 载荷(docs/dynamic-workflow/authoring.md「How the user sees them」)走同一条读取器。
  2196. // 读取器本身是 `workflowNotificationMetaSchema.safeParse` 的直传,而那份 zod **剥离**未声明
  2197. // 的键——所以「schema 里没加 artifacts」的症状不是报错,是 chips 在冷恢复后无声消失。
  2198. // 这条正向断言就是那个坑的钉子。
  2199. it("cold hydration 恢复 manifest 载荷里的 artifacts 与 artifactsTruncated", () => {
  2200. const workflowNotification = {
  2201. kind: "terminal",
  2202. status: "completed",
  2203. summary: "nightly audit",
  2204. artifacts: [
  2205. {
  2206. id: "audit",
  2207. kind: "file",
  2208. title: "审计报告",
  2209. version: 2,
  2210. contentType: "application/pdf",
  2211. },
  2212. { id: "perf", kind: "chart", version: 1 },
  2213. ],
  2214. artifactsTruncated: true,
  2215. };
  2216. const background = syntheticUserMessage("wake-workflow-art", "workflow result", 2000, {
  2217. metadata: {
  2218. originMeta: {
  2219. backgroundSource: "workflow",
  2220. title: "nightly audit",
  2221. workId: "dwfrun-art",
  2222. workflowNotification,
  2223. },
  2224. source: "background_task",
  2225. visibility: "model-only",
  2226. },
  2227. source: "background_task",
  2228. visibility: "model-only",
  2229. });
  2230. const { projection } = reduce([
  2231. background,
  2232. assistantMessage("a-wake-art", "wake-workflow-art", "workflow done", 2001),
  2233. ]);
  2234. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  2235. const restored = (header as { originMeta?: { workflowNotification?: Record<string, unknown> } })
  2236. .originMeta?.workflowNotification;
  2237. expect(restored?.artifacts).toEqual(workflowNotification.artifacts);
  2238. expect(restored?.artifactsTruncated).toBe(true);
  2239. });
  2240. // 畸形产物条目(未知 kind)让整份载荷被 zod 拒掉 → 只丢载荷、保三基字段。发射侧因此必须
  2241. // 在构造前过滤未知 kind,而不是指望读取端救场。
  2242. it("cold hydration 丢弃带未知 artifact kind 的载荷但保留三基字段", () => {
  2243. const background = syntheticUserMessage("wake-workflow-art-bad", "workflow result", 2000, {
  2244. metadata: {
  2245. originMeta: {
  2246. backgroundSource: "workflow",
  2247. title: "nightly audit",
  2248. workId: "dwfrun-art-bad",
  2249. workflowNotification: {
  2250. kind: "terminal",
  2251. status: "completed",
  2252. summary: "nightly audit",
  2253. artifacts: [{ id: "future", kind: "hologram", version: 1 }],
  2254. },
  2255. },
  2256. source: "background_task",
  2257. visibility: "model-only",
  2258. },
  2259. source: "background_task",
  2260. visibility: "model-only",
  2261. });
  2262. const { projection } = reduce([
  2263. background,
  2264. assistantMessage("a-wake-art-bad", "wake-workflow-art-bad", "workflow done", 2001),
  2265. ]);
  2266. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  2267. expect(header).toMatchObject({
  2268. originMeta: {
  2269. backgroundSource: "workflow",
  2270. title: "nightly audit",
  2271. workId: "dwfrun-art-bad",
  2272. },
  2273. });
  2274. expect(
  2275. (header as { originMeta?: { workflowNotification?: unknown } }).originMeta
  2276. ?.workflowNotification,
  2277. ).toBeUndefined();
  2278. });
  2279. it("legacy fork synthetic user 合成为 fork timeline,不合成为 userInput", () => {
  2280. const forkMetadata = {
  2281. forkContext: {
  2282. kind: "session_fork",
  2283. parentSessionId: "sess_parent",
  2284. restoredFileCount: 0,
  2285. targetMessageId: "msg_parent_assistant",
  2286. },
  2287. source: "fork",
  2288. visibility: "user-visible",
  2289. };
  2290. const messages = [
  2291. syntheticUserMessage(
  2292. "u_fork",
  2293. "This session was forked from a previous session message.",
  2294. 1000,
  2295. {
  2296. metadata: forkMetadata,
  2297. source: "fork",
  2298. visibility: "user-visible",
  2299. },
  2300. ),
  2301. ];
  2302. const { events, projection } = reduce(messages);
  2303. expect(events.some((event) => event.type === SessionEventType.TurnStarted)).toBe(false);
  2304. expect(events.some((event) => event.type === SessionEventType.SessionForked)).toBe(true);
  2305. expect(eventsCoverTranscript([], messages)).toBe(false);
  2306. const rows = projection.getSnapshot().rows.window;
  2307. expect(rows.some((row) => row.kind === "userInput")).toBe(false);
  2308. expect(rows).toContainEqual(
  2309. expect.objectContaining({
  2310. kind: "timelineMarker",
  2311. marker: expect.objectContaining({
  2312. parentSessionId: "sess_parent",
  2313. type: "forkNotice",
  2314. }),
  2315. }),
  2316. );
  2317. });
  2318. it("model-only fork raw notice 不重复合成 fork timeline", () => {
  2319. const forkMetadata = {
  2320. forkContext: {
  2321. kind: "session_fork",
  2322. parentSessionId: "sess_parent",
  2323. restoredFileCount: 0,
  2324. targetMessageId: "msg_parent_assistant",
  2325. },
  2326. source: "fork",
  2327. visibility: "model-only",
  2328. };
  2329. const messages = [
  2330. assistantMessageWithParts(
  2331. "a_fork_timeline",
  2332. "u1",
  2333. [
  2334. {
  2335. id: "a_fork_timeline_part" as never,
  2336. sessionID: "s1" as never,
  2337. messageID: "a_fork_timeline" as never,
  2338. type: "timeline",
  2339. timelineType: "session_fork",
  2340. display: "separator",
  2341. status: "completed",
  2342. parentSessionId: "sess_parent" as never,
  2343. targetMessageId: "msg_parent_assistant" as never,
  2344. restoredFileCount: 0,
  2345. },
  2346. ],
  2347. 1000,
  2348. ),
  2349. syntheticUserMessage(
  2350. "u_fork_raw",
  2351. "This session was forked from a previous session message.",
  2352. 1001,
  2353. {
  2354. metadata: forkMetadata,
  2355. semantics: {
  2356. kind: "fork_notice",
  2357. origin: "agent_runtime",
  2358. providerVisibility: "visible",
  2359. source: "fork",
  2360. transcriptVisibility: "hidden",
  2361. uiVisibility: "hidden",
  2362. },
  2363. source: "fork",
  2364. visibility: "model-only",
  2365. },
  2366. ),
  2367. ];
  2368. const { events, projection } = reduce(messages);
  2369. expect(events.filter((event) => event.type === SessionEventType.TurnStarted)).toHaveLength(0);
  2370. expect(events.filter((event) => event.type === SessionEventType.SessionForked)).toHaveLength(1);
  2371. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2372. expect(
  2373. projection
  2374. .getSnapshot()
  2375. .rows.window.filter(
  2376. (row) =>
  2377. row.kind === "timelineMarker" &&
  2378. (row.marker.type === "forkNotice" || row.marker.type === "forkCreated"),
  2379. ),
  2380. ).toHaveLength(1);
  2381. });
  2382. it("assistant reasoning/tool/compact/Agent part → 对应 v4 rows,Agent tool 同时保留 subagent row", () => {
  2383. const agentOutput = JSON.stringify({
  2384. agentId: "agent-1",
  2385. agentType: "Explore",
  2386. childSessionId: "sess_child_1",
  2387. description: "探索项目",
  2388. content: [{ type: "text", text: "子代理总结" }],
  2389. status: "completed",
  2390. });
  2391. const messages = [
  2392. userMessage("u1", "分析一下", 1000),
  2393. assistantMessageWithParts(
  2394. "a1",
  2395. "u1",
  2396. [
  2397. {
  2398. id: "a1-r" as never,
  2399. sessionID: "s1" as never,
  2400. messageID: "a1" as never,
  2401. type: "reasoning",
  2402. text: "先想一想",
  2403. time: { start: 1001, end: 1002 },
  2404. },
  2405. {
  2406. id: "a1-tool-read" as never,
  2407. sessionID: "s1" as never,
  2408. messageID: "a1" as never,
  2409. type: "tool",
  2410. callID: "call-read",
  2411. tool: "Read",
  2412. state: {
  2413. status: "completed",
  2414. input: { file_path: "README.md" },
  2415. output: "README 内容",
  2416. title: "Read README.md",
  2417. metadata: {},
  2418. time: { start: 1002, end: 1003 },
  2419. },
  2420. },
  2421. {
  2422. id: "a1-compact" as never,
  2423. sessionID: "s1" as never,
  2424. messageID: "a1" as never,
  2425. type: "timeline",
  2426. timelineType: "context_compaction",
  2427. display: "separator",
  2428. status: CompactTimelineStatus.Completed,
  2429. operationId: "cmp-1",
  2430. trigger: CompactTrigger.Manual,
  2431. sourceCommandId: "command-compact-cold",
  2432. preCompactTokenCount: 900,
  2433. postCompactTokenCount: 300,
  2434. },
  2435. {
  2436. id: "a1-browser-shot" as never,
  2437. sessionID: "s1" as never,
  2438. messageID: "a1" as never,
  2439. type: "tool",
  2440. callID: "call-browser-shot",
  2441. tool: "mcp__node_repl__js",
  2442. state: {
  2443. status: "completed",
  2444. input: { source: "browser_turn_end" },
  2445. output: "",
  2446. title: "mcp__node_repl__js",
  2447. metadata: {
  2448. schemaVersion: 1,
  2449. display: {
  2450. kind: "node_repl_images",
  2451. source: "browser_turn_end",
  2452. images: [{ base64: "AAAA", mimeType: "image/png" }],
  2453. },
  2454. },
  2455. time: { start: 1003, end: 1003 },
  2456. },
  2457. },
  2458. {
  2459. id: "a1-mcp-tool" as never,
  2460. sessionID: "s1" as never,
  2461. messageID: "a1" as never,
  2462. type: "tool",
  2463. callID: "call-mcp-tool",
  2464. tool: "custom-provider-visible-name",
  2465. state: {
  2466. status: "completed",
  2467. input: { query: "is:open" },
  2468. output: "12 issues",
  2469. title: "custom-provider-visible-name",
  2470. metadata: {
  2471. schemaVersion: 1,
  2472. display: {
  2473. kind: "mcp_tool",
  2474. serverName: "s".repeat(256),
  2475. toolName: "t".repeat(256),
  2476. description: "d".repeat(4 * 1024),
  2477. },
  2478. },
  2479. time: { start: 1003, end: 1004 },
  2480. },
  2481. },
  2482. {
  2483. id: "a1-tool-agent" as never,
  2484. sessionID: "s1" as never,
  2485. messageID: "a1" as never,
  2486. type: "tool",
  2487. callID: "call-agent",
  2488. tool: "Agent",
  2489. state: {
  2490. status: "completed",
  2491. input: { description: "探索项目", prompt: "请探索项目" },
  2492. output: agentOutput,
  2493. title: "Agent 探索项目",
  2494. metadata: {},
  2495. time: { start: 1004, end: 1010 },
  2496. },
  2497. },
  2498. {
  2499. id: "a1-cua-shot" as never,
  2500. sessionID: "s1" as never,
  2501. messageID: "a1" as never,
  2502. type: "tool",
  2503. callID: "call-cua-shot",
  2504. tool: "mcp__computer-use__computer-use",
  2505. state: {
  2506. status: "completed",
  2507. input: { action: "screenshot" },
  2508. output: "[Attached image/jpeg: MCP image]",
  2509. title: "computer-use screenshot",
  2510. metadata: {
  2511. schemaVersion: 1,
  2512. display: {
  2513. kind: "cua",
  2514. schemaVersion: 1,
  2515. toolName: "computer-use",
  2516. status: "success",
  2517. input: '{"action":"screenshot"}',
  2518. media: [{ mimeType: "image/jpeg", data: "AAAA" }],
  2519. },
  2520. },
  2521. time: { start: 1003, end: 1004 },
  2522. },
  2523. },
  2524. {
  2525. id: "a1-t" as never,
  2526. sessionID: "s1" as never,
  2527. messageID: "a1" as never,
  2528. type: "text",
  2529. text: "完成",
  2530. },
  2531. ],
  2532. 1001,
  2533. ),
  2534. ];
  2535. const { events, projection } = reduce(messages);
  2536. const rows = projection.getSnapshot().rows.window;
  2537. expect(eventsCoverTranscript([], messages)).toBe(false);
  2538. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2539. expect(rows.find((row) => row.kind === "reasoning")).toMatchObject({
  2540. text: "先想一想",
  2541. state: "complete",
  2542. });
  2543. expect(
  2544. rows.find((row) => row.kind === "toolCall" && row.toolCallId === "call-read"),
  2545. ).toMatchObject({
  2546. status: "success",
  2547. output: { text: "README 内容" },
  2548. });
  2549. expect(
  2550. rows.find((row) => row.kind === "toolCall" && row.toolCallId === "call-agent"),
  2551. ).toMatchObject({
  2552. status: "success",
  2553. });
  2554. expect(
  2555. rows.find((row) => row.kind === "toolCall" && row.toolCallId === "call-browser-shot"),
  2556. ).toMatchObject({
  2557. status: "success",
  2558. display: { kind: "node_repl_images", source: "browser_turn_end" },
  2559. });
  2560. expect(
  2561. rows.find((row) => row.kind === "toolCall" && row.toolCallId === "call-mcp-tool"),
  2562. ).toMatchObject({
  2563. status: "success",
  2564. display: {
  2565. kind: "mcp_tool",
  2566. serverName: "s".repeat(256),
  2567. toolName: "t".repeat(256),
  2568. description: "d".repeat(4 * 1024),
  2569. },
  2570. });
  2571. expect(
  2572. rows.find((row) => row.kind === "toolCall" && row.toolCallId === "call-cua-shot"),
  2573. ).toMatchObject({
  2574. status: "success",
  2575. output: {
  2576. text: "[Attached image/jpeg: MCP image]",
  2577. display: {
  2578. kind: "cua",
  2579. media: [{ mimeType: "image/jpeg", data: "AAAA" }],
  2580. },
  2581. },
  2582. });
  2583. expect(rows.find((row) => row.kind === "subagent")).toMatchObject({
  2584. childSessionId: "sess_child_1",
  2585. parentToolCallId: "call-agent",
  2586. status: "success",
  2587. subagentType: "Explore",
  2588. summaryText: "子代理总结",
  2589. });
  2590. expect(rows.find((row) => row.kind === "timelineMarker")).toMatchObject({
  2591. lane: "assistantWork",
  2592. sourceCommandId: "command-compact-cold",
  2593. marker: {
  2594. status: "success",
  2595. tokensAfter: 300,
  2596. tokensBefore: 900,
  2597. type: "compact",
  2598. },
  2599. });
  2600. });
  2601. it("失败 MCP 工具的字符串 modelContent 不丢失冷恢复展示信息", () => {
  2602. const display = {
  2603. kind: "mcp_tool",
  2604. serverName: "Document Service",
  2605. toolName: "get_page",
  2606. description: "Fetch page contents",
  2607. } as const;
  2608. const messages = [
  2609. userMessage("u1", "读取页面", 1000),
  2610. assistantMessageWithParts(
  2611. "a1",
  2612. "u1",
  2613. [
  2614. {
  2615. id: "a1-tool" as never,
  2616. sessionID: "s1" as never,
  2617. messageID: "a1" as never,
  2618. type: "tool",
  2619. callID: "call-mcp",
  2620. tool: "mcp__Document_Service__get_page",
  2621. state: {
  2622. status: "error",
  2623. input: {},
  2624. error: "Permission denied",
  2625. metadata: {
  2626. schemaVersion: 1,
  2627. modelContent: "MCP request failed: permission denied",
  2628. display,
  2629. },
  2630. time: { start: 1001, end: 1002 },
  2631. },
  2632. },
  2633. ],
  2634. 1001,
  2635. ),
  2636. ];
  2637. const { projection } = reduce(messages);
  2638. expect(
  2639. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2640. ).toMatchObject({
  2641. status: "error",
  2642. display,
  2643. });
  2644. });
  2645. it("历史 pending/running tool 不复活 active work,冷恢复收口为 cancelled", () => {
  2646. const messages = [
  2647. userMessage("u1", "跑个长任务", 1000),
  2648. assistantMessageWithParts(
  2649. "a1",
  2650. "u1",
  2651. [
  2652. {
  2653. id: "a1-tool" as never,
  2654. sessionID: "s1" as never,
  2655. messageID: "a1" as never,
  2656. type: "tool",
  2657. callID: "call-bash",
  2658. tool: "Bash",
  2659. state: {
  2660. status: "running",
  2661. input: { command: "sleep 100" },
  2662. title: "sleep 100",
  2663. metadata: {
  2664. schemaVersion: 1,
  2665. display: {
  2666. kind: "mcp_tool",
  2667. serverName: "firebase",
  2668. toolName: "read_resources",
  2669. },
  2670. },
  2671. time: { start: 1001 },
  2672. },
  2673. },
  2674. ],
  2675. 1001,
  2676. ),
  2677. ];
  2678. const { projection } = reduce(messages);
  2679. const snapshot = projection.getSnapshot();
  2680. expect(snapshot.control.phase).toBe("completedInterrupted");
  2681. expect(snapshot.control.activeWorks).toEqual([]);
  2682. expect(snapshot.control.canStop).toBe(false);
  2683. expect(snapshot.rows.window.find((row) => row.kind === "toolCall")).toMatchObject({
  2684. status: "cancelled",
  2685. display: { kind: "mcp_tool", serverName: "firebase", toolName: "read_resources" },
  2686. });
  2687. });
  2688. it("eventsCoverTranscript:事件有 turn 但缺 tool footprint → false", () => {
  2689. const messages = [
  2690. userMessage("u1", "读文件", 1000),
  2691. assistantMessageWithParts(
  2692. "a1",
  2693. "u1",
  2694. [
  2695. {
  2696. id: "a1-tool" as never,
  2697. sessionID: "s1" as never,
  2698. messageID: "a1" as never,
  2699. type: "tool",
  2700. callID: "call-read",
  2701. tool: "Read",
  2702. state: {
  2703. status: "completed",
  2704. input: { file_path: "README.md" },
  2705. output: "README",
  2706. title: "Read README.md",
  2707. metadata: {},
  2708. time: { start: 1001, end: 1002 },
  2709. },
  2710. },
  2711. ],
  2712. 1001,
  2713. ),
  2714. ];
  2715. const textOnlyEvents = synthesizeEventsFromMessages(
  2716. [userMessage("u1", "读文件", 1000), assistantMessage("a1", "u1", "", 1001)],
  2717. { sessionId: "s1" },
  2718. );
  2719. expect(eventsCoverTranscript(textOnlyEvents, messages)).toBe(false);
  2720. });
  2721. it.each(["", " \t "])(
  2722. "空名恢复 tool part(%j)不生成冷恢复工具行,也不进入可见 footprint",
  2723. (toolName) => {
  2724. const messages = [
  2725. userMessage("u-empty-tool", "继续", 1000),
  2726. assistantMessageWithParts(
  2727. "a-empty-tool",
  2728. "u-empty-tool",
  2729. [
  2730. {
  2731. id: "a-empty-tool-part" as never,
  2732. sessionID: "s1" as never,
  2733. messageID: "a-empty-tool" as never,
  2734. type: "tool",
  2735. callID: "call-empty-tool",
  2736. tool: toolName,
  2737. state: {
  2738. status: "error",
  2739. input: {},
  2740. error: "Model returned an invalid tool call: tool name is empty.",
  2741. time: { start: 1001, end: 1002 },
  2742. },
  2743. },
  2744. ],
  2745. 1001,
  2746. ),
  2747. ];
  2748. const { events, projection } = reduce(messages);
  2749. expect(projection.getSnapshot().rows.window.filter((row) => row.kind === "toolCall")).toEqual(
  2750. [],
  2751. );
  2752. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2753. },
  2754. );
  2755. it("带原始空名 metadata 的存储占位不生成冷恢复工具行", () => {
  2756. const messages = [
  2757. userMessage("u-empty-tool", "继续", 1000),
  2758. assistantMessageWithParts(
  2759. "a-empty-tool",
  2760. "u-empty-tool",
  2761. [
  2762. {
  2763. id: "a-empty-tool-part" as never,
  2764. sessionID: "s1" as never,
  2765. messageID: "a-empty-tool" as never,
  2766. type: "tool",
  2767. callID: "call-empty-tool",
  2768. tool: "empty_tool_name",
  2769. metadata: { providerToolName: "" },
  2770. state: {
  2771. status: "error",
  2772. input: {},
  2773. error: "Model returned an invalid tool call: tool name is empty.",
  2774. time: { start: 1001, end: 1002 },
  2775. },
  2776. },
  2777. ],
  2778. 1001,
  2779. ),
  2780. ];
  2781. const { events, projection } = reduce(messages);
  2782. expect(projection.getSnapshot().rows.window.filter((row) => row.kind === "toolCall")).toEqual(
  2783. [],
  2784. );
  2785. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2786. });
  2787. it("裸 empty_tool_name 按合法工具生成冷恢复工具行和可见 footprint", () => {
  2788. const messages = [
  2789. userMessage("u-legitimate-tool", "运行工具", 1000),
  2790. assistantMessageWithParts(
  2791. "a-legitimate-tool",
  2792. "u-legitimate-tool",
  2793. [
  2794. {
  2795. id: "a-legitimate-tool-part" as never,
  2796. sessionID: "s1" as never,
  2797. messageID: "a-legitimate-tool" as never,
  2798. type: "tool",
  2799. callID: "call-legitimate-tool",
  2800. tool: "empty_tool_name",
  2801. state: {
  2802. status: "completed",
  2803. input: { value: 1 },
  2804. output: "ok",
  2805. title: "empty_tool_name",
  2806. metadata: {},
  2807. time: { start: 1001, end: 1002 },
  2808. },
  2809. },
  2810. ],
  2811. 1001,
  2812. ),
  2813. ];
  2814. const { events, projection } = reduce(messages);
  2815. expect(
  2816. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2817. ).toMatchObject({
  2818. status: "success",
  2819. toolCallId: "call-legitimate-tool",
  2820. toolName: "empty_tool_name",
  2821. });
  2822. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2823. });
  2824. it("无 user 消息的 transcript → 视为已覆盖(不触发合成)", () => {
  2825. expect(eventsCoverTranscript([], [])).toBe(true);
  2826. });
  2827. it("确定性:同一 transcript 合成两次逐字节相等", () => {
  2828. const messages = [userMessage("u1", "x", 1000), assistantMessage("a1", "u1", "y", 1001)];
  2829. const a = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  2830. const b = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  2831. expect(JSON.stringify(a)).toBe(JSON.stringify(b));
  2832. });
  2833. });
  2834. // ── M5④ 附件渲染:FilePart → 合成 TurnStarted.attachments → row.attachments ──
  2835. describe("transcript 附件合成(M5④)", () => {
  2836. function userMessageWithFile(id: string, text: string, created: number): MessageWithParts {
  2837. const base = userMessage(id, text, created);
  2838. return {
  2839. ...base,
  2840. info: {
  2841. ...base.info,
  2842. anchor: { sourceCommandId: "command-cold" },
  2843. metadata: {
  2844. conversationInputIntent: {
  2845. sourceCommandId: "command-cold",
  2846. queueItemId: "queue_command-cold",
  2847. clientId: "mobile-cold",
  2848. kind: "sendText",
  2849. text,
  2850. attachments: [],
  2851. delivery: { requested: "startNow", admitted: "startNow" },
  2852. order: { admissionSeq: 8 },
  2853. steer: { state: "notRequested" },
  2854. dispatch: { state: "drained" },
  2855. admittedAt: 999,
  2856. },
  2857. },
  2858. },
  2859. parts: [
  2860. ...base.parts,
  2861. {
  2862. id: `${id}-f1` as never,
  2863. sessionID: "s1" as never,
  2864. messageID: id as never,
  2865. type: "file",
  2866. mime: "image/png",
  2867. filename: "diagram.png",
  2868. url: "/workspace/diagram.png",
  2869. metadata: { sizeBytes: 2048 },
  2870. },
  2871. // data URL:无稳定引用 → ref 缺省;filename 缺省 → 序号占位。
  2872. {
  2873. id: `${id}-f2` as never,
  2874. sessionID: "s1" as never,
  2875. messageID: id as never,
  2876. type: "file",
  2877. mime: "text/plain",
  2878. url: "data:text/plain;base64,aGk=",
  2879. },
  2880. ],
  2881. };
  2882. }
  2883. it("file parts 进入 userInput row.attachments(冷路径与 live 同一投影入口)", () => {
  2884. const { projection } = reduce([
  2885. userMessageWithFile("u1", "看图", 1000),
  2886. assistantMessage("a1", "u1", "好的", 2000),
  2887. ]);
  2888. const userInput = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  2889. const attachments = userInput?.kind === "userInput" ? userInput.attachments : undefined;
  2890. expect(userInput).toMatchObject({
  2891. sourceCommandId: "command-cold",
  2892. clientId: "mobile-cold",
  2893. });
  2894. expect(attachments).toHaveLength(2);
  2895. expect(attachments?.[0]).toEqual({
  2896. ref: "/workspace/diagram.png",
  2897. fileName: "diagram.png",
  2898. mime: "image/png",
  2899. bytes: 2048,
  2900. });
  2901. expect(attachments?.[1]).toMatchObject({
  2902. fileName: "attachment-2",
  2903. mime: "text/plain",
  2904. bytes: 0,
  2905. });
  2906. });
  2907. it("无 file part 的消息不带 attachments(合成保持最小序列)", () => {
  2908. const { projection } = reduce([
  2909. userMessage("u1", "纯文本", 1000),
  2910. assistantMessage("a1", "u1", "好的", 2000),
  2911. ]);
  2912. const userInput = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  2913. expect(userInput?.kind === "userInput" ? "attachments" in userInput : null).toBe(false);
  2914. });
  2915. // ── 16-timeline-authority-plan P1 golden ──
  2916. it("GV-cold:goal_verification timeline part 冷恢复后 marker 仍在(含身份/结论/无 goal 状态不丢)", () => {
  2917. const messages = [
  2918. userMessage("u1", "修 lint", 1000),
  2919. assistantMessage("a1", "u1", "修好了", 1001),
  2920. goalVerificationHostMessage("gv1", "a1", 2000, {
  2921. status: "completed",
  2922. goalIteration: 1,
  2923. verification: { passed: true, reason: "全部通过" },
  2924. }),
  2925. ];
  2926. // 空事件日志对含 goal verify 的 transcript 不再被误判为已覆盖(守恒判据曾对此全盲)。
  2927. const turnOnlyEvents = synthesizeEventsFromMessages(
  2928. [userMessage("u1", "修 lint", 1000), assistantMessage("a1", "u1", "修好了", 1001)],
  2929. { sessionId: "s1" },
  2930. );
  2931. expect(eventsCoverTranscript(turnOnlyEvents, messages)).toBe(false);
  2932. const { events, projection } = reduce(messages);
  2933. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2934. const marker = projection
  2935. .getSnapshot()
  2936. .rows.window.find((row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify");
  2937. expect(marker?.kind === "timelineMarker" ? marker.marker : null).toMatchObject({
  2938. type: "goalVerify",
  2939. iteration: 1,
  2940. outcome: "pass",
  2941. });
  2942. // 合成事件流没有 TargetChanged → goal 状态保持 null,但 boundary 不再被整条丢弃。
  2943. expect(projection.getSnapshot().goal).toBeNull();
  2944. });
  2945. it("GV-cold:started 态残留的 verifier 冷恢复收口为 failed(cancelled),不复活 running", () => {
  2946. const { projection } = reduce([
  2947. userMessage("u1", "修 lint", 1000),
  2948. assistantMessage("a1", "u1", "修好了", 1001),
  2949. goalVerificationHostMessage("gv1", "a1", 2000, { status: "started", goalIteration: 2 }),
  2950. ]);
  2951. const marker = projection
  2952. .getSnapshot()
  2953. .rows.window.find((row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify");
  2954. expect(marker?.kind === "timelineMarker" ? marker.marker : null).toMatchObject({
  2955. iteration: 2,
  2956. outcome: "failed",
  2957. detail: "cancelled",
  2958. });
  2959. // 冷恢复不得复活 active work / stop 入口。
  2960. expect(projection.getSnapshot().control.activeWorks).toEqual([]);
  2961. });
  2962. it("MC-cold:相邻轮持久化选型不同 → modelChange marker 重建;首轮不产 marker", () => {
  2963. const messages = [
  2964. userMessageWithModel("u1", "先用 A", 1000, { providerId: "p1", modelId: "m1" }),
  2965. assistantMessage("a1", "u1", "好的", 1001),
  2966. userMessageWithModel("u2", "换 B 再来", 2000, { providerId: "p2", modelId: "m2" }),
  2967. assistantMessage("a2", "u2", "已切换", 2001),
  2968. ];
  2969. const { events, projection } = reduce(messages);
  2970. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2971. const markers = projection
  2972. .getSnapshot()
  2973. .rows.window.filter(
  2974. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  2975. );
  2976. expect(markers).toHaveLength(1);
  2977. expect(markers[0]?.kind === "timelineMarker" ? markers[0].marker : null).toMatchObject({
  2978. type: "modelChange",
  2979. fromProvider: "p1",
  2980. fromModel: "m1",
  2981. toProvider: "p2",
  2982. toModel: "m2",
  2983. });
  2984. // marker 位于第二轮 turnHeader 之前(同 turnId、先 append)。
  2985. const rows = projection.getSnapshot().rows.window;
  2986. const markerIndex = rows.findIndex(
  2987. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  2988. );
  2989. const secondHeaderIndex = rows.findIndex(
  2990. (row, index) =>
  2991. row.kind === "turnHeader" && index > 0 && rows[index]!.turnId === rows[markerIndex]!.turnId,
  2992. );
  2993. expect(markerIndex).toBeGreaterThan(-1);
  2994. expect(secondHeaderIndex).toBe(markerIndex + 1);
  2995. });
  2996. it("MC-cold:Highspeed 单轮执行模型不参与普通模型切换基线", () => {
  2997. const messages = [
  2998. userMessageWithModel("u1", "普通模型执行", 1000, { providerId: "p1", modelId: "m1" }),
  2999. assistantMessage("a1", "u1", "完成", 1001),
  3000. // 加速轮持久化的 Selection 指向隐藏的加速卡内建 Provider,冷恢复必须按 Family 谓词
  3001. // 识别并跳过,不能参与 modelChange 基线。
  3002. userMessageWithModel("u2", "加速执行", 2000, {
  3003. providerId: "account:bigmodel-highspeed-card",
  3004. modelId: "GLM-5.3",
  3005. }),
  3006. assistantMessage("a2", "u2", "加速完成", 2001),
  3007. userMessageWithModel("u3", "继续使用普通模型", 3000, {
  3008. providerId: "p1",
  3009. modelId: "m1",
  3010. }),
  3011. assistantMessage("a3", "u3", "完成", 3001),
  3012. ];
  3013. const { events, projection } = reduce(messages);
  3014. expect(eventsCoverTranscript(events, messages)).toBe(true);
  3015. expect(
  3016. projection
  3017. .getSnapshot()
  3018. .rows.window.filter(
  3019. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  3020. ),
  3021. ).toHaveLength(0);
  3022. });
  3023. it("MC-cold:Highspeed 后真实切换普通模型仍重建原普通模型到新模型的 marker", () => {
  3024. const messages = [
  3025. userMessageWithModel("u1", "普通模型 A", 1000, { providerId: "p1", modelId: "m1" }),
  3026. assistantMessage("a1", "u1", "完成", 1001),
  3027. userMessageWithModel("u2", "加速执行", 2000, {
  3028. providerId: "account:bigmodel-highspeed-card",
  3029. modelId: "GLM-5.3",
  3030. }),
  3031. assistantMessage("a2", "u2", "加速完成", 2001),
  3032. userMessageWithModel("u3", "切换普通模型 B", 3000, {
  3033. providerId: "p2",
  3034. modelId: "m2",
  3035. }),
  3036. assistantMessage("a3", "u3", "完成", 3001),
  3037. ];
  3038. const { events, projection } = reduce(messages);
  3039. const markers = projection
  3040. .getSnapshot()
  3041. .rows.window.filter(
  3042. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  3043. );
  3044. expect(eventsCoverTranscript(events, messages)).toBe(true);
  3045. expect(markers).toHaveLength(1);
  3046. expect(markers[0]).toMatchObject({
  3047. marker: {
  3048. type: "modelChange",
  3049. fromProvider: "p1",
  3050. fromModel: "m1",
  3051. toProvider: "p2",
  3052. toModel: "m2",
  3053. },
  3054. });
  3055. });
  3056. it("MC-cold:source-less model_change 恢复 Subagent 初始模型 marker 且只出现一次", () => {
  3057. const messages = [
  3058. initialModelHostMessage("mc-initial", 900),
  3059. userMessageWithModel("u1", "child prompt", 1000, {
  3060. providerId: "child-provider",
  3061. modelId: "child-model",
  3062. }),
  3063. assistantMessage("a1", "u1", "done", 1001),
  3064. ];
  3065. const { events, projection } = reduce(messages);
  3066. const markers = projection
  3067. .getSnapshot()
  3068. .rows.window.filter(
  3069. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  3070. );
  3071. expect(markers).toHaveLength(1);
  3072. expect(markers[0]).toMatchObject({
  3073. marker: {
  3074. type: "modelChange",
  3075. toProvider: "child-provider",
  3076. toModel: "child-model",
  3077. },
  3078. });
  3079. expect(markers[0]?.kind === "timelineMarker" ? markers[0].marker : {}).not.toHaveProperty(
  3080. "fromModel",
  3081. );
  3082. expect(events.filter((event) => event.type === SessionEventType.ModelSelected)).toEqual([
  3083. expect.objectContaining({
  3084. payload: expect.objectContaining({ previousModelSelection: null }),
  3085. }),
  3086. ]);
  3087. });
  3088. it("assistant-head-skip:首条真实用户消息之前的 assistant 回复不再整段消失", () => {
  3089. // 会话头部是 compact summary(providerContextOnly,非真实用户)→ 其后的 assistant
  3090. // 回复旧实现整段跳过:刷新后「上一轮回复没了」的冷路径向量。
  3091. const messages = [
  3092. syntheticUserMessage("u_sum", "compact 摘要", 900, {
  3093. semantics: { kind: "compact_summary" } as never,
  3094. }),
  3095. assistantMessage("a0", "u_sum", "基于摘要继续的回复", 901),
  3096. userMessage("u1", "下一个问题", 2000),
  3097. assistantMessage("a1", "u1", "答", 2001),
  3098. ];
  3099. const { projection } = reduce(messages);
  3100. const rows = projection.getSnapshot().rows.window;
  3101. const assistantTexts = rows
  3102. .filter((row) => row.kind === "assistantText")
  3103. .map((row) => (row.kind === "assistantText" ? row.text : ""));
  3104. expect(assistantTexts).toEqual(["基于摘要继续的回复", "答"]);
  3105. // preface 轮是 model-only:不产可见 user 气泡,可见 user 轮数不受影响。
  3106. const userRows = rows.filter((row) => row.kind === "userInput");
  3107. expect(userRows).toHaveLength(1);
  3108. expect(rows.filter((row) => row.kind === "turnHeader")).toHaveLength(2);
  3109. });
  3110. it("GV-cold-session_entry:goal verify 只存在 legacy session_entry 时冷恢复可重建(含生命周期合并/锚定落位)", () => {
  3111. const messages = [
  3112. userMessage("u1", "修 lint", 1000),
  3113. assistantMessage("a1", "u1", "修好了", 1001),
  3114. userMessage("u2", "再看看测试", 2000),
  3115. assistantMessage("a2", "u2", "测试也过了", 2001),
  3116. ];
  3117. // legacy 形态:同一 verification 的 started/terminal 各一条 entry,无 timeline part。
  3118. const goalVerificationEntries = [
  3119. {
  3120. payload: {
  3121. targetId: "target-1",
  3122. status: "started",
  3123. verificationId: "v1",
  3124. goalIteration: 1,
  3125. anchorAssistantMessageId: "a1",
  3126. },
  3127. sequenceNumber: 5,
  3128. timeCreated: 1500,
  3129. },
  3130. {
  3131. payload: {
  3132. targetId: "target-1",
  3133. status: "completed",
  3134. verificationId: "v1",
  3135. goalIteration: 1,
  3136. anchorAssistantMessageId: "a1",
  3137. verification: { passed: true, reason: "ok" },
  3138. },
  3139. sequenceNumber: 9,
  3140. timeCreated: 1600,
  3141. },
  3142. ];
  3143. // 覆盖判据必须看见 entry 源:空事件日志不再被误判为已覆盖。
  3144. const turnOnlyEvents = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  3145. expect(eventsCoverTranscript(turnOnlyEvents, messages, { goalVerificationEntries })).toBe(
  3146. false,
  3147. );
  3148. const events = synthesizeEventsFromMessages(messages, {
  3149. sessionId: "s1",
  3150. goalVerificationEntries,
  3151. });
  3152. expect(eventsCoverTranscript(events, messages, { goalVerificationEntries })).toBe(true);
  3153. const projection = new ProductProjection("s1", "epoch");
  3154. for (const event of events) projection.applyEvent(event);
  3155. const rows = projection.getSnapshot().rows.window;
  3156. const markers = rows.filter(
  3157. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  3158. );
  3159. // 生命周期两条 entry 合并为单一 marker,终态覆盖 started。
  3160. expect(markers).toHaveLength(1);
  3161. expect(markers[0]?.kind === "timelineMarker" ? markers[0].marker : null).toMatchObject({
  3162. iteration: 1,
  3163. outcome: "pass",
  3164. });
  3165. // 锚定落位:marker 归属 a1 所在的第一轮(turn tail),不漂到第二轮之后。
  3166. const markerIndex = rows.findIndex(
  3167. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  3168. );
  3169. const secondTurnFirstIndex = rows.findIndex(
  3170. (row) => row.kind === "userInput" && row.text === "再看看测试",
  3171. );
  3172. expect(markerIndex).toBeGreaterThan(-1);
  3173. expect(markerIndex).toBeLessThan(secondTurnFirstIndex);
  3174. });
  3175. it("GV 跨源去重:timeline part 与 session_entry 表达同一事实 → 单一 marker;无 anchor 的 entry 落尾不丢", () => {
  3176. const messages = [
  3177. userMessage("u1", "修 lint", 1000),
  3178. assistantMessage("a1", "u1", "修好了", 1001),
  3179. goalVerificationHostMessage("gv1", "a1", 1500, {
  3180. status: "completed",
  3181. goalIteration: 1,
  3182. verification: { passed: true, reason: "ok" },
  3183. }),
  3184. ];
  3185. const goalVerificationEntries = [
  3186. // 与 part 同 key(target-1_1):去重,不产生第二个 marker。
  3187. {
  3188. payload: {
  3189. targetId: "target-1",
  3190. status: "completed",
  3191. verificationId: "verify-gv1",
  3192. goalIteration: 1,
  3193. anchorAssistantMessageId: "a1",
  3194. verification: { passed: true, reason: "ok" },
  3195. },
  3196. timeCreated: 1500,
  3197. },
  3198. // 无 anchor 的孤儿 entry(iteration 2):落到已知时间线末尾,不静默丢。
  3199. {
  3200. payload: {
  3201. targetId: "target-1",
  3202. status: "completed",
  3203. verificationId: "v-orphan",
  3204. goalIteration: 2,
  3205. verification: { passed: false, reason: "还差一点" },
  3206. },
  3207. timeCreated: 1700,
  3208. },
  3209. ];
  3210. const events = synthesizeEventsFromMessages(messages, {
  3211. sessionId: "s1",
  3212. goalVerificationEntries,
  3213. });
  3214. const projection = new ProductProjection("s1", "epoch");
  3215. for (const event of events) projection.applyEvent(event);
  3216. const markers = projection
  3217. .getSnapshot()
  3218. .rows.window.filter(
  3219. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  3220. );
  3221. expect(markers.map((row) => (row.kind === "timelineMarker" ? row.marker : null))).toEqual([
  3222. expect.objectContaining({ iteration: 1, outcome: "pass" }),
  3223. expect.objectContaining({ iteration: 2, outcome: "notSatisfied" }),
  3224. ]);
  3225. });
  3226. it("S1 cold:guide steer 持久标记内联当前轮;queue 标记独立轮(与 live 切分一致)", () => {
  3227. const withDelivery = (
  3228. message: MessageWithParts,
  3229. delivery: "guide" | "queue",
  3230. ): MessageWithParts => ({
  3231. ...message,
  3232. info: {
  3233. ...message.info,
  3234. metadata: { turnSteerDelivery: delivery },
  3235. } as MessageWithParts["info"],
  3236. });
  3237. const messages = [
  3238. userMessage("u1", "问题一", 1000),
  3239. assistantMessage("a1", "u1", "回答一", 1001),
  3240. withDelivery(userMessage("u_steer", "补充说明", 1500), "guide"),
  3241. assistantMessage("a2", "u1", "回答二", 1600),
  3242. withDelivery(userMessage("u_q2", "排队问题", 2000), "queue"),
  3243. assistantMessage("a3", "u_q2", "排队回答", 2001),
  3244. ];
  3245. const { projection } = reduce(messages);
  3246. const rows = projection.getSnapshot().rows.window;
  3247. // guide steer 内联:u_steer 与 a1/a2 同轮;queue 项独立轮。
  3248. const visible = rows
  3249. .filter((row) => row.kind === "userInput" || row.kind === "assistantText")
  3250. .map((row) => [
  3251. row.turnId,
  3252. row.kind === "userInput" || row.kind === "assistantText" ? row.text : "",
  3253. ]);
  3254. expect(visible).toEqual([
  3255. ["u1", "问题一"],
  3256. ["u1", "回答一"],
  3257. ["u1", "补充说明"],
  3258. ["u1", "回答二"],
  3259. ["u_q2", "排队问题"],
  3260. ["u_q2", "排队回答"],
  3261. ]);
  3262. expect(rows.filter((row) => row.kind === "turnHeader")).toHaveLength(2);
  3263. // 内联 steer 行登记了持久 messageId(entityId 派生)。
  3264. const steerRow = rows.find((row) => row.kind === "userInput" && row.text === "补充说明");
  3265. expect(projection.getMessageIdForRow(steerRow!.rowId)).toBe("u_steer");
  3266. const guideHeader = rows.find((row) => row.kind === "turnHeader" && row.turnId === "u1");
  3267. expect(guideHeader).toMatchObject({
  3268. workSegments: [
  3269. { segmentId: "u1:initial", startedAt: 1000, endedAt: 1500, activeMs: 500 },
  3270. {
  3271. segmentId: "u_steer",
  3272. triggerEntityId: "u_steer",
  3273. startedAt: 1500,
  3274. endedAt: 1601,
  3275. activeMs: 101,
  3276. },
  3277. ],
  3278. });
  3279. });
  3280. it.each([
  3281. ["中间没有 assistant:同一次取出,共用一段", false, ["u1:initial", "u_g1"]],
  3282. [
  3283. "中间有一条没有可见内容的 assistant:两次取出,各开一段",
  3284. true,
  3285. ["u1:initial", "u_g1", "u_g2"],
  3286. ],
  3287. ])("M06f cold:相邻两条 guide,%s", (_label, hiddenStepBetween, segmentIds) => {
  3288. const guide = (id: string, text: string, created: number): MessageWithParts => {
  3289. const message = userMessage(id, text, created);
  3290. return {
  3291. ...message,
  3292. info: {
  3293. ...message.info,
  3294. metadata: { turnSteerDelivery: "guide" },
  3295. } as MessageWithParts["info"],
  3296. };
  3297. };
  3298. const messages = [
  3299. userMessage("u1", "问题一", 1000),
  3300. assistantMessage("a1", "u1", "回答一", 1001),
  3301. guide("u_g1", "引导一", 1500),
  3302. ...(hiddenStepBetween ? [assistantMessage("a_hidden", "u1", "", 1550)] : []),
  3303. guide("u_g2", "引导二", 1600),
  3304. assistantMessage("a2", "u1", "回答二", 1700),
  3305. ];
  3306. const rows = reduce(messages).projection.getSnapshot().rows.window;
  3307. const header = rows.find((row) => row.kind === "turnHeader");
  3308. expect(
  3309. header?.kind === "turnHeader"
  3310. ? header.workSegments?.map((segment) => segment.segmentId)
  3311. : undefined,
  3312. ).toEqual(segmentIds);
  3313. });
  3314. it("S1 cold:guide steer 从持久 metadata 恢复完整 intent,row 与 live 字段保真", () => {
  3315. const guide = userMessage("u_guide", "带附件补充", 1500);
  3316. const attachment = {
  3317. ref: "attachment://guide-1",
  3318. fileName: "guide.png",
  3319. mime: "image/png",
  3320. bytes: 2048,
  3321. previewRef: "preview://guide-1",
  3322. };
  3323. const messages: MessageWithParts[] = [
  3324. userMessage("u1", "问题一", 1000),
  3325. assistantMessage("a1", "u1", "回答一", 1001),
  3326. {
  3327. ...guide,
  3328. info: {
  3329. ...guide.info,
  3330. anchor: { sourceCommandId: "command-guide-1" },
  3331. metadata: {
  3332. turnSteerDelivery: "guide",
  3333. conversationInputIntent: {
  3334. sourceCommandId: "command-guide-1",
  3335. queueItemId: "queue_command-guide-1",
  3336. clientId: "mobile-guide",
  3337. kind: "sendGoalCommand",
  3338. text: "带附件补充",
  3339. attachments: [attachment],
  3340. delivery: {
  3341. requested: "guide",
  3342. admitted: "guide",
  3343. fallbackReasonCode: "guide_fallback_test",
  3344. },
  3345. order: { admissionSeq: 19, queuePosition: 2 },
  3346. steer: { state: "guided" },
  3347. dispatch: { state: "drained" },
  3348. admittedAt: 1499,
  3349. },
  3350. },
  3351. } as MessageWithParts["info"],
  3352. },
  3353. assistantMessage("a2", "u1", "回答二", 1600),
  3354. ];
  3355. const events = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  3356. const drained = events.find((event) => event.type === SessionEventType.TurnSteerDrained);
  3357. expect(drained?.payload).toMatchObject({
  3358. pendingInputIds: ["queue_command-guide-1"],
  3359. drainedInputs: [
  3360. {
  3361. pendingInputId: "queue_command-guide-1",
  3362. messageId: "u_guide",
  3363. text: "带附件补充",
  3364. delivery: "guide",
  3365. intent: {
  3366. sourceCommandId: "command-guide-1",
  3367. queueItemId: "queue_command-guide-1",
  3368. clientId: "mobile-guide",
  3369. kind: "sendGoalCommand",
  3370. admissionSeq: 19,
  3371. queuePosition: 2,
  3372. admittedAt: 1499,
  3373. requestedDelivery: "guide",
  3374. admittedDelivery: "guide",
  3375. fallbackReasonCode: "guide_fallback_test",
  3376. attachmentRefs: [attachment],
  3377. },
  3378. },
  3379. ],
  3380. });
  3381. const projection = new ProductProjection("s1", "epoch");
  3382. for (const event of events) projection.applyEvent(event);
  3383. const row = projection
  3384. .getSnapshot()
  3385. .rows.window.find((candidate) => candidate.kind === "userInput" && candidate.guided);
  3386. expect(row).toMatchObject({
  3387. turnId: "u1",
  3388. text: "带附件补充",
  3389. guided: true,
  3390. sourceCommandId: "command-guide-1",
  3391. clientId: "mobile-guide",
  3392. attachments: [attachment],
  3393. });
  3394. });
  3395. it("timeline 宿主消息(model_change)不开 preface 空轮", () => {
  3396. const messages = [
  3397. userMessageWithModel("u1", "先用 A", 1000, { providerId: "p1", modelId: "m1" }),
  3398. assistantMessage("a1", "u1", "好的", 1001),
  3399. modelChangeHostMessage("mc1", "a1", 1500),
  3400. userMessageWithModel("u2", "换 B", 2000, { providerId: "p2", modelId: "m2" }),
  3401. assistantMessage("a2", "u2", "已切换", 2001),
  3402. ];
  3403. const { projection } = reduce(messages);
  3404. const rows = projection.getSnapshot().rows.window;
  3405. // 宿主消息本身无可渲染内容:不产生第三个 turnHeader,也不产生空「已工作」壳。
  3406. expect(rows.filter((row) => row.kind === "turnHeader")).toHaveLength(2);
  3407. // marker 仍由选型事实重建(宿主的 defaultModelSelection 占位不参与选型来源)。
  3408. expect(
  3409. rows.filter((row) => row.kind === "timelineMarker" && row.marker.type === "modelChange"),
  3410. ).toHaveLength(1);
  3411. });
  3412. it("MC-cold:model_change timeline part 在后续 user model 快照滞后时仍是边界权威", () => {
  3413. const messages = [
  3414. userMessageWithModel("u1", "先用 A", 1000, { providerId: "p1", modelId: "m1" }),
  3415. assistantMessage("a1", "u1", "好的", 1001),
  3416. modelChangeHostMessage("mc1", "a1", 1500),
  3417. syntheticUserMessage("legacy-context", "internal context", 1600, {
  3418. source: "rewind",
  3419. visibility: "model-only",
  3420. }),
  3421. // 模拟旧数据:user message 仍带上一轮快照,但 timeline part 已持久 p2/m2。
  3422. userMessageWithModel("u2", "换 B", 2000, { providerId: "p1", modelId: "m1" }),
  3423. assistantMessage("a2", "u2", "已切换", 2001),
  3424. ];
  3425. const { events, projection } = reduce(messages);
  3426. const marker = projection
  3427. .getSnapshot()
  3428. .rows.window.find(
  3429. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  3430. );
  3431. expect(marker).toEqual(
  3432. expect.objectContaining({
  3433. marker: expect.objectContaining({
  3434. fromProvider: "p1",
  3435. fromModel: "m1",
  3436. toProvider: "p2",
  3437. toModel: "m2",
  3438. }),
  3439. }),
  3440. );
  3441. expect(
  3442. eventsCoverTranscript(
  3443. events.filter((event) => event.type !== SessionEventType.ModelSelected),
  3444. messages,
  3445. ),
  3446. ).toBe(false);
  3447. });
  3448. });
  3449. function userMessageWithModel(
  3450. id: string,
  3451. text: string,
  3452. created: number,
  3453. model: { providerId: string; modelId: string; reasoningLevel?: string },
  3454. ): MessageWithParts {
  3455. const base = userMessage(id, text, created);
  3456. return {
  3457. ...base,
  3458. info: {
  3459. ...base.info,
  3460. modelSelection: {
  3461. providerId: model.providerId as never,
  3462. modelId: model.modelId as never,
  3463. ...(model.reasoningLevel ? { options: { reasoningLevel: model.reasoningLevel } } : {}),
  3464. },
  3465. } as MessageWithParts["info"],
  3466. };
  3467. }
  3468. const TIMELINE_HOST_SEMANTICS = {
  3469. origin: "system",
  3470. kind: "timeline_event",
  3471. uiVisibility: "visible",
  3472. providerVisibility: "hidden",
  3473. transcriptVisibility: "visible",
  3474. } as never;
  3475. function goalVerificationHostMessage(
  3476. id: string,
  3477. parentId: string,
  3478. created: number,
  3479. overrides: {
  3480. status: string;
  3481. goalIteration?: number;
  3482. verification?: { passed: boolean; reason: string };
  3483. },
  3484. ): MessageWithParts {
  3485. const base = assistantMessage(id, parentId, "", created);
  3486. return {
  3487. ...base,
  3488. info: { ...base.info, semantics: TIMELINE_HOST_SEMANTICS } as MessageWithParts["info"],
  3489. parts: [
  3490. {
  3491. id: `${id}-timeline` as never,
  3492. sessionID: "s1" as never,
  3493. messageID: id as never,
  3494. type: "timeline",
  3495. timelineType: "goal_verification",
  3496. display: "separator",
  3497. status: overrides.status,
  3498. targetId: "target-1",
  3499. verificationId: `verify-${id}`,
  3500. ...(overrides.goalIteration !== undefined
  3501. ? { goalIteration: overrides.goalIteration }
  3502. : {}),
  3503. anchorMessageId: parentId as never,
  3504. ...(overrides.verification ? { verification: overrides.verification } : {}),
  3505. } as MessagePart,
  3506. ],
  3507. };
  3508. }
  3509. function modelChangeHostMessage(id: string, parentId: string, created: number): MessageWithParts {
  3510. const base = assistantMessage(id, parentId, "", created);
  3511. return {
  3512. ...base,
  3513. info: { ...base.info, semantics: TIMELINE_HOST_SEMANTICS } as MessageWithParts["info"],
  3514. parts: [
  3515. {
  3516. id: `${id}-timeline` as never,
  3517. sessionID: "s1" as never,
  3518. messageID: id as never,
  3519. type: "timeline",
  3520. timelineType: "model_change",
  3521. display: "separator",
  3522. status: "completed",
  3523. anchorMessageId: parentId as never,
  3524. fromModel: { providerId: "p1" as never, modelId: "m1" as never, label: "A" },
  3525. toModel: { providerId: "p2" as never, modelId: "m2" as never, label: "B" },
  3526. } as MessagePart,
  3527. ],
  3528. };
  3529. }
  3530. function initialModelHostMessage(id: string, created: number): MessageWithParts {
  3531. // 首条 timeline 事实没有上一条 conversation message,运行时会把 parentID
  3532. // 固定为自身。测试必须保持这一真实持久化形态,防止冷恢复只在理想夹具下通过。
  3533. const base = assistantMessage(id, id, "", created);
  3534. return {
  3535. ...base,
  3536. info: { ...base.info, semantics: TIMELINE_HOST_SEMANTICS } as MessageWithParts["info"],
  3537. parts: [
  3538. {
  3539. id: `${id}-timeline` as never,
  3540. sessionID: "s1" as never,
  3541. messageID: id as never,
  3542. type: "timeline",
  3543. timelineType: "model_change",
  3544. display: "separator",
  3545. status: "completed",
  3546. toModel: {
  3547. providerId: "child-provider" as never,
  3548. modelId: "child-model" as never,
  3549. label: "Child Model",
  3550. },
  3551. } as MessagePart,
  3552. ],
  3553. };
  3554. }
  3555. // 中枢直接启动已保存工作流的启动轮(docs/dynamic-workflow/launch.md):冷恢复由 source
  3556. // "workflow_launch" + metadata.workflowLaunch 重建可见 controlOnly 启动轮。这条消息是 synthetic
  3557. // 却语义上属用户真实动作,共享 policy 会把它归成 hiddenSynthetic;若无专用分支就会被跳过。
  3558. // 断言:冷路径产出的 turnHeader/userInput 行在相关字段上与活投影逐字相等(origin/executionKind/
  3559. // text/workflowLaunch),且无助手行。
  3560. describe("workflow-direct-launch 启动轮冷恢复", () => {
  3561. const workflowLaunch = {
  3562. runId: "dwfrun-9",
  3563. toolCallId: "launch-abc",
  3564. name: "deep-research",
  3565. scope: "global" as const,
  3566. path: "/home/u/.zcode/workflows/deep-research.ts",
  3567. args: { topic: "adaptive concurrency" },
  3568. description: "Deep-dive a topic",
  3569. };
  3570. const launchText = 'Started the saved workflow "deep-research" (global) as run dwfrun-9.';
  3571. // GUI「配置」的设置轮(docs/dynamic-workflow/launch.md「The settings turn」):同一条冷路径,元数据
  3572. // 没有 scope / path,多一块 amend。
  3573. const settingsLaunch = {
  3574. runId: "dwfrun-10",
  3575. toolCallId: "settings-abc",
  3576. name: "deep-research",
  3577. amend: {
  3578. predecessorRunId: "dwfrun-9",
  3579. maxConcurrency: { from: 13, to: 4 },
  3580. ceiling: 13,
  3581. },
  3582. };
  3583. function launchMessage(meta: object = workflowLaunch): MessageWithParts {
  3584. return syntheticUserMessage("message-launch-1", launchText, 1_700_000_000_000, {
  3585. source: "workflow_launch",
  3586. visibility: "user-visible",
  3587. metadata: { workflowLaunch: meta },
  3588. semantics: {
  3589. origin: "real_user",
  3590. kind: "user_prompt",
  3591. source: "workflow_launch",
  3592. uiVisibility: "visible",
  3593. providerVisibility: "visible",
  3594. transcriptVisibility: "visible",
  3595. } as MessageWithParts["info"]["semantics"],
  3596. });
  3597. }
  3598. // 相关字段投影:跨 live/cold 稳定(不含 rowId / turnId / createdAt 这些身份差异字段)。
  3599. function relevantRow(row: Record<string, unknown>): Record<string, unknown> {
  3600. return {
  3601. kind: row.kind,
  3602. origin: row.origin,
  3603. ...(row.executionKind !== undefined ? { executionKind: row.executionKind } : {}),
  3604. ...(row.state !== undefined ? { state: row.state } : {}),
  3605. ...(row.text !== undefined ? { text: row.text } : {}),
  3606. ...(row.workflowLaunch !== undefined ? { workflowLaunch: row.workflowLaunch } : {}),
  3607. };
  3608. }
  3609. function liveRows(meta: object = workflowLaunch): Record<string, unknown>[] {
  3610. const projection = new ProductProjection("s1", "epoch");
  3611. const base = (seq: number) => ({
  3612. id: `event-${seq}` as never,
  3613. sessionId: "s1" as never,
  3614. traceId: "trace-live" as never,
  3615. sequenceNumber: seq,
  3616. timestamp: new Date(1_700_000_000_000 + seq),
  3617. });
  3618. const events: SessionEvent[] = [
  3619. {
  3620. ...base(1),
  3621. type: SessionEventType.SessionCreated,
  3622. payload: { mode: "default", contextWindow: 200_000 },
  3623. } as unknown as SessionEvent,
  3624. {
  3625. ...base(2),
  3626. turnId: "turn-launch" as never,
  3627. type: SessionEventType.TurnStarted,
  3628. payload: {
  3629. turnNumber: 1,
  3630. input: launchText,
  3631. messageId: "message-launch-1",
  3632. executionKind: "controlOnly",
  3633. inputSource: "workflow_launch",
  3634. workflowLaunch: meta,
  3635. },
  3636. } as unknown as SessionEvent,
  3637. {
  3638. ...base(3),
  3639. turnId: "turn-launch" as never,
  3640. type: SessionEventType.TurnComplete,
  3641. payload: {
  3642. response: "",
  3643. tokenCount: 0,
  3644. toolCallCount: 0,
  3645. duration: 0,
  3646. resultType: "success",
  3647. },
  3648. } as unknown as SessionEvent,
  3649. ];
  3650. for (const event of events) projection.applyEvent(event);
  3651. return projection
  3652. .getSnapshot()
  3653. .rows.window.map((row) => relevantRow(row as Record<string, unknown>));
  3654. }
  3655. it("冷恢复重建双行(origin=workflowLaunch + 元数据),且与活投影相关字段逐字相等,无助手行", () => {
  3656. const { projection } = reduce([launchMessage()]);
  3657. const coldRows = projection
  3658. .getSnapshot()
  3659. .rows.window.map((row) => relevantRow(row as Record<string, unknown>));
  3660. expect(coldRows).toEqual([
  3661. {
  3662. kind: "turnHeader",
  3663. origin: "workflowLaunch",
  3664. executionKind: "controlOnly",
  3665. state: "completedSuccess",
  3666. workflowLaunch,
  3667. },
  3668. {
  3669. kind: "userInput",
  3670. origin: "workflowLaunch",
  3671. text: launchText,
  3672. workflowLaunch,
  3673. },
  3674. ]);
  3675. // 冷热同形:相关字段逐字相等(rowId/turnId 等身份字段除外)。
  3676. expect(coldRows).toEqual(liveRows());
  3677. });
  3678. it("设置轮(无 scope / path、带 amend 块)走同一条冷路径,冷热同形", () => {
  3679. const { projection } = reduce([launchMessage(settingsLaunch)]);
  3680. const coldRows = projection
  3681. .getSnapshot()
  3682. .rows.window.map((row) => relevantRow(row as Record<string, unknown>));
  3683. expect(coldRows).toEqual([
  3684. {
  3685. kind: "turnHeader",
  3686. origin: "workflowLaunch",
  3687. executionKind: "controlOnly",
  3688. state: "completedSuccess",
  3689. workflowLaunch: settingsLaunch,
  3690. },
  3691. {
  3692. kind: "userInput",
  3693. origin: "workflowLaunch",
  3694. text: launchText,
  3695. workflowLaunch: settingsLaunch,
  3696. },
  3697. ]);
  3698. expect(coldRows).toEqual(liveRows(settingsLaunch));
  3699. });
  3700. });
  3701. // docs/dynamic-workflow/transcript-and-notifications.md:冷路径从用户消息 metadata 读回边界,
  3702. // 与热路径落在同一个 TurnStarted 字段上;非非负整数按缺席处理。
  3703. describe("epilogueStart 冷恢复", () => {
  3704. function turnStartedOf(events: SessionEvent[], messageId: string) {
  3705. return events.find(
  3706. (event) =>
  3707. event.type === SessionEventType.TurnStarted &&
  3708. (event.payload as { messageId?: string }).messageId === messageId,
  3709. );
  3710. }
  3711. it("metadata.epilogueStart → TurnStarted.epilogueStart → userInput 行", () => {
  3712. const ask = userMessage("u-ask", "Summarize\n\n---\nStandard", 1000);
  3713. ask.info.metadata = { epilogueStart: 9 };
  3714. const nudge = userMessage("u-nudge", "You ended your turn without submitting a result.", 2000);
  3715. nudge.info.metadata = { epilogueStart: 0 };
  3716. const plain = userMessage("u-plain", "plain", 3000);
  3717. const bogus = userMessage("u-bogus", "bogus", 4000);
  3718. bogus.info.metadata = { epilogueStart: -3 };
  3719. const events = synthesizeEventsFromMessages([ask, nudge, plain, bogus], { sessionId: "s1" });
  3720. expect(turnStartedOf(events, "u-ask")?.payload).toMatchObject({ epilogueStart: 9 });
  3721. expect(turnStartedOf(events, "u-nudge")?.payload).toMatchObject({ epilogueStart: 0 });
  3722. expect(turnStartedOf(events, "u-plain")?.payload).not.toHaveProperty("epilogueStart");
  3723. expect(turnStartedOf(events, "u-bogus")?.payload).not.toHaveProperty("epilogueStart");
  3724. const projection = new ProductProjection("s1", "epoch");
  3725. for (const event of events) projection.applyEvent(event);
  3726. const rows = projection.getSnapshot().rows.window.filter((row) => row.kind === "userInput");
  3727. expect(rows.map((row) => (row.kind === "userInput" ? row.epilogueStart : null))).toEqual([
  3728. 9,
  3729. 0,
  3730. undefined,
  3731. undefined,
  3732. ]);
  3733. });
  3734. });
  3735. it("cold canonical input retains Gen UI context for edit/retry while rows expose only text", () => {
  3736. const message = userMessage("gen-ui-input", "Question", 1000);
  3737. const genUiContext = [{ path: "/project/page.html", state: "FROZEN_CONTEXT" }];
  3738. message.info.metadata = {
  3739. conversationInputIntent: {
  3740. sourceCommandId: "gen-ui-command",
  3741. queueItemId: "gen-ui-queue",
  3742. clientId: "desktop",
  3743. kind: "sendText",
  3744. text: "Question",
  3745. genUiContext,
  3746. attachments: [],
  3747. delivery: { requested: "startNow", admitted: "startNow" },
  3748. order: { admissionSeq: 1 },
  3749. steer: { state: "notRequested" },
  3750. dispatch: { state: "drained" },
  3751. admittedAt: 999,
  3752. },
  3753. };
  3754. const { projection } = reduce([
  3755. message,
  3756. assistantMessage("gen-ui-reply", "gen-ui-input", "Done", 1001),
  3757. ]);
  3758. expect(projection.resolveEditTargetByEntityId("gen-ui-input")?.intent).toMatchObject({
  3759. text: "Question",
  3760. genUiContext,
  3761. });
  3762. expect(JSON.stringify(projection.getSnapshot().rows)).not.toContain("FROZEN_CONTEXT");
  3763. });