command-flow.test.ts 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674
  1. import { describe, expect, it, vi } from "vitest";
  2. import { TuiCommandFlow } from "../../../../../src/tui/controller/product/command-flow.js";
  3. import {
  4. MINIMAX_CODE_TUI_LOGIN_REQUIRED_MESSAGE,
  5. TuiLoginRequiredError,
  6. } from "../../../../../src/application/login-gate.js";
  7. function createFeatureFlowMock() {
  8. return {
  9. skillCommands: () => [],
  10. waitForWelcomeModelSelection: vi.fn(async () => undefined),
  11. applyPendingModelSelection: vi.fn(async () => undefined),
  12. applyPendingModelSelection: vi.fn(async () => undefined),
  13. showChangelog: vi.fn(async () => undefined),
  14. };
  15. }
  16. function createReadinessCommandFlow(options: {
  17. whenReady: () => Promise<void>;
  18. whenControllerReady?: () => Promise<void>;
  19. showHelp?: () => void | Promise<void>;
  20. showChangelog?: () => void | Promise<void>;
  21. showTasks?: () => void | Promise<void>;
  22. showStatusLine?: () => void;
  23. showAccountStatus?: () => void | Promise<void>;
  24. copyLastAssistantReply?: () => void | Promise<void>;
  25. exportCurrentTranscript?: (args: string) => void | Promise<void>;
  26. hasSession?: boolean;
  27. setHint?: (message: string | undefined) => void;
  28. surface?: {
  29. show(component: unknown): void;
  30. close(component?: unknown): boolean;
  31. };
  32. surfaceHost?: {
  33. getChatMode(): "regular" | "fullscreen";
  34. setChatMode(mode: "regular" | "fullscreen"): boolean;
  35. };
  36. persistTuiMode?: (mode: "regular" | "fullscreen") => void;
  37. reloadTui?: () => Promise<void>;
  38. append?: (text: string, kind?: "info" | "warning" | "error") => void;
  39. queuedCount?: number;
  40. }) {
  41. return new TuiCommandFlow({
  42. workspaceDir: "/workspace",
  43. controller: {
  44. snapshot: vi.fn(() => ({
  45. status: "idle" as const,
  46. sessions: [],
  47. ...(options.hasSession ? { session: { sessionId: "session-a" } } : {}),
  48. })),
  49. } as never,
  50. activeRunFlow: { showHelp: options.showHelp ?? vi.fn() } as never,
  51. featureFlow: {
  52. ...createFeatureFlowMock(),
  53. skillCommands: () => [],
  54. showAccountStatus: options.showAccountStatus ?? vi.fn(),
  55. showChangelog: options.showChangelog ?? vi.fn(),
  56. copyLastAssistantReply: options.copyLastAssistantReply ?? vi.fn(),
  57. exportCurrentTranscript: options.exportCurrentTranscript ?? vi.fn(),
  58. } as never,
  59. feedbackFlow: {} as never,
  60. updateFlow: {} as never,
  61. interactionFlow: {
  62. handleCommand: vi.fn(async () => false),
  63. hasPending: vi.fn(() => false),
  64. } as never,
  65. sessionFlow: {} as never,
  66. queueFlow: {} as never,
  67. composerDraft: { hasContent: vi.fn(() => false) } as never,
  68. workspaceRoots: { additionalDirectories: () => [] } as never,
  69. runProjection: {
  70. snapshot: () => ({ queuedCount: options.queuedCount ?? 0 }),
  71. } as never,
  72. editor: {} as never,
  73. surface: (options.surface ?? {}) as never,
  74. surfaceHost: (options.surfaceHost ?? {}) as never,
  75. ...(options.showTasks ? { showTasks: options.showTasks } : {}),
  76. persistTuiMode: options.persistTuiMode,
  77. showStatusLine: options.showStatusLine,
  78. reloadTui: options.reloadTui,
  79. queueEnabled: true,
  80. liveRunId: () => undefined,
  81. runtimeStopping: () => false,
  82. abortLiveTurn: vi.fn(async () => false),
  83. leaveUi: vi.fn(async () => undefined),
  84. whenReady: options.whenReady,
  85. ...(options.whenControllerReady
  86. ? { whenControllerReady: options.whenControllerReady }
  87. : {}),
  88. append: options.append ?? vi.fn(),
  89. setHint: options.setHint ?? vi.fn(),
  90. onChanged: vi.fn(),
  91. });
  92. }
  93. describe("TuiCommandFlow", () => {
  94. it("opens /statusline locally without waiting for hydration or submitting a model turn", async () => {
  95. const showStatusLine = vi.fn();
  96. const whenReady = vi.fn(() => new Promise<void>(() => undefined));
  97. const flow = createReadinessCommandFlow({ whenReady, showStatusLine });
  98. await expect(flow.submit("/statusline")).resolves.toBe("consumed");
  99. expect(showStatusLine).toHaveBeenCalledOnce();
  100. expect(whenReady).not.toHaveBeenCalled();
  101. });
  102. it("opens local help without waiting for application hydration", async () => {
  103. let releaseReady: (() => void) | undefined;
  104. const ready = new Promise<void>((resolve) => {
  105. releaseReady = resolve;
  106. });
  107. const showHelp = vi.fn();
  108. const flow = createReadinessCommandFlow({
  109. whenReady: () => ready,
  110. showHelp,
  111. });
  112. const opening = flow.submit("/help");
  113. await vi.waitFor(() => expect(showHelp).toHaveBeenCalledOnce());
  114. await expect(opening).resolves.toBe("consumed");
  115. releaseReady?.();
  116. });
  117. it("opens the packaged changelog through the command catalog", async () => {
  118. const showChangelog = vi.fn(async () => undefined);
  119. const flow = createReadinessCommandFlow({
  120. whenReady: async () => undefined,
  121. showChangelog,
  122. });
  123. await expect(flow.submit("/changelog")).resolves.toBe("consumed");
  124. expect(showChangelog).toHaveBeenCalledOnce();
  125. });
  126. it("submits /review with hidden fixed transport and local_changes provenance", async () => {
  127. const submit = vi.fn(
  128. async (
  129. _content: string,
  130. options: {
  131. onSessionResolved?: (sessionId: string) => void;
  132. onRuntimeAccepted?: (sessionId: string) => void;
  133. },
  134. ) => {
  135. options.onSessionResolved?.("session-a");
  136. options.onRuntimeAccepted?.("session-a");
  137. return "succeeded" as const;
  138. },
  139. );
  140. const attachment = {
  141. type: "file" as const,
  142. filePath: "/workspace/context.txt",
  143. fileName: "context.txt",
  144. mimeType: "text/plain",
  145. sizeBytes: 10,
  146. };
  147. const resources = { attachments: [attachment] };
  148. const restoreSubmission = vi.fn();
  149. const completeSubmission = vi.fn(async () => undefined);
  150. const flow = new TuiCommandFlow({
  151. workspaceDir: "/workspace",
  152. controller: {
  153. snapshot: vi.fn(() => ({
  154. status: "idle" as const,
  155. sessions: [],
  156. session: { sessionId: "session-a" },
  157. })),
  158. submit,
  159. refreshSessionMetadata: vi.fn(async () => undefined),
  160. } as never,
  161. activeRunFlow: {} as never,
  162. featureFlow: createFeatureFlowMock() as never,
  163. feedbackFlow: {} as never,
  164. updateFlow: {} as never,
  165. interactionFlow: {
  166. handleCommand: vi.fn(async () => false),
  167. hasPending: vi.fn(() => false),
  168. } as never,
  169. sessionFlow: {} as never,
  170. queueFlow: {} as never,
  171. composerDraft: {
  172. hasContent: vi.fn(() => false),
  173. capture: vi.fn(() => resources),
  174. reserveSubmission: vi.fn(),
  175. restoreSubmission,
  176. completeSubmission,
  177. } as never,
  178. workspaceRoots: { additionalDirectories: () => [] } as never,
  179. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  180. editor: {
  181. captureDraft: vi.fn(() => ({
  182. schemaVersion: 1,
  183. text: "/review",
  184. cursor: 7,
  185. pastes: [],
  186. pasteCounter: 0,
  187. })),
  188. } as never,
  189. surface: {} as never,
  190. surfaceHost: {} as never,
  191. queueEnabled: true,
  192. liveRunId: () => undefined,
  193. runtimeStopping: () => false,
  194. abortLiveTurn: vi.fn(async () => false),
  195. leaveUi: vi.fn(async () => undefined),
  196. whenReady: vi.fn(async () => undefined),
  197. append: vi.fn(),
  198. setHint: vi.fn(),
  199. onChanged: vi.fn(),
  200. });
  201. await expect(
  202. flow.submit("/review", {
  203. sessionId: "session-a",
  204. editor: {
  205. schemaVersion: 1,
  206. text: "/review",
  207. cursor: 7,
  208. pastes: [],
  209. pasteCounter: 0,
  210. },
  211. resources,
  212. }),
  213. ).resolves.toBe("consumed");
  214. expect(restoreSubmission).toHaveBeenCalledWith(resources);
  215. expect(submit).toHaveBeenCalledWith(
  216. "Please review my uncommitted changes.",
  217. expect.objectContaining({
  218. displayContent: "/review",
  219. reviewRequest: { scope: "local_changes" },
  220. attachments: [],
  221. }),
  222. );
  223. expect(completeSubmission).toHaveBeenCalledWith({ attachments: [] });
  224. });
  225. it("opens the unified background task center for the current Session", async () => {
  226. const showTasks = vi.fn(async () => undefined);
  227. const flow = createReadinessCommandFlow({
  228. whenReady: async () => undefined,
  229. hasSession: true,
  230. showTasks,
  231. });
  232. await expect(flow.submit("/tasks")).resolves.toBe("consumed");
  233. expect(showTasks).toHaveBeenCalledOnce();
  234. });
  235. it("starts status after controller hydration without waiting for unrelated readiness", async () => {
  236. const fullReady = new Promise<void>(() => undefined);
  237. let releaseController: (() => void) | undefined;
  238. const controllerReady = new Promise<void>((resolve) => {
  239. releaseController = resolve;
  240. });
  241. let releaseStatus: (() => void) | undefined;
  242. const status = new Promise<void>((resolve) => {
  243. releaseStatus = resolve;
  244. });
  245. const showAccountStatus = vi.fn(() => status);
  246. const setHint = vi.fn();
  247. const flow = createReadinessCommandFlow({
  248. whenReady: () => fullReady,
  249. whenControllerReady: () => controllerReady,
  250. showAccountStatus,
  251. setHint,
  252. });
  253. const loading = flow.submit("/status");
  254. expect(setHint).toHaveBeenCalledWith("Loading account status…");
  255. expect(showAccountStatus).not.toHaveBeenCalled();
  256. releaseController?.();
  257. await vi.waitFor(() => expect(showAccountStatus).toHaveBeenCalledOnce());
  258. expect(setHint).toHaveBeenLastCalledWith("Loading account status…");
  259. releaseStatus?.();
  260. await expect(loading).resolves.toBe("consumed");
  261. expect(setHint).toHaveBeenLastCalledWith(undefined);
  262. });
  263. it("dispatches /copy to the latest Assistant response clipboard action", async () => {
  264. const copyLastAssistantReply = vi.fn(async () => undefined);
  265. const flow = createReadinessCommandFlow({
  266. whenReady: vi.fn(async () => undefined),
  267. copyLastAssistantReply,
  268. hasSession: true,
  269. });
  270. await expect(flow.submit("/copy")).resolves.toBe("consumed");
  271. expect(copyLastAssistantReply).toHaveBeenCalledOnce();
  272. });
  273. it("dispatches /export with the requested Markdown path", async () => {
  274. const exportCurrentTranscript = vi.fn(async () => undefined);
  275. const flow = createReadinessCommandFlow({
  276. whenReady: vi.fn(async () => undefined),
  277. exportCurrentTranscript,
  278. hasSession: true,
  279. });
  280. await expect(flow.submit('/export "docs/session.md"')).resolves.toBe(
  281. "consumed",
  282. );
  283. expect(exportCurrentTranscript).toHaveBeenCalledWith('"docs/session.md"');
  284. });
  285. it("switches and persists the explicitly selected TUI mode", async () => {
  286. const surface = { show: vi.fn(), close: vi.fn(() => true) };
  287. const surfaceHost = {
  288. getChatMode: vi.fn(() => "regular" as const),
  289. setChatMode: vi.fn(() => true),
  290. };
  291. const persistTuiMode = vi.fn();
  292. const flow = createReadinessCommandFlow({
  293. whenReady: vi.fn(async () => undefined),
  294. surface,
  295. surfaceHost,
  296. persistTuiMode,
  297. });
  298. await expect(flow.submit("/settings")).resolves.toBe("consumed");
  299. const picker = surface.show.mock.calls.at(-1)?.[0] as {
  300. handleInput(data: string): void;
  301. };
  302. picker.handleInput("\u001b[B");
  303. picker.handleInput("\r");
  304. expect(surfaceHost.setChatMode).toHaveBeenCalledWith("fullscreen");
  305. expect(persistTuiMode).toHaveBeenCalledWith("fullscreen");
  306. expect(surface.close).toHaveBeenCalledWith(picker);
  307. });
  308. it("reloads TUI configuration only while the product is idle", async () => {
  309. const reloadTui = vi.fn(async () => undefined);
  310. const setHint = vi.fn();
  311. const flow = createReadinessCommandFlow({
  312. whenReady: vi.fn(async () => undefined),
  313. reloadTui,
  314. setHint,
  315. });
  316. await expect(flow.submit("/reload")).resolves.toBe("consumed");
  317. expect(reloadTui).toHaveBeenCalledOnce();
  318. expect(setHint).toHaveBeenCalledWith("Reloading TUI configuration…");
  319. expect(setHint).toHaveBeenLastCalledWith("TUI configuration reloaded.");
  320. });
  321. it.each(['Plugin refresh failed', 'Invalid keybindings.json'])("preserves /reload cause: %s", async (message) => {
  322. const append = vi.fn();
  323. const flow = createReadinessCommandFlow({
  324. whenReady: async () => {}, append,
  325. reloadTui: async () => { throw new Error(message); },
  326. });
  327. await expect(flow.submit('/reload')).resolves.toBe('consumed');
  328. expect(append).toHaveBeenCalledWith(expect.stringContaining(message), 'warning');
  329. expect(append).toHaveBeenCalledWith(expect.stringContaining('configuration or plugin refresh error'), 'warning');
  330. expect(JSON.stringify(append.mock.calls)).not.toContain('Fix keybindings.json');
  331. });
  332. it("retains /reload while queued work is present", async () => {
  333. const reloadTui = vi.fn(async () => undefined);
  334. const setHint = vi.fn();
  335. const flow = createReadinessCommandFlow({
  336. whenReady: vi.fn(async () => undefined),
  337. reloadTui,
  338. queuedCount: 1,
  339. setHint,
  340. });
  341. await expect(flow.submit("/reload")).resolves.toBe("retained");
  342. expect(reloadTui).not.toHaveBeenCalled();
  343. expect(setHint).toHaveBeenCalledWith(
  344. "Clear the Queue before reloading TUI.",
  345. );
  346. });
  347. it.each([
  348. {
  349. prompt: "/context 这样还是会显示上下文信息",
  350. stagesOptimistically: true,
  351. },
  352. { prompt: "/ALLOW", stagesOptimistically: false },
  353. ])(
  354. "submits command-like prompt $prompt after TUI readiness settles",
  355. async ({ prompt, stagesOptimistically }) => {
  356. let releaseReady: (() => void) | undefined;
  357. const ready = new Promise<void>((resolve) => {
  358. releaseReady = resolve;
  359. });
  360. const projectOptimisticUserMessage = vi.fn();
  361. const removeOptimisticUserMessage = vi.fn();
  362. const submit = vi.fn(async () => "succeeded" as const);
  363. const resources = { attachments: [] };
  364. const flow = new TuiCommandFlow({
  365. workspaceDir: "/workspace",
  366. controller: {
  367. snapshot: vi.fn(() => ({
  368. status: "idle" as const,
  369. sessions: [],
  370. session: { sessionId: "session-a" },
  371. })),
  372. projectOptimisticUserMessage,
  373. removeOptimisticUserMessage,
  374. submit,
  375. } as never,
  376. activeRunFlow: {} as never,
  377. featureFlow: createFeatureFlowMock() as never,
  378. feedbackFlow: {} as never,
  379. updateFlow: {} as never,
  380. interactionFlow: {
  381. handleCommand: vi.fn(async () => false),
  382. hasPending: vi.fn(() => false),
  383. } as never,
  384. sessionFlow: {} as never,
  385. queueFlow: {} as never,
  386. composerDraft: {
  387. hasContent: vi.fn(() => false),
  388. completeSubmission: vi.fn(async () => undefined),
  389. } as never,
  390. workspaceRoots: { additionalDirectories: () => [] } as never,
  391. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  392. editor: {} as never,
  393. surface: {} as never,
  394. surfaceHost: {} as never,
  395. queueEnabled: true,
  396. liveRunId: () => undefined,
  397. runtimeStopping: () => false,
  398. abortLiveTurn: vi.fn(async () => false),
  399. leaveUi: vi.fn(async () => undefined),
  400. whenReady: vi.fn(() => ready),
  401. append: vi.fn(),
  402. setHint: vi.fn(),
  403. onChanged: vi.fn(),
  404. userMessageCount: () => 0,
  405. });
  406. const seed = {
  407. sessionId: "session-a",
  408. editor: {
  409. schemaVersion: 1 as const,
  410. text: prompt,
  411. cursor: prompt.length,
  412. pasteCounter: 0,
  413. pastes: [],
  414. },
  415. resources,
  416. };
  417. const sending = flow.submit(prompt, seed);
  418. if (stagesOptimistically) {
  419. expect(projectOptimisticUserMessage).toHaveBeenCalledWith(
  420. expect.stringMatching(/^\d+-\d+$/u),
  421. prompt,
  422. expect.any(Number),
  423. [],
  424. );
  425. } else {
  426. expect(projectOptimisticUserMessage).not.toHaveBeenCalled();
  427. }
  428. expect(submit).not.toHaveBeenCalled();
  429. releaseReady?.();
  430. await expect(sending).resolves.toBe("consumed");
  431. expect(submit).toHaveBeenCalledWith(
  432. prompt,
  433. expect.objectContaining({ attachments: [] }),
  434. );
  435. if (stagesOptimistically)
  436. expect(removeOptimisticUserMessage).toHaveBeenCalled();
  437. },
  438. );
  439. it("reserves one captured seed and restores its resources before a Session command", async () => {
  440. const editorDraft = {
  441. schemaVersion: 1 as const,
  442. text: "/new [Image #1] ",
  443. cursor: 4,
  444. pasteCounter: 0,
  445. pastes: [],
  446. attachmentPlaceholders: [
  447. { id: "/tmp/a.png", label: "[Image #1]", start: 5, end: 15 },
  448. ],
  449. };
  450. const resources = {
  451. attachments: [
  452. { filePath: "/tmp/a.png", fileName: "a.png", mimeType: "image/png" },
  453. ],
  454. };
  455. const reserveSubmission = vi.fn();
  456. const restoreSubmission = vi.fn();
  457. const startNew = vi.fn();
  458. const projectOptimisticUserMessage = vi.fn();
  459. const flow = new TuiCommandFlow({
  460. workspaceDir: "/workspace",
  461. controller: {
  462. snapshot: vi.fn(() => ({
  463. status: "idle" as const,
  464. sessions: [],
  465. session: { sessionId: "session-a" },
  466. })),
  467. projectOptimisticUserMessage,
  468. } as never,
  469. activeRunFlow: {} as never,
  470. featureFlow: createFeatureFlowMock() as never,
  471. feedbackFlow: {} as never,
  472. updateFlow: {} as never,
  473. interactionFlow: {
  474. handleCommand: vi.fn(async () => false),
  475. hasPending: vi.fn(() => false),
  476. } as never,
  477. sessionFlow: { startNew } as never,
  478. queueFlow: {} as never,
  479. composerDraft: {
  480. capture: vi.fn(() => resources),
  481. reserveSubmission,
  482. restoreSubmission,
  483. hasContent: vi.fn(() => false),
  484. } as never,
  485. workspaceRoots: {
  486. additionalDirectories: () => ["/captured-root"],
  487. } as never,
  488. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  489. editor: { captureDraft: vi.fn(() => editorDraft) } as never,
  490. surface: {} as never,
  491. surfaceHost: {} as never,
  492. queueEnabled: true,
  493. liveRunId: () => undefined,
  494. runtimeStopping: () => false,
  495. abortLiveTurn: vi.fn(async () => false),
  496. leaveUi: vi.fn(async () => undefined),
  497. whenReady: vi.fn(async () => undefined),
  498. append: vi.fn(),
  499. setHint: vi.fn(),
  500. onChanged: vi.fn(),
  501. });
  502. const seed = flow.captureSubmissionSeed(editorDraft);
  503. await expect(flow.submit("/new", seed)).resolves.toBe("consumed");
  504. expect(seed).toEqual({
  505. sessionId: "session-a",
  506. editor: editorDraft,
  507. resources,
  508. });
  509. expect(reserveSubmission).toHaveBeenCalledWith(resources);
  510. expect(restoreSubmission).toHaveBeenCalledWith(resources);
  511. expect(restoreSubmission.mock.invocationCallOrder[0]).toBeLessThan(
  512. startNew.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
  513. );
  514. expect(projectOptimisticUserMessage).not.toHaveBeenCalled();
  515. });
  516. it("keeps Goal command attachments in the Composer instead of submitting an ordinary Turn", async () => {
  517. const attachment = {
  518. type: "image" as const,
  519. filePath: "/tmp/goal.png",
  520. fileName: "goal.png",
  521. mimeType: "image/png",
  522. sizeBytes: 100,
  523. };
  524. const resources = { attachments: [attachment] };
  525. const restoreSubmission = vi.fn();
  526. const executeGoal = vi.fn(async () => "consumed" as const);
  527. const submit = vi.fn(async () => "succeeded" as const);
  528. const flow = new TuiCommandFlow({
  529. workspaceDir: "/workspace",
  530. controller: {
  531. snapshot: vi.fn(() => ({
  532. status: "idle" as const,
  533. sessions: [],
  534. session: { sessionId: "session-a" },
  535. })),
  536. submit,
  537. } as never,
  538. activeRunFlow: {} as never,
  539. featureFlow: createFeatureFlowMock() as never,
  540. feedbackFlow: {} as never,
  541. updateFlow: {} as never,
  542. goalFlow: { execute: executeGoal },
  543. interactionFlow: {
  544. handleCommand: vi.fn(async () => false),
  545. hasPending: vi.fn(() => false),
  546. } as never,
  547. sessionFlow: {} as never,
  548. queueFlow: {} as never,
  549. composerDraft: {
  550. hasContent: vi.fn(() => false),
  551. restoreSubmission,
  552. } as never,
  553. workspaceRoots: { additionalDirectories: () => [] } as never,
  554. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  555. editor: {} as never,
  556. surface: {} as never,
  557. surfaceHost: {} as never,
  558. queueEnabled: true,
  559. liveRunId: () => undefined,
  560. runtimeStopping: () => false,
  561. abortLiveTurn: vi.fn(async () => false),
  562. leaveUi: vi.fn(async () => undefined),
  563. whenReady: vi.fn(async () => undefined),
  564. append: vi.fn(),
  565. setHint: vi.fn(),
  566. onChanged: vi.fn(),
  567. });
  568. const seed = {
  569. sessionId: "session-a",
  570. editor: {
  571. schemaVersion: 1 as const,
  572. text: "/goal clear",
  573. cursor: 11,
  574. pasteCounter: 0,
  575. pastes: [],
  576. },
  577. resources,
  578. };
  579. await expect(flow.submit("/goal clear", seed)).resolves.toBe("consumed");
  580. expect(restoreSubmission).toHaveBeenCalledWith(resources);
  581. expect(executeGoal).toHaveBeenCalledWith("clear");
  582. expect(restoreSubmission.mock.invocationCallOrder[0]).toBeLessThan(
  583. executeGoal.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
  584. );
  585. expect(submit).not.toHaveBeenCalled();
  586. });
  587. it("admits an attachment-only captured Submission", async () => {
  588. const attachment = {
  589. filePath: "/tmp/a.png",
  590. fileName: "a.png",
  591. mimeType: "image/png",
  592. };
  593. const submit = vi.fn(async () => "succeeded" as const);
  594. const completeSubmission = vi.fn(async () => undefined);
  595. const flow = new TuiCommandFlow({
  596. workspaceDir: "/workspace",
  597. controller: {
  598. snapshot: vi.fn(() => ({
  599. status: "idle" as const,
  600. sessions: [],
  601. session: { sessionId: "session-a" },
  602. })),
  603. submit,
  604. } as never,
  605. activeRunFlow: {} as never,
  606. featureFlow: createFeatureFlowMock() as never,
  607. feedbackFlow: {} as never,
  608. updateFlow: {} as never,
  609. interactionFlow: {
  610. handleCommand: vi.fn(async () => false),
  611. hasPending: vi.fn(() => false),
  612. } as never,
  613. sessionFlow: {} as never,
  614. queueFlow: {} as never,
  615. composerDraft: {
  616. hasContent: vi.fn(() => false),
  617. completeSubmission,
  618. } as never,
  619. workspaceRoots: { additionalDirectories: () => [] } as never,
  620. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  621. editor: {} as never,
  622. surface: {} as never,
  623. surfaceHost: {} as never,
  624. queueEnabled: true,
  625. liveRunId: () => undefined,
  626. runtimeStopping: () => false,
  627. abortLiveTurn: vi.fn(async () => false),
  628. leaveUi: vi.fn(async () => undefined),
  629. whenReady: vi.fn(async () => undefined),
  630. append: vi.fn(),
  631. setHint: vi.fn(),
  632. onChanged: vi.fn(),
  633. });
  634. const resources = { attachments: [attachment] };
  635. await expect(
  636. flow.submit("", {
  637. sessionId: "session-a",
  638. editor: {
  639. schemaVersion: 1,
  640. text: "[Image #1] ",
  641. cursor: 0,
  642. pasteCounter: 0,
  643. pastes: [],
  644. },
  645. resources,
  646. }),
  647. ).resolves.toBe("consumed");
  648. expect(submit).toHaveBeenCalledWith(
  649. "",
  650. expect.objectContaining({ attachments: [attachment] }),
  651. );
  652. expect(completeSubmission).toHaveBeenCalledWith(resources);
  653. });
  654. it("sends directory-like @ text without resolving a directory reference", async () => {
  655. const resolveMentionedDirectories = vi.fn(async () => [
  656. {
  657. schemaVersion: 1 as const,
  658. referenceId: "dirref_src",
  659. rootName: "src",
  660. rootPath: "/workspace/src",
  661. },
  662. ]);
  663. const submit = vi.fn(async () => "succeeded" as const);
  664. const completeSubmission = vi.fn(async () => undefined);
  665. const flow = new TuiCommandFlow({
  666. workspaceDir: "/workspace",
  667. controller: {
  668. snapshot: vi.fn(() => ({
  669. status: "idle" as const,
  670. sessions: [],
  671. session: { sessionId: "session-a" },
  672. })),
  673. submit,
  674. } as never,
  675. activeRunFlow: {} as never,
  676. featureFlow: createFeatureFlowMock() as never,
  677. feedbackFlow: {} as never,
  678. updateFlow: {} as never,
  679. interactionFlow: {
  680. handleCommand: vi.fn(async () => false),
  681. hasPending: vi.fn(() => false),
  682. } as never,
  683. sessionFlow: {} as never,
  684. queueFlow: {} as never,
  685. composerDraft: {
  686. hasContent: vi.fn(() => false),
  687. resolveMentionedDirectories,
  688. completeSubmission,
  689. } as never,
  690. workspaceRoots: { additionalDirectories: () => [] } as never,
  691. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  692. editor: {} as never,
  693. surface: {} as never,
  694. surfaceHost: {} as never,
  695. queueEnabled: true,
  696. liveRunId: () => undefined,
  697. runtimeStopping: () => false,
  698. abortLiveTurn: vi.fn(async () => false),
  699. leaveUi: vi.fn(async () => undefined),
  700. whenReady: vi.fn(async () => undefined),
  701. append: vi.fn(),
  702. setHint: vi.fn(),
  703. onChanged: vi.fn(),
  704. });
  705. const resources = { attachments: [] };
  706. await expect(
  707. flow.submit("Review @src/ ", {
  708. sessionId: "session-a",
  709. editor: {
  710. schemaVersion: 1,
  711. text: "Review @src/ ",
  712. cursor: 13,
  713. pasteCounter: 0,
  714. pastes: [],
  715. },
  716. resources,
  717. }),
  718. ).resolves.toBe("consumed");
  719. expect(resolveMentionedDirectories).not.toHaveBeenCalled();
  720. expect(submit).toHaveBeenCalledWith(
  721. "Review @src/",
  722. expect.objectContaining({ attachments: [] }),
  723. );
  724. expect(completeSubmission).toHaveBeenCalledWith(resources);
  725. });
  726. it("waits for Draft recovery before releasing a Submission during shutdown", async () => {
  727. let stopped = false;
  728. let finishPrimary: ((status: "cancelled") => void) | undefined;
  729. let finishRecovery: (() => void) | undefined;
  730. const primary = new Promise<"cancelled">((resolve) => {
  731. finishPrimary = resolve;
  732. });
  733. const recovery = new Promise<void>((resolve) => {
  734. finishRecovery = resolve;
  735. });
  736. const completeSubmission = vi.fn(async () => undefined);
  737. const submit = vi.fn(() => primary);
  738. const flow = new TuiCommandFlow({
  739. workspaceDir: "/workspace",
  740. controller: {
  741. snapshot: vi.fn(() => ({
  742. status: "idle" as const,
  743. sessions: [],
  744. session: { sessionId: "session-a" },
  745. })),
  746. submit,
  747. } as never,
  748. activeRunFlow: {} as never,
  749. featureFlow: createFeatureFlowMock() as never,
  750. feedbackFlow: {} as never,
  751. updateFlow: {} as never,
  752. interactionFlow: {
  753. handleCommand: vi.fn(async () => false),
  754. hasPending: vi.fn(() => false),
  755. } as never,
  756. sessionFlow: {} as never,
  757. queueFlow: {} as never,
  758. composerDraft: {
  759. hasContent: vi.fn(() => false),
  760. completeSubmission,
  761. } as never,
  762. workspaceRoots: { additionalDirectories: () => [] } as never,
  763. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  764. editor: {} as never,
  765. surface: {} as never,
  766. surfaceHost: {} as never,
  767. queueEnabled: true,
  768. liveRunId: () => undefined,
  769. runtimeStopping: () => false,
  770. abortLiveTurn: vi.fn(async () => false),
  771. leaveUi: vi.fn(async () => undefined),
  772. whenReady: vi.fn(async () => undefined),
  773. whenStopping: vi.fn(() => recovery),
  774. isStopped: () => stopped,
  775. append: vi.fn(),
  776. setHint: vi.fn(),
  777. onChanged: vi.fn(),
  778. });
  779. const resources = {
  780. attachments: [
  781. { filePath: "/tmp/a.png", fileName: "a.png", mimeType: "image/png" },
  782. ],
  783. };
  784. const sending = flow.submit("preserve attachment", {
  785. sessionId: "session-a",
  786. editor: {
  787. schemaVersion: 1,
  788. text: "preserve attachment",
  789. cursor: 19,
  790. pasteCounter: 0,
  791. pastes: [],
  792. },
  793. resources,
  794. });
  795. await vi.waitFor(() => expect(submit).toHaveBeenCalledOnce());
  796. stopped = true;
  797. finishPrimary?.("cancelled");
  798. await Promise.resolve();
  799. expect(completeSubmission).not.toHaveBeenCalled();
  800. finishRecovery?.();
  801. await expect(sending).resolves.toBe("consumed");
  802. expect(completeSubmission).toHaveBeenCalledWith(resources);
  803. });
  804. it("routes a rapid follow-up into the Runtime queue", async () => {
  805. let liveRunId: string | undefined;
  806. let finishPrimary: ((status: "succeeded") => void) | undefined;
  807. let releaseQueueLogin: (() => void) | undefined;
  808. const primary = new Promise<"succeeded">((resolve) => {
  809. finishPrimary = resolve;
  810. });
  811. const queueLogin = new Promise<void>((resolve) => {
  812. releaseQueueLogin = resolve;
  813. });
  814. const projectOptimisticUserMessage = vi.fn();
  815. const controller = {
  816. snapshot: vi.fn(() => ({
  817. status: liveRunId ? ("running" as const) : ("idle" as const),
  818. sessions: [],
  819. session: { sessionId: "session-1" },
  820. activeTurnId: liveRunId,
  821. })),
  822. submit: vi.fn(() => {
  823. liveRunId = "turn-1";
  824. return primary;
  825. }),
  826. requireLoginForAgentAction: vi.fn(() => queueLogin),
  827. projectOptimisticUserMessage,
  828. removeOptimisticUserMessage: vi.fn(),
  829. };
  830. const composerDraft = {
  831. hasContent: vi.fn(() => false),
  832. capture: vi.fn(() => ({
  833. attachments: [],
  834. })),
  835. reserveSubmission: vi.fn(() => ({
  836. attachments: [],
  837. })),
  838. restoreSubmission: vi.fn(),
  839. completeSubmission: vi.fn(async () => undefined),
  840. };
  841. const queueFlow = {
  842. beginAdmission: vi.fn(),
  843. cancelAdmission: vi.fn(),
  844. enqueue: vi.fn(async () => undefined),
  845. };
  846. const flow = new TuiCommandFlow({
  847. workspaceDir: "/workspace",
  848. controller: controller as never,
  849. activeRunFlow: {} as never,
  850. featureFlow: createFeatureFlowMock() as never,
  851. feedbackFlow: {} as never,
  852. updateFlow: {} as never,
  853. interactionFlow: {
  854. handleCommand: vi.fn(async () => false),
  855. hasPending: vi.fn(() => false),
  856. showPending: vi.fn(),
  857. } as never,
  858. sessionFlow: {} as never,
  859. queueFlow: queueFlow as never,
  860. composerDraft: composerDraft as never,
  861. workspaceRoots: { additionalDirectories: () => [] } as never,
  862. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  863. editor: { setText: vi.fn() } as never,
  864. surface: {} as never,
  865. surfaceHost: {} as never,
  866. queueEnabled: true,
  867. liveRunId: () => liveRunId,
  868. runtimeStopping: () => false,
  869. abortLiveTurn: vi.fn(async () => false),
  870. leaveUi: vi.fn(async () => undefined),
  871. whenReady: vi.fn(async () => undefined),
  872. append: vi.fn(),
  873. setHint: vi.fn(),
  874. onChanged: vi.fn(),
  875. });
  876. const first = flow.submit("first");
  877. await vi.waitFor(() => expect(controller.submit).toHaveBeenCalledTimes(1));
  878. const followUpSeed = {
  879. sessionId: "session-1",
  880. editor: {
  881. schemaVersion: 1 as const,
  882. text: "follow-up",
  883. cursor: 9,
  884. pasteCounter: 0,
  885. pastes: [],
  886. },
  887. resources: { attachments: [] },
  888. };
  889. const followUp = flow.submit("follow-up", followUpSeed);
  890. expect(projectOptimisticUserMessage).not.toHaveBeenCalled();
  891. expect(queueFlow.beginAdmission).toHaveBeenCalledWith(
  892. expect.stringMatching(/^\d+-\d+$/u),
  893. "follow-up",
  894. [],
  895. );
  896. expect(queueFlow.enqueue).not.toHaveBeenCalled();
  897. releaseQueueLogin?.();
  898. await vi.waitFor(() => expect(queueFlow.enqueue).toHaveBeenCalledTimes(1));
  899. await expect(followUp).resolves.toBe("consumed");
  900. expect(projectOptimisticUserMessage).not.toHaveBeenCalled();
  901. expect(controller.submit).toHaveBeenCalledTimes(1);
  902. expect(queueFlow.enqueue).toHaveBeenCalledWith(
  903. "follow-up",
  904. expect.objectContaining({ attachments: [] }),
  905. expect.objectContaining({ content: "follow-up" }),
  906. expect.stringMatching(/^\d+-\d+$/u),
  907. );
  908. finishPrimary?.("succeeded");
  909. await expect(first).resolves.toBe("consumed");
  910. expect(composerDraft.completeSubmission).toHaveBeenCalledTimes(1);
  911. });
  912. it("steers an active Turn with Enter intent and preserves structured attachments", async () => {
  913. const attachment = {
  914. type: "image" as const,
  915. filePath: "/workspace/diagram.png",
  916. fileName: "diagram.png",
  917. mimeType: "image/png",
  918. sizeBytes: 42,
  919. };
  920. const activeRunFlow = { steer: vi.fn(async () => true) };
  921. const controller = {
  922. snapshot: vi.fn(() => ({
  923. status: "running" as const,
  924. sessions: [],
  925. session: { sessionId: "session-1" },
  926. activeTurnId: "turn-active",
  927. })),
  928. hasInProcessRun: vi.fn(() => true),
  929. requireLoginForAgentAction: vi.fn(async () => undefined),
  930. projectOptimisticUserMessage: vi.fn(),
  931. removeOptimisticUserMessage: vi.fn(),
  932. };
  933. const composerDraft = {
  934. hasContent: vi.fn(() => false),
  935. restoreSubmission: vi.fn(),
  936. completeSubmission: vi.fn(async () => undefined),
  937. };
  938. const queueFlow = {
  939. beginAdmission: vi.fn(),
  940. cancelAdmission: vi.fn(),
  941. enqueue: vi.fn(async () => undefined),
  942. };
  943. const flow = new TuiCommandFlow({
  944. workspaceDir: "/workspace",
  945. controller: controller as never,
  946. activeRunFlow: activeRunFlow as never,
  947. featureFlow: createFeatureFlowMock() as never,
  948. feedbackFlow: {} as never,
  949. updateFlow: {} as never,
  950. interactionFlow: {
  951. handleCommand: vi.fn(async () => false),
  952. hasPending: vi.fn(() => false),
  953. } as never,
  954. sessionFlow: {} as never,
  955. queueFlow: queueFlow as never,
  956. composerDraft: composerDraft as never,
  957. workspaceRoots: { additionalDirectories: () => [] } as never,
  958. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  959. editor: {} as never,
  960. surface: {} as never,
  961. surfaceHost: {} as never,
  962. queueEnabled: true,
  963. liveRunId: () => "turn-active",
  964. runtimeStopping: () => false,
  965. abortLiveTurn: vi.fn(async () => false),
  966. leaveUi: vi.fn(async () => undefined),
  967. whenReady: vi.fn(async () => undefined),
  968. append: vi.fn(),
  969. setHint: vi.fn(),
  970. onChanged: vi.fn(),
  971. });
  972. const seed = {
  973. sessionId: "session-1",
  974. editor: {
  975. schemaVersion: 1 as const,
  976. text: "[Image #1] focus on this diagram",
  977. cursor: 32,
  978. pasteCounter: 0,
  979. pastes: [],
  980. },
  981. resources: { attachments: [attachment] },
  982. };
  983. await expect(
  984. flow.submit("focus on this diagram", seed, { busyAction: "steer" }),
  985. ).resolves.toBe("consumed");
  986. expect(activeRunFlow.steer).toHaveBeenCalledWith("focus on this diagram", {
  987. requireActiveTurn: true,
  988. attachments: [attachment],
  989. transcriptAttachments: [attachment],
  990. });
  991. expect(queueFlow.beginAdmission).not.toHaveBeenCalled();
  992. expect(queueFlow.enqueue).not.toHaveBeenCalled();
  993. expect(controller.projectOptimisticUserMessage).not.toHaveBeenCalled();
  994. expect(composerDraft.completeSubmission).toHaveBeenCalledWith({
  995. attachments: [attachment],
  996. });
  997. });
  998. it.each([
  999. ["accepts the handoff", false],
  1000. ["rejects the handoff", true],
  1001. ] as const)(
  1002. "preserves direct-admission semantics when the Runtime queue %s",
  1003. async (_scenario, enqueueFails) => {
  1004. const draft = { attachments: [] };
  1005. const append = vi.fn();
  1006. const controller = {
  1007. snapshot: vi.fn(() => ({
  1008. status: "idle" as const,
  1009. sessions: [],
  1010. session: { sessionId: "session-1" },
  1011. activeTurnId: undefined,
  1012. })),
  1013. submit: vi.fn(async () => "queue-required" as const),
  1014. requireLoginForAgentAction: vi.fn(async () => undefined),
  1015. };
  1016. const composerDraft = {
  1017. hasContent: vi.fn(() => false),
  1018. reserveSubmission: vi.fn(() => draft),
  1019. restoreSubmission: vi.fn(),
  1020. completeSubmission: vi.fn(async () => undefined),
  1021. };
  1022. const queueFlow = {
  1023. beginAdmission: vi.fn(),
  1024. cancelAdmission: vi.fn(),
  1025. enqueue: vi.fn(async () => {
  1026. if (enqueueFails) throw new Error("queue unavailable");
  1027. }),
  1028. };
  1029. const flow = new TuiCommandFlow({
  1030. workspaceDir: "/workspace",
  1031. controller: controller as never,
  1032. activeRunFlow: {} as never,
  1033. featureFlow: createFeatureFlowMock() as never,
  1034. feedbackFlow: {} as never,
  1035. updateFlow: {} as never,
  1036. interactionFlow: {
  1037. handleCommand: vi.fn(async () => false),
  1038. hasPending: vi.fn(() => false),
  1039. } as never,
  1040. sessionFlow: {} as never,
  1041. queueFlow: queueFlow as never,
  1042. composerDraft: composerDraft as never,
  1043. workspaceRoots: { additionalDirectories: () => [] } as never,
  1044. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  1045. editor: {} as never,
  1046. surface: {} as never,
  1047. surfaceHost: {} as never,
  1048. queueEnabled: true,
  1049. liveRunId: () => undefined,
  1050. runtimeStopping: () => false,
  1051. abortLiveTurn: vi.fn(async () => false),
  1052. leaveUi: vi.fn(async () => undefined),
  1053. whenReady: vi.fn(async () => undefined),
  1054. append,
  1055. setHint: vi.fn(),
  1056. onChanged: vi.fn(),
  1057. });
  1058. await expect(flow.submit("follow-up")).resolves.toBe(
  1059. enqueueFails ? "retained" : "consumed",
  1060. );
  1061. expect(queueFlow.enqueue).toHaveBeenCalledWith(
  1062. "follow-up",
  1063. draft,
  1064. undefined,
  1065. expect.stringMatching(/^\d+-\d+$/u),
  1066. );
  1067. expect(queueFlow.beginAdmission).toHaveBeenCalledWith(
  1068. expect.stringMatching(/^\d+-\d+$/u),
  1069. "follow-up",
  1070. [],
  1071. );
  1072. expect(composerDraft.completeSubmission).not.toHaveBeenCalled();
  1073. if (enqueueFails) {
  1074. expect(queueFlow.cancelAdmission).toHaveBeenCalledWith(
  1075. expect.stringMatching(/^\d+-\d+$/u),
  1076. );
  1077. expect(composerDraft.restoreSubmission).toHaveBeenCalledWith(draft);
  1078. expect(append).toHaveBeenCalledWith(
  1079. "Couldn't add this message to the Queue: queue unavailable. Retry after the current response finishes. Your draft is preserved.",
  1080. "warning",
  1081. );
  1082. } else {
  1083. expect(queueFlow.cancelAdmission).not.toHaveBeenCalled();
  1084. expect(composerDraft.restoreSubmission).not.toHaveBeenCalled();
  1085. }
  1086. },
  1087. );
  1088. it("moves a direct optimistic message into Queue projection on queue-required fallback", async () => {
  1089. const projectOptimisticUserMessage = vi.fn();
  1090. const removeOptimisticUserMessage = vi.fn();
  1091. const beginAdmission = vi.fn();
  1092. const enqueue = vi.fn(async () => undefined);
  1093. const draft = { attachments: [] };
  1094. const flow = new TuiCommandFlow({
  1095. workspaceDir: "/workspace",
  1096. controller: {
  1097. snapshot: vi.fn(() => ({
  1098. status: "idle" as const,
  1099. sessions: [],
  1100. session: { sessionId: "session-1" },
  1101. })),
  1102. submit: vi.fn(async () => "queue-required" as const),
  1103. requireLoginForAgentAction: vi.fn(async () => undefined),
  1104. projectOptimisticUserMessage,
  1105. removeOptimisticUserMessage,
  1106. } as never,
  1107. activeRunFlow: {} as never,
  1108. featureFlow: createFeatureFlowMock() as never,
  1109. feedbackFlow: {} as never,
  1110. updateFlow: {} as never,
  1111. interactionFlow: {
  1112. handleCommand: vi.fn(async () => false),
  1113. hasPending: vi.fn(() => false),
  1114. } as never,
  1115. sessionFlow: {} as never,
  1116. queueFlow: {
  1117. beginAdmission,
  1118. cancelAdmission: vi.fn(),
  1119. enqueue,
  1120. } as never,
  1121. composerDraft: {
  1122. hasContent: vi.fn(() => false),
  1123. completeSubmission: vi.fn(async () => undefined),
  1124. } as never,
  1125. workspaceRoots: { additionalDirectories: () => [] } as never,
  1126. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  1127. editor: {} as never,
  1128. surface: {} as never,
  1129. surfaceHost: {} as never,
  1130. queueEnabled: true,
  1131. liveRunId: () => undefined,
  1132. runtimeStopping: () => false,
  1133. abortLiveTurn: vi.fn(async () => false),
  1134. leaveUi: vi.fn(async () => undefined),
  1135. whenReady: vi.fn(async () => undefined),
  1136. append: vi.fn(),
  1137. setHint: vi.fn(),
  1138. onChanged: vi.fn(),
  1139. });
  1140. const seed = {
  1141. sessionId: "session-1",
  1142. editor: {
  1143. schemaVersion: 1 as const,
  1144. text: "follow-up",
  1145. cursor: 9,
  1146. pasteCounter: 0,
  1147. pastes: [],
  1148. },
  1149. resources: draft,
  1150. };
  1151. await expect(flow.submit("follow-up", seed)).resolves.toBe("consumed");
  1152. expect(projectOptimisticUserMessage).toHaveBeenCalledOnce();
  1153. expect(
  1154. removeOptimisticUserMessage.mock.invocationCallOrder[0],
  1155. ).toBeLessThan(
  1156. beginAdmission.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
  1157. );
  1158. expect(enqueue).toHaveBeenCalledWith(
  1159. "follow-up",
  1160. draft,
  1161. expect.objectContaining({ content: "follow-up" }),
  1162. expect.stringMatching(/^\d+-\d+$/u),
  1163. );
  1164. });
  1165. it("preserves the draft and guides login when a direct Agent Turn is blocked", async () => {
  1166. const draft = { attachments: [] };
  1167. const append = vi.fn();
  1168. const controller = {
  1169. snapshot: vi.fn(() => ({ status: "idle" as const, sessions: [] })),
  1170. submit: vi.fn(async () => {
  1171. throw new TuiLoginRequiredError(
  1172. { status: "needs-login", managedTokenPresent: false, warnings: [] },
  1173. MINIMAX_CODE_TUI_LOGIN_REQUIRED_MESSAGE,
  1174. );
  1175. }),
  1176. requireLoginForAgentAction: vi.fn(async () => undefined),
  1177. };
  1178. const composerDraft = {
  1179. hasContent: vi.fn(() => false),
  1180. reserveSubmission: vi.fn(() => draft),
  1181. restoreSubmission: vi.fn(),
  1182. completeSubmission: vi.fn(async () => undefined),
  1183. };
  1184. const flow = new TuiCommandFlow({
  1185. workspaceDir: "/workspace",
  1186. controller: controller as never,
  1187. activeRunFlow: {} as never,
  1188. featureFlow: createFeatureFlowMock() as never,
  1189. feedbackFlow: {} as never,
  1190. updateFlow: {} as never,
  1191. interactionFlow: {
  1192. handleCommand: vi.fn(async () => false),
  1193. hasPending: vi.fn(() => false),
  1194. } as never,
  1195. sessionFlow: {} as never,
  1196. queueFlow: {} as never,
  1197. composerDraft: composerDraft as never,
  1198. workspaceRoots: { additionalDirectories: () => [] } as never,
  1199. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  1200. editor: {} as never,
  1201. surface: {} as never,
  1202. surfaceHost: {} as never,
  1203. queueEnabled: true,
  1204. liveRunId: () => undefined,
  1205. runtimeStopping: () => false,
  1206. abortLiveTurn: vi.fn(async () => false),
  1207. leaveUi: vi.fn(async () => undefined),
  1208. whenReady: vi.fn(async () => undefined),
  1209. append,
  1210. setHint: vi.fn(),
  1211. onChanged: vi.fn(),
  1212. });
  1213. await expect(flow.submit("retry after login")).resolves.toBe("retained");
  1214. expect(composerDraft.restoreSubmission).toHaveBeenCalledWith(draft);
  1215. expect(composerDraft.completeSubmission).not.toHaveBeenCalled();
  1216. expect(append).toHaveBeenCalledWith(
  1217. MINIMAX_CODE_TUI_LOGIN_REQUIRED_MESSAGE,
  1218. "warning",
  1219. );
  1220. });
  1221. it("restores one atomic Submission to the Composer when admission throws synchronously", async () => {
  1222. const restoreSubmittedDraft = vi.fn(() => true);
  1223. const setChatFocus = vi.fn();
  1224. const controller = {
  1225. snapshot: vi.fn(() => ({
  1226. status: "idle" as const,
  1227. sessions: [],
  1228. session: { sessionId: "session-1" },
  1229. })),
  1230. submit: vi.fn(() => {
  1231. throw new Error("admission failed");
  1232. }),
  1233. requireLoginForAgentAction: vi.fn(async () => undefined),
  1234. };
  1235. const composerDraft = {
  1236. hasContent: vi.fn(() => true),
  1237. reserveSubmission: vi.fn(),
  1238. restoreSubmission: vi.fn(),
  1239. completeSubmission: vi.fn(async () => undefined),
  1240. };
  1241. const flow = new TuiCommandFlow({
  1242. workspaceDir: "/workspace",
  1243. controller: controller as never,
  1244. activeRunFlow: {} as never,
  1245. featureFlow: createFeatureFlowMock() as never,
  1246. feedbackFlow: {} as never,
  1247. updateFlow: {} as never,
  1248. interactionFlow: {
  1249. handleCommand: vi.fn(async () => false),
  1250. hasPending: vi.fn(() => false),
  1251. } as never,
  1252. sessionFlow: {} as never,
  1253. queueFlow: {} as never,
  1254. composerDraft: composerDraft as never,
  1255. workspaceRoots: { additionalDirectories: () => ["/shared"] } as never,
  1256. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  1257. editor: { restoreSubmittedDraft } as never,
  1258. surface: {} as never,
  1259. surfaceHost: { setChatFocus } as never,
  1260. queueEnabled: true,
  1261. liveRunId: () => undefined,
  1262. runtimeStopping: () => false,
  1263. abortLiveTurn: vi.fn(async () => false),
  1264. leaveUi: vi.fn(async () => undefined),
  1265. whenReady: vi.fn(async () => undefined),
  1266. append: vi.fn(),
  1267. setHint: vi.fn(),
  1268. onChanged: vi.fn(),
  1269. });
  1270. const seed = {
  1271. sessionId: "session-1",
  1272. editor: {
  1273. schemaVersion: 1 as const,
  1274. text: "send A",
  1275. cursor: 6,
  1276. pasteCounter: 0,
  1277. pastes: [],
  1278. },
  1279. resources: {
  1280. attachments: [],
  1281. },
  1282. };
  1283. await expect(flow.submit("send A", seed)).resolves.toBe("retained");
  1284. expect(restoreSubmittedDraft).toHaveBeenCalledWith(seed.editor);
  1285. expect(composerDraft.restoreSubmission).toHaveBeenCalledWith(
  1286. seed.resources,
  1287. );
  1288. expect(setChatFocus).toHaveBeenCalled();
  1289. });
  1290. it.each(["failed", "retracted"] as const)(
  1291. "restores an atomic Submission to the Composer when the Turn is %s",
  1292. async (status) => {
  1293. const restoreSubmittedDraft = vi.fn(() => true);
  1294. const restoreSubmission = vi.fn();
  1295. const flow = new TuiCommandFlow({
  1296. workspaceDir: "/workspace",
  1297. controller: {
  1298. snapshot: vi.fn(() => ({
  1299. status: "idle" as const,
  1300. sessions: [],
  1301. session: { sessionId: "session-1" },
  1302. })),
  1303. submit: vi.fn(async () => status),
  1304. } as never,
  1305. activeRunFlow: {} as never,
  1306. featureFlow: createFeatureFlowMock() as never,
  1307. feedbackFlow: {} as never,
  1308. updateFlow: {} as never,
  1309. interactionFlow: {
  1310. handleCommand: vi.fn(async () => false),
  1311. hasPending: vi.fn(() => false),
  1312. } as never,
  1313. sessionFlow: {} as never,
  1314. queueFlow: {} as never,
  1315. composerDraft: {
  1316. hasContent: vi.fn(() => false),
  1317. restoreSubmission,
  1318. } as never,
  1319. workspaceRoots: { additionalDirectories: () => [] } as never,
  1320. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  1321. editor: { restoreSubmittedDraft } as never,
  1322. surface: {} as never,
  1323. surfaceHost: { setChatFocus: vi.fn() } as never,
  1324. queueEnabled: true,
  1325. liveRunId: () => undefined,
  1326. runtimeStopping: () => false,
  1327. abortLiveTurn: vi.fn(async () => false),
  1328. leaveUi: vi.fn(async () => undefined),
  1329. whenReady: vi.fn(async () => undefined),
  1330. append: vi.fn(),
  1331. setHint: vi.fn(),
  1332. onChanged: vi.fn(),
  1333. });
  1334. const seed = {
  1335. sessionId: "session-1",
  1336. editor: {
  1337. schemaVersion: 1 as const,
  1338. text: "send A",
  1339. cursor: 6,
  1340. pasteCounter: 0,
  1341. pastes: [],
  1342. },
  1343. resources: { attachments: [] },
  1344. };
  1345. await expect(flow.submit("send A", seed)).resolves.toBe("retained");
  1346. expect(restoreSubmittedDraft).toHaveBeenCalledWith(seed.editor);
  1347. expect(restoreSubmission).toHaveBeenCalledWith(seed.resources);
  1348. },
  1349. );
  1350. it("restores a captured Submission to the Composer when focus changes before admission", async () => {
  1351. const restoreSubmittedDraft = vi.fn(() => true);
  1352. const restoreSubmission = vi.fn();
  1353. const controller = {
  1354. snapshot: vi.fn(() => ({
  1355. status: "idle" as const,
  1356. sessions: [],
  1357. session: { sessionId: "session-b" },
  1358. })),
  1359. submit: vi.fn(),
  1360. requireLoginForAgentAction: vi.fn(),
  1361. };
  1362. const flow = new TuiCommandFlow({
  1363. workspaceDir: "/workspace",
  1364. controller: controller as never,
  1365. activeRunFlow: {} as never,
  1366. featureFlow: createFeatureFlowMock() as never,
  1367. feedbackFlow: {} as never,
  1368. updateFlow: {} as never,
  1369. interactionFlow: {
  1370. handleCommand: vi.fn(async () => false),
  1371. hasPending: vi.fn(() => false),
  1372. } as never,
  1373. sessionFlow: {} as never,
  1374. queueFlow: {} as never,
  1375. composerDraft: {
  1376. hasContent: vi.fn(() => true),
  1377. restoreSubmission,
  1378. } as never,
  1379. workspaceRoots: {
  1380. additionalDirectories: () => ["/current-root"],
  1381. } as never,
  1382. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  1383. editor: { restoreSubmittedDraft } as never,
  1384. surface: {} as never,
  1385. surfaceHost: { setChatFocus: vi.fn() } as never,
  1386. queueEnabled: true,
  1387. liveRunId: () => undefined,
  1388. runtimeStopping: () => false,
  1389. abortLiveTurn: vi.fn(async () => false),
  1390. leaveUi: vi.fn(async () => undefined),
  1391. whenReady: vi.fn(async () => undefined),
  1392. append: vi.fn(),
  1393. setHint: vi.fn(),
  1394. onChanged: vi.fn(),
  1395. });
  1396. await expect(
  1397. flow.submit("send in A", {
  1398. sessionId: "session-a",
  1399. editor: {
  1400. schemaVersion: 1,
  1401. text: "send in A",
  1402. cursor: 9,
  1403. pasteCounter: 0,
  1404. pastes: [],
  1405. },
  1406. resources: { attachments: [] },
  1407. }),
  1408. ).resolves.toBe("retained");
  1409. expect(controller.submit).not.toHaveBeenCalled();
  1410. expect(restoreSubmittedDraft).toHaveBeenCalledWith(
  1411. expect.objectContaining({ text: "send in A" }),
  1412. );
  1413. expect(restoreSubmission).toHaveBeenCalledWith({ attachments: [] });
  1414. });
  1415. it("does not admit protected actions when their login gate rejects", async () => {
  1416. const loginError = new TuiLoginRequiredError(
  1417. {
  1418. status: "needs-login",
  1419. managedTokenPresent: false,
  1420. warnings: [],
  1421. },
  1422. MINIMAX_CODE_TUI_LOGIN_REQUIRED_MESSAGE,
  1423. );
  1424. const append = vi.fn();
  1425. const queueFlow = { enqueue: vi.fn(async () => undefined) };
  1426. const feedbackFlow = { show: vi.fn(async () => undefined) };
  1427. const activeRunFlow = {
  1428. handle: vi.fn(async () => {
  1429. throw loginError;
  1430. }),
  1431. };
  1432. const featureFlow = {
  1433. skillCommands: () => [],
  1434. compactSession: vi.fn(async () => undefined),
  1435. };
  1436. const controller = {
  1437. snapshot: vi.fn(() => ({
  1438. status: "running" as const,
  1439. sessions: [],
  1440. session: { sessionId: "session-1" },
  1441. activeTurnId: "turn-1",
  1442. })),
  1443. submit: vi.fn(),
  1444. requireLoginForAgentAction: vi.fn(async () => {
  1445. throw loginError;
  1446. }),
  1447. };
  1448. const composerDraft = {
  1449. hasContent: vi.fn(() => false),
  1450. capture: vi.fn(() => ({ attachments: [] })),
  1451. reserveSubmission: vi.fn(),
  1452. restoreSubmission: vi.fn(),
  1453. completeSubmission: vi.fn(async () => undefined),
  1454. };
  1455. const flow = new TuiCommandFlow({
  1456. workspaceDir: "/workspace",
  1457. controller: controller as never,
  1458. activeRunFlow: activeRunFlow as never,
  1459. featureFlow: featureFlow as never,
  1460. feedbackFlow: feedbackFlow as never,
  1461. updateFlow: {} as never,
  1462. interactionFlow: {
  1463. handleCommand: vi.fn(async () => false),
  1464. hasPending: vi.fn(() => false),
  1465. } as never,
  1466. sessionFlow: {} as never,
  1467. queueFlow: queueFlow as never,
  1468. composerDraft: composerDraft as never,
  1469. workspaceRoots: { additionalDirectories: () => [] } as never,
  1470. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  1471. editor: {} as never,
  1472. surface: {} as never,
  1473. surfaceHost: {} as never,
  1474. queueEnabled: true,
  1475. liveRunId: () => "run-1",
  1476. runtimeStopping: () => false,
  1477. abortLiveTurn: vi.fn(async () => false),
  1478. leaveUi: vi.fn(async () => undefined),
  1479. whenReady: vi.fn(async () => undefined),
  1480. append,
  1481. setHint: vi.fn(),
  1482. onChanged: vi.fn(),
  1483. });
  1484. await expect(flow.submit("queue me")).resolves.toBe("retained");
  1485. await expect(flow.submit("/compact")).resolves.toBe("consumed");
  1486. await expect(flow.submit("/steer focus here")).resolves.toBe("retained");
  1487. expect(queueFlow.enqueue).not.toHaveBeenCalled();
  1488. expect(featureFlow.compactSession).not.toHaveBeenCalled();
  1489. expect(activeRunFlow.handle).toHaveBeenCalledWith("/steer focus here");
  1490. expect(append).toHaveBeenCalledWith(
  1491. MINIMAX_CODE_TUI_LOGIN_REQUIRED_MESSAGE,
  1492. "warning",
  1493. );
  1494. });
  1495. it("retains steer text when fresh Runtime admission rejects it", async () => {
  1496. const activeRunFlow = { handle: vi.fn(async () => false) };
  1497. const controller = {
  1498. snapshot: vi.fn(() => ({
  1499. status: "running" as const,
  1500. sessions: [],
  1501. session: { sessionId: "session-1" },
  1502. activeTurnId: "turn-1",
  1503. })),
  1504. requireLoginForAgentAction: vi.fn(async () => undefined),
  1505. };
  1506. const flow = new TuiCommandFlow({
  1507. workspaceDir: "/workspace",
  1508. controller: controller as never,
  1509. activeRunFlow: activeRunFlow as never,
  1510. featureFlow: createFeatureFlowMock() as never,
  1511. feedbackFlow: {} as never,
  1512. updateFlow: {} as never,
  1513. interactionFlow: {
  1514. handleCommand: vi.fn(async () => false),
  1515. hasPending: vi.fn(() => false),
  1516. } as never,
  1517. sessionFlow: {} as never,
  1518. queueFlow: {} as never,
  1519. composerDraft: { hasContent: vi.fn(() => false) } as never,
  1520. workspaceRoots: { additionalDirectories: () => [] } as never,
  1521. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  1522. editor: {} as never,
  1523. surface: {} as never,
  1524. surfaceHost: {} as never,
  1525. queueEnabled: true,
  1526. liveRunId: () => "turn-1",
  1527. runtimeStopping: () => false,
  1528. abortLiveTurn: vi.fn(async () => false),
  1529. leaveUi: vi.fn(async () => undefined),
  1530. whenReady: vi.fn(async () => undefined),
  1531. append: vi.fn(),
  1532. setHint: vi.fn(),
  1533. onChanged: vi.fn(),
  1534. });
  1535. await expect(flow.submit("/steer keep this guidance")).resolves.toBe(
  1536. "retained",
  1537. );
  1538. expect(activeRunFlow.handle).toHaveBeenCalledWith(
  1539. "/steer keep this guidance",
  1540. );
  1541. });
  1542. it("retains steer guidance while an Agent interaction is pending", async () => {
  1543. const activeRunFlow = { handle: vi.fn(async () => true) };
  1544. const showPending = vi.fn();
  1545. const flow = new TuiCommandFlow({
  1546. workspaceDir: "/workspace",
  1547. controller: {
  1548. snapshot: vi.fn(() => ({
  1549. status: "running" as const,
  1550. sessions: [],
  1551. session: { sessionId: "session-1" },
  1552. activeTurnId: "turn-1",
  1553. })),
  1554. } as never,
  1555. activeRunFlow: activeRunFlow as never,
  1556. featureFlow: createFeatureFlowMock() as never,
  1557. feedbackFlow: {} as never,
  1558. updateFlow: {} as never,
  1559. interactionFlow: {
  1560. handleCommand: vi.fn(async () => false),
  1561. hasPending: vi.fn(() => true),
  1562. showPending,
  1563. } as never,
  1564. sessionFlow: {} as never,
  1565. queueFlow: {} as never,
  1566. composerDraft: { hasContent: vi.fn(() => false) } as never,
  1567. workspaceRoots: { additionalDirectories: () => [] } as never,
  1568. runProjection: { snapshot: () => ({ queuedCount: 0 }) } as never,
  1569. editor: {} as never,
  1570. surface: {} as never,
  1571. surfaceHost: {} as never,
  1572. queueEnabled: true,
  1573. liveRunId: () => "turn-1",
  1574. runtimeStopping: () => false,
  1575. abortLiveTurn: vi.fn(async () => false),
  1576. leaveUi: vi.fn(async () => undefined),
  1577. whenReady: vi.fn(async () => undefined),
  1578. append: vi.fn(),
  1579. setHint: vi.fn(),
  1580. onChanged: vi.fn(),
  1581. });
  1582. await expect(flow.submit("/steer keep rollback guidance")).resolves.toBe(
  1583. "retained",
  1584. );
  1585. expect(showPending).toHaveBeenCalledTimes(1);
  1586. expect(activeRunFlow.handle).not.toHaveBeenCalled();
  1587. });
  1588. });