tui-chat-controller.test.ts 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747
  1. import { describe, expect, it, vi } from 'vitest';
  2. import type { SendMessageReq } from '@mavis/local-runtime-v2/cli-service';
  3. import { TuiFailure } from '../../src/failure.js';
  4. import {
  5. TuiChatController as ProductionTuiChatController,
  6. type CreateTuiChatControllerOptions,
  7. } from '../../src/tui/controller/chat-controller.js';
  8. import type { TuiStreamEvent } from '../../src/runtime/stream-events.js';
  9. import { TranscriptStore } from '../../src/tui/transcript/store.js';
  10. import { TranscriptView } from '../../src/tui/transcript/view.js';
  11. import { TuiRunCoordinator, type TuiRunRuntime } from '../../src/application/run-coordinator.js';
  12. import { resolveTuiVisiblePresentation } from '../../src/tui/controller/projection/visible-presentation.js';
  13. import { TuiActivityLine } from '../../src/tui/shell/activity-line.js';
  14. import { isQuestionnaireTool } from '../../src/tui/controller/projection/turn-tool-projection.js';
  15. class TuiChatController extends ProductionTuiChatController {
  16. constructor(options: CreateTuiChatControllerOptions) {
  17. super(options);
  18. }
  19. }
  20. describe('TuiChatController', () => {
  21. it('hides plain and namespaced AskUser protocol tools from the transcript', () => {
  22. expect(isQuestionnaireTool('ask_user')).toBe(true);
  23. expect(isQuestionnaireTool('functions.AskUser')).toBe(true);
  24. expect(isQuestionnaireTool('tools.ask_user_question')).toBe(true);
  25. expect(isQuestionnaireTool('read_file')).toBe(false);
  26. });
  27. it('shows estimated output throughput while a text response is still streaming', async () => {
  28. let nowMs = 0;
  29. let releaseResponse: (() => void) | undefined;
  30. const responseGate = new Promise<void>((resolve) => {
  31. releaseResponse = resolve;
  32. });
  33. const runtime = {
  34. createSession: vi.fn(async () => ({ sessionId: 'session-live-output-rate' })),
  35. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  36. yield {
  37. type: 'delta',
  38. turnId: 'turn-live-output-rate',
  39. messageId: 'message-live-output-rate',
  40. content: 'hello',
  41. timestamp: 1_000,
  42. };
  43. nowMs = 250;
  44. yield {
  45. type: 'delta',
  46. turnId: 'turn-live-output-rate',
  47. messageId: 'message-live-output-rate',
  48. content: ' world',
  49. timestamp: 2_000,
  50. };
  51. await responseGate;
  52. yield {
  53. type: 'delta',
  54. turnId: 'turn-live-output-rate',
  55. messageId: 'message-live-output-rate',
  56. finish: true,
  57. timestamp: 3_000,
  58. };
  59. yield {
  60. type: 'message',
  61. message: {
  62. id: 'message-live-output-rate',
  63. turnId: 'turn-live-output-rate',
  64. role: 'assistant',
  65. content: 'hello world',
  66. usage: { outputTokens: 126, requestDurationMs: 2_000 },
  67. },
  68. };
  69. yield { type: 'done', turnId: 'turn-live-output-rate' };
  70. }),
  71. abortSession: vi.fn(async () => true),
  72. };
  73. const transcript = new TranscriptStore();
  74. const controller = new ProductionTuiChatController({
  75. runtime: runtime as never,
  76. transcript,
  77. workspaceDir: '/workspace',
  78. createTurnId: () => 'turn-live-output-rate',
  79. now: () => nowMs,
  80. });
  81. const submission = controller.submit('Say hello');
  82. await vi.waitFor(() =>
  83. expect(controller.snapshot()).toMatchObject({
  84. activeTurnId: 'turn-live-output-rate',
  85. outputTokensPerSecond: 2,
  86. outputTokensPerSecondEstimated: true,
  87. }),
  88. );
  89. const snapshot = controller.snapshot();
  90. const presentation = resolveTuiVisiblePresentation({
  91. snapshot,
  92. connection: { phase: 'live', generation: 1 },
  93. surface: 'conversation',
  94. currentLiveRunId: snapshot.activeTurnId,
  95. transcript,
  96. runtimeQueuedCount: 0,
  97. queueEnabled: true,
  98. activePermission: false,
  99. activeQuestionnaire: false,
  100. compacting: false,
  101. attachmentCount: 0,
  102. version: 'test',
  103. workspace: '/workspace',
  104. });
  105. const line = new TuiActivityLine(presentation.activity, { animate: false });
  106. expect(line.render(120).join('\n')).toContain('⚡ ~2.0 tok/s');
  107. releaseResponse?.();
  108. await submission;
  109. });
  110. it('keeps provider-calibrated output throughput visible after a text-only turn settles', async () => {
  111. const runtime = {
  112. createSession: vi.fn(async () => ({ sessionId: 'session-output-rate' })),
  113. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  114. yield {
  115. type: 'delta',
  116. turnId: 'turn-output-rate',
  117. messageId: 'message-output-rate',
  118. content: 'hello',
  119. timestamp: 1_000,
  120. };
  121. yield {
  122. type: 'delta',
  123. turnId: 'turn-output-rate',
  124. messageId: 'message-output-rate',
  125. finish: true,
  126. timestamp: 3_000,
  127. };
  128. yield {
  129. type: 'message',
  130. message: {
  131. id: 'message-output-rate',
  132. turnId: 'turn-output-rate',
  133. role: 'assistant',
  134. content: 'hello',
  135. usage: { outputTokens: 126, requestDurationMs: 2_000 },
  136. },
  137. };
  138. yield { type: 'done', turnId: 'turn-output-rate' };
  139. }),
  140. abortSession: vi.fn(async () => true),
  141. };
  142. const transcript = new TranscriptStore();
  143. const controller = new ProductionTuiChatController({
  144. runtime: runtime as never,
  145. transcript,
  146. workspaceDir: '/workspace',
  147. createTurnId: () => 'turn-output-rate',
  148. });
  149. await controller.submit('Say hello');
  150. const view = new TranscriptView(() => transcript.snapshot());
  151. expect(view.render(80).join('\n')).toContain('⚡ 63.0 tok/s');
  152. });
  153. it('accumulates provider output throughput for one turn and resets it for the next', () => {
  154. const controller = new ProductionTuiChatController({
  155. runtime: {} as never,
  156. transcript: new TranscriptStore(),
  157. workspaceDir: '/workspace',
  158. });
  159. controller.beginRuntimeTurn('turn-1', 500);
  160. controller.applyRuntimeTurnEvent('turn-1', {
  161. type: 'delta',
  162. turnId: 'turn-1',
  163. messageId: 'message-1',
  164. content: 'first chunk',
  165. timestamp: 1_000,
  166. });
  167. controller.applyRuntimeTurnEvent('turn-1', {
  168. type: 'delta',
  169. turnId: 'turn-1',
  170. messageId: 'message-1',
  171. finish: true,
  172. timestamp: 3_000,
  173. });
  174. controller.applyRuntimeTurnEvent('turn-1', {
  175. type: 'message',
  176. message: {
  177. id: 'message-1',
  178. turnId: 'turn-1',
  179. role: 'assistant',
  180. usage: { outputTokens: 126, requestDurationMs: 2_000 },
  181. },
  182. });
  183. expect(controller.snapshot().outputTokensPerSecond).toBe(63);
  184. controller.beginRuntimeTurn('turn-2', 4_000);
  185. expect(controller.snapshot().outputTokensPerSecond).toBeUndefined();
  186. });
  187. it('publishes one state change when a stream event updates throughput and Transcript', () => {
  188. let nowMs = 0;
  189. const onChange = vi.fn();
  190. const controller = new ProductionTuiChatController({
  191. runtime: {} as never,
  192. transcript: new TranscriptStore(),
  193. workspaceDir: '/workspace',
  194. onChange,
  195. now: () => nowMs,
  196. });
  197. controller.beginRuntimeTurn('turn-batched', 500);
  198. controller.applyRuntimeTurnEvent('turn-batched', {
  199. type: 'delta',
  200. turnId: 'turn-batched',
  201. messageId: 'message-batched',
  202. content: 'first chunk',
  203. timestamp: 1_000,
  204. });
  205. onChange.mockClear();
  206. nowMs = 250;
  207. controller.applyRuntimeTurnEvent('turn-batched', {
  208. type: 'delta',
  209. turnId: 'turn-batched',
  210. messageId: 'message-batched',
  211. content: 'second chunk',
  212. timestamp: 2_000,
  213. });
  214. expect(controller.snapshot().outputTokensPerSecond).toBeGreaterThan(0);
  215. expect(onChange).toHaveBeenCalledOnce();
  216. });
  217. it('projects a pending user message before the login preflight settles', async () => {
  218. let resolveAccount:
  219. | ((account: { status: 'ready'; managedTokenPresent: true; warnings: never[] }) => void)
  220. | undefined;
  221. const runtime = {
  222. getAccountStatus: vi.fn(
  223. () =>
  224. new Promise<{
  225. status: 'ready';
  226. managedTokenPresent: true;
  227. warnings: never[];
  228. }>((resolve) => {
  229. resolveAccount = resolve;
  230. }),
  231. ),
  232. createSession: vi.fn(async () => ({
  233. sessionId: 'session-optimistic',
  234. workspaceDir: '/workspace',
  235. })),
  236. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  237. yield { type: 'done', turnId: 'turn-optimistic' };
  238. }),
  239. abortSession: vi.fn(async () => true),
  240. steer: vi.fn(),
  241. };
  242. const transcript = new TranscriptStore();
  243. const onUserSubmissionProjected = vi.fn();
  244. const controller = new ProductionTuiChatController({
  245. runtime: runtime as never,
  246. transcript,
  247. workspaceDir: '/workspace',
  248. createTurnId: () => 'turn-optimistic',
  249. now: () => 100,
  250. onUserSubmissionProjected,
  251. });
  252. controller.projectOptimisticUserMessage('submission-1', 'Show this immediately', 90);
  253. const sending = controller.submit('Show this immediately', {
  254. optimisticRequestId: 'submission-1',
  255. });
  256. expect(transcript.get('user:turn-optimistic')).toMatchObject({
  257. kind: 'user',
  258. status: 'pending',
  259. content: 'Show this immediately',
  260. createdAtMs: 90,
  261. });
  262. expect(transcript.get('optimistic:user:submission-1')).toBeUndefined();
  263. expect(transcript.snapshot().filter((cell) => cell.kind === 'user')).toHaveLength(1);
  264. expect(onUserSubmissionProjected).toHaveBeenCalledOnce();
  265. expect(runtime.createSession).not.toHaveBeenCalled();
  266. expect(runtime.sendMessage).not.toHaveBeenCalled();
  267. resolveAccount?.({ status: 'ready', managedTokenPresent: true, warnings: [] });
  268. await expect(sending).resolves.toBe('succeeded');
  269. });
  270. it('detaches the foreground observer when switching Sessions without aborting the Runtime turn', async () => {
  271. let releaseTurn: (() => void) | undefined;
  272. const runtime = {
  273. createSession: vi.fn(),
  274. getSession: vi.fn(async (sessionId: string) => ({
  275. sessionId,
  276. workspaceDir: '/workspace',
  277. })),
  278. getMessages: vi.fn(async () => []),
  279. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  280. await new Promise<void>((resolve) => {
  281. releaseTurn = resolve;
  282. });
  283. yield { type: 'delta', text: 'late answer from A' };
  284. yield { type: 'done' };
  285. }),
  286. abortSession: vi.fn(async () => true),
  287. };
  288. const transcript = new TranscriptStore();
  289. const controller = new TuiChatController({
  290. runtime,
  291. transcript,
  292. workspaceDir: '/workspace',
  293. createTurnId: () => 'turn-a',
  294. now: () => 100,
  295. });
  296. await controller.loadSessionProjection('session-a');
  297. const running = controller.submit('keep running in A');
  298. await vi.waitFor(() => expect(releaseTurn).toBeTypeOf('function'));
  299. await controller.loadSessionProjection('session-b');
  300. expect(runtime.abortSession).not.toHaveBeenCalled();
  301. expect(controller.snapshot().session?.sessionId).toBe('session-b');
  302. releaseTurn?.();
  303. await expect(running).resolves.toBe('succeeded');
  304. expect(controller.snapshot().session?.sessionId).toBe('session-b');
  305. expect(transcript.snapshot().some((cell) => cell.content.includes('late answer from A'))).toBe(
  306. false,
  307. );
  308. });
  309. it('requires MiniMax login before starting a managed-model Turn', async () => {
  310. const runtime = {
  311. getAccountStatus: vi.fn(async () => ({
  312. status: 'needs-login' as const,
  313. authMode: 'managed-login',
  314. modelSource: 'token-plan' as const,
  315. managedTokenPresent: false,
  316. warnings: [],
  317. })),
  318. createSession: vi.fn(async () => ({
  319. sessionId: 'session-login-required',
  320. workspaceDir: '/workspace',
  321. })),
  322. sendMessage: vi.fn(),
  323. abortSession: vi.fn(async () => true),
  324. steer: vi.fn(),
  325. };
  326. const transcript = new TranscriptStore();
  327. const controller = new ProductionTuiChatController({
  328. runtime: runtime as never,
  329. transcript,
  330. workspaceDir: '/workspace',
  331. createTurnId: () => 'turn-login-required',
  332. now: () => 100,
  333. });
  334. await expect(controller.submit('Do not send this yet')).rejects.toMatchObject({
  335. name: 'TuiLoginRequiredError',
  336. code: 'auth.login_required',
  337. });
  338. expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, undefined);
  339. expect(runtime.createSession).not.toHaveBeenCalled();
  340. expect(runtime.sendMessage).not.toHaveBeenCalled();
  341. expect(transcript.snapshot()).toEqual([]);
  342. expect(controller.snapshot()).toMatchObject({
  343. status: 'idle',
  344. activeTurnId: undefined,
  345. account: { managedTokenPresent: false },
  346. });
  347. });
  348. it('defers owner history reconciliation until the active Turn has settled', async () => {
  349. let releaseTurn: (() => void) | undefined;
  350. const runtime = {
  351. createSession: vi.fn(async () => ({
  352. sessionId: 'session-history-deferred',
  353. workspaceDir: '/workspace',
  354. })),
  355. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  356. await new Promise<void>((resolve) => {
  357. releaseTurn = resolve;
  358. });
  359. yield { type: 'done', turnId: 'turn-history-deferred' };
  360. }),
  361. abortSession: vi.fn(async () => true),
  362. getSession: vi.fn(async () => ({
  363. sessionId: 'session-history-deferred',
  364. workspaceDir: '/workspace',
  365. })),
  366. getMessages: vi.fn(async () => []),
  367. };
  368. const controller = new TuiChatController({
  369. runtime,
  370. transcript: new TranscriptStore(),
  371. workspaceDir: '/workspace',
  372. createTurnId: () => 'turn-history-deferred',
  373. now: () => 100,
  374. });
  375. const submission = controller.submit('Keep the Turn active');
  376. await vi.waitFor(() =>
  377. expect(controller.snapshot().activeTurnId).toBe('turn-history-deferred'),
  378. );
  379. await vi.waitFor(() => expect(releaseTurn).toBeTypeOf('function'));
  380. await expect(controller.reconcileOwnerHistory(false)).resolves.toBe(false);
  381. expect(runtime.getMessages).not.toHaveBeenCalled();
  382. releaseTurn?.();
  383. await submission;
  384. await vi.waitFor(() =>
  385. expect(runtime.getMessages).toHaveBeenCalledWith('session-history-deferred'),
  386. );
  387. });
  388. it('shares in-flight session creation with runtime-owned follow-up submission', async () => {
  389. let resolveSession: ((session: { sessionId: string }) => void) | undefined;
  390. const runtime = {
  391. createSession: vi.fn(
  392. () =>
  393. new Promise<{ sessionId: string }>((resolve) => {
  394. resolveSession = resolve;
  395. }),
  396. ),
  397. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  398. yield { type: 'done' };
  399. }),
  400. abortSession: vi.fn(async () => true),
  401. };
  402. const controller = new TuiChatController({
  403. runtime,
  404. transcript: new TranscriptStore(),
  405. workspaceDir: '/workspace',
  406. });
  407. const submitting = controller.submit('First turn');
  408. await vi.waitFor(() => expect(resolveSession).toBeTypeOf('function'));
  409. const waitingForSession = controller.waitForCurrentSession();
  410. resolveSession?.({ sessionId: 'session-1' });
  411. await expect(waitingForSession).resolves.toEqual({ sessionId: 'session-1' });
  412. await submitting;
  413. expect(runtime.createSession).toHaveBeenCalledTimes(1);
  414. });
  415. it('creates a session lazily and updates one assistant cell in place while streaming', async () => {
  416. const runtime = {
  417. createSession: vi.fn(async () => ({
  418. sessionId: 'session-1',
  419. title: 'New session',
  420. workspaceDir: '/workspace',
  421. })),
  422. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  423. yield { type: 'delta', turnId: 'turn-1', role: 'assistant', content: 'Hel' };
  424. yield { type: 'delta', turnId: 'turn-1', role: 'assistant', content: 'lo' };
  425. yield { type: 'done', turnId: 'turn-1' };
  426. }),
  427. abortSession: vi.fn(async () => true),
  428. };
  429. const transcript = new TranscriptStore();
  430. const controller = new TuiChatController({
  431. runtime,
  432. transcript,
  433. workspaceDir: '/workspace',
  434. createTurnId: () => 'turn-1',
  435. now: (() => {
  436. let value = 100;
  437. return () => value++;
  438. })(),
  439. });
  440. await controller.submit(' Say hello ');
  441. expect(runtime.createSession).toHaveBeenCalledWith({ workspaceDir: '/workspace' });
  442. expect(runtime.sendMessage).toHaveBeenCalledWith(
  443. { id: 'session-1', content: 'Say hello', turnId: 'turn-1' },
  444. expect.any(AbortSignal),
  445. );
  446. expect(transcript.snapshot()).toEqual([
  447. expect.objectContaining({
  448. id: 'user:turn-1',
  449. kind: 'user',
  450. status: 'succeeded',
  451. content: 'Say hello',
  452. }),
  453. expect.objectContaining({
  454. id: 'assistant:turn-1',
  455. kind: 'assistant',
  456. status: 'succeeded',
  457. content: 'Hello',
  458. }),
  459. expect.objectContaining({
  460. id: 'turn-duration:turn-1',
  461. kind: 'turn-duration',
  462. status: 'succeeded',
  463. }),
  464. ]);
  465. expect(controller.snapshot()).toMatchObject({
  466. status: 'idle',
  467. session: { sessionId: 'session-1' },
  468. });
  469. });
  470. it('refreshes the authoritative interaction mode after an accepted direct Turn', async () => {
  471. const runtime = {
  472. createSession: vi.fn(async () => ({
  473. sessionId: 'session-plan-sync',
  474. workspaceDir: '/workspace',
  475. })),
  476. getSession: vi.fn(async () => ({
  477. sessionId: 'session-plan-sync',
  478. workspaceDir: '/workspace',
  479. interactionMode: 'plan' as const,
  480. })),
  481. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  482. yield { type: 'done', turnId: 'turn-plan-sync' };
  483. }),
  484. abortSession: vi.fn(async () => true),
  485. };
  486. const controller = new TuiChatController({
  487. runtime,
  488. transcript: new TranscriptStore(),
  489. workspaceDir: '/workspace',
  490. createTurnId: () => 'turn-plan-sync',
  491. });
  492. await expect(controller.submit('Let the Agent decide whether to plan')).resolves.toBe(
  493. 'succeeded',
  494. );
  495. expect(runtime.getSession).toHaveBeenCalledWith('session-plan-sync');
  496. expect(controller.snapshot().session?.interactionMode).toBe('plan');
  497. });
  498. it('records content review rewind as failed even after assistant output', async () => {
  499. const runtime = {
  500. createSession: vi.fn(async () => ({ sessionId: 'session-blocked' })),
  501. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  502. yield {
  503. type: 'message',
  504. message: {
  505. id: 'message-before-block',
  506. turnId: 'turn-blocked',
  507. role: 'assistant',
  508. content: 'Partial response before the block.',
  509. },
  510. };
  511. yield {
  512. type: 'generic',
  513. eventType: 'messages-rewound',
  514. data: {},
  515. } as TuiStreamEvent;
  516. }),
  517. abortSession: vi.fn(async () => true),
  518. };
  519. const controller = new TuiChatController({
  520. runtime,
  521. transcript: new TranscriptStore(),
  522. workspaceDir: '/workspace',
  523. createTurnId: () => 'turn-blocked',
  524. });
  525. await expect(controller.submit('Stop for input')).resolves.toBe('failed');
  526. expect(controller.snapshot().lastSettledTurn).toEqual({
  527. sessionId: 'session-blocked',
  528. turnId: 'turn-blocked',
  529. status: 'failed',
  530. });
  531. });
  532. it('records every Runtime-owned terminal outcome against its current Session', async () => {
  533. const runtime = {
  534. createSession: vi.fn(async () => ({ sessionId: 'session-runtime-owned' })),
  535. };
  536. const controller = new TuiChatController({
  537. runtime,
  538. transcript: new TranscriptStore(),
  539. workspaceDir: '/workspace',
  540. });
  541. await controller.ensureSession();
  542. for (const [turnId, status] of [
  543. ['turn-runtime-done', 'succeeded'],
  544. ['turn-runtime-fail', 'failed'],
  545. ['turn-runtime-blocked', 'blocked'],
  546. ['turn-runtime-cancel', 'cancelled'],
  547. ] as const) {
  548. controller.beginRuntimeTurn(turnId, 0);
  549. await controller.runtimeTurnSettlement.settle('session-runtime-owned', turnId, status, 12);
  550. expect(controller.snapshot().lastSettledTurn).toEqual({
  551. sessionId: 'session-runtime-owned',
  552. turnId,
  553. status,
  554. });
  555. }
  556. await controller.runtimeTurnSettlement.settle('session-other', 'turn-foreign', 'succeeded', 12);
  557. expect(controller.snapshot().lastSettledTurn).toEqual({
  558. sessionId: 'session-runtime-owned',
  559. turnId: 'turn-runtime-cancel',
  560. status: 'cancelled',
  561. });
  562. });
  563. it('writes a Runtime-owned result before publishing its terminal outcome', async () => {
  564. const delivered = Promise.withResolvers<void>();
  565. const writeAutomationResult = vi.fn(async () => delivered.promise);
  566. const transcript = new TranscriptStore();
  567. transcript.upsert({
  568. id: 'assistant:turn-previous',
  569. kind: 'assistant',
  570. status: 'succeeded',
  571. content: 'Previous answer',
  572. turnId: 'turn-previous',
  573. createdAtMs: 1,
  574. updatedAtMs: 1,
  575. });
  576. const controller = new TuiChatController({
  577. runtime: {
  578. createSession: vi.fn(async () => ({ sessionId: 'session-runtime-result' })),
  579. },
  580. transcript,
  581. workspaceDir: '/workspace',
  582. writeAutomationResult,
  583. });
  584. await controller.ensureSession();
  585. controller.beginRuntimeTurn('turn-runtime-result', 10);
  586. controller.applyRuntimeTurnEvent('turn-runtime-result', {
  587. type: 'message',
  588. message: {
  589. id: 'message-runtime-result',
  590. turnId: 'turn-runtime-result',
  591. role: 'assistant',
  592. content: 'Runtime-owned answer',
  593. },
  594. });
  595. controller.runtimeTurnSettlement.settleProjection('turn-runtime-result', 'succeeded', 20);
  596. const settledTurn = controller.runtimeTurnSettlement.prepare(
  597. 'session-runtime-result',
  598. 'turn-runtime-result',
  599. 'succeeded',
  600. );
  601. expect(settledTurn).toBeDefined();
  602. if (!settledTurn) throw new Error('Expected a Runtime-owned settled turn.');
  603. const publishing = controller.runtimeTurnSettlement.publish(settledTurn, 20);
  604. await vi.waitFor(() => expect(writeAutomationResult).toHaveBeenCalledOnce());
  605. expect(writeAutomationResult).toHaveBeenCalledWith(
  606. expect.objectContaining({
  607. sessionId: 'session-runtime-result',
  608. turnId: 'turn-runtime-result',
  609. status: 'succeeded',
  610. answer: 'Runtime-owned answer',
  611. durationMs: 20,
  612. }),
  613. );
  614. expect(controller.snapshot().lastSettledTurn).toBeUndefined();
  615. delivered.resolve();
  616. await publishing;
  617. expect(controller.snapshot().lastSettledTurn).toEqual({
  618. sessionId: 'session-runtime-result',
  619. turnId: 'turn-runtime-result',
  620. status: 'succeeded',
  621. });
  622. });
  623. it('fails a Runtime-owned automation turn that has no final assistant answer', async () => {
  624. const writeAutomationResult = vi.fn();
  625. const controller = new TuiChatController({
  626. runtime: {
  627. createSession: vi.fn(async () => ({ sessionId: 'session-runtime-empty' })),
  628. },
  629. transcript: new TranscriptStore(),
  630. workspaceDir: '/workspace',
  631. writeAutomationResult,
  632. });
  633. await controller.ensureSession();
  634. controller.beginRuntimeTurn('turn-runtime-empty', 10);
  635. controller.runtimeTurnSettlement.settleProjection('turn-runtime-empty', 'succeeded', 20);
  636. const settledTurn = controller.runtimeTurnSettlement.prepare(
  637. 'session-runtime-empty',
  638. 'turn-runtime-empty',
  639. 'succeeded',
  640. );
  641. if (!settledTurn) throw new Error('Expected a Runtime-owned settled turn.');
  642. await controller.runtimeTurnSettlement.publish(settledTurn, 20);
  643. expect(writeAutomationResult).toHaveBeenCalledWith(
  644. expect.objectContaining({
  645. status: 'failed',
  646. answer: null,
  647. error: expect.objectContaining({ code: 'EMPTY_RESPONSE' }),
  648. }),
  649. );
  650. expect(controller.snapshot().lastSettledTurn).toEqual({
  651. sessionId: 'session-runtime-empty',
  652. turnId: 'turn-runtime-empty',
  653. status: 'failed',
  654. });
  655. });
  656. it('does not publish a terminal turn before the enabled automation result is written', async () => {
  657. const delivered = Promise.withResolvers<void>();
  658. const writeAutomationResult = vi.fn(async () => delivered.promise);
  659. const onAutomationResultPublished = vi.fn();
  660. const runtime = {
  661. createSession: vi.fn(async () => ({ sessionId: 'session-automation-result' })),
  662. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  663. yield {
  664. type: 'message',
  665. message: { role: 'assistant', content: 'structured answer' },
  666. };
  667. yield { type: 'done' };
  668. }),
  669. abortSession: vi.fn(async () => true),
  670. };
  671. const controller = new TuiChatController({
  672. runtime,
  673. transcript: new TranscriptStore(),
  674. workspaceDir: '/workspace',
  675. createTurnId: () => 'turn-automation-result',
  676. writeAutomationResult,
  677. onAutomationResultPublished,
  678. });
  679. const submission = controller.submit('Answer');
  680. await vi.waitFor(() => expect(writeAutomationResult).toHaveBeenCalledOnce());
  681. expect(onAutomationResultPublished).not.toHaveBeenCalled();
  682. expect(controller.snapshot()).toMatchObject({
  683. status: 'running',
  684. activeTurnId: 'turn-automation-result',
  685. lastSettledTurn: undefined,
  686. });
  687. delivered.resolve();
  688. await expect(submission).resolves.toBe('succeeded');
  689. expect(onAutomationResultPublished).toHaveBeenCalledWith(
  690. expect.objectContaining({
  691. sessionId: 'session-automation-result',
  692. turnId: 'turn-automation-result',
  693. status: 'succeeded',
  694. }),
  695. );
  696. expect(controller.snapshot().lastSettledTurn).toEqual({
  697. sessionId: 'session-automation-result',
  698. turnId: 'turn-automation-result',
  699. status: 'succeeded',
  700. });
  701. });
  702. it.each([
  703. ['local_session_busy', 'queue-required'],
  704. ['local_session_compacting', 'queue-required'],
  705. ['local_session_queue_paused', 'draft-kept'],
  706. ] as const)('does not publish unaccepted %s as a terminal result', async (code, status) => {
  707. const writeAutomationResult = vi.fn();
  708. const runtime = {
  709. createSession: vi.fn(async () => ({ sessionId: 'session-queue-fallback' })),
  710. sendMessage: vi.fn(async function* rejectedAdmission(): AsyncGenerator<TuiStreamEvent> {
  711. yield* [];
  712. throw new TuiFailure('runtime', 'Session is busy', {
  713. code,
  714. retryable: false,
  715. });
  716. }),
  717. abortSession: vi.fn(async () => true),
  718. };
  719. const controller = new TuiChatController({
  720. runtime,
  721. transcript: new TranscriptStore(),
  722. workspaceDir: '/workspace',
  723. createTurnId: () => 'turn-queue-fallback',
  724. writeAutomationResult,
  725. });
  726. await expect(controller.submit('Queue this', { onQueuePaused: async () => 'cancel' })).resolves.toBe(status);
  727. expect(writeAutomationResult).not.toHaveBeenCalled();
  728. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  729. expect(controller.snapshot().lastSettledTurn).toBeUndefined();
  730. expect(controller.snapshot()).toMatchObject({
  731. status: 'idle',
  732. activeTurnId: undefined,
  733. error: undefined,
  734. });
  735. });
  736. it('retains a rejected paused recovery instead of silently enqueuing the new instruction', async () => {
  737. const runtime = {
  738. createSession: vi.fn(async () => ({ sessionId: 'session-recovery-race' })),
  739. sendMessage: vi.fn<TuiRunRuntime['sendMessage']>(async function* (_request, _signal, options) {
  740. yield* [];
  741. throw new TuiFailure('runtime', 'Admission rejected', {
  742. code: options ? 'local_session_busy' : 'local_session_queue_paused',
  743. retryable: false,
  744. });
  745. }),
  746. abortSession: vi.fn(async () => true),
  747. };
  748. const controller = new TuiChatController({ runtime, transcript: new TranscriptStore(), workspaceDir: '/workspace' });
  749. await expect(controller.submit('Enter Plan first', {
  750. clientIntent: 'plan-entry', onQueuePaused: async () => 'paused-queue-keep',
  751. })).resolves.toBe('failed');
  752. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  753. expect(runtime.sendMessage.mock.calls[1]?.[0]).toMatchObject({ clientIntent: 'plan-entry' });
  754. });
  755. it('keeps submission serialized until authoritative Session metadata is refreshed', async () => {
  756. let resolveMetadata: ((session: { sessionId: string }) => void) | undefined;
  757. const runtime = {
  758. createSession: vi.fn(async () => ({ sessionId: 'session-metadata-fence' })),
  759. getSession: vi.fn(
  760. async () =>
  761. await new Promise<{ sessionId: string }>((resolve) => {
  762. resolveMetadata = resolve;
  763. }),
  764. ),
  765. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  766. yield { type: 'done', turnId: 'turn-metadata-fence' };
  767. }),
  768. abortSession: vi.fn(async () => true),
  769. };
  770. const controller = new TuiChatController({
  771. runtime,
  772. transcript: new TranscriptStore(),
  773. workspaceDir: '/workspace',
  774. createTurnId: () => 'turn-metadata-fence',
  775. });
  776. const first = controller.submit('First');
  777. await vi.waitFor(() => expect(resolveMetadata).toBeTypeOf('function'));
  778. await expect(controller.submit('Second')).rejects.toThrow('already running');
  779. resolveMetadata?.({ sessionId: 'session-metadata-fence' });
  780. await expect(first).resolves.toBe('succeeded');
  781. });
  782. it('keeps pre-token waiting state out of the durable Transcript', async () => {
  783. let releaseFirstEvent: (() => void) | undefined;
  784. const firstEventGate = new Promise<void>((resolve) => {
  785. releaseFirstEvent = resolve;
  786. });
  787. const runtime = {
  788. createSession: vi.fn(async () => ({ sessionId: 'session-thinking-placeholder' })),
  789. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  790. await firstEventGate;
  791. yield {
  792. type: 'delta',
  793. turnId: 'turn-thinking-placeholder',
  794. content: 'Direct answer',
  795. };
  796. yield { type: 'done', turnId: 'turn-thinking-placeholder' };
  797. }),
  798. abortSession: vi.fn(async () => true),
  799. };
  800. const transcript = new TranscriptStore();
  801. const controller = new TuiChatController({
  802. runtime,
  803. transcript,
  804. workspaceDir: '/workspace',
  805. createTurnId: () => 'turn-thinking-placeholder',
  806. now: () => 100,
  807. });
  808. const submission = controller.submit('Answer directly');
  809. await vi.waitFor(() =>
  810. expect(transcript.snapshot()).toEqual([
  811. expect.objectContaining({ kind: 'user', content: 'Answer directly' }),
  812. ]),
  813. );
  814. releaseFirstEvent?.();
  815. await submission;
  816. expect(transcript.snapshot()).toEqual([
  817. expect.objectContaining({ kind: 'user', content: 'Answer directly' }),
  818. expect.objectContaining({
  819. id: 'assistant:turn-thinking-placeholder',
  820. kind: 'assistant',
  821. status: 'succeeded',
  822. content: 'Direct answer',
  823. }),
  824. expect.objectContaining({
  825. id: 'turn-duration:turn-thinking-placeholder',
  826. kind: 'turn-duration',
  827. status: 'succeeded',
  828. }),
  829. ]);
  830. });
  831. it('preserves thinking, preamble, tool, and final-answer chronology across one turn', async () => {
  832. const runtime = {
  833. createSession: vi.fn(async () => ({ sessionId: 'session-segmented' })),
  834. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  835. yield { type: 'delta', turnId: 'turn-segmented', thinking: 'Plan the inspection' };
  836. yield {
  837. type: 'delta',
  838. turnId: 'turn-segmented',
  839. messageId: 'message-preamble',
  840. content: 'I will inspect the workspace.',
  841. };
  842. yield {
  843. type: 'delta',
  844. turnId: 'turn-segmented',
  845. toolCalls: [
  846. {
  847. id: 'tool-read',
  848. name: 'read',
  849. status: 'running',
  850. input: { path: 'README.md' },
  851. },
  852. ],
  853. };
  854. yield {
  855. type: 'delta',
  856. turnId: 'turn-segmented',
  857. toolCalls: [
  858. {
  859. id: 'tool-read',
  860. name: 'read',
  861. status: 'completed',
  862. input: { path: 'README.md' },
  863. output: 'workspace details',
  864. },
  865. ],
  866. };
  867. yield { type: 'delta', turnId: 'turn-segmented', thinking: 'Interpret the result' };
  868. yield {
  869. type: 'delta',
  870. turnId: 'turn-segmented',
  871. messageId: 'message-final',
  872. content: 'Here is the conclusion.',
  873. };
  874. yield { type: 'done', turnId: 'turn-segmented' };
  875. }),
  876. abortSession: vi.fn(async () => true),
  877. };
  878. const transcript = new TranscriptStore();
  879. const controller = new TuiChatController({
  880. runtime,
  881. transcript,
  882. workspaceDir: '/workspace',
  883. createTurnId: () => 'turn-segmented',
  884. now: (() => {
  885. let value = 100;
  886. return () => value++;
  887. })(),
  888. });
  889. await controller.submit('Inspect');
  890. expect(transcript.snapshot()).toEqual([
  891. expect.objectContaining({
  892. id: 'user:turn-segmented',
  893. kind: 'user',
  894. content: 'Inspect',
  895. }),
  896. expect.objectContaining({
  897. id: 'thinking:turn-segmented',
  898. kind: 'thinking',
  899. status: 'succeeded',
  900. content: 'Plan the inspection',
  901. }),
  902. expect.objectContaining({
  903. id: 'assistant:turn-segmented',
  904. kind: 'assistant-preamble',
  905. status: 'succeeded',
  906. content: 'I will inspect the workspace.',
  907. }),
  908. expect.objectContaining({
  909. id: 'tool:turn-segmented:tool-read',
  910. kind: 'tool',
  911. status: 'succeeded',
  912. content: '{"path":"README.md"}',
  913. detail: 'workspace details',
  914. }),
  915. expect.objectContaining({
  916. id: 'thinking:turn-segmented:2',
  917. kind: 'thinking',
  918. status: 'succeeded',
  919. content: 'Interpret the result',
  920. }),
  921. expect.objectContaining({
  922. id: 'assistant:turn-segmented:2',
  923. kind: 'assistant',
  924. status: 'succeeded',
  925. content: 'Here is the conclusion.',
  926. }),
  927. expect.objectContaining({
  928. id: 'turn-duration:turn-segmented',
  929. kind: 'turn-duration',
  930. status: 'succeeded',
  931. }),
  932. ]);
  933. });
  934. it('does not reactivate an earlier preamble when its completed message arrives after a tool', async () => {
  935. const runtime = {
  936. createSession: vi.fn(async () => ({ sessionId: 'session-delayed-completion' })),
  937. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  938. yield {
  939. type: 'delta',
  940. turnId: 'turn-delayed-completion',
  941. messageId: 'message-preamble',
  942. content: 'I will inspect this.',
  943. };
  944. yield {
  945. type: 'delta',
  946. turnId: 'turn-delayed-completion',
  947. toolCalls: [{ id: 'tool-read', name: 'read', status: 'completed' }],
  948. };
  949. yield {
  950. type: 'message',
  951. message: {
  952. id: 'message-preamble',
  953. turnId: 'turn-delayed-completion',
  954. role: 'assistant',
  955. content: 'I will inspect this.',
  956. },
  957. };
  958. yield {
  959. type: 'delta',
  960. turnId: 'turn-delayed-completion',
  961. messageId: 'message-final',
  962. content: 'The inspection is complete.',
  963. };
  964. yield { type: 'done', turnId: 'turn-delayed-completion' };
  965. }),
  966. abortSession: vi.fn(async () => true),
  967. };
  968. const transcript = new TranscriptStore();
  969. const controller = new TuiChatController({
  970. runtime,
  971. transcript,
  972. workspaceDir: '/workspace',
  973. createTurnId: () => 'turn-delayed-completion',
  974. now: () => 100,
  975. });
  976. await controller.submit('Inspect');
  977. expect(
  978. transcript
  979. .snapshot()
  980. .filter((cell) => cell.kind === 'assistant' || cell.kind === 'assistant-preamble'),
  981. ).toEqual([
  982. expect.objectContaining({
  983. id: 'assistant:turn-delayed-completion',
  984. kind: 'assistant-preamble',
  985. content: 'I will inspect this.',
  986. }),
  987. expect.objectContaining({
  988. id: 'assistant:turn-delayed-completion:2',
  989. kind: 'assistant',
  990. content: 'The inspection is complete.',
  991. }),
  992. ]);
  993. });
  994. it('uses authoritative Thinking duration from the completed message lifecycle', async () => {
  995. const runtime = {
  996. createSession: vi.fn(async () => ({ sessionId: 'session-thinking-duration' })),
  997. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  998. yield {
  999. type: 'delta',
  1000. turnId: 'turn-thinking-duration',
  1001. messageId: 'message-1',
  1002. thinking: 'Inspect carefully',
  1003. };
  1004. yield {
  1005. type: 'message',
  1006. message: {
  1007. id: 'message-1',
  1008. turnId: 'turn-thinking-duration',
  1009. role: 'assistant',
  1010. kind: 'final',
  1011. thinking: 'Inspect carefully',
  1012. thinkingDurationMs: 4_200,
  1013. content: 'Done.',
  1014. },
  1015. };
  1016. yield { type: 'done', turnId: 'turn-thinking-duration' };
  1017. }),
  1018. abortSession: vi.fn(async () => true),
  1019. };
  1020. const transcript = new TranscriptStore();
  1021. const controller = new TuiChatController({
  1022. runtime,
  1023. transcript,
  1024. workspaceDir: '/workspace',
  1025. createTurnId: () => 'turn-thinking-duration',
  1026. now: () => 100,
  1027. });
  1028. await controller.submit('Inspect');
  1029. expect(transcript.get('thinking:turn-thinking-duration')).toMatchObject({
  1030. status: 'succeeded',
  1031. durationMs: 4_200,
  1032. content: 'Inspect carefully',
  1033. });
  1034. });
  1035. it('restores aggregate Thinking before text when its empty start placeholder was removed', async () => {
  1036. const runtime = {
  1037. createSession: vi.fn(async () => ({ sessionId: 'session-late-thinking-snapshot' })),
  1038. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  1039. yield {
  1040. type: 'delta',
  1041. turnId: 'turn-late-thinking-snapshot',
  1042. messageId: 'message-1',
  1043. started: true,
  1044. };
  1045. yield {
  1046. type: 'delta',
  1047. turnId: 'turn-late-thinking-snapshot',
  1048. messageId: 'message-1',
  1049. content: 'Direct answer',
  1050. };
  1051. yield {
  1052. type: 'message',
  1053. message: {
  1054. id: 'message-1',
  1055. turnId: 'turn-late-thinking-snapshot',
  1056. role: 'assistant',
  1057. kind: 'final',
  1058. thinking: 'Late aggregate snapshot',
  1059. thinkingDurationMs: 900,
  1060. content: 'Direct answer',
  1061. },
  1062. };
  1063. yield { type: 'done', turnId: 'turn-late-thinking-snapshot' };
  1064. }),
  1065. abortSession: vi.fn(async () => true),
  1066. };
  1067. const transcript = new TranscriptStore();
  1068. const controller = new TuiChatController({
  1069. runtime,
  1070. transcript,
  1071. workspaceDir: '/workspace',
  1072. createTurnId: () => 'turn-late-thinking-snapshot',
  1073. now: () => 100,
  1074. });
  1075. await expect(controller.submit('Answer')).resolves.toBe('succeeded');
  1076. expect(transcript.snapshot()).toEqual([
  1077. expect.objectContaining({ kind: 'user' }),
  1078. expect.objectContaining({
  1079. kind: 'thinking',
  1080. status: 'succeeded',
  1081. content: 'Late aggregate snapshot',
  1082. durationMs: 900,
  1083. }),
  1084. expect.objectContaining({ kind: 'assistant', content: 'Direct answer' }),
  1085. expect.objectContaining({ kind: 'turn-duration', status: 'succeeded' }),
  1086. ]);
  1087. });
  1088. it('opens a new ordered Thinking segment when a real delta follows direct text', async () => {
  1089. const runtime = {
  1090. createSession: vi.fn(async () => ({ sessionId: 'session-late-thinking-delta' })),
  1091. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  1092. yield {
  1093. type: 'delta',
  1094. turnId: 'turn-late-thinking-delta',
  1095. messageId: 'message-1',
  1096. started: true,
  1097. };
  1098. yield {
  1099. type: 'delta',
  1100. turnId: 'turn-late-thinking-delta',
  1101. messageId: 'message-1',
  1102. content: 'First text',
  1103. };
  1104. yield {
  1105. type: 'delta',
  1106. turnId: 'turn-late-thinking-delta',
  1107. messageId: 'message-1',
  1108. thinking: 'Reconsider',
  1109. };
  1110. yield {
  1111. type: 'delta',
  1112. turnId: 'turn-late-thinking-delta',
  1113. messageId: 'message-2',
  1114. content: 'Final text',
  1115. };
  1116. yield { type: 'done', turnId: 'turn-late-thinking-delta' };
  1117. }),
  1118. abortSession: vi.fn(async () => true),
  1119. };
  1120. const transcript = new TranscriptStore();
  1121. const controller = new TuiChatController({
  1122. runtime,
  1123. transcript,
  1124. workspaceDir: '/workspace',
  1125. createTurnId: () => 'turn-late-thinking-delta',
  1126. now: () => 100,
  1127. });
  1128. await expect(controller.submit('Reconsider')).resolves.toBe('succeeded');
  1129. expect(transcript.snapshot().map((cell) => cell.kind)).toEqual([
  1130. 'user',
  1131. 'assistant-preamble',
  1132. 'thinking',
  1133. 'assistant',
  1134. 'turn-duration',
  1135. ]);
  1136. });
  1137. it('appends partial tool updates without duplicating cumulative snapshots', async () => {
  1138. const runtime = {
  1139. createSession: vi.fn(async () => ({ sessionId: 'session-tool-progress' })),
  1140. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  1141. yield {
  1142. type: 'delta',
  1143. turnId: 'turn-tool-progress',
  1144. toolCalls: [
  1145. {
  1146. id: 'tool-bash',
  1147. name: 'bash',
  1148. status: 'started',
  1149. input: { command: 'pnpm test' },
  1150. },
  1151. ],
  1152. };
  1153. yield {
  1154. type: 'delta',
  1155. turnId: 'turn-tool-progress',
  1156. toolCalls: [{ id: 'tool-bash', name: 'bash', status: 'running', output: 'first\n' }],
  1157. };
  1158. yield {
  1159. type: 'delta',
  1160. turnId: 'turn-tool-progress',
  1161. toolCalls: [
  1162. {
  1163. id: 'tool-bash',
  1164. name: 'bash',
  1165. status: 'running',
  1166. output: 'first\nsecond\n',
  1167. },
  1168. ],
  1169. };
  1170. yield {
  1171. type: 'delta',
  1172. turnId: 'turn-tool-progress',
  1173. toolCalls: [
  1174. {
  1175. id: 'tool-bash',
  1176. name: 'bash',
  1177. status: 'completed',
  1178. output: 'first\nsecond\npassed',
  1179. },
  1180. ],
  1181. };
  1182. yield { type: 'done', turnId: 'turn-tool-progress' };
  1183. }),
  1184. abortSession: vi.fn(async () => true),
  1185. };
  1186. const transcript = new TranscriptStore();
  1187. const controller = new TuiChatController({
  1188. runtime,
  1189. transcript,
  1190. workspaceDir: '/workspace',
  1191. createTurnId: () => 'turn-tool-progress',
  1192. now: () => 100,
  1193. });
  1194. await controller.submit('Test');
  1195. expect(transcript.get('tool:turn-tool-progress:tool-bash')).toMatchObject({
  1196. status: 'succeeded',
  1197. content: '{"command":"pnpm test"}',
  1198. detail: 'first\nsecond\npassed',
  1199. });
  1200. });
  1201. it('places a final reply after tool activity when tool events arrive first', async () => {
  1202. let releaseReply: (() => void) | undefined;
  1203. const runtime = {
  1204. createSession: vi.fn(async () => ({ sessionId: 'session-ordered' })),
  1205. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  1206. yield {
  1207. type: 'delta',
  1208. turnId: 'turn-ordered',
  1209. thinking: 'Inspecting files',
  1210. toolCalls: [
  1211. {
  1212. id: 'read-a',
  1213. name: 'read',
  1214. status: 'completed',
  1215. input: { path: 'src/a.ts' },
  1216. },
  1217. {
  1218. id: 'read-b',
  1219. name: 'read',
  1220. status: 'completed',
  1221. input: { path: 'src/b.ts' },
  1222. },
  1223. ],
  1224. };
  1225. await new Promise<void>((resolve) => {
  1226. releaseReply = resolve;
  1227. });
  1228. yield { type: 'delta', turnId: 'turn-ordered', content: 'Finished.' };
  1229. yield { type: 'done', turnId: 'turn-ordered' };
  1230. }),
  1231. abortSession: vi.fn(async () => true),
  1232. };
  1233. const transcript = new TranscriptStore();
  1234. const controller = new TuiChatController({
  1235. runtime,
  1236. transcript,
  1237. workspaceDir: '/workspace',
  1238. createTurnId: () => 'turn-ordered',
  1239. now: () => 100,
  1240. });
  1241. const submission = controller.submit('Inspect');
  1242. await vi.waitFor(() =>
  1243. expect(transcript.snapshot().map((cell) => cell.kind)).toEqual([
  1244. 'user',
  1245. 'thinking',
  1246. 'tool',
  1247. 'tool',
  1248. ]),
  1249. );
  1250. releaseReply?.();
  1251. await submission;
  1252. expect(transcript.snapshot().map((cell) => cell.kind)).toEqual([
  1253. 'user',
  1254. 'thinking',
  1255. 'tool',
  1256. 'tool',
  1257. 'assistant',
  1258. 'turn-duration',
  1259. ]);
  1260. expect(transcript.snapshot().at(-2)).toMatchObject({
  1261. kind: 'assistant',
  1262. content: 'Finished.',
  1263. status: 'succeeded',
  1264. });
  1265. });
  1266. it('does not create an empty assistant row for a successful turn with no text', async () => {
  1267. const runtime = {
  1268. createSession: vi.fn(async () => ({ sessionId: 'session-no-text' })),
  1269. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  1270. yield { type: 'done', turnId: 'turn-no-text' };
  1271. }),
  1272. abortSession: vi.fn(async () => true),
  1273. };
  1274. const transcript = new TranscriptStore();
  1275. const controller = new TuiChatController({
  1276. runtime,
  1277. transcript,
  1278. workspaceDir: '/workspace',
  1279. createTurnId: () => 'turn-no-text',
  1280. now: () => 100,
  1281. });
  1282. await controller.submit('Run');
  1283. expect(transcript.snapshot().map((cell) => cell.kind)).toEqual(['user', 'turn-duration']);
  1284. });
  1285. it('does not create a thinking row for whitespace-only runtime deltas or history', async () => {
  1286. const runtime = {
  1287. createSession: vi.fn(async () => ({ sessionId: 'session-empty-thinking' })),
  1288. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  1289. yield { type: 'delta', turnId: 'turn-empty-thinking', thinking: ' \n\t' };
  1290. yield {
  1291. type: 'message',
  1292. turnId: 'turn-empty-thinking',
  1293. message: {
  1294. role: 'assistant',
  1295. thinking: ' ',
  1296. },
  1297. };
  1298. yield { type: 'done', turnId: 'turn-empty-thinking' };
  1299. }),
  1300. abortSession: vi.fn(async () => true),
  1301. };
  1302. const transcript = new TranscriptStore();
  1303. const controller = new TuiChatController({
  1304. runtime,
  1305. transcript,
  1306. workspaceDir: '/workspace',
  1307. createTurnId: () => 'turn-empty-thinking',
  1308. now: () => 100,
  1309. });
  1310. await controller.submit('Run');
  1311. expect(transcript.snapshot().map((cell) => cell.kind)).toEqual(['user', 'turn-duration']);
  1312. });
  1313. it('submits attachment-only turns and keeps attachment metadata in the user transcript', async () => {
  1314. const runtime = {
  1315. createSession: vi.fn(async () => ({ sessionId: 'session-attachment' })),
  1316. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  1317. yield { type: 'done' };
  1318. }),
  1319. abortSession: vi.fn(async () => true),
  1320. };
  1321. const transcript = new TranscriptStore();
  1322. const controller = new TuiChatController({
  1323. runtime,
  1324. transcript,
  1325. workspaceDir: '/workspace',
  1326. createTurnId: () => 'turn-attachment',
  1327. now: () => 100,
  1328. });
  1329. const attachments = [
  1330. {
  1331. type: 'image' as const,
  1332. filePath: '/workspace/diagram.png',
  1333. fileName: 'diagram.png',
  1334. mimeType: 'image/png',
  1335. sizeBytes: 2048,
  1336. },
  1337. ];
  1338. await controller.submit('', { attachments });
  1339. expect(runtime.sendMessage).toHaveBeenCalledWith(
  1340. {
  1341. id: 'session-attachment',
  1342. content: '',
  1343. turnId: 'turn-attachment',
  1344. attachments: [
  1345. {
  1346. local: { filePath: '/workspace/diagram.png' },
  1347. meta: {
  1348. attachmentType: 'image',
  1349. fileName: 'diagram.png',
  1350. mimeType: 'image/png',
  1351. sizeBytes: 2048,
  1352. },
  1353. },
  1354. ],
  1355. },
  1356. expect.any(AbortSignal),
  1357. );
  1358. expect(transcript.get('user:turn-attachment')).toMatchObject({
  1359. content: '',
  1360. attachments: [
  1361. {
  1362. type: 'image',
  1363. fileName: 'diagram.png',
  1364. mimeType: 'image/png',
  1365. sizeBytes: 2048,
  1366. filePath: '/workspace/diagram.png',
  1367. },
  1368. ],
  1369. });
  1370. });
  1371. it('reconciles a pasted image with a Runtime echo that omits its local size', async () => {
  1372. const runtime = {
  1373. createSession: vi.fn(async () => ({ sessionId: 'session-image-echo' })),
  1374. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  1375. yield {
  1376. type: 'message',
  1377. message: {
  1378. id: 'message-image-echo',
  1379. turnId: 'turn-image-echo',
  1380. role: 'user',
  1381. content: 'Inspect this image',
  1382. attachments: [
  1383. {
  1384. type: 'image',
  1385. fileName: 'clipboard.png',
  1386. mimeType: 'image/png',
  1387. },
  1388. ],
  1389. },
  1390. };
  1391. yield { type: 'done', turnId: 'turn-image-echo' };
  1392. }),
  1393. abortSession: vi.fn(async () => true),
  1394. };
  1395. const transcript = new TranscriptStore();
  1396. const controller = new TuiChatController({
  1397. runtime,
  1398. transcript,
  1399. workspaceDir: '/workspace',
  1400. createTurnId: () => 'turn-image-echo',
  1401. now: () => 100,
  1402. });
  1403. await controller.submit('Inspect this image', {
  1404. attachments: [
  1405. {
  1406. type: 'image',
  1407. filePath: '/tmp/clipboard.png',
  1408. fileName: 'clipboard.png',
  1409. mimeType: 'image/png',
  1410. sizeBytes: 2_048,
  1411. },
  1412. ],
  1413. });
  1414. const userCells = transcript.snapshot().filter((cell) => cell.kind === 'user');
  1415. expect(userCells).toHaveLength(1);
  1416. expect(userCells[0]).toMatchObject({
  1417. id: 'user:turn-image-echo',
  1418. sourceMessageId: 'message-image-echo',
  1419. status: 'succeeded',
  1420. attachments: [expect.objectContaining({ sizeBytes: 2_048 })],
  1421. });
  1422. const rendered = new TranscriptView(() => transcript.snapshot()).render(80).join('\n');
  1423. expect(rendered.match(/Image {2}clipboard\.png/gu)).toHaveLength(1);
  1424. expect(rendered.match(/2 KB/gu)).toHaveLength(1);
  1425. expect(rendered.match(/Inspect this image/gu)).toHaveLength(1);
  1426. });
  1427. it('renders thinking, tools, and a useful runtime error without losing partial output', async () => {
  1428. const runtime = {
  1429. createSession: vi.fn(async () => ({ sessionId: 'session-2' })),
  1430. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  1431. yield { type: 'delta', turnId: 'turn-2', thinking: 'Inspecting files' };
  1432. yield {
  1433. type: 'delta',
  1434. turnId: 'turn-2',
  1435. content: 'Partial answer',
  1436. toolCalls: [{ id: 'tool-1', name: 'read', status: 'running' }],
  1437. };
  1438. yield { type: 'error', turnId: 'turn-2', message: 'provider unavailable' };
  1439. }),
  1440. abortSession: vi.fn(async () => true),
  1441. };
  1442. const transcript = new TranscriptStore();
  1443. const controller = new TuiChatController({
  1444. runtime,
  1445. transcript,
  1446. workspaceDir: '/workspace',
  1447. createTurnId: () => 'turn-2',
  1448. now: () => 100,
  1449. });
  1450. await controller.submit('Inspect');
  1451. expect(transcript.snapshot()).toEqual(
  1452. expect.arrayContaining([
  1453. expect.objectContaining({
  1454. id: 'thinking:turn-2',
  1455. kind: 'thinking',
  1456. content: 'Inspecting files',
  1457. }),
  1458. expect.objectContaining({
  1459. id: 'tool:turn-2:tool-1',
  1460. kind: 'tool',
  1461. status: 'failed',
  1462. title: 'read',
  1463. }),
  1464. expect.objectContaining({
  1465. id: 'assistant:turn-2',
  1466. kind: 'assistant-preamble',
  1467. status: 'succeeded',
  1468. content: 'Partial answer',
  1469. }),
  1470. expect.objectContaining({
  1471. id: 'error:turn-2',
  1472. kind: 'error',
  1473. content:
  1474. 'The model provider is temporarily unavailable.\nRun /retry to resend your last message. Your prompt is preserved.',
  1475. }),
  1476. ]),
  1477. );
  1478. expect(transcript.snapshot()).not.toEqual(
  1479. expect.arrayContaining([expect.objectContaining({ content: 'provider unavailable' })]),
  1480. );
  1481. expect(controller.snapshot().status).toBe('error');
  1482. });
  1483. it('preserves the submitted message and renders an error when session creation fails', async () => {
  1484. const runtime = {
  1485. createSession: vi.fn(async () => {
  1486. throw new Error('authentication required');
  1487. }),
  1488. sendMessage: vi.fn(),
  1489. abortSession: vi.fn(async () => true),
  1490. };
  1491. const transcript = new TranscriptStore();
  1492. const controller = new TuiChatController({
  1493. runtime,
  1494. transcript,
  1495. workspaceDir: '/workspace',
  1496. createTurnId: () => 'turn-auth',
  1497. now: () => 100,
  1498. });
  1499. await expect(controller.submit('Hello')).resolves.toBe('failed');
  1500. expect(runtime.sendMessage).not.toHaveBeenCalled();
  1501. expect(transcript.snapshot()).toEqual([
  1502. expect.objectContaining({
  1503. id: 'user:turn-auth',
  1504. kind: 'user',
  1505. status: 'failed',
  1506. content: 'Hello',
  1507. }),
  1508. expect.objectContaining({
  1509. id: 'assistant:turn-auth',
  1510. kind: 'assistant',
  1511. status: 'failed',
  1512. }),
  1513. expect.objectContaining({
  1514. id: 'error:turn-auth',
  1515. kind: 'error',
  1516. content:
  1517. 'The service rejected request authentication.\nIf the problem persists, report this error and its code. Your prompt is preserved.',
  1518. }),
  1519. ]);
  1520. expect(controller.snapshot()).toMatchObject({
  1521. status: 'error',
  1522. error:
  1523. 'The service rejected request authentication.\nIf the problem persists, report this error and its code. Your prompt is preserved.',
  1524. });
  1525. });
  1526. it('does not suggest retry when local-runtime marks a failure as non-retryable', async () => {
  1527. const runtime = {
  1528. createSession: vi.fn(async () => ({ sessionId: 'session-non-retryable' })),
  1529. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  1530. yield* [] as TuiStreamEvent[];
  1531. throw Object.assign(new Error('provider unavailable'), { retryable: false });
  1532. }),
  1533. abortSession: vi.fn(async () => true),
  1534. };
  1535. const transcript = new TranscriptStore();
  1536. const controller = new TuiChatController({
  1537. runtime,
  1538. transcript,
  1539. workspaceDir: '/workspace',
  1540. createTurnId: () => 'turn-non-retryable',
  1541. now: () => 100,
  1542. });
  1543. await expect(controller.submit('Unsupported request')).resolves.toBe('failed');
  1544. expect(controller.snapshot()).toMatchObject({
  1545. status: 'error',
  1546. errorRetryable: false,
  1547. });
  1548. expect(controller.snapshot().error).not.toContain('/retry');
  1549. expect(transcript.get('error:turn-non-retryable')?.content).not.toContain('/retry');
  1550. });
  1551. it('maps local-runtime numeric tool statuses to terminal states', async () => {
  1552. const runtime = {
  1553. createSession: vi.fn(async () => ({ sessionId: 'session-tools' })),
  1554. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  1555. yield {
  1556. type: 'delta',
  1557. toolCalls: [
  1558. { id: 'tool-finished', name: 'read', status: 2 },
  1559. { id: 'tool-failed', name: 'bash', status: 3 },
  1560. ],
  1561. };
  1562. yield { type: 'done' };
  1563. }),
  1564. abortSession: vi.fn(async () => true),
  1565. };
  1566. const transcript = new TranscriptStore();
  1567. const controller = new TuiChatController({
  1568. runtime,
  1569. transcript,
  1570. workspaceDir: '/workspace',
  1571. createTurnId: () => 'turn-tools',
  1572. now: () => 100,
  1573. });
  1574. await controller.submit('Run tools');
  1575. expect(transcript.get('tool:turn-tools:tool-finished')).toMatchObject({
  1576. status: 'succeeded',
  1577. });
  1578. expect(transcript.get('tool:turn-tools:tool-failed')).toMatchObject({
  1579. status: 'failed',
  1580. });
  1581. });
  1582. it('routes stop through local-runtime and marks the turn cancelled', async () => {
  1583. const runtime = {
  1584. createSession: vi.fn(async () => ({ sessionId: 'session-3' })),
  1585. sendMessage: vi.fn(async function* sendMessage(
  1586. _req: SendMessageReq,
  1587. signal?: AbortSignal,
  1588. ): AsyncGenerator<TuiStreamEvent> {
  1589. await new Promise<void>((resolve) => {
  1590. signal?.addEventListener('abort', () => resolve(), { once: true });
  1591. });
  1592. yield { type: 'done', turnId: 'turn-3' };
  1593. }),
  1594. abortSession: vi.fn(async () => true),
  1595. };
  1596. const transcript = new TranscriptStore();
  1597. const controller = new TuiChatController({
  1598. runtime,
  1599. transcript,
  1600. workspaceDir: '/workspace',
  1601. createTurnId: () => 'turn-3',
  1602. now: () => 100,
  1603. });
  1604. const submitting = controller.submit('Wait');
  1605. await vi.waitFor(() => expect(controller.snapshot().status).toBe('running'));
  1606. await expect(controller.abort()).resolves.toBe(true);
  1607. await submitting;
  1608. expect(runtime.abortSession).toHaveBeenCalledWith({
  1609. id: 'session-3',
  1610. turnId: 'turn-3',
  1611. reason: 'user_stop',
  1612. });
  1613. expect(transcript.get('assistant:turn-3')).toMatchObject({ status: 'cancelled' });
  1614. expect(controller.snapshot().status).toBe('idle');
  1615. });
  1616. it('cancels a turn while its first session is still being created', async () => {
  1617. let finishSessionCreation:
  1618. | ((session: { sessionId: string; workspaceDir: string }) => void)
  1619. | undefined;
  1620. const runtime = {
  1621. createSession: vi.fn(
  1622. async () =>
  1623. await new Promise<{ sessionId: string; workspaceDir: string }>((resolve) => {
  1624. finishSessionCreation = resolve;
  1625. }),
  1626. ),
  1627. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  1628. yield { type: 'done' };
  1629. }),
  1630. abortSession: vi.fn(async () => true),
  1631. };
  1632. const transcript = new TranscriptStore();
  1633. const controller = new TuiChatController({
  1634. runtime,
  1635. transcript,
  1636. workspaceDir: '/workspace',
  1637. createTurnId: () => 'turn-creating-session',
  1638. now: () => 100,
  1639. });
  1640. const submitting = controller.submit('Wait for the session');
  1641. await vi.waitFor(() =>
  1642. expect(controller.snapshot()).toMatchObject({
  1643. status: 'starting',
  1644. activeTurnId: 'turn-creating-session',
  1645. }),
  1646. );
  1647. await expect(controller.abort()).resolves.toBe(true);
  1648. finishSessionCreation?.({ sessionId: 'session-created', workspaceDir: '/workspace' });
  1649. await expect(submitting).resolves.toBe('cancelled');
  1650. expect(runtime.sendMessage).not.toHaveBeenCalled();
  1651. expect(runtime.abortSession).not.toHaveBeenCalled();
  1652. expect(transcript.get('assistant:turn-creating-session')).toMatchObject({
  1653. status: 'cancelled',
  1654. });
  1655. expect(controller.snapshot()).toMatchObject({
  1656. status: 'idle',
  1657. activeTurnId: undefined,
  1658. });
  1659. expect(controller.snapshot().session).toBeUndefined();
  1660. });
  1661. it('retries Session creation after cancellation and ignores the stale result', async () => {
  1662. const resolvers: Array<(session: { sessionId: string; workspaceDir: string }) => void> = [];
  1663. const runtime = {
  1664. createSession: vi.fn(
  1665. async () =>
  1666. await new Promise<{ sessionId: string; workspaceDir: string }>((resolve) => {
  1667. resolvers.push(resolve);
  1668. }),
  1669. ),
  1670. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  1671. yield { type: 'done' };
  1672. }),
  1673. abortSession: vi.fn(async () => true),
  1674. };
  1675. let turnSequence = 0;
  1676. const controller = new TuiChatController({
  1677. runtime,
  1678. transcript: new TranscriptStore(),
  1679. workspaceDir: '/workspace',
  1680. createTurnId: () => `turn-session-retry-${++turnSequence}`,
  1681. now: () => 100,
  1682. });
  1683. const first = controller.submit('First attempt');
  1684. await vi.waitFor(() => expect(resolvers).toHaveLength(1));
  1685. await expect(controller.abort()).resolves.toBe(true);
  1686. await expect(first).resolves.toBe('cancelled');
  1687. const second = controller.submit('Second attempt');
  1688. await vi.waitFor(() => expect(resolvers).toHaveLength(2));
  1689. resolvers[1]?.({ sessionId: 'session-current', workspaceDir: '/workspace' });
  1690. await expect(second).resolves.toBe('succeeded');
  1691. resolvers[0]?.({ sessionId: 'session-stale', workspaceDir: '/workspace' });
  1692. await Promise.resolve();
  1693. expect(runtime.createSession).toHaveBeenCalledTimes(2);
  1694. expect(runtime.sendMessage).toHaveBeenCalledWith(
  1695. {
  1696. id: 'session-current',
  1697. content: 'Second attempt',
  1698. turnId: 'turn-session-retry-2',
  1699. },
  1700. expect.any(AbortSignal),
  1701. );
  1702. expect(controller.snapshot().session?.sessionId).toBe('session-current');
  1703. });
  1704. it('stops the local stream even when the remote abort request fails', async () => {
  1705. const runtime = {
  1706. createSession: vi.fn(async () => ({ sessionId: 'session-4' })),
  1707. sendMessage: vi.fn(async function* sendMessage(
  1708. _req: SendMessageReq,
  1709. signal?: AbortSignal,
  1710. ): AsyncGenerator<TuiStreamEvent> {
  1711. await new Promise<void>((resolve) => {
  1712. signal?.addEventListener('abort', () => resolve(), { once: true });
  1713. });
  1714. yield { type: 'done', turnId: 'turn-4' };
  1715. }),
  1716. abortSession: vi.fn(async () => {
  1717. throw new Error('abort endpoint unavailable');
  1718. }),
  1719. };
  1720. const transcript = new TranscriptStore();
  1721. const controller = new TuiChatController({
  1722. runtime,
  1723. transcript,
  1724. workspaceDir: '/workspace',
  1725. createTurnId: () => 'turn-4',
  1726. now: () => 100,
  1727. });
  1728. const submitting = controller.submit('Wait');
  1729. await vi.waitFor(() => expect(controller.snapshot().status).toBe('running'));
  1730. await expect(controller.abort()).resolves.toBe(false);
  1731. await submitting;
  1732. expect(transcript.get('assistant:turn-4')).toMatchObject({ status: 'cancelled' });
  1733. expect(controller.snapshot().status).toBe('idle');
  1734. });
  1735. it('keeps the controller editable but blocks a new turn until cancellation retires', async () => {
  1736. let sequence = 0;
  1737. let releaseCancelledStream: (() => void) | undefined;
  1738. const runtime = {
  1739. createSession: vi.fn(async () => ({ sessionId: 'session-hung-cancel' })),
  1740. sendMessage: vi.fn(async function* sendMessage(
  1741. req: SendMessageReq,
  1742. signal?: AbortSignal,
  1743. ): AsyncGenerator<TuiStreamEvent> {
  1744. if (req.content === 'First') {
  1745. await new Promise<void>((resolve) => {
  1746. signal?.addEventListener('abort', resolve, { once: true });
  1747. });
  1748. await new Promise<void>((resolve) => {
  1749. releaseCancelledStream = resolve;
  1750. });
  1751. }
  1752. yield { type: 'delta', content: 'Recovered' };
  1753. yield { type: 'done' };
  1754. }),
  1755. abortSession: vi.fn(async () => true),
  1756. steer: vi.fn(),
  1757. };
  1758. const transcript = new TranscriptStore();
  1759. const controller = new ProductionTuiChatController({
  1760. runtime,
  1761. transcript,
  1762. workspaceDir: '/workspace',
  1763. createTurnId: () => `turn-${++sequence}`,
  1764. retirementWarningTimeoutMs: 5,
  1765. runCoordinator: new TuiRunCoordinator(runtime, {
  1766. cancellationSettlementTimeoutMs: 10,
  1767. }),
  1768. });
  1769. void controller.submit('First');
  1770. await vi.waitFor(() => expect(controller.snapshot().status).toBe('running'));
  1771. await expect(controller.abort()).resolves.toBe(true);
  1772. expect(controller.snapshot()).toMatchObject({
  1773. status: 'idle',
  1774. activeTurnId: undefined,
  1775. cancelling: false,
  1776. retiringTurnId: 'turn-1',
  1777. });
  1778. await expect(controller.submit('Second')).rejects.toThrow(
  1779. 'The previous run is still stopping.',
  1780. );
  1781. await vi.waitFor(() => {
  1782. expect(controller.snapshot()).toMatchObject({
  1783. status: 'error',
  1784. retiringTurnId: 'turn-1',
  1785. error: expect.stringContaining('taking too long to stop'),
  1786. });
  1787. });
  1788. releaseCancelledStream?.();
  1789. await vi.waitFor(() => expect(controller.snapshot().retiringTurnId).toBeUndefined());
  1790. expect(controller.snapshot()).toMatchObject({ status: 'idle', error: undefined });
  1791. await expect(controller.submit('Second')).resolves.toBe('succeeded');
  1792. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  1793. expect(transcript.get('assistant:turn-2')).toMatchObject({
  1794. status: 'succeeded',
  1795. content: 'Recovered',
  1796. });
  1797. });
  1798. it('defers an automation cancel terminal until a slow result write retires', async () => {
  1799. const resultWritten = Promise.withResolvers<void>();
  1800. const writeAutomationResult = vi.fn(async () => resultWritten.promise);
  1801. const runtime = {
  1802. createSession: vi.fn(async () => ({ sessionId: 'session-slow-result-cancel' })),
  1803. sendMessage: vi.fn(async function* sendMessage(
  1804. _req: SendMessageReq,
  1805. signal?: AbortSignal,
  1806. ): AsyncGenerator<TuiStreamEvent> {
  1807. await new Promise<void>((resolve) => {
  1808. signal?.addEventListener('abort', resolve, { once: true });
  1809. });
  1810. yield { type: 'done' };
  1811. }),
  1812. abortSession: vi.fn(async () => true),
  1813. };
  1814. const controller = new TuiChatController({
  1815. runtime,
  1816. transcript: new TranscriptStore(),
  1817. workspaceDir: '/workspace',
  1818. createTurnId: () => 'turn-slow-result-cancel',
  1819. writeAutomationResult,
  1820. runCoordinator: new TuiRunCoordinator(runtime, {
  1821. cancellationSettlementTimeoutMs: 1,
  1822. }),
  1823. });
  1824. const submitting = controller.submit('Wait');
  1825. await vi.waitFor(() => expect(controller.snapshot().status).toBe('running'));
  1826. await expect(controller.abort()).resolves.toBe(true);
  1827. await vi.waitFor(() => expect(writeAutomationResult).toHaveBeenCalledOnce());
  1828. expect(controller.snapshot()).toMatchObject({
  1829. retiringTurnId: 'turn-slow-result-cancel',
  1830. lastSettledTurn: undefined,
  1831. });
  1832. resultWritten.resolve();
  1833. await submitting;
  1834. await vi.waitFor(() =>
  1835. expect(controller.snapshot().lastSettledTurn).toEqual({
  1836. sessionId: 'session-slow-result-cancel',
  1837. turnId: 'turn-slow-result-cancel',
  1838. status: 'cancelled',
  1839. }),
  1840. );
  1841. });
  1842. it('loads Desktop sessions, hydrates history, and supports rename and archive', async () => {
  1843. const runtime = {
  1844. createSession: vi.fn(async (input: { parentSessionId?: string; title?: string }) => ({
  1845. sessionId: 'session-fork',
  1846. parentSessionId: input.parentSessionId,
  1847. title: input.title,
  1848. workspaceDir: '/workspace',
  1849. })),
  1850. listSessions: vi.fn(async () => [
  1851. {
  1852. sessionId: 'session-1',
  1853. title: 'Existing',
  1854. workspaceDir: '/workspace',
  1855. updatedAt: 200,
  1856. },
  1857. ]),
  1858. getSession: vi.fn(async () => ({
  1859. sessionId: 'session-1',
  1860. title: 'Existing',
  1861. workspaceDir: '/workspace',
  1862. })),
  1863. getMessages: vi.fn(async () => [
  1864. {
  1865. id: 'message-user',
  1866. turnId: 'turn-history',
  1867. role: 'user' as const,
  1868. content: 'Earlier question',
  1869. attachments: [
  1870. {
  1871. type: 'file' as const,
  1872. fileName: 'notes.md',
  1873. mimeType: 'text/markdown',
  1874. sizeBytes: 2048,
  1875. },
  1876. ],
  1877. timestamp: 100,
  1878. },
  1879. {
  1880. id: 'message-assistant',
  1881. turnId: 'turn-history',
  1882. role: 'assistant' as const,
  1883. content: 'Earlier answer',
  1884. toolCalls: [{ id: 'tool-history', name: 'read', status: 'completed' }],
  1885. timestamp: 101,
  1886. },
  1887. ]),
  1888. renameSession: vi.fn(async (_sessionId: string, title: string) => ({
  1889. sessionId: 'session-1',
  1890. title,
  1891. workspaceDir: '/workspace',
  1892. })),
  1893. archiveSession: vi.fn(async () => undefined),
  1894. getAccountStatus: vi.fn(async () => ({
  1895. status: 'ready' as const,
  1896. defaultModel: 'minimax/MiniMax-M2.7',
  1897. providerId: 'minimax',
  1898. authMode: 'managed-login',
  1899. managedTokenPresent: true,
  1900. warnings: [],
  1901. })),
  1902. sendMessage: vi.fn(),
  1903. abortSession: vi.fn(async () => true),
  1904. };
  1905. const transcript = new TranscriptStore();
  1906. const controller = new TuiChatController({
  1907. runtime,
  1908. transcript,
  1909. workspaceDir: '/workspace',
  1910. now: () => 300,
  1911. });
  1912. await controller.initialize();
  1913. await controller.loadSessionProjection('session-1');
  1914. expect(controller.snapshot()).toMatchObject({
  1915. status: 'idle',
  1916. session: { sessionId: 'session-1', title: 'Existing' },
  1917. sessions: [expect.objectContaining({ sessionId: 'session-1' })],
  1918. account: expect.objectContaining({
  1919. status: 'ready',
  1920. defaultModel: 'minimax/MiniMax-M2.7',
  1921. }),
  1922. });
  1923. expect(transcript.snapshot()).toEqual([
  1924. expect.objectContaining({
  1925. kind: 'user',
  1926. content: 'Earlier question',
  1927. attachments: [
  1928. {
  1929. type: 'file',
  1930. fileName: 'notes.md',
  1931. mimeType: 'text/markdown',
  1932. sizeBytes: 2048,
  1933. },
  1934. ],
  1935. turnId: 'turn-history',
  1936. }),
  1937. expect.objectContaining({
  1938. kind: 'assistant-preamble',
  1939. content: 'Earlier answer',
  1940. turnId: 'turn-history',
  1941. }),
  1942. expect.objectContaining({
  1943. kind: 'tool',
  1944. title: 'read',
  1945. status: 'succeeded',
  1946. }),
  1947. ]);
  1948. await controller.renameCurrentSession('Renamed');
  1949. expect(controller.snapshot().session?.title).toBe('Renamed');
  1950. await controller.runtimeTurnSettlement.settle('session-1', 'turn-archived', 'succeeded', 0);
  1951. await controller.archiveCurrentSession();
  1952. expect(runtime.archiveSession).toHaveBeenCalledWith('session-1', true);
  1953. expect(controller.snapshot().session).toBeUndefined();
  1954. expect(controller.snapshot().lastSettledTurn).toBeUndefined();
  1955. });
  1956. it('drops a stale Session resume when a newer Session finishes loading first', async () => {
  1957. let resolveFirstMessages:
  1958. | ((messages: Array<{ id: string; role: 'user'; content: string }>) => void)
  1959. | undefined;
  1960. const runtime = {
  1961. createSession: vi.fn(async () => ({ sessionId: 'session-created' })),
  1962. getSession: vi.fn(async (sessionId: string) => ({ sessionId, title: sessionId })),
  1963. getMessages: vi.fn(async (sessionId: string) => {
  1964. if (sessionId === 'session-a') {
  1965. return await new Promise<Array<{ id: string; role: 'user'; content: string }>>(
  1966. (resolve) => {
  1967. resolveFirstMessages = resolve;
  1968. },
  1969. );
  1970. }
  1971. return [{ id: 'message-b', role: 'user' as const, content: 'History B' }];
  1972. }),
  1973. sendMessage: vi.fn(),
  1974. abortSession: vi.fn(async () => true),
  1975. steer: vi.fn(),
  1976. };
  1977. const transcript = new TranscriptStore();
  1978. const controller = new ProductionTuiChatController({
  1979. runtime,
  1980. transcript,
  1981. workspaceDir: '/workspace',
  1982. });
  1983. const firstResume = controller.loadSessionProjection('session-a');
  1984. await vi.waitFor(() => expect(resolveFirstMessages).toBeTypeOf('function'));
  1985. await controller.loadSessionProjection('session-b');
  1986. resolveFirstMessages?.([{ id: 'message-a', role: 'user', content: 'History A' }]);
  1987. await firstResume;
  1988. expect(controller.snapshot()).toMatchObject({
  1989. status: 'idle',
  1990. session: { sessionId: 'session-b' },
  1991. });
  1992. expect(transcript.snapshot()).toEqual([
  1993. expect.objectContaining({ kind: 'user', content: 'History B' }),
  1994. ]);
  1995. });
  1996. it('keeps the latest Session catalog when refreshes resolve out of order', async () => {
  1997. const sessionResolvers: Array<(sessions: Array<{ sessionId: string; title: string }>) => void> =
  1998. [];
  1999. const runtime = {
  2000. listSessions: vi.fn(
  2001. async () =>
  2002. await new Promise<Array<{ sessionId: string; title: string }>>((resolve) => {
  2003. sessionResolvers.push(resolve);
  2004. }),
  2005. ),
  2006. };
  2007. const controller = new ProductionTuiChatController({
  2008. runtime: runtime as never,
  2009. transcript: new TranscriptStore(),
  2010. workspaceDir: '/workspace',
  2011. });
  2012. const olderRefresh = controller.refreshSessionList();
  2013. const newerRefresh = controller.refreshSessionList();
  2014. await vi.waitFor(() => expect(sessionResolvers).toHaveLength(2));
  2015. sessionResolvers[1]?.([{ sessionId: 'session-new', title: 'New catalog' }]);
  2016. await newerRefresh;
  2017. sessionResolvers[0]?.([{ sessionId: 'session-old', title: 'Old catalog' }]);
  2018. await olderRefresh;
  2019. expect(controller.snapshot().sessions).toEqual([
  2020. expect.objectContaining({ sessionId: 'session-new', title: 'New catalog' }),
  2021. ]);
  2022. });
  2023. it('refreshes account quota after a completed turn', async () => {
  2024. const runtime = {
  2025. createSession: vi.fn(async () => ({ sessionId: 'session-meters' })),
  2026. listSessions: vi.fn(async () => []),
  2027. getAccountStatus: vi.fn(async (_sessionId, options) => ({
  2028. status: 'ready' as const,
  2029. defaultModel: 'minimax/MiniMax-M2.7',
  2030. providerId: 'minimax',
  2031. modelId: 'MiniMax-M2.7',
  2032. authMode: 'managed-login',
  2033. managedTokenPresent: true,
  2034. modelSource: 'token-plan' as const,
  2035. ...(options?.includeMembership === true
  2036. ? {
  2037. tokenPlanQuota: {
  2038. fiveHour: { remainingPercent: 82, unlimited: false },
  2039. weekly: { remainingPercent: 64, unlimited: false },
  2040. },
  2041. }
  2042. : {}),
  2043. warnings: [],
  2044. })),
  2045. sendMessage: vi.fn(async function* sendMessage(): AsyncGenerator<TuiStreamEvent> {
  2046. yield { type: 'delta', content: 'Done' };
  2047. yield { type: 'done' };
  2048. }),
  2049. abortSession: vi.fn(async () => true),
  2050. };
  2051. const controller = new TuiChatController({
  2052. runtime,
  2053. transcript: new TranscriptStore(),
  2054. workspaceDir: '/workspace',
  2055. });
  2056. await controller.initialize();
  2057. await controller.submit('Measure this turn');
  2058. await vi.waitFor(() => {
  2059. expect(controller.snapshot()).toMatchObject({
  2060. account: {
  2061. modelSource: 'token-plan',
  2062. tokenPlanQuota: {
  2063. fiveHour: { remainingPercent: 82 },
  2064. weekly: { remainingPercent: 64 },
  2065. },
  2066. },
  2067. });
  2068. });
  2069. expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
  2070. includeMembership: false,
  2071. });
  2072. expect(runtime.getAccountStatus).toHaveBeenCalledWith('session-meters', {
  2073. includeMembership: false,
  2074. });
  2075. await vi.waitFor(() =>
  2076. expect(runtime.getAccountStatus).toHaveBeenCalledWith('session-meters', {
  2077. includeMembership: true,
  2078. }),
  2079. );
  2080. });
  2081. it('preserves ephemeral local cells in place during same-Session history reconciliation', async () => {
  2082. let messages = [
  2083. {
  2084. id: 'message-1',
  2085. turnId: 'turn-1',
  2086. role: 'assistant' as const,
  2087. content: 'First durable answer',
  2088. },
  2089. ];
  2090. const runtime = {
  2091. getSession: vi.fn(async (sessionId: string) => ({ sessionId })),
  2092. getMessages: vi.fn(async () => messages),
  2093. };
  2094. const transcript = new TranscriptStore();
  2095. const controller = new ProductionTuiChatController({
  2096. runtime: runtime as never,
  2097. transcript,
  2098. workspaceDir: '/workspace',
  2099. });
  2100. await controller.loadSessionProjection('session-local-cells');
  2101. transcript.upsert({
  2102. id: 'local:status',
  2103. kind: 'final-summary',
  2104. status: 'succeeded',
  2105. content: 'MCode status',
  2106. ephemeral: true,
  2107. createdAtMs: 100,
  2108. updatedAtMs: 100,
  2109. });
  2110. messages = [
  2111. {
  2112. ...messages[0],
  2113. id: 'message-1-reprojected',
  2114. },
  2115. {
  2116. id: 'message-2',
  2117. turnId: 'turn-2',
  2118. role: 'assistant' as const,
  2119. content: 'Second durable answer',
  2120. },
  2121. ];
  2122. await controller.refreshCurrentSessionHistory();
  2123. expect(transcript.snapshot().map((cell) => cell.content)).toEqual([
  2124. 'First durable answer',
  2125. 'MCode status',
  2126. 'Second durable answer',
  2127. ]);
  2128. messages = [];
  2129. await controller.loadSessionProjection('session-other');
  2130. expect(transcript.snapshot()).toEqual([]);
  2131. });
  2132. it('restores thinking, tool evidence and Tasks while filtering durable protocol rows', async () => {
  2133. const onTodoChange = vi.fn();
  2134. const runtime = {
  2135. createSession: vi.fn(),
  2136. getSession: vi.fn(async () => ({ sessionId: 'session-resume' })),
  2137. getMessages: vi.fn(async () => [
  2138. {
  2139. id: 'assistant-tool',
  2140. turnId: 'turn-resume',
  2141. role: 'assistant' as const,
  2142. thinking: 'Inspect the history projection.',
  2143. toolCalls: [
  2144. {
  2145. id: 'tool-grep',
  2146. name: 'grep',
  2147. status: 'completed',
  2148. input: '{"pattern":"hydrateHistory","path":"packages/tui"}',
  2149. output:
  2150. '{"content":[{"type":"text","text":"packages/tui/src/a.ts:12:hydrateHistory"}]}',
  2151. },
  2152. ],
  2153. },
  2154. {
  2155. id: 'todo-event',
  2156. turnId: 'turn-resume',
  2157. role: 'unknown' as const,
  2158. content: JSON.stringify({
  2159. eventType: 'todo_updated',
  2160. todos: [{ content: 'Verify resume', status: 'completed', priority: 'high' }],
  2161. }),
  2162. },
  2163. {
  2164. id: 'todo-tool',
  2165. turnId: 'turn-resume',
  2166. role: 'assistant' as const,
  2167. toolCalls: [{ id: 'todo-write', name: 'functions.TodoWrite', status: 'completed' }],
  2168. },
  2169. ]),
  2170. sendMessage: vi.fn(),
  2171. abortSession: vi.fn(async () => true),
  2172. };
  2173. const transcript = new TranscriptStore();
  2174. const controller = new TuiChatController({
  2175. runtime,
  2176. transcript,
  2177. workspaceDir: '/workspace',
  2178. onTodoChange,
  2179. });
  2180. await controller.loadSessionProjection('session-resume');
  2181. expect(transcript.snapshot()).toEqual([
  2182. expect.objectContaining({
  2183. kind: 'thinking',
  2184. content: 'Inspect the history projection.',
  2185. }),
  2186. expect.objectContaining({
  2187. kind: 'tool',
  2188. title: 'grep',
  2189. content: '{"pattern":"hydrateHistory","path":"packages/tui"}',
  2190. detail: 'packages/tui/src/a.ts:12:hydrateHistory',
  2191. }),
  2192. ]);
  2193. expect(onTodoChange).toHaveBeenLastCalledWith([
  2194. { content: 'Verify resume', status: 'completed' },
  2195. ]);
  2196. const view = new TranscriptView(() => transcript.snapshot());
  2197. const compact = view.render(80).join('\n');
  2198. expect(compact).toContain('Thought');
  2199. expect(compact).toContain('Searched (hydrateHistory in packages/tui)');
  2200. expect(compact).not.toContain('Inspect the history projection.');
  2201. expect(compact).not.toContain('packages/tui/src/a.ts:12:hydrateHistory');
  2202. view.toggleDetailMode();
  2203. const detailed = view.render(80).join('\n');
  2204. expect(detailed).toContain('Inspect the history projection.');
  2205. expect(detailed).toContain('Searched (hydrateHistory in packages/tui)');
  2206. expect(detailed).toContain('packages/tui/src/a.ts:12:hydrateHistory');
  2207. expect(detailed).not.toContain('todo_updated');
  2208. expect(detailed).not.toContain('TodoWrite');
  2209. });
  2210. it('hydrates ordered message parts without flattening text and tools', async () => {
  2211. const runtime = {
  2212. createSession: vi.fn(),
  2213. listSessions: vi.fn(async () => []),
  2214. getSession: vi.fn(async () => ({ sessionId: 'session-parts' })),
  2215. getMessages: vi.fn(async () => [
  2216. {
  2217. id: 'message-parts',
  2218. turnId: 'turn-parts',
  2219. role: 'assistant' as const,
  2220. parts: [
  2221. { id: 'thinking-1', type: 'thinking' as const, content: 'Plan' },
  2222. { id: 'text-1', type: 'text' as const, content: 'I will inspect.' },
  2223. {
  2224. id: 'tool-1',
  2225. type: 'tool' as const,
  2226. toolCall: {
  2227. id: 'call-1',
  2228. name: 'read',
  2229. status: 'completed',
  2230. input: { path: 'README.md' },
  2231. },
  2232. },
  2233. { id: 'thinking-2', type: 'thinking' as const, content: 'Interpret' },
  2234. { id: 'text-2', type: 'text' as const, content: 'Done.' },
  2235. ],
  2236. },
  2237. ]),
  2238. sendMessage: vi.fn(),
  2239. abortSession: vi.fn(async () => true),
  2240. };
  2241. const transcript = new TranscriptStore();
  2242. const controller = new TuiChatController({
  2243. runtime,
  2244. transcript,
  2245. workspaceDir: '/workspace',
  2246. });
  2247. await controller.loadSessionProjection('session-parts');
  2248. expect(
  2249. transcript.snapshot().map((cell) => ({
  2250. kind: cell.kind,
  2251. content: cell.content,
  2252. title: cell.title,
  2253. })),
  2254. ).toEqual([
  2255. { kind: 'thinking', content: 'Plan', title: undefined },
  2256. { kind: 'assistant-preamble', content: 'I will inspect.', title: undefined },
  2257. { kind: 'tool', content: '{"path":"README.md"}', title: 'read' },
  2258. { kind: 'thinking', content: 'Interpret', title: undefined },
  2259. { kind: 'assistant', content: 'Done.', title: undefined },
  2260. ]);
  2261. });
  2262. it('keeps distinct durable assistant messages when one turn repeats the same text', async () => {
  2263. const runtime = {
  2264. createSession: vi.fn(),
  2265. getSession: vi.fn(async () => ({ sessionId: 'session-repeated-text' })),
  2266. getMessages: vi.fn(async () => [
  2267. {
  2268. id: 'assistant-first',
  2269. turnId: 'turn-repeated-text',
  2270. role: 'assistant' as const,
  2271. content: 'Same answer',
  2272. timestamp: 100,
  2273. },
  2274. {
  2275. id: 'assistant-second',
  2276. turnId: 'turn-repeated-text',
  2277. role: 'assistant' as const,
  2278. content: 'Same answer',
  2279. timestamp: 101,
  2280. },
  2281. ]),
  2282. };
  2283. const transcript = new TranscriptStore();
  2284. const controller = new TuiChatController({
  2285. runtime,
  2286. transcript,
  2287. workspaceDir: '/workspace',
  2288. });
  2289. await controller.loadSessionProjection('session-repeated-text');
  2290. expect(
  2291. transcript
  2292. .snapshot()
  2293. .filter((cell) => cell.kind === 'assistant')
  2294. .map((cell) => cell.id),
  2295. ).toEqual(['history:assistant:assistant-first', 'history:assistant:assistant-second']);
  2296. });
  2297. it('projects questionnaire history as a readable receipt and hides internal Ask User protocol', async () => {
  2298. const runtime = {
  2299. createSession: vi.fn(async () => ({ sessionId: 'session-questionnaire' })),
  2300. listSessions: vi.fn(async () => []),
  2301. getSession: vi.fn(async () => ({ sessionId: 'session-questionnaire' })),
  2302. getMessages: vi.fn(async () => [
  2303. {
  2304. id: 'ask-preamble',
  2305. turnId: 'turn-ask',
  2306. role: 'assistant' as const,
  2307. content: 'I need two choices before continuing.',
  2308. toolCalls: [
  2309. {
  2310. id: 'ask-tool',
  2311. name: 'functions.AskUser',
  2312. status: 'completed',
  2313. input: { title: 'Choose', steps: [{ question: 'Which option?' }] },
  2314. },
  2315. ],
  2316. },
  2317. {
  2318. id: 'ask-reply',
  2319. turnId: 'turn-ask-reply',
  2320. role: 'user' as const,
  2321. content: [
  2322. '<questionnaire-response>',
  2323. ' <requestId>ask_1</requestId>',
  2324. ' <answers />',
  2325. '</questionnaire-response>',
  2326. '',
  2327. 'Q: Which option? ',
  2328. 'A: Stable',
  2329. ].join('\n'),
  2330. },
  2331. {
  2332. id: 'final-a',
  2333. turnId: 'turn-final',
  2334. role: 'assistant' as const,
  2335. content: 'Continuing with Stable.',
  2336. },
  2337. ]),
  2338. sendMessage: vi.fn(),
  2339. abortSession: vi.fn(async () => true),
  2340. };
  2341. const transcript = new TranscriptStore();
  2342. const controller = new TuiChatController({
  2343. runtime,
  2344. transcript,
  2345. workspaceDir: '/workspace',
  2346. });
  2347. await controller.loadSessionProjection('session-questionnaire');
  2348. expect(transcript.snapshot()).toEqual([
  2349. expect.objectContaining({
  2350. kind: 'assistant',
  2351. content: 'I need two choices before continuing.',
  2352. }),
  2353. expect.objectContaining({
  2354. id: 'question:ask_1',
  2355. kind: 'question',
  2356. status: 'resolved',
  2357. title: 'Answers sent',
  2358. content: 'Which option? Stable',
  2359. }),
  2360. expect.objectContaining({
  2361. kind: 'assistant',
  2362. content: 'Continuing with Stable.',
  2363. }),
  2364. ]);
  2365. const renderedContent = transcript
  2366. .snapshot()
  2367. .map((cell) => `${cell.title ?? ''}\n${cell.content}`)
  2368. .join('\n');
  2369. expect(renderedContent).not.toContain('functions.AskUser');
  2370. expect(renderedContent).not.toContain('questionnaire-response');
  2371. expect(renderedContent.match(/Continuing with Stable\./gu)).toHaveLength(1);
  2372. });
  2373. it('replays the durable continuation reply after a resolved questionnaire', async () => {
  2374. const runtime = {
  2375. createSession: vi.fn(),
  2376. getSession: vi.fn(async () => ({ sessionId: 'session-questionnaire-continuation' })),
  2377. getMessages: vi.fn(async () => [
  2378. {
  2379. id: 'ask-user-turn',
  2380. turnId: 'turn-ask-user',
  2381. role: 'assistant' as const,
  2382. content: '',
  2383. toolCalls: [{ name: 'ask_user', status: 'completed' }],
  2384. timestamp: 100,
  2385. },
  2386. {
  2387. id: 'ask-user-reply',
  2388. turnId: 'turn-questionnaire-continuation',
  2389. role: 'user' as const,
  2390. content: [
  2391. '<questionnaire-response>',
  2392. ' <requestId>ask_1</requestId>',
  2393. ' <answers />',
  2394. '</questionnaire-response>',
  2395. '',
  2396. 'Q: What next? ',
  2397. 'A: Chat',
  2398. ].join('\n'),
  2399. timestamp: 200,
  2400. },
  2401. {
  2402. id: 'continuation-final',
  2403. turnId: 'turn-questionnaire-continuation',
  2404. role: 'assistant' as const,
  2405. content: '好呀,那就随便聊聊。',
  2406. timestamp: 300,
  2407. },
  2408. ]),
  2409. sendMessage: vi.fn(),
  2410. abortSession: vi.fn(async () => true),
  2411. };
  2412. const transcript = new TranscriptStore();
  2413. const controller = new TuiChatController({
  2414. runtime,
  2415. transcript,
  2416. workspaceDir: '/workspace',
  2417. });
  2418. await controller.loadSessionProjection('session-questionnaire-continuation');
  2419. expect(transcript.snapshot()).toContainEqual(
  2420. expect.objectContaining({
  2421. kind: 'assistant',
  2422. turnId: 'turn-questionnaire-continuation',
  2423. content: '好呀,那就随便聊聊。',
  2424. }),
  2425. );
  2426. });
  2427. it('restores an archived Session before making it the active projection', async () => {
  2428. let archived = true;
  2429. const runtime = {
  2430. getSession: vi.fn(async () => ({
  2431. sessionId: 'session-archived',
  2432. workspaceDir: '/workspace',
  2433. archived,
  2434. })),
  2435. getMessages: vi.fn(async () => []),
  2436. archiveSession: vi.fn(async (_sessionId: string, value: boolean) => {
  2437. archived = value;
  2438. }),
  2439. sendMessage: vi.fn(),
  2440. abortSession: vi.fn(async () => true),
  2441. };
  2442. const controller = new TuiChatController({
  2443. runtime,
  2444. transcript: new TranscriptStore(),
  2445. workspaceDir: '/workspace',
  2446. });
  2447. await controller.loadSessionProjection('session-archived');
  2448. expect(runtime.archiveSession).toHaveBeenCalledWith('session-archived', false);
  2449. expect(controller.snapshot().session).toMatchObject({
  2450. sessionId: 'session-archived',
  2451. archived: false,
  2452. });
  2453. });
  2454. it('manages a selected Desktop session without requiring it to be active first', async () => {
  2455. let archived = false;
  2456. const runtime = {
  2457. createSession: vi.fn(
  2458. async (input: { parentSessionId?: string; title?: string; workspaceDir: string }) => ({
  2459. sessionId: 'session-fork',
  2460. parentSessionId: input.parentSessionId,
  2461. title: input.title,
  2462. workspaceDir: input.workspaceDir,
  2463. }),
  2464. ),
  2465. listSessions: vi.fn(async () => [
  2466. {
  2467. sessionId: 'session-1',
  2468. title: 'First',
  2469. workspaceDir: '/workspace',
  2470. updatedAt: 200,
  2471. },
  2472. {
  2473. sessionId: 'session-2',
  2474. title: 'Second',
  2475. workspaceDir: '/other',
  2476. updatedAt: 100,
  2477. },
  2478. ]),
  2479. getSession: vi.fn(async (sessionId: string) => ({
  2480. sessionId,
  2481. title: sessionId === 'session-2' ? 'Renamed second' : 'First',
  2482. workspaceDir: sessionId === 'session-2' ? '/other' : '/workspace',
  2483. archived,
  2484. })),
  2485. getMessages: vi.fn(async () => []),
  2486. renameSession: vi.fn(async (sessionId: string, title: string) => ({
  2487. sessionId,
  2488. title,
  2489. workspaceDir: '/other',
  2490. })),
  2491. archiveSession: vi.fn(async (_sessionId: string, value: boolean) => {
  2492. archived = value;
  2493. }),
  2494. getAccountStatus: vi.fn(async () => ({
  2495. status: 'ready' as const,
  2496. warnings: [],
  2497. })),
  2498. sendMessage: vi.fn(),
  2499. abortSession: vi.fn(async () => true),
  2500. };
  2501. const controller = new TuiChatController({
  2502. runtime,
  2503. transcript: new TranscriptStore(),
  2504. workspaceDir: '/workspace',
  2505. });
  2506. await controller.initialize();
  2507. await controller.loadSessionProjection('session-1');
  2508. await expect(controller.renameSession('session-2', 'Renamed second')).resolves.toMatchObject({
  2509. sessionId: 'session-2',
  2510. title: 'Renamed second',
  2511. });
  2512. expect(controller.snapshot().session?.sessionId).toBe('session-1');
  2513. await controller.loadSessionProjection('session-1');
  2514. await controller.setSessionArchived('session-2', true);
  2515. expect(controller.snapshot().sessions.map((session) => session.sessionId)).not.toContain(
  2516. 'session-2',
  2517. );
  2518. expect(controller.snapshot().session?.sessionId).toBe('session-1');
  2519. await expect(controller.renameSession('session-2', 'Archived second')).resolves.toMatchObject({
  2520. sessionId: 'session-2',
  2521. title: 'Archived second',
  2522. archived: true,
  2523. });
  2524. expect(controller.snapshot().sessions.map((session) => session.sessionId)).not.toContain(
  2525. 'session-2',
  2526. );
  2527. await expect(controller.setSessionArchived('session-2', false)).resolves.toMatchObject({
  2528. sessionId: 'session-2',
  2529. archived: false,
  2530. });
  2531. expect(controller.snapshot().sessions.map((session) => session.sessionId)).toContain(
  2532. 'session-2',
  2533. );
  2534. });
  2535. it('clears input-adjacent tasks when starting a new session', () => {
  2536. const onTodoChange = vi.fn();
  2537. const controller = new ProductionTuiChatController({
  2538. runtime: {} as never,
  2539. transcript: new TranscriptStore(),
  2540. workspaceDir: '/workspace',
  2541. onTodoChange,
  2542. });
  2543. controller.applyRuntimeTurnEvent('turn-todo', {
  2544. type: 'generic',
  2545. eventType: 'todo_updated',
  2546. turnId: 'turn-todo',
  2547. data: { todos: [{ content: 'Current session task', status: 'in_progress' }] },
  2548. });
  2549. expect(onTodoChange).toHaveBeenLastCalledWith([
  2550. { content: 'Current session task', status: 'in_progress' },
  2551. ]);
  2552. controller.startNewSession();
  2553. expect(onTodoChange).toHaveBeenLastCalledWith([]);
  2554. });
  2555. it('carries the clear source from /new to the lazily-created session', async () => {
  2556. const onSessionLifecycle = vi.fn();
  2557. const controller = new ProductionTuiChatController({
  2558. runtime: {
  2559. createSession: vi.fn(async () => ({ sessionId: 'session-after-clear' })),
  2560. } as never,
  2561. transcript: new TranscriptStore(),
  2562. workspaceDir: '/workspace',
  2563. onSessionLifecycle,
  2564. });
  2565. controller.startNewSession();
  2566. await controller.ensureSession();
  2567. expect(onSessionLifecycle.mock.calls).toEqual([[], ['session-after-clear']]);
  2568. });
  2569. });