@google/gemini-cli-core 0.3.0-nightly.20250822.15c62bad → 0.3.0-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (403) hide show
  1. package/dist/index.d.ts +2 -0
  2. package/dist/index.js +2 -0
  3. package/dist/index.js.map +1 -1
  4. package/dist/src/code_assist/codeAssist.d.ts +4 -3
  5. package/dist/src/code_assist/codeAssist.js.map +1 -1
  6. package/dist/src/code_assist/converter.d.ts +2 -1
  7. package/dist/src/code_assist/converter.js +36 -4
  8. package/dist/src/code_assist/converter.js.map +1 -1
  9. package/dist/src/code_assist/converter.test.js +83 -0
  10. package/dist/src/code_assist/converter.test.js.map +1 -1
  11. package/dist/src/code_assist/oauth2.d.ts +1 -1
  12. package/dist/src/code_assist/oauth2.js +8 -8
  13. package/dist/src/code_assist/oauth2.js.map +1 -1
  14. package/dist/src/code_assist/oauth2.test.js +5 -5
  15. package/dist/src/code_assist/oauth2.test.js.map +1 -1
  16. package/dist/src/code_assist/server.d.ts +5 -5
  17. package/dist/src/code_assist/server.js +1 -1
  18. package/dist/src/code_assist/server.js.map +1 -1
  19. package/dist/src/code_assist/setup.d.ts +1 -1
  20. package/dist/src/code_assist/setup.js +1 -1
  21. package/dist/src/code_assist/setup.js.map +1 -1
  22. package/dist/src/code_assist/setup.test.js.map +1 -1
  23. package/dist/src/config/config.d.ts +27 -5
  24. package/dist/src/config/config.js +58 -12
  25. package/dist/src/config/config.js.map +1 -1
  26. package/dist/src/config/config.test.js +113 -2
  27. package/dist/src/config/config.test.js.map +1 -1
  28. package/dist/src/config/storage.js +3 -3
  29. package/dist/src/config/storage.js.map +1 -1
  30. package/dist/src/config/storage.test.js +1 -1
  31. package/dist/src/config/storage.test.js.map +1 -1
  32. package/dist/src/core/client.d.ts +15 -9
  33. package/dist/src/core/client.js +57 -14
  34. package/dist/src/core/client.js.map +1 -1
  35. package/dist/src/core/client.test.js +336 -82
  36. package/dist/src/core/client.test.js.map +1 -1
  37. package/dist/src/core/contentGenerator.d.ts +3 -3
  38. package/dist/src/core/contentGenerator.js +1 -1
  39. package/dist/src/core/contentGenerator.js.map +1 -1
  40. package/dist/src/core/contentGenerator.test.js.map +1 -1
  41. package/dist/src/core/coreToolScheduler.d.ts +12 -3
  42. package/dist/src/core/coreToolScheduler.js +99 -46
  43. package/dist/src/core/coreToolScheduler.js.map +1 -1
  44. package/dist/src/core/coreToolScheduler.test.js +196 -56
  45. package/dist/src/core/coreToolScheduler.test.js.map +1 -1
  46. package/dist/src/core/geminiChat.d.ts +18 -14
  47. package/dist/src/core/geminiChat.js +197 -159
  48. package/dist/src/core/geminiChat.js.map +1 -1
  49. package/dist/src/core/geminiChat.test.js +708 -257
  50. package/dist/src/core/geminiChat.test.js.map +1 -1
  51. package/dist/src/core/geminiRequest.js +1 -0
  52. package/dist/src/core/geminiRequest.js.map +1 -1
  53. package/dist/src/core/logger.d.ts +2 -2
  54. package/dist/src/core/logger.test.js.map +1 -1
  55. package/dist/src/core/loggingContentGenerator.d.ts +3 -3
  56. package/dist/src/core/loggingContentGenerator.js +3 -1
  57. package/dist/src/core/loggingContentGenerator.js.map +1 -1
  58. package/dist/src/core/nonInteractiveToolExecutor.d.ts +1 -1
  59. package/dist/src/core/nonInteractiveToolExecutor.js.map +1 -1
  60. package/dist/src/core/nonInteractiveToolExecutor.test.js +54 -35
  61. package/dist/src/core/nonInteractiveToolExecutor.test.js.map +1 -1
  62. package/dist/src/core/subagent.d.ts +24 -18
  63. package/dist/src/core/subagent.js +122 -84
  64. package/dist/src/core/subagent.js.map +1 -1
  65. package/dist/src/core/subagent.test.js +28 -23
  66. package/dist/src/core/subagent.test.js.map +1 -1
  67. package/dist/src/core/turn.d.ts +16 -5
  68. package/dist/src/core/turn.js +12 -1
  69. package/dist/src/core/turn.js.map +1 -1
  70. package/dist/src/core/turn.test.js +1 -1
  71. package/dist/src/core/turn.test.js.map +1 -1
  72. package/dist/src/generated/git-commit.d.ts +2 -2
  73. package/dist/src/generated/git-commit.js +2 -2
  74. package/dist/src/generated/git-commit.js.map +1 -1
  75. package/dist/src/ide/detect-ide.d.ts +8 -3
  76. package/dist/src/ide/detect-ide.js +29 -11
  77. package/dist/src/ide/detect-ide.js.map +1 -1
  78. package/dist/src/ide/detect-ide.test.js +96 -52
  79. package/dist/src/ide/detect-ide.test.js.map +1 -1
  80. package/dist/src/ide/ide-client.d.ts +6 -5
  81. package/dist/src/ide/ide-client.js +19 -17
  82. package/dist/src/ide/ide-client.js.map +1 -1
  83. package/dist/src/ide/ide-client.test.js +14 -10
  84. package/dist/src/ide/ide-client.test.js.map +1 -1
  85. package/dist/src/ide/ide-installer.d.ts +1 -1
  86. package/dist/src/ide/ide-installer.js +29 -20
  87. package/dist/src/ide/ide-installer.js.map +1 -1
  88. package/dist/src/ide/ide-installer.test.js +82 -22
  89. package/dist/src/ide/ide-installer.test.js.map +1 -1
  90. package/dist/src/ide/ideContext.d.ts +11 -11
  91. package/dist/src/ide/process-utils.d.ts +7 -4
  92. package/dist/src/ide/process-utils.js +47 -34
  93. package/dist/src/ide/process-utils.js.map +1 -1
  94. package/dist/src/ide/process-utils.test.d.ts +6 -0
  95. package/dist/src/ide/process-utils.test.js +72 -0
  96. package/dist/src/ide/process-utils.test.js.map +1 -0
  97. package/dist/src/index.d.ts +8 -2
  98. package/dist/src/index.js +6 -1
  99. package/dist/src/index.js.map +1 -1
  100. package/dist/src/mcp/google-auth-provider.d.ts +3 -3
  101. package/dist/src/mcp/google-auth-provider.test.js.map +1 -1
  102. package/dist/src/mcp/oauth-provider.d.ts +2 -2
  103. package/dist/src/mcp/oauth-provider.js.map +1 -1
  104. package/dist/src/mcp/oauth-provider.test.js +1 -1
  105. package/dist/src/mcp/oauth-provider.test.js.map +1 -1
  106. package/dist/src/mcp/oauth-token-storage.d.ts +5 -25
  107. package/dist/src/mcp/oauth-token-storage.js.map +1 -1
  108. package/dist/src/mcp/oauth-token-storage.test.js +1 -1
  109. package/dist/src/mcp/oauth-token-storage.test.js.map +1 -1
  110. package/dist/src/mcp/oauth-utils.d.ts +9 -1
  111. package/dist/src/mcp/oauth-utils.js +41 -27
  112. package/dist/src/mcp/oauth-utils.js.map +1 -1
  113. package/dist/src/mcp/oauth-utils.test.js +41 -1
  114. package/dist/src/mcp/oauth-utils.test.js.map +1 -1
  115. package/dist/src/mcp/token-storage/base-token-storage.d.ts +19 -0
  116. package/dist/src/mcp/token-storage/base-token-storage.js +36 -0
  117. package/dist/src/mcp/token-storage/base-token-storage.js.map +1 -0
  118. package/dist/src/mcp/token-storage/base-token-storage.test.d.ts +6 -0
  119. package/dist/src/mcp/token-storage/base-token-storage.test.js +160 -0
  120. package/dist/src/mcp/token-storage/base-token-storage.test.js.map +1 -0
  121. package/dist/src/mcp/token-storage/types.d.ts +34 -0
  122. package/dist/src/mcp/token-storage/types.js +7 -0
  123. package/dist/src/mcp/token-storage/types.js.map +1 -0
  124. package/dist/src/prompts/mcp-prompts.d.ts +2 -2
  125. package/dist/src/prompts/prompt-registry.d.ts +1 -1
  126. package/dist/src/services/chatRecordingService.d.ts +1 -1
  127. package/dist/src/services/chatRecordingService.js +3 -0
  128. package/dist/src/services/chatRecordingService.js.map +1 -1
  129. package/dist/src/services/chatRecordingService.test.js +2 -2
  130. package/dist/src/services/chatRecordingService.test.js.map +1 -1
  131. package/dist/src/services/fileDiscoveryService.js +1 -1
  132. package/dist/src/services/fileDiscoveryService.js.map +1 -1
  133. package/dist/src/services/fileDiscoveryService.test.js +3 -3
  134. package/dist/src/services/fileDiscoveryService.test.js.map +1 -1
  135. package/dist/src/services/fileSystemService.js +1 -1
  136. package/dist/src/services/fileSystemService.js.map +1 -1
  137. package/dist/src/services/fileSystemService.test.js +1 -1
  138. package/dist/src/services/fileSystemService.test.js.map +1 -1
  139. package/dist/src/services/gitService.d.ts +1 -1
  140. package/dist/src/services/gitService.js +17 -7
  141. package/dist/src/services/gitService.js.map +1 -1
  142. package/dist/src/services/gitService.test.js +3 -3
  143. package/dist/src/services/gitService.test.js.map +1 -1
  144. package/dist/src/services/loopDetectionService.d.ts +2 -2
  145. package/dist/src/services/loopDetectionService.js +9 -3
  146. package/dist/src/services/loopDetectionService.js.map +1 -1
  147. package/dist/src/services/loopDetectionService.test.js +23 -1
  148. package/dist/src/services/loopDetectionService.test.js.map +1 -1
  149. package/dist/src/services/shellExecutionService.js +5 -4
  150. package/dist/src/services/shellExecutionService.js.map +1 -1
  151. package/dist/src/services/shellExecutionService.test.js +4 -3
  152. package/dist/src/services/shellExecutionService.test.js.map +1 -1
  153. package/dist/src/telemetry/clearcut-logger/clearcut-logger.d.ts +13 -3
  154. package/dist/src/telemetry/clearcut-logger/clearcut-logger.js +127 -2
  155. package/dist/src/telemetry/clearcut-logger/clearcut-logger.js.map +1 -1
  156. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.js +11 -3
  157. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.js.map +1 -1
  158. package/dist/src/telemetry/clearcut-logger/event-metadata-key.d.ts +22 -1
  159. package/dist/src/telemetry/clearcut-logger/event-metadata-key.js +55 -1
  160. package/dist/src/telemetry/clearcut-logger/event-metadata-key.js.map +1 -1
  161. package/dist/src/telemetry/constants.d.ts +8 -0
  162. package/dist/src/telemetry/constants.js +8 -0
  163. package/dist/src/telemetry/constants.js.map +1 -1
  164. package/dist/src/telemetry/file-exporters.d.ts +5 -4
  165. package/dist/src/telemetry/file-exporters.js +1 -1
  166. package/dist/src/telemetry/file-exporters.js.map +1 -1
  167. package/dist/src/telemetry/index.d.ts +5 -2
  168. package/dist/src/telemetry/index.js +3 -2
  169. package/dist/src/telemetry/index.js.map +1 -1
  170. package/dist/src/telemetry/loggers.d.ts +8 -2
  171. package/dist/src/telemetry/loggers.js +102 -2
  172. package/dist/src/telemetry/loggers.js.map +1 -1
  173. package/dist/src/telemetry/loggers.test.circular.js.map +1 -1
  174. package/dist/src/telemetry/loggers.test.js +65 -9
  175. package/dist/src/telemetry/loggers.test.js.map +1 -1
  176. package/dist/src/telemetry/metrics.d.ts +16 -4
  177. package/dist/src/telemetry/metrics.js +47 -3
  178. package/dist/src/telemetry/metrics.js.map +1 -1
  179. package/dist/src/telemetry/sdk.d.ts +1 -1
  180. package/dist/src/telemetry/telemetry-utils.d.ts +6 -0
  181. package/dist/src/telemetry/telemetry-utils.js +14 -0
  182. package/dist/src/telemetry/telemetry-utils.js.map +1 -0
  183. package/dist/src/telemetry/telemetry-utils.test.d.ts +6 -0
  184. package/dist/src/telemetry/telemetry-utils.test.js +40 -0
  185. package/dist/src/telemetry/telemetry-utils.test.js.map +1 -0
  186. package/dist/src/telemetry/types.d.ts +50 -6
  187. package/dist/src/telemetry/types.js +75 -1
  188. package/dist/src/telemetry/types.js.map +1 -1
  189. package/dist/src/telemetry/uiTelemetry.d.ts +2 -2
  190. package/dist/src/telemetry/uiTelemetry.js +1 -1
  191. package/dist/src/telemetry/uiTelemetry.js.map +1 -1
  192. package/dist/src/telemetry/uiTelemetry.test.js +16 -12
  193. package/dist/src/telemetry/uiTelemetry.test.js.map +1 -1
  194. package/dist/src/test-utils/config.d.ts +2 -1
  195. package/dist/src/test-utils/config.js.map +1 -1
  196. package/dist/src/test-utils/mockWorkspaceContext.d.ts +1 -1
  197. package/dist/src/test-utils/tools.d.ts +3 -2
  198. package/dist/src/test-utils/tools.js.map +1 -1
  199. package/dist/src/tools/diffOptions.d.ts +1 -1
  200. package/dist/src/tools/edit.d.ts +4 -3
  201. package/dist/src/tools/edit.js +28 -7
  202. package/dist/src/tools/edit.js.map +1 -1
  203. package/dist/src/tools/edit.test.js +27 -3
  204. package/dist/src/tools/edit.test.js.map +1 -1
  205. package/dist/src/tools/glob.d.ts +3 -2
  206. package/dist/src/tools/glob.js +4 -4
  207. package/dist/src/tools/glob.js.map +1 -1
  208. package/dist/src/tools/glob.test.js +6 -3
  209. package/dist/src/tools/glob.test.js.map +1 -1
  210. package/dist/src/tools/grep.d.ts +3 -2
  211. package/dist/src/tools/grep.js +30 -15
  212. package/dist/src/tools/grep.js.map +1 -1
  213. package/dist/src/tools/grep.test.js +15 -3
  214. package/dist/src/tools/grep.test.js.map +1 -1
  215. package/dist/src/tools/ls.d.ts +3 -2
  216. package/dist/src/tools/ls.js +3 -3
  217. package/dist/src/tools/ls.js.map +1 -1
  218. package/dist/src/tools/ls.test.js +2 -2
  219. package/dist/src/tools/ls.test.js.map +1 -1
  220. package/dist/src/tools/mcp-client-manager.d.ts +4 -4
  221. package/dist/src/tools/mcp-client.d.ts +7 -7
  222. package/dist/src/tools/mcp-client.js +2 -2
  223. package/dist/src/tools/mcp-client.js.map +1 -1
  224. package/dist/src/tools/mcp-tool.d.ts +3 -2
  225. package/dist/src/tools/mcp-tool.js +1 -1
  226. package/dist/src/tools/mcp-tool.js.map +1 -1
  227. package/dist/src/tools/mcp-tool.test.js +7 -3
  228. package/dist/src/tools/mcp-tool.test.js.map +1 -1
  229. package/dist/src/tools/memoryTool.d.ts +3 -2
  230. package/dist/src/tools/memoryTool.js +2 -2
  231. package/dist/src/tools/memoryTool.js.map +1 -1
  232. package/dist/src/tools/memoryTool.test.js +4 -4
  233. package/dist/src/tools/memoryTool.test.js.map +1 -1
  234. package/dist/src/tools/modifiable-tool.d.ts +2 -2
  235. package/dist/src/tools/modifiable-tool.js +3 -3
  236. package/dist/src/tools/modifiable-tool.js.map +1 -1
  237. package/dist/src/tools/modifiable-tool.test.js +4 -4
  238. package/dist/src/tools/modifiable-tool.test.js.map +1 -1
  239. package/dist/src/tools/read-file.d.ts +3 -2
  240. package/dist/src/tools/read-file.js +10 -4
  241. package/dist/src/tools/read-file.js.map +1 -1
  242. package/dist/src/tools/read-file.test.js +8 -5
  243. package/dist/src/tools/read-file.test.js.map +1 -1
  244. package/dist/src/tools/read-many-files.d.ts +3 -2
  245. package/dist/src/tools/read-many-files.js +28 -51
  246. package/dist/src/tools/read-many-files.js.map +1 -1
  247. package/dist/src/tools/read-many-files.test.js +39 -7
  248. package/dist/src/tools/read-many-files.test.js.map +1 -1
  249. package/dist/src/tools/ripGrep.d.ts +47 -0
  250. package/dist/src/tools/ripGrep.js +368 -0
  251. package/dist/src/tools/ripGrep.js.map +1 -0
  252. package/dist/src/tools/ripGrep.test.d.ts +6 -0
  253. package/dist/src/tools/ripGrep.test.js +874 -0
  254. package/dist/src/tools/ripGrep.test.js.map +1 -0
  255. package/dist/src/tools/shell.d.ts +3 -2
  256. package/dist/src/tools/shell.js +17 -6
  257. package/dist/src/tools/shell.js.map +1 -1
  258. package/dist/src/tools/shell.test.js +22 -5
  259. package/dist/src/tools/shell.test.js.map +1 -1
  260. package/dist/src/tools/tool-error.d.ts +1 -0
  261. package/dist/src/tools/tool-error.js +2 -0
  262. package/dist/src/tools/tool-error.js.map +1 -1
  263. package/dist/src/tools/tool-registry.d.ts +8 -3
  264. package/dist/src/tools/tool-registry.js +7 -1
  265. package/dist/src/tools/tool-registry.js.map +1 -1
  266. package/dist/src/tools/tool-registry.test.js +15 -2
  267. package/dist/src/tools/tool-registry.test.js.map +1 -1
  268. package/dist/src/tools/tools.d.ts +8 -2
  269. package/dist/src/tools/tools.js +12 -0
  270. package/dist/src/tools/tools.js.map +1 -1
  271. package/dist/src/tools/tools.test.js +1 -1
  272. package/dist/src/tools/tools.test.js.map +1 -1
  273. package/dist/src/tools/web-fetch.d.ts +3 -2
  274. package/dist/src/tools/web-fetch.js +1 -1
  275. package/dist/src/tools/web-fetch.js.map +1 -1
  276. package/dist/src/tools/web-fetch.test.js.map +1 -1
  277. package/dist/src/tools/web-search.d.ts +4 -3
  278. package/dist/src/tools/web-search.js +23 -7
  279. package/dist/src/tools/web-search.js.map +1 -1
  280. package/dist/src/tools/web-search.test.js +66 -0
  281. package/dist/src/tools/web-search.test.js.map +1 -1
  282. package/dist/src/tools/write-file.d.ts +4 -3
  283. package/dist/src/tools/write-file.js +9 -5
  284. package/dist/src/tools/write-file.js.map +1 -1
  285. package/dist/src/tools/write-file.test.js +9 -5
  286. package/dist/src/tools/write-file.test.js.map +1 -1
  287. package/dist/src/utils/bfsFileSearch.d.ts +2 -2
  288. package/dist/src/utils/bfsFileSearch.js +2 -2
  289. package/dist/src/utils/bfsFileSearch.js.map +1 -1
  290. package/dist/src/utils/bfsFileSearch.test.js +3 -3
  291. package/dist/src/utils/bfsFileSearch.test.js.map +1 -1
  292. package/dist/src/utils/editCorrector.d.ts +2 -2
  293. package/dist/src/utils/editCorrector.js +1 -1
  294. package/dist/src/utils/editCorrector.js.map +1 -1
  295. package/dist/src/utils/editCorrector.test.js +2 -3
  296. package/dist/src/utils/editCorrector.test.js.map +1 -1
  297. package/dist/src/utils/editor.js +2 -2
  298. package/dist/src/utils/editor.js.map +1 -1
  299. package/dist/src/utils/editor.test.js +2 -2
  300. package/dist/src/utils/editor.test.js.map +1 -1
  301. package/dist/src/utils/environmentContext.d.ts +2 -2
  302. package/dist/src/utils/errorReporting.d.ts +1 -1
  303. package/dist/src/utils/errors.d.ts +19 -0
  304. package/dist/src/utils/errors.js +32 -0
  305. package/dist/src/utils/errors.js.map +1 -1
  306. package/dist/src/utils/fetch.js +1 -1
  307. package/dist/src/utils/fetch.js.map +1 -1
  308. package/dist/src/utils/fileUtils.d.ts +2 -2
  309. package/dist/src/utils/fileUtils.js +2 -30
  310. package/dist/src/utils/fileUtils.js.map +1 -1
  311. package/dist/src/utils/filesearch/crawler.d.ts +1 -1
  312. package/dist/src/utils/filesearch/crawler.test.js +2 -2
  313. package/dist/src/utils/filesearch/crawler.test.js.map +1 -1
  314. package/dist/src/utils/filesearch/fileSearch.d.ts +1 -0
  315. package/dist/src/utils/filesearch/fileSearch.js +12 -8
  316. package/dist/src/utils/filesearch/fileSearch.js.map +1 -1
  317. package/dist/src/utils/filesearch/fileSearch.test.js +68 -0
  318. package/dist/src/utils/filesearch/fileSearch.test.js.map +1 -1
  319. package/dist/src/utils/generateContentResponseUtilities.d.ts +1 -2
  320. package/dist/src/utils/generateContentResponseUtilities.js +1 -13
  321. package/dist/src/utils/generateContentResponseUtilities.js.map +1 -1
  322. package/dist/src/utils/generateContentResponseUtilities.test.js +2 -40
  323. package/dist/src/utils/generateContentResponseUtilities.test.js.map +1 -1
  324. package/dist/src/utils/getFolderStructure.d.ts +2 -2
  325. package/dist/src/utils/getFolderStructure.js +2 -2
  326. package/dist/src/utils/getFolderStructure.js.map +1 -1
  327. package/dist/src/utils/getFolderStructure.test.js +4 -4
  328. package/dist/src/utils/getFolderStructure.test.js.map +1 -1
  329. package/dist/src/utils/gitIgnoreParser.js +3 -3
  330. package/dist/src/utils/gitIgnoreParser.js.map +1 -1
  331. package/dist/src/utils/gitIgnoreParser.test.js +3 -3
  332. package/dist/src/utils/gitIgnoreParser.test.js.map +1 -1
  333. package/dist/src/utils/gitUtils.js +2 -2
  334. package/dist/src/utils/gitUtils.js.map +1 -1
  335. package/dist/src/utils/ignorePatterns.d.ts +103 -0
  336. package/dist/src/utils/ignorePatterns.js +220 -0
  337. package/dist/src/utils/ignorePatterns.js.map +1 -0
  338. package/dist/src/utils/ignorePatterns.test.d.ts +6 -0
  339. package/dist/src/utils/ignorePatterns.test.js +250 -0
  340. package/dist/src/utils/ignorePatterns.test.js.map +1 -0
  341. package/dist/src/utils/installationManager.js +2 -2
  342. package/dist/src/utils/installationManager.js.map +1 -1
  343. package/dist/src/utils/installationManager.test.js +1 -1
  344. package/dist/src/utils/installationManager.test.js.map +1 -1
  345. package/dist/src/utils/language-detection.d.ts +6 -0
  346. package/dist/src/utils/language-detection.js +101 -0
  347. package/dist/src/utils/language-detection.js.map +1 -0
  348. package/dist/src/utils/memoryDiscovery.d.ts +2 -2
  349. package/dist/src/utils/memoryDiscovery.js +5 -5
  350. package/dist/src/utils/memoryDiscovery.js.map +1 -1
  351. package/dist/src/utils/memoryDiscovery.test.js +3 -3
  352. package/dist/src/utils/memoryDiscovery.test.js.map +1 -1
  353. package/dist/src/utils/memoryImportProcessor.js +2 -2
  354. package/dist/src/utils/memoryImportProcessor.js.map +1 -1
  355. package/dist/src/utils/memoryImportProcessor.test.js +2 -141
  356. package/dist/src/utils/memoryImportProcessor.test.js.map +1 -1
  357. package/dist/src/utils/messageInspectors.d.ts +1 -1
  358. package/dist/src/utils/nextSpeakerChecker.d.ts +2 -2
  359. package/dist/src/utils/nextSpeakerChecker.test.js.map +1 -1
  360. package/dist/src/utils/partUtils.d.ts +22 -1
  361. package/dist/src/utils/partUtils.js +68 -0
  362. package/dist/src/utils/partUtils.js.map +1 -1
  363. package/dist/src/utils/partUtils.test.js +112 -1
  364. package/dist/src/utils/partUtils.test.js.map +1 -1
  365. package/dist/src/utils/pathReader.d.ts +17 -0
  366. package/dist/src/utils/pathReader.js +92 -0
  367. package/dist/src/utils/pathReader.js.map +1 -0
  368. package/dist/src/utils/pathReader.test.d.ts +6 -0
  369. package/dist/src/utils/pathReader.test.js +363 -0
  370. package/dist/src/utils/pathReader.test.js.map +1 -0
  371. package/dist/src/utils/paths.js +2 -2
  372. package/dist/src/utils/paths.js.map +1 -1
  373. package/dist/src/utils/quotaErrorDetection.d.ts +1 -1
  374. package/dist/src/utils/retry.test.js +4 -1
  375. package/dist/src/utils/retry.test.js.map +1 -1
  376. package/dist/src/utils/schemaValidator.js +4 -0
  377. package/dist/src/utils/schemaValidator.js.map +1 -1
  378. package/dist/src/utils/session.js +1 -1
  379. package/dist/src/utils/session.js.map +1 -1
  380. package/dist/src/utils/shell-utils.d.ts +1 -1
  381. package/dist/src/utils/shell-utils.js +23 -29
  382. package/dist/src/utils/shell-utils.js.map +1 -1
  383. package/dist/src/utils/shell-utils.test.js +4 -0
  384. package/dist/src/utils/shell-utils.test.js.map +1 -1
  385. package/dist/src/utils/summarizer.d.ts +2 -2
  386. package/dist/src/utils/summarizer.test.js.map +1 -1
  387. package/dist/src/utils/systemEncoding.js +2 -2
  388. package/dist/src/utils/systemEncoding.js.map +1 -1
  389. package/dist/src/utils/systemEncoding.test.js +2 -2
  390. package/dist/src/utils/systemEncoding.test.js.map +1 -1
  391. package/dist/src/utils/tool-utils.d.ts +19 -0
  392. package/dist/src/utils/tool-utils.js +58 -0
  393. package/dist/src/utils/tool-utils.js.map +1 -0
  394. package/dist/src/utils/tool-utils.test.d.ts +6 -0
  395. package/dist/src/utils/tool-utils.test.js +61 -0
  396. package/dist/src/utils/tool-utils.test.js.map +1 -0
  397. package/dist/src/utils/userAccountManager.test.js.map +1 -1
  398. package/dist/src/utils/workspaceContext.js +13 -7
  399. package/dist/src/utils/workspaceContext.js.map +1 -1
  400. package/dist/src/utils/workspaceContext.test.js +41 -16
  401. package/dist/src/utils/workspaceContext.test.js.map +1 -1
  402. package/dist/tsconfig.tsbuildinfo +1 -1
  403. package/package.json +10 -7
@@ -4,7 +4,7 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
  import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
7
- import { GeminiChat } from './geminiChat.js';
7
+ import { GeminiChat, EmptyStreamError } from './geminiChat.js';
8
8
  import { setSimulate429 } from '../utils/testUtils.js';
9
9
  // Mocks
10
10
  const mockModelsModule = {
@@ -14,6 +14,16 @@ const mockModelsModule = {
14
14
  embedContent: vi.fn(),
15
15
  batchEmbedContents: vi.fn(),
16
16
  };
17
+ const { mockLogInvalidChunk, mockLogContentRetry, mockLogContentRetryFailure } = vi.hoisted(() => ({
18
+ mockLogInvalidChunk: vi.fn(),
19
+ mockLogContentRetry: vi.fn(),
20
+ mockLogContentRetryFailure: vi.fn(),
21
+ }));
22
+ vi.mock('../telemetry/loggers.js', () => ({
23
+ logInvalidChunk: mockLogInvalidChunk,
24
+ logContentRetry: mockLogContentRetry,
25
+ logContentRetryFailure: mockLogContentRetryFailure,
26
+ }));
17
27
  describe('GeminiChat', () => {
18
28
  let chat;
19
29
  let mockConfig;
@@ -45,6 +55,110 @@ describe('GeminiChat', () => {
45
55
  vi.resetAllMocks();
46
56
  });
47
57
  describe('sendMessage', () => {
58
+ it('should throw an error when attempting to add a user turn after another user turn', async () => {
59
+ // 1. Setup: Create a history that already ends with a user turn (a functionResponse).
60
+ const initialHistory = [
61
+ { role: 'user', parts: [{ text: 'Initial prompt' }] },
62
+ {
63
+ role: 'model',
64
+ parts: [{ functionCall: { name: 'test_tool', args: {} } }],
65
+ },
66
+ {
67
+ role: 'user',
68
+ parts: [{ functionResponse: { name: 'test_tool', response: {} } }],
69
+ },
70
+ ];
71
+ chat.setHistory(initialHistory);
72
+ // 2. Mock a valid model response so the call doesn't fail for other reasons.
73
+ const mockResponse = {
74
+ candidates: [
75
+ { content: { role: 'model', parts: [{ text: 'some response' }] } },
76
+ ],
77
+ };
78
+ vi.mocked(mockModelsModule.generateContent).mockResolvedValue(mockResponse);
79
+ // 3. Action & Assert: Expect that sending another user message immediately
80
+ // after a user-role turn throws the specific error.
81
+ await expect(chat.sendMessage({ message: 'This is an invalid consecutive user message' }, 'prompt-id-1')).rejects.toThrow('Cannot add a user turn after another user turn.');
82
+ });
83
+ it('should preserve text parts that are in the same response as a thought', async () => {
84
+ // 1. Mock the API to return a single response containing both a thought and visible text.
85
+ const mixedContentResponse = {
86
+ candidates: [
87
+ {
88
+ content: {
89
+ role: 'model',
90
+ parts: [
91
+ { thought: 'This is a thought.' },
92
+ { text: 'This is the visible text that should not be lost.' },
93
+ ],
94
+ },
95
+ },
96
+ ],
97
+ };
98
+ vi.mocked(mockModelsModule.generateContent).mockResolvedValue(mixedContentResponse);
99
+ // 2. Action: Send a standard, non-streaming message.
100
+ await chat.sendMessage({ message: 'test message' }, 'prompt-id-mixed-response');
101
+ // 3. Assert: Check the final state of the history.
102
+ const history = chat.getHistory();
103
+ // The history should contain two turns: the user's message and the model's response.
104
+ expect(history.length).toBe(2);
105
+ const modelTurn = history[1];
106
+ expect(modelTurn.role).toBe('model');
107
+ // CRUCIAL ASSERTION:
108
+ // Buggy code would discard the entire response because a "thought" was present,
109
+ // resulting in an empty placeholder turn with 0 parts.
110
+ // The corrected code will pass, preserving the single visible text part.
111
+ expect(modelTurn?.parts?.length).toBe(1);
112
+ expect(modelTurn?.parts[0].text).toBe('This is the visible text that should not be lost.');
113
+ });
114
+ it('should add a placeholder model turn when a tool call is followed by an empty model response', async () => {
115
+ // 1. Setup: A history where the model has just made a function call.
116
+ const initialHistory = [
117
+ {
118
+ role: 'user',
119
+ parts: [{ text: 'Find a good Italian restaurant for me.' }],
120
+ },
121
+ {
122
+ role: 'model',
123
+ parts: [
124
+ {
125
+ functionCall: {
126
+ name: 'find_restaurant',
127
+ args: { cuisine: 'Italian' },
128
+ },
129
+ },
130
+ ],
131
+ },
132
+ ];
133
+ chat.setHistory(initialHistory);
134
+ // 2. Mock the API to return an empty/thought-only response.
135
+ const emptyModelResponse = {
136
+ candidates: [
137
+ { content: { role: 'model', parts: [{ thought: true }] } },
138
+ ],
139
+ };
140
+ vi.mocked(mockModelsModule.generateContent).mockResolvedValue(emptyModelResponse);
141
+ // 3. Action: Send the function response back to the model.
142
+ await chat.sendMessage({
143
+ message: {
144
+ functionResponse: {
145
+ name: 'find_restaurant',
146
+ response: { name: 'Vesuvio' },
147
+ },
148
+ },
149
+ }, 'prompt-id-1');
150
+ // 4. Assert: The history should now have four valid, alternating turns.
151
+ const history = chat.getHistory();
152
+ expect(history.length).toBe(4);
153
+ // The final turn must be the empty model placeholder.
154
+ const lastTurn = history[3];
155
+ expect(lastTurn.role).toBe('model');
156
+ expect(lastTurn?.parts?.length).toBe(0);
157
+ // The second-to-last turn must be the function response we sent.
158
+ const secondToLastTurn = history[2];
159
+ expect(secondToLastTurn.role).toBe('user');
160
+ expect(secondToLastTurn?.parts[0].functionResponse).toBeDefined();
161
+ });
48
162
  it('should call generateContent with the correct parameters', async () => {
49
163
  const response = {
50
164
  candidates: [
@@ -70,6 +184,226 @@ describe('GeminiChat', () => {
70
184
  });
71
185
  });
72
186
  describe('sendMessageStream', () => {
187
+ it('should not consolidate text into a part that also contains a functionCall', async () => {
188
+ // 1. Mock the API to stream a malformed part followed by a valid text part.
189
+ const multiChunkStream = (async function* () {
190
+ // This malformed part has both text and a functionCall.
191
+ yield {
192
+ candidates: [
193
+ {
194
+ content: {
195
+ role: 'model',
196
+ parts: [
197
+ {
198
+ text: 'Some text',
199
+ functionCall: { name: 'do_stuff', args: {} },
200
+ },
201
+ ],
202
+ },
203
+ },
204
+ ],
205
+ };
206
+ // This valid text part should NOT be merged into the malformed one.
207
+ yield {
208
+ candidates: [
209
+ {
210
+ content: {
211
+ role: 'model',
212
+ parts: [{ text: ' that should not be merged.' }],
213
+ },
214
+ },
215
+ ],
216
+ };
217
+ })();
218
+ vi.mocked(mockModelsModule.generateContentStream).mockResolvedValue(multiChunkStream);
219
+ // 2. Action: Send a message and consume the stream.
220
+ const stream = await chat.sendMessageStream({ message: 'test message' }, 'prompt-id-malformed-chunk');
221
+ for await (const _ of stream) {
222
+ // Consume the stream to trigger history recording.
223
+ }
224
+ // 3. Assert: Check that the final history was not incorrectly consolidated.
225
+ const history = chat.getHistory();
226
+ expect(history.length).toBe(2);
227
+ const modelTurn = history[1];
228
+ // CRUCIAL ASSERTION: There should be two separate parts.
229
+ // The old, non-strict logic would incorrectly merge them, resulting in one part.
230
+ expect(modelTurn?.parts?.length).toBe(2);
231
+ // Verify the contents of each part.
232
+ expect(modelTurn?.parts[0].text).toBe('Some text');
233
+ expect(modelTurn?.parts[0].functionCall).toBeDefined();
234
+ expect(modelTurn?.parts[1].text).toBe(' that should not be merged.');
235
+ });
236
+ it('should consolidate subsequent text chunks after receiving an empty text chunk', async () => {
237
+ // 1. Mock the API to return a stream where one chunk is just an empty text part.
238
+ const multiChunkStream = (async function* () {
239
+ yield {
240
+ candidates: [
241
+ { content: { role: 'model', parts: [{ text: 'Hello' }] } },
242
+ ],
243
+ };
244
+ // FIX: The original test used { text: '' }, which is invalid.
245
+ // A chunk can be empty but still valid. This chunk is now removed
246
+ // as the important part is consolidating what comes after.
247
+ yield {
248
+ candidates: [
249
+ { content: { role: 'model', parts: [{ text: ' World!' }] } },
250
+ ],
251
+ };
252
+ })();
253
+ vi.mocked(mockModelsModule.generateContentStream).mockResolvedValue(multiChunkStream);
254
+ // 2. Action: Send a message and consume the stream.
255
+ const stream = await chat.sendMessageStream({ message: 'test message' }, 'prompt-id-empty-chunk-consolidation');
256
+ for await (const _ of stream) {
257
+ // Consume the stream
258
+ }
259
+ // 3. Assert: Check that the final history was correctly consolidated.
260
+ const history = chat.getHistory();
261
+ expect(history.length).toBe(2);
262
+ const modelTurn = history[1];
263
+ expect(modelTurn?.parts?.length).toBe(1);
264
+ expect(modelTurn?.parts[0].text).toBe('Hello World!');
265
+ });
266
+ it('should consolidate adjacent text parts that arrive in separate stream chunks', async () => {
267
+ // 1. Mock the API to return a stream of multiple, adjacent text chunks.
268
+ const multiChunkStream = (async function* () {
269
+ yield {
270
+ candidates: [
271
+ { content: { role: 'model', parts: [{ text: 'This is the ' }] } },
272
+ ],
273
+ };
274
+ yield {
275
+ candidates: [
276
+ { content: { role: 'model', parts: [{ text: 'first part.' }] } },
277
+ ],
278
+ };
279
+ // This function call should break the consolidation.
280
+ yield {
281
+ candidates: [
282
+ {
283
+ content: {
284
+ role: 'model',
285
+ parts: [{ functionCall: { name: 'do_stuff', args: {} } }],
286
+ },
287
+ },
288
+ ],
289
+ };
290
+ yield {
291
+ candidates: [
292
+ {
293
+ content: {
294
+ role: 'model',
295
+ parts: [{ text: 'This is the second part.' }],
296
+ },
297
+ },
298
+ ],
299
+ };
300
+ })();
301
+ vi.mocked(mockModelsModule.generateContentStream).mockResolvedValue(multiChunkStream);
302
+ // 2. Action: Send a message and consume the stream.
303
+ const stream = await chat.sendMessageStream({ message: 'test message' }, 'prompt-id-multi-chunk');
304
+ for await (const _ of stream) {
305
+ // Consume the stream to trigger history recording.
306
+ }
307
+ // 3. Assert: Check that the final history was correctly consolidated.
308
+ const history = chat.getHistory();
309
+ // The history should contain the user's turn and ONE consolidated model turn.
310
+ expect(history.length).toBe(2);
311
+ const modelTurn = history[1];
312
+ expect(modelTurn.role).toBe('model');
313
+ // The model turn should have 3 distinct parts: the merged text, the function call, and the final text.
314
+ expect(modelTurn?.parts?.length).toBe(3);
315
+ expect(modelTurn?.parts[0].text).toBe('This is the first part.');
316
+ expect(modelTurn.parts[1].functionCall).toBeDefined();
317
+ expect(modelTurn.parts[2].text).toBe('This is the second part.');
318
+ });
319
+ it('should preserve text parts that stream in the same chunk as a thought', async () => {
320
+ // 1. Mock the API to return a single chunk containing both a thought and visible text.
321
+ const mixedContentStream = (async function* () {
322
+ yield {
323
+ candidates: [
324
+ {
325
+ content: {
326
+ role: 'model',
327
+ parts: [
328
+ { thought: 'This is a thought.' },
329
+ { text: 'This is the visible text that should not be lost.' },
330
+ ],
331
+ },
332
+ },
333
+ ],
334
+ };
335
+ })();
336
+ vi.mocked(mockModelsModule.generateContentStream).mockResolvedValue(mixedContentStream);
337
+ // 2. Action: Send a message and fully consume the stream to trigger history recording.
338
+ const stream = await chat.sendMessageStream({ message: 'test message' }, 'prompt-id-mixed-chunk');
339
+ for await (const _ of stream) {
340
+ // This loop consumes the stream.
341
+ }
342
+ // 3. Assert: Check the final state of the history.
343
+ const history = chat.getHistory();
344
+ // The history should contain two turns: the user's message and the model's response.
345
+ expect(history.length).toBe(2);
346
+ const modelTurn = history[1];
347
+ expect(modelTurn.role).toBe('model');
348
+ // CRUCIAL ASSERTION:
349
+ // The buggy code would fail here, resulting in parts.length being 0.
350
+ // The corrected code will pass, preserving the single visible text part.
351
+ expect(modelTurn?.parts?.length).toBe(1);
352
+ expect(modelTurn?.parts[0].text).toBe('This is the visible text that should not be lost.');
353
+ });
354
+ it('should add a placeholder model turn when a tool call is followed by an empty stream response', async () => {
355
+ // 1. Setup: A history where the model has just made a function call.
356
+ const initialHistory = [
357
+ {
358
+ role: 'user',
359
+ parts: [{ text: 'Find a good Italian restaurant for me.' }],
360
+ },
361
+ {
362
+ role: 'model',
363
+ parts: [
364
+ {
365
+ functionCall: {
366
+ name: 'find_restaurant',
367
+ args: { cuisine: 'Italian' },
368
+ },
369
+ },
370
+ ],
371
+ },
372
+ ];
373
+ chat.setHistory(initialHistory);
374
+ // 2. Mock the API to return an empty/thought-only stream.
375
+ const emptyStreamResponse = (async function* () {
376
+ yield {
377
+ candidates: [
378
+ { content: { role: 'model', parts: [{ thought: true }] } },
379
+ ],
380
+ };
381
+ })();
382
+ vi.mocked(mockModelsModule.generateContentStream).mockResolvedValue(emptyStreamResponse);
383
+ // 3. Action: Send the function response back to the model and consume the stream.
384
+ const stream = await chat.sendMessageStream({
385
+ message: {
386
+ functionResponse: {
387
+ name: 'find_restaurant',
388
+ response: { name: 'Vesuvio' },
389
+ },
390
+ },
391
+ }, 'prompt-id-stream-1');
392
+ for await (const _ of stream) {
393
+ // This loop consumes the stream to trigger the internal logic.
394
+ }
395
+ // 4. Assert: The history should now have four valid, alternating turns.
396
+ const history = chat.getHistory();
397
+ expect(history.length).toBe(4);
398
+ // The final turn must be the empty model placeholder.
399
+ const lastTurn = history[3];
400
+ expect(lastTurn.role).toBe('model');
401
+ expect(lastTurn?.parts?.length).toBe(0);
402
+ // The second-to-last turn must be the function response we sent.
403
+ const secondToLastTurn = history[2];
404
+ expect(secondToLastTurn.role).toBe('user');
405
+ expect(secondToLastTurn?.parts[0].functionResponse).toBeDefined();
406
+ });
73
407
  it('should call generateContentStream with the correct parameters', async () => {
74
408
  const response = (async function* () {
75
409
  yield {
@@ -88,7 +422,10 @@ describe('GeminiChat', () => {
88
422
  };
89
423
  })();
90
424
  vi.mocked(mockModelsModule.generateContentStream).mockResolvedValue(response);
91
- await chat.sendMessageStream({ message: 'hello' }, 'prompt-id-1');
425
+ const stream = await chat.sendMessageStream({ message: 'hello' }, 'prompt-id-1');
426
+ for await (const _ of stream) {
427
+ // consume stream to trigger internal logic
428
+ }
92
429
  expect(mockModelsModule.generateContentStream).toHaveBeenCalledWith({
93
430
  model: 'gemini-pro',
94
431
  contents: [{ role: 'user', parts: [{ text: 'hello' }] }],
@@ -101,295 +438,128 @@ describe('GeminiChat', () => {
101
438
  role: 'user',
102
439
  parts: [{ text: 'User input' }],
103
440
  };
104
- it('should add user input and a single model output to history', () => {
441
+ it('should consolidate all consecutive model turns into a single turn', () => {
442
+ const userInput = {
443
+ role: 'user',
444
+ parts: [{ text: 'User input' }],
445
+ };
446
+ // This simulates a multi-part model response with different part types.
105
447
  const modelOutput = [
106
- { role: 'model', parts: [{ text: 'Model output' }] },
448
+ { role: 'model', parts: [{ text: 'Thinking...' }] },
449
+ {
450
+ role: 'model',
451
+ parts: [{ functionCall: { name: 'do_stuff', args: {} } }],
452
+ },
107
453
  ];
108
- // @ts-expect-error Accessing private method for testing purposes
454
+ // @ts-expect-error Accessing private method for testing
109
455
  chat.recordHistory(userInput, modelOutput);
110
456
  const history = chat.getHistory();
111
- expect(history).toEqual([userInput, modelOutput[0]]);
112
- });
113
- it('should consolidate adjacent model outputs', () => {
114
- const modelOutputParts = [
115
- { role: 'model', parts: [{ text: 'Model part 1' }] },
116
- { role: 'model', parts: [{ text: 'Model part 2' }] },
117
- ];
118
- // @ts-expect-error Accessing private method for testing purposes
119
- chat.recordHistory(userInput, modelOutputParts);
120
- const history = chat.getHistory();
457
+ // The history should contain the user's turn and ONE consolidated model turn.
458
+ // The old code would fail here, resulting in a length of 3.
459
+ //expect(history).toBe([]);
121
460
  expect(history.length).toBe(2);
122
- expect(history[0]).toEqual(userInput);
123
- expect(history[1].role).toBe('model');
124
- expect(history[1].parts).toEqual([{ text: 'Model part 1Model part 2' }]);
461
+ const modelTurn = history[1];
462
+ expect(modelTurn.role).toBe('model');
463
+ // The consolidated turn should contain both the text part and the functionCall part.
464
+ expect(modelTurn?.parts?.length).toBe(2);
465
+ expect(modelTurn?.parts[0].text).toBe('Thinking...');
466
+ expect(modelTurn?.parts[1].functionCall).toBeDefined();
125
467
  });
126
- it('should handle a mix of user and model roles in outputContents (though unusual)', () => {
127
- const mixedOutput = [
128
- { role: 'model', parts: [{ text: 'Model 1' }] },
129
- { role: 'user', parts: [{ text: 'Unexpected User' }] }, // This should be pushed as is
130
- { role: 'model', parts: [{ text: 'Model 2' }] },
131
- ];
132
- // @ts-expect-error Accessing private method for testing purposes
133
- chat.recordHistory(userInput, mixedOutput);
134
- const history = chat.getHistory();
135
- expect(history.length).toBe(4); // user, model1, user_unexpected, model2
136
- expect(history[0]).toEqual(userInput);
137
- expect(history[1]).toEqual(mixedOutput[0]);
138
- expect(history[2]).toEqual(mixedOutput[1]);
139
- expect(history[3]).toEqual(mixedOutput[2]);
140
- });
141
- it('should consolidate multiple adjacent model outputs correctly', () => {
142
- const modelOutputParts = [
143
- { role: 'model', parts: [{ text: 'M1' }] },
144
- { role: 'model', parts: [{ text: 'M2' }] },
145
- { role: 'model', parts: [{ text: 'M3' }] },
146
- ];
147
- // @ts-expect-error Accessing private method for testing purposes
148
- chat.recordHistory(userInput, modelOutputParts);
149
- const history = chat.getHistory();
150
- expect(history.length).toBe(2);
151
- expect(history[1].parts).toEqual([{ text: 'M1M2M3' }]);
152
- });
153
- it('should not consolidate if roles are different between model outputs', () => {
154
- const modelOutputParts = [
155
- { role: 'model', parts: [{ text: 'M1' }] },
156
- { role: 'user', parts: [{ text: 'Interjecting User' }] },
157
- { role: 'model', parts: [{ text: 'M2' }] },
158
- ];
159
- // @ts-expect-error Accessing private method for testing purposes
160
- chat.recordHistory(userInput, modelOutputParts);
161
- const history = chat.getHistory();
162
- expect(history.length).toBe(4); // user, M1, Interjecting User, M2
163
- expect(history[1].parts).toEqual([{ text: 'M1' }]);
164
- expect(history[3].parts).toEqual([{ text: 'M2' }]);
165
- });
166
- it('should merge with last history entry if it is also a model output', () => {
167
- // @ts-expect-error Accessing private property for test setup
168
- chat.history = [
169
- userInput,
170
- { role: 'model', parts: [{ text: 'Initial Model Output' }] },
171
- ]; // Prime the history
172
- const newModelOutput = [
173
- { role: 'model', parts: [{ text: 'New Model Part 1' }] },
174
- { role: 'model', parts: [{ text: 'New Model Part 2' }] },
175
- ];
176
- // @ts-expect-error Accessing private method for testing purposes
177
- chat.recordHistory(userInput, newModelOutput); // userInput here is for the *next* turn, but history is already primed
178
- // Reset and set up a more realistic scenario for merging with existing history
179
- chat = new GeminiChat(mockConfig, mockModelsModule, config, []);
180
- const firstUserInput = {
181
- role: 'user',
182
- parts: [{ text: 'First user input' }],
183
- };
184
- const firstModelOutput = [
185
- { role: 'model', parts: [{ text: 'First model response' }] },
186
- ];
187
- // @ts-expect-error Accessing private method for testing purposes
188
- chat.recordHistory(firstUserInput, firstModelOutput);
189
- const secondUserInput = {
190
- role: 'user',
191
- parts: [{ text: 'Second user input' }],
192
- };
193
- const secondModelOutput = [
194
- { role: 'model', parts: [{ text: 'Second model response part 1' }] },
195
- { role: 'model', parts: [{ text: 'Second model response part 2' }] },
468
+ it('should add a placeholder model turn when a tool call is followed by an empty response', () => {
469
+ // 1. Setup: A history where the model has just made a function call.
470
+ const initialHistory = [
471
+ { role: 'user', parts: [{ text: 'Initial prompt' }] },
472
+ {
473
+ role: 'model',
474
+ parts: [{ functionCall: { name: 'test_tool', args: {} } }],
475
+ },
196
476
  ];
197
- // @ts-expect-error Accessing private method for testing purposes
198
- chat.recordHistory(secondUserInput, secondModelOutput);
199
- const finalHistory = chat.getHistory();
200
- expect(finalHistory.length).toBe(4); // user1, model1, user2, model2(consolidated)
201
- expect(finalHistory[0]).toEqual(firstUserInput);
202
- expect(finalHistory[1]).toEqual(firstModelOutput[0]);
203
- expect(finalHistory[2]).toEqual(secondUserInput);
204
- expect(finalHistory[3].role).toBe('model');
205
- expect(finalHistory[3].parts).toEqual([
206
- { text: 'Second model response part 1Second model response part 2' },
207
- ]);
208
- });
209
- it('should correctly merge consolidated new output with existing model history', () => {
210
- // Setup: history ends with a model turn
211
- const initialUser = {
477
+ chat.setHistory(initialHistory);
478
+ // 2. Action: The user provides the tool's response, and the model's
479
+ // final output is empty (e.g., just a thought, which gets filtered out).
480
+ const functionResponse = {
212
481
  role: 'user',
213
- parts: [{ text: 'Initial user query' }],
214
- };
215
- const initialModel = {
216
- role: 'model',
217
- parts: [{ text: 'Initial model answer.' }],
482
+ parts: [{ functionResponse: { name: 'test_tool', response: {} } }],
218
483
  };
219
- chat = new GeminiChat(mockConfig, mockModelsModule, config, [
220
- initialUser,
221
- initialModel,
484
+ const emptyModelOutput = [];
485
+ // @ts-expect-error Accessing private method for testing
486
+ chat.recordHistory(functionResponse, emptyModelOutput, [
487
+ functionResponse,
222
488
  ]);
223
- // New interaction
224
- const currentUserInput = {
225
- role: 'user',
226
- parts: [{ text: 'Follow-up question' }],
227
- };
228
- const newModelParts = [
229
- { role: 'model', parts: [{ text: 'Part A of new answer.' }] },
230
- { role: 'model', parts: [{ text: 'Part B of new answer.' }] },
231
- ];
232
- // @ts-expect-error Accessing private method for testing purposes
233
- chat.recordHistory(currentUserInput, newModelParts);
489
+ // 3. Assert: The history should now have four valid, alternating turns.
234
490
  const history = chat.getHistory();
235
- // Expected: initialUser, initialModel, currentUserInput, consolidatedNewModelParts
236
491
  expect(history.length).toBe(4);
237
- expect(history[0]).toEqual(initialUser);
238
- expect(history[1]).toEqual(initialModel);
239
- expect(history[2]).toEqual(currentUserInput);
240
- expect(history[3].role).toBe('model');
241
- expect(history[3].parts).toEqual([
242
- { text: 'Part A of new answer.Part B of new answer.' },
243
- ]);
492
+ // The final turn must be the empty model placeholder.
493
+ const lastTurn = history[3];
494
+ expect(lastTurn.role).toBe('model');
495
+ expect(lastTurn?.parts?.length).toBe(0);
496
+ // The second-to-last turn must be the function response we provided.
497
+ const secondToLastTurn = history[2];
498
+ expect(secondToLastTurn.role).toBe('user');
499
+ expect(secondToLastTurn?.parts[0].functionResponse).toBeDefined();
244
500
  });
245
- it('should handle empty modelOutput array', () => {
246
- // @ts-expect-error Accessing private method for testing purposes
247
- chat.recordHistory(userInput, []);
248
- const history = chat.getHistory();
249
- // If modelOutput is empty, it might push a default empty model part depending on isFunctionResponse
250
- // Assuming isFunctionResponse(userInput) is false for this simple text input
251
- expect(history.length).toBe(2);
252
- expect(history[0]).toEqual(userInput);
253
- expect(history[1].role).toBe('model');
254
- expect(history[1].parts).toEqual([]);
255
- });
256
- it('should handle aggregating modelOutput', () => {
257
- const modelOutputUndefinedParts = [
258
- { role: 'model', parts: [{ text: 'First model part' }] },
259
- { role: 'model', parts: [{ text: 'Second model part' }] },
260
- { role: 'model', parts: undefined }, // Test undefined parts
261
- { role: 'model', parts: [{ text: 'Third model part' }] },
262
- { role: 'model', parts: [] }, // Test empty parts array
263
- ];
264
- // @ts-expect-error Accessing private method for testing purposes
265
- chat.recordHistory(userInput, modelOutputUndefinedParts);
266
- const history = chat.getHistory();
267
- expect(history.length).toBe(5);
268
- expect(history[0]).toEqual(userInput);
269
- expect(history[1].role).toBe('model');
270
- expect(history[1].parts).toEqual([
271
- { text: 'First model partSecond model part' },
272
- ]);
273
- expect(history[2].role).toBe('model');
274
- expect(history[2].parts).toBeUndefined();
275
- expect(history[3].role).toBe('model');
276
- expect(history[3].parts).toEqual([{ text: 'Third model part' }]);
277
- expect(history[4].role).toBe('model');
278
- expect(history[4].parts).toEqual([]);
279
- });
280
- it('should handle modelOutput with parts being undefined or empty (if they pass initial every check)', () => {
281
- const modelOutputUndefinedParts = [
282
- { role: 'model', parts: [{ text: 'Text part' }] },
283
- { role: 'model', parts: undefined }, // Test undefined parts
284
- { role: 'model', parts: [] }, // Test empty parts array
285
- ];
286
- // @ts-expect-error Accessing private method for testing purposes
287
- chat.recordHistory(userInput, modelOutputUndefinedParts);
288
- const history = chat.getHistory();
289
- expect(history.length).toBe(4); // userInput, model1 (text), model2 (undefined parts), model3 (empty parts)
290
- expect(history[0]).toEqual(userInput);
291
- expect(history[1].role).toBe('model');
292
- expect(history[1].parts).toEqual([{ text: 'Text part' }]);
293
- expect(history[2].role).toBe('model');
294
- expect(history[2].parts).toBeUndefined();
295
- expect(history[3].role).toBe('model');
296
- expect(history[3].parts).toEqual([]);
297
- });
298
- it('should correctly handle automaticFunctionCallingHistory', () => {
299
- const afcHistory = [
300
- { role: 'user', parts: [{ text: 'AFC User' }] },
301
- { role: 'model', parts: [{ text: 'AFC Model' }] },
302
- ];
303
- const modelOutput = [
304
- { role: 'model', parts: [{ text: 'Regular Model Output' }] },
305
- ];
306
- // @ts-expect-error Accessing private method for testing purposes
307
- chat.recordHistory(userInput, modelOutput, afcHistory);
308
- const history = chat.getHistory();
309
- expect(history.length).toBe(3);
310
- expect(history[0]).toEqual(afcHistory[0]);
311
- expect(history[1]).toEqual(afcHistory[1]);
312
- expect(history[2]).toEqual(modelOutput[0]);
313
- });
314
- it('should add userInput if AFC history is present but empty', () => {
501
+ it('should add user input and a single model output to history', () => {
315
502
  const modelOutput = [
316
- { role: 'model', parts: [{ text: 'Model Output' }] },
503
+ { role: 'model', parts: [{ text: 'Model output' }] },
317
504
  ];
318
- // @ts-expect-error Accessing private method for testing purposes
319
- chat.recordHistory(userInput, modelOutput, []); // Empty AFC history
505
+ // @ts-expect-error Accessing private method for testing
506
+ chat.recordHistory(userInput, modelOutput);
320
507
  const history = chat.getHistory();
321
508
  expect(history.length).toBe(2);
322
509
  expect(history[0]).toEqual(userInput);
323
510
  expect(history[1]).toEqual(modelOutput[0]);
324
511
  });
325
- it('should skip "thought" content from modelOutput', () => {
326
- const modelOutputWithThought = [
327
- { role: 'model', parts: [{ thought: true }, { text: 'Visible text' }] },
328
- { role: 'model', parts: [{ text: 'Another visible text' }] },
512
+ it('should consolidate adjacent text parts from multiple content objects', () => {
513
+ const modelOutput = [
514
+ { role: 'model', parts: [{ text: 'Part 1.' }] },
515
+ { role: 'model', parts: [{ text: ' Part 2.' }] },
516
+ { role: 'model', parts: [{ text: ' Part 3.' }] },
329
517
  ];
330
- // @ts-expect-error Accessing private method for testing purposes
331
- chat.recordHistory(userInput, modelOutputWithThought);
518
+ // @ts-expect-error Accessing private method for testing
519
+ chat.recordHistory(userInput, modelOutput);
332
520
  const history = chat.getHistory();
333
- expect(history.length).toBe(2); // User input + consolidated model output
334
- expect(history[0]).toEqual(userInput);
521
+ expect(history.length).toBe(2);
335
522
  expect(history[1].role).toBe('model');
336
- // The 'thought' part is skipped, 'Another visible text' becomes the first part.
337
- expect(history[1].parts).toEqual([{ text: 'Another visible text' }]);
523
+ expect(history[1].parts).toEqual([{ text: 'Part 1. Part 2. Part 3.' }]);
338
524
  });
339
- it('should skip "thought" content even if it is the only content', () => {
340
- const modelOutputOnlyThought = [
341
- { role: 'model', parts: [{ thought: true }] },
342
- ];
343
- // @ts-expect-error Accessing private method for testing purposes
344
- chat.recordHistory(userInput, modelOutputOnlyThought);
345
- const history = chat.getHistory();
346
- expect(history.length).toBe(1); // User input + default empty model part
347
- expect(history[0]).toEqual(userInput);
348
- });
349
- it('should correctly consolidate text parts when a thought part is in between', () => {
350
- const modelOutputMixed = [
351
- { role: 'model', parts: [{ text: 'Part 1.' }] },
352
- {
353
- role: 'model',
354
- parts: [{ thought: true }, { text: 'Should be skipped' }],
355
- },
356
- { role: 'model', parts: [{ text: 'Part 2.' }] },
357
- ];
358
- // @ts-expect-error Accessing private method for testing purposes
359
- chat.recordHistory(userInput, modelOutputMixed);
525
+ it('should add an empty placeholder turn if modelOutput is empty', () => {
526
+ // This simulates receiving a pre-filtered, thought-only response.
527
+ const emptyModelOutput = [];
528
+ // @ts-expect-error Accessing private method for testing
529
+ chat.recordHistory(userInput, emptyModelOutput);
360
530
  const history = chat.getHistory();
361
531
  expect(history.length).toBe(2);
362
532
  expect(history[0]).toEqual(userInput);
363
533
  expect(history[1].role).toBe('model');
364
- expect(history[1].parts).toEqual([{ text: 'Part 1.Part 2.' }]);
534
+ expect(history[1].parts).toEqual([]);
365
535
  });
366
- it('should handle multiple thought parts correctly', () => {
367
- const modelOutputMultipleThoughts = [
368
- { role: 'model', parts: [{ thought: true }] },
369
- { role: 'model', parts: [{ text: 'Visible 1' }] },
370
- { role: 'model', parts: [{ thought: true }] },
371
- { role: 'model', parts: [{ text: 'Visible 2' }] },
536
+ it('should preserve model outputs with undefined or empty parts arrays', () => {
537
+ const malformedOutput = [
538
+ { role: 'model', parts: [{ text: 'Text part' }] },
539
+ { role: 'model', parts: undefined },
540
+ { role: 'model', parts: [] },
372
541
  ];
373
- // @ts-expect-error Accessing private method for testing purposes
374
- chat.recordHistory(userInput, modelOutputMultipleThoughts);
542
+ // @ts-expect-error Accessing private method for testing
543
+ chat.recordHistory(userInput, malformedOutput);
375
544
  const history = chat.getHistory();
376
- expect(history.length).toBe(2);
377
- expect(history[0]).toEqual(userInput);
378
- expect(history[1].role).toBe('model');
379
- expect(history[1].parts).toEqual([{ text: 'Visible 1Visible 2' }]);
545
+ expect(history.length).toBe(4); // userInput + 3 model turns
546
+ expect(history[1].parts).toEqual([{ text: 'Text part' }]);
547
+ expect(history[2].parts).toBeUndefined();
548
+ expect(history[3].parts).toEqual([]);
380
549
  });
381
- it('should handle thought part at the end of outputContents', () => {
382
- const modelOutputThoughtAtEnd = [
383
- { role: 'model', parts: [{ text: 'Visible text' }] },
384
- { role: 'model', parts: [{ thought: true }] },
550
+ it('should not consolidate content with different roles', () => {
551
+ const mixedOutput = [
552
+ { role: 'model', parts: [{ text: 'Model 1' }] },
553
+ { role: 'user', parts: [{ text: 'Unexpected User' }] },
554
+ { role: 'model', parts: [{ text: 'Model 2' }] },
385
555
  ];
386
- // @ts-expect-error Accessing private method for testing purposes
387
- chat.recordHistory(userInput, modelOutputThoughtAtEnd);
556
+ // @ts-expect-error Accessing private method for testing
557
+ chat.recordHistory(userInput, mixedOutput);
388
558
  const history = chat.getHistory();
389
- expect(history.length).toBe(2);
390
- expect(history[0]).toEqual(userInput);
391
- expect(history[1].role).toBe('model');
392
- expect(history[1].parts).toEqual([{ text: 'Visible text' }]);
559
+ expect(history.length).toBe(4); // userInput, model1, unexpected_user, model2
560
+ expect(history[1]).toEqual(mixedOutput[0]);
561
+ expect(history[2]).toEqual(mixedOutput[1]);
562
+ expect(history[3]).toEqual(mixedOutput[2]);
393
563
  });
394
564
  });
395
565
  describe('addHistory', () => {
@@ -420,5 +590,286 @@ describe('GeminiChat', () => {
420
590
  expect(history[1]).toEqual(content2);
421
591
  });
422
592
  });
593
+ describe('sendMessageStream with retries', () => {
594
+ it('should retry on invalid content, succeed, and report metrics', async () => {
595
+ // Use mockImplementationOnce to provide a fresh, promise-wrapped generator for each attempt.
596
+ vi.mocked(mockModelsModule.generateContentStream)
597
+ .mockImplementationOnce(async () =>
598
+ // First call returns an invalid stream
599
+ (async function* () {
600
+ yield {
601
+ candidates: [{ content: { parts: [{ text: '' }] } }], // Invalid empty text part
602
+ };
603
+ })())
604
+ .mockImplementationOnce(async () =>
605
+ // Second call returns a valid stream
606
+ (async function* () {
607
+ yield {
608
+ candidates: [
609
+ { content: { parts: [{ text: 'Successful response' }] } },
610
+ ],
611
+ };
612
+ })());
613
+ const stream = await chat.sendMessageStream({ message: 'test' }, 'prompt-id-retry-success');
614
+ const chunks = [];
615
+ for await (const chunk of stream) {
616
+ chunks.push(chunk);
617
+ }
618
+ // Assertions
619
+ expect(mockLogInvalidChunk).toHaveBeenCalledTimes(1);
620
+ expect(mockLogContentRetry).toHaveBeenCalledTimes(1);
621
+ expect(mockLogContentRetryFailure).not.toHaveBeenCalled();
622
+ expect(mockModelsModule.generateContentStream).toHaveBeenCalledTimes(2);
623
+ expect(chunks.some((c) => c.candidates?.[0]?.content?.parts?.[0]?.text ===
624
+ 'Successful response')).toBe(true);
625
+ // Check that history was recorded correctly once, with no duplicates.
626
+ const history = chat.getHistory();
627
+ expect(history.length).toBe(2);
628
+ expect(history[0]).toEqual({
629
+ role: 'user',
630
+ parts: [{ text: 'test' }],
631
+ });
632
+ expect(history[1]).toEqual({
633
+ role: 'model',
634
+ parts: [{ text: 'Successful response' }],
635
+ });
636
+ });
637
+ it('should fail after all retries on persistent invalid content and report metrics', async () => {
638
+ vi.mocked(mockModelsModule.generateContentStream).mockImplementation(async () => (async function* () {
639
+ yield {
640
+ candidates: [
641
+ {
642
+ content: {
643
+ parts: [{ text: '' }],
644
+ role: 'model',
645
+ },
646
+ },
647
+ ],
648
+ };
649
+ })());
650
+ // This helper function consumes the stream and allows us to test for rejection.
651
+ async function consumeStreamAndExpectError() {
652
+ const stream = await chat.sendMessageStream({ message: 'test' }, 'prompt-id-retry-fail');
653
+ for await (const _ of stream) {
654
+ // Must loop to trigger the internal logic that throws.
655
+ }
656
+ }
657
+ await expect(consumeStreamAndExpectError()).rejects.toThrow(EmptyStreamError);
658
+ // Should be called 3 times (initial + 2 retries)
659
+ expect(mockModelsModule.generateContentStream).toHaveBeenCalledTimes(3);
660
+ expect(mockLogInvalidChunk).toHaveBeenCalledTimes(3);
661
+ expect(mockLogContentRetry).toHaveBeenCalledTimes(2);
662
+ expect(mockLogContentRetryFailure).toHaveBeenCalledTimes(1);
663
+ // History should be clean, as if the failed turn never happened.
664
+ const history = chat.getHistory();
665
+ expect(history.length).toBe(0);
666
+ });
667
+ });
668
+ it('should correctly retry and append to an existing history mid-conversation', async () => {
669
+ // 1. Setup
670
+ const initialHistory = [
671
+ { role: 'user', parts: [{ text: 'First question' }] },
672
+ { role: 'model', parts: [{ text: 'First answer' }] },
673
+ ];
674
+ chat.setHistory(initialHistory);
675
+ // 2. Mock the API to fail once with an empty stream, then succeed.
676
+ vi.mocked(mockModelsModule.generateContentStream)
677
+ .mockImplementationOnce(async () => (async function* () {
678
+ yield {
679
+ candidates: [{ content: { parts: [{ text: '' }] } }],
680
+ };
681
+ })())
682
+ .mockImplementationOnce(async () =>
683
+ // Second attempt succeeds
684
+ (async function* () {
685
+ yield {
686
+ candidates: [{ content: { parts: [{ text: 'Second answer' }] } }],
687
+ };
688
+ })());
689
+ // 3. Send a new message
690
+ const stream = await chat.sendMessageStream({ message: 'Second question' }, 'prompt-id-retry-existing');
691
+ for await (const _ of stream) {
692
+ // consume stream
693
+ }
694
+ // 4. Assert the final history and metrics
695
+ const history = chat.getHistory();
696
+ expect(history.length).toBe(4);
697
+ // Assert that the correct metrics were reported for one empty-stream retry
698
+ expect(mockLogContentRetry).toHaveBeenCalledTimes(1);
699
+ // Explicitly verify the structure of each part to satisfy TypeScript
700
+ const turn1 = history[0];
701
+ if (!turn1?.parts?.[0] || !('text' in turn1.parts[0])) {
702
+ throw new Error('Test setup error: First turn is not a valid text part.');
703
+ }
704
+ expect(turn1.parts[0].text).toBe('First question');
705
+ const turn2 = history[1];
706
+ if (!turn2?.parts?.[0] || !('text' in turn2.parts[0])) {
707
+ throw new Error('Test setup error: Second turn is not a valid text part.');
708
+ }
709
+ expect(turn2.parts[0].text).toBe('First answer');
710
+ const turn3 = history[2];
711
+ if (!turn3?.parts?.[0] || !('text' in turn3.parts[0])) {
712
+ throw new Error('Test setup error: Third turn is not a valid text part.');
713
+ }
714
+ expect(turn3.parts[0].text).toBe('Second question');
715
+ const turn4 = history[3];
716
+ if (!turn4?.parts?.[0] || !('text' in turn4.parts[0])) {
717
+ throw new Error('Test setup error: Fourth turn is not a valid text part.');
718
+ }
719
+ expect(turn4.parts[0].text).toBe('Second answer');
720
+ });
721
+ describe('concurrency control', () => {
722
+ it('should queue a subsequent sendMessage call until the first one completes', async () => {
723
+ // 1. Create promises to manually control when the API calls resolve
724
+ let firstCallResolver;
725
+ const firstCallPromise = new Promise((resolve) => {
726
+ firstCallResolver = resolve;
727
+ });
728
+ let secondCallResolver;
729
+ const secondCallPromise = new Promise((resolve) => {
730
+ secondCallResolver = resolve;
731
+ });
732
+ // A standard response body for the mock
733
+ const mockResponse = {
734
+ candidates: [
735
+ {
736
+ content: { parts: [{ text: 'response' }], role: 'model' },
737
+ },
738
+ ],
739
+ };
740
+ // 2. Mock the API to return our controllable promises in order
741
+ vi.mocked(mockModelsModule.generateContent)
742
+ .mockReturnValueOnce(firstCallPromise)
743
+ .mockReturnValueOnce(secondCallPromise);
744
+ // 3. Start the first message call. Do not await it yet.
745
+ const firstMessagePromise = chat.sendMessage({ message: 'first' }, 'prompt-1');
746
+ // Give the event loop a chance to run the async call up to the `await`
747
+ await new Promise(process.nextTick);
748
+ // 4. While the first call is "in-flight", start the second message call.
749
+ const secondMessagePromise = chat.sendMessage({ message: 'second' }, 'prompt-2');
750
+ // 5. CRUCIAL CHECK: At this point, only the first API call should have been made.
751
+ // The second call should be waiting on `sendPromise`.
752
+ expect(mockModelsModule.generateContent).toHaveBeenCalledTimes(1);
753
+ expect(mockModelsModule.generateContent).toHaveBeenCalledWith(expect.objectContaining({
754
+ contents: expect.arrayContaining([
755
+ expect.objectContaining({ parts: [{ text: 'first' }] }),
756
+ ]),
757
+ }), 'prompt-1');
758
+ // 6. Unblock the first API call and wait for the first message to fully complete.
759
+ firstCallResolver(mockResponse);
760
+ await firstMessagePromise;
761
+ // Give the event loop a chance to unblock and run the second call.
762
+ await new Promise(process.nextTick);
763
+ // 7. CRUCIAL CHECK: Now, the second API call should have been made.
764
+ expect(mockModelsModule.generateContent).toHaveBeenCalledTimes(2);
765
+ expect(mockModelsModule.generateContent).toHaveBeenCalledWith(expect.objectContaining({
766
+ contents: expect.arrayContaining([
767
+ expect.objectContaining({ parts: [{ text: 'second' }] }),
768
+ ]),
769
+ }), 'prompt-2');
770
+ // 8. Clean up by resolving the second call.
771
+ secondCallResolver(mockResponse);
772
+ await secondMessagePromise;
773
+ });
774
+ });
775
+ it('should retry if the model returns a completely empty stream (no chunks)', async () => {
776
+ // 1. Mock the API to return an empty stream first, then a valid one.
777
+ vi.mocked(mockModelsModule.generateContentStream)
778
+ .mockImplementationOnce(
779
+ // First call resolves to an async generator that yields nothing.
780
+ async () => (async function* () { })())
781
+ .mockImplementationOnce(
782
+ // Second call returns a valid stream.
783
+ async () => (async function* () {
784
+ yield {
785
+ candidates: [
786
+ {
787
+ content: {
788
+ parts: [{ text: 'Successful response after empty' }],
789
+ },
790
+ },
791
+ ],
792
+ };
793
+ })());
794
+ // 2. Call the method and consume the stream.
795
+ const stream = await chat.sendMessageStream({ message: 'test empty stream' }, 'prompt-id-empty-stream');
796
+ const chunks = [];
797
+ for await (const chunk of stream) {
798
+ chunks.push(chunk);
799
+ }
800
+ // 3. Assert the results.
801
+ expect(mockModelsModule.generateContentStream).toHaveBeenCalledTimes(2);
802
+ expect(chunks.some((c) => c.candidates?.[0]?.content?.parts?.[0]?.text ===
803
+ 'Successful response after empty')).toBe(true);
804
+ const history = chat.getHistory();
805
+ expect(history.length).toBe(2);
806
+ // Explicitly verify the structure of each part to satisfy TypeScript
807
+ const turn1 = history[0];
808
+ if (!turn1?.parts?.[0] || !('text' in turn1.parts[0])) {
809
+ throw new Error('Test setup error: First turn is not a valid text part.');
810
+ }
811
+ expect(turn1.parts[0].text).toBe('test empty stream');
812
+ const turn2 = history[1];
813
+ if (!turn2?.parts?.[0] || !('text' in turn2.parts[0])) {
814
+ throw new Error('Test setup error: Second turn is not a valid text part.');
815
+ }
816
+ expect(turn2.parts[0].text).toBe('Successful response after empty');
817
+ });
818
+ it('should queue a subsequent sendMessageStream call until the first stream is fully consumed', async () => {
819
+ // 1. Create a promise to manually control the stream's lifecycle
820
+ let continueFirstStream;
821
+ const firstStreamContinuePromise = new Promise((resolve) => {
822
+ continueFirstStream = resolve;
823
+ });
824
+ // 2. Mock the API to return controllable async generators
825
+ const firstStreamGenerator = (async function* () {
826
+ yield {
827
+ candidates: [
828
+ { content: { parts: [{ text: 'first response part 1' }] } },
829
+ ],
830
+ };
831
+ await firstStreamContinuePromise; // Pause the stream
832
+ yield {
833
+ candidates: [{ content: { parts: [{ text: ' part 2' }] } }],
834
+ };
835
+ })();
836
+ const secondStreamGenerator = (async function* () {
837
+ yield {
838
+ candidates: [{ content: { parts: [{ text: 'second response' }] } }],
839
+ };
840
+ })();
841
+ vi.mocked(mockModelsModule.generateContentStream)
842
+ .mockResolvedValueOnce(firstStreamGenerator)
843
+ .mockResolvedValueOnce(secondStreamGenerator);
844
+ // 3. Start the first stream and consume only the first chunk to pause it
845
+ const firstStream = await chat.sendMessageStream({ message: 'first' }, 'prompt-1');
846
+ const firstStreamIterator = firstStream[Symbol.asyncIterator]();
847
+ await firstStreamIterator.next();
848
+ // 4. While the first stream is paused, start the second call. It will block.
849
+ const secondStreamPromise = chat.sendMessageStream({ message: 'second' }, 'prompt-2');
850
+ // 5. Assert that only one API call has been made so far.
851
+ expect(mockModelsModule.generateContentStream).toHaveBeenCalledTimes(1);
852
+ // 6. Unblock and fully consume the first stream to completion.
853
+ continueFirstStream();
854
+ await firstStreamIterator.next(); // Consume the rest of the stream
855
+ await firstStreamIterator.next(); // Finish the iterator
856
+ // 7. Now that the first stream is done, await the second promise to get its generator.
857
+ const secondStream = await secondStreamPromise;
858
+ // 8. Start consuming the second stream, which triggers its internal API call.
859
+ const secondStreamIterator = secondStream[Symbol.asyncIterator]();
860
+ await secondStreamIterator.next();
861
+ // 9. The second API call should now have been made.
862
+ expect(mockModelsModule.generateContentStream).toHaveBeenCalledTimes(2);
863
+ // 10. FIX: Fully consume the second stream to ensure recordHistory is called.
864
+ await secondStreamIterator.next(); // This finishes the iterator.
865
+ // 11. Final check on history.
866
+ const history = chat.getHistory();
867
+ expect(history.length).toBe(4);
868
+ const turn4 = history[3];
869
+ if (!turn4?.parts?.[0] || !('text' in turn4.parts[0])) {
870
+ throw new Error('Test setup error: Fourth turn is not a valid text part.');
871
+ }
872
+ expect(turn4.parts[0].text).toBe('second response');
873
+ });
423
874
  });
424
875
  //# sourceMappingURL=geminiChat.test.js.map