@google/gemini-cli-core 0.0.3-preview.4

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 (669) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +310 -0
  3. package/dist/.last_build +0 -0
  4. package/dist/google-gemini-cli-core-0.3.0-preview.3.tgz +0 -0
  5. package/dist/index.d.ts +12 -0
  6. package/dist/index.js +13 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/src/__mocks__/fs/promises.d.ts +11 -0
  9. package/dist/src/__mocks__/fs/promises.js +17 -0
  10. package/dist/src/__mocks__/fs/promises.js.map +1 -0
  11. package/dist/src/code_assist/codeAssist.d.ts +10 -0
  12. package/dist/src/code_assist/codeAssist.js +19 -0
  13. package/dist/src/code_assist/codeAssist.js.map +1 -0
  14. package/dist/src/code_assist/converter.d.ts +72 -0
  15. package/dist/src/code_assist/converter.js +159 -0
  16. package/dist/src/code_assist/converter.js.map +1 -0
  17. package/dist/src/code_assist/converter.test.d.ts +6 -0
  18. package/dist/src/code_assist/converter.test.js +362 -0
  19. package/dist/src/code_assist/converter.test.js.map +1 -0
  20. package/dist/src/code_assist/oauth2.d.ts +22 -0
  21. package/dist/src/code_assist/oauth2.js +353 -0
  22. package/dist/src/code_assist/oauth2.js.map +1 -0
  23. package/dist/src/code_assist/oauth2.test.d.ts +6 -0
  24. package/dist/src/code_assist/oauth2.test.js +427 -0
  25. package/dist/src/code_assist/oauth2.test.js.map +1 -0
  26. package/dist/src/code_assist/server.d.ts +37 -0
  27. package/dist/src/code_assist/server.js +125 -0
  28. package/dist/src/code_assist/server.js.map +1 -0
  29. package/dist/src/code_assist/server.test.d.ts +6 -0
  30. package/dist/src/code_assist/server.test.js +134 -0
  31. package/dist/src/code_assist/server.test.js.map +1 -0
  32. package/dist/src/code_assist/setup.d.ts +20 -0
  33. package/dist/src/code_assist/setup.js +101 -0
  34. package/dist/src/code_assist/setup.js.map +1 -0
  35. package/dist/src/code_assist/setup.test.d.ts +6 -0
  36. package/dist/src/code_assist/setup.test.js +171 -0
  37. package/dist/src/code_assist/setup.test.js.map +1 -0
  38. package/dist/src/code_assist/types.d.ts +148 -0
  39. package/dist/src/code_assist/types.js +46 -0
  40. package/dist/src/code_assist/types.js.map +1 -0
  41. package/dist/src/config/config.d.ts +318 -0
  42. package/dist/src/config/config.js +633 -0
  43. package/dist/src/config/config.js.map +1 -0
  44. package/dist/src/config/config.test.d.ts +6 -0
  45. package/dist/src/config/config.test.js +585 -0
  46. package/dist/src/config/config.test.js.map +1 -0
  47. package/dist/src/config/flashFallback.test.d.ts +6 -0
  48. package/dist/src/config/flashFallback.test.js +87 -0
  49. package/dist/src/config/flashFallback.test.js.map +1 -0
  50. package/dist/src/config/models.d.ts +9 -0
  51. package/dist/src/config/models.js +10 -0
  52. package/dist/src/config/models.js.map +1 -0
  53. package/dist/src/config/storage.d.ts +32 -0
  54. package/dist/src/config/storage.js +90 -0
  55. package/dist/src/config/storage.js.map +1 -0
  56. package/dist/src/config/storage.test.d.ts +6 -0
  57. package/dist/src/config/storage.test.js +43 -0
  58. package/dist/src/config/storage.test.js.map +1 -0
  59. package/dist/src/core/client.d.ts +65 -0
  60. package/dist/src/core/client.js +689 -0
  61. package/dist/src/core/client.js.map +1 -0
  62. package/dist/src/core/client.test.d.ts +6 -0
  63. package/dist/src/core/client.test.js +1857 -0
  64. package/dist/src/core/client.test.js.map +1 -0
  65. package/dist/src/core/contentGenerator.d.ts +33 -0
  66. package/dist/src/core/contentGenerator.js +80 -0
  67. package/dist/src/core/contentGenerator.js.map +1 -0
  68. package/dist/src/core/contentGenerator.test.d.ts +6 -0
  69. package/dist/src/core/contentGenerator.test.js +124 -0
  70. package/dist/src/core/contentGenerator.test.js.map +1 -0
  71. package/dist/src/core/coreToolScheduler.d.ts +126 -0
  72. package/dist/src/core/coreToolScheduler.js +605 -0
  73. package/dist/src/core/coreToolScheduler.js.map +1 -0
  74. package/dist/src/core/coreToolScheduler.test.d.ts +6 -0
  75. package/dist/src/core/coreToolScheduler.test.js +923 -0
  76. package/dist/src/core/coreToolScheduler.test.js.map +1 -0
  77. package/dist/src/core/geminiChat.d.ts +122 -0
  78. package/dist/src/core/geminiChat.js +547 -0
  79. package/dist/src/core/geminiChat.js.map +1 -0
  80. package/dist/src/core/geminiChat.test.d.ts +6 -0
  81. package/dist/src/core/geminiChat.test.js +875 -0
  82. package/dist/src/core/geminiChat.test.js.map +1 -0
  83. package/dist/src/core/geminiRequest.d.ts +13 -0
  84. package/dist/src/core/geminiRequest.js +11 -0
  85. package/dist/src/core/geminiRequest.js.map +1 -0
  86. package/dist/src/core/logger.d.ts +60 -0
  87. package/dist/src/core/logger.js +360 -0
  88. package/dist/src/core/logger.js.map +1 -0
  89. package/dist/src/core/logger.test.d.ts +6 -0
  90. package/dist/src/core/logger.test.js +534 -0
  91. package/dist/src/core/logger.test.js.map +1 -0
  92. package/dist/src/core/loggingContentGenerator.d.ts +25 -0
  93. package/dist/src/core/loggingContentGenerator.js +97 -0
  94. package/dist/src/core/loggingContentGenerator.js.map +1 -0
  95. package/dist/src/core/nonInteractiveToolExecutor.d.ts +10 -0
  96. package/dist/src/core/nonInteractiveToolExecutor.js +24 -0
  97. package/dist/src/core/nonInteractiveToolExecutor.js.map +1 -0
  98. package/dist/src/core/nonInteractiveToolExecutor.test.d.ts +6 -0
  99. package/dist/src/core/nonInteractiveToolExecutor.test.js +236 -0
  100. package/dist/src/core/nonInteractiveToolExecutor.test.js.map +1 -0
  101. package/dist/src/core/prompts.d.ts +12 -0
  102. package/dist/src/core/prompts.js +359 -0
  103. package/dist/src/core/prompts.js.map +1 -0
  104. package/dist/src/core/prompts.test.d.ts +6 -0
  105. package/dist/src/core/prompts.test.js +214 -0
  106. package/dist/src/core/prompts.test.js.map +1 -0
  107. package/dist/src/core/subagent.d.ts +236 -0
  108. package/dist/src/core/subagent.js +485 -0
  109. package/dist/src/core/subagent.js.map +1 -0
  110. package/dist/src/core/subagent.test.d.ts +6 -0
  111. package/dist/src/core/subagent.test.js +520 -0
  112. package/dist/src/core/subagent.test.js.map +1 -0
  113. package/dist/src/core/tokenLimits.d.ts +10 -0
  114. package/dist/src/core/tokenLimits.js +28 -0
  115. package/dist/src/core/tokenLimits.js.map +1 -0
  116. package/dist/src/core/turn.d.ts +125 -0
  117. package/dist/src/core/turn.js +154 -0
  118. package/dist/src/core/turn.js.map +1 -0
  119. package/dist/src/core/turn.test.d.ts +6 -0
  120. package/dist/src/core/turn.test.js +388 -0
  121. package/dist/src/core/turn.test.js.map +1 -0
  122. package/dist/src/generated/git-commit.d.ts +7 -0
  123. package/dist/src/generated/git-commit.js +10 -0
  124. package/dist/src/generated/git-commit.js.map +1 -0
  125. package/dist/src/ide/constants.d.ts +6 -0
  126. package/dist/src/ide/constants.js +7 -0
  127. package/dist/src/ide/constants.js.map +1 -0
  128. package/dist/src/ide/detect-ide.d.ts +25 -0
  129. package/dist/src/ide/detect-ide.js +104 -0
  130. package/dist/src/ide/detect-ide.js.map +1 -0
  131. package/dist/src/ide/detect-ide.test.d.ts +6 -0
  132. package/dist/src/ide/detect-ide.test.js +109 -0
  133. package/dist/src/ide/detect-ide.test.js.map +1 -0
  134. package/dist/src/ide/ide-client.d.ts +67 -0
  135. package/dist/src/ide/ide-client.js +418 -0
  136. package/dist/src/ide/ide-client.js.map +1 -0
  137. package/dist/src/ide/ide-client.test.d.ts +6 -0
  138. package/dist/src/ide/ide-client.test.js +155 -0
  139. package/dist/src/ide/ide-client.test.js.map +1 -0
  140. package/dist/src/ide/ide-installer.d.ts +14 -0
  141. package/dist/src/ide/ide-installer.js +107 -0
  142. package/dist/src/ide/ide-installer.js.map +1 -0
  143. package/dist/src/ide/ide-installer.test.d.ts +6 -0
  144. package/dist/src/ide/ide-installer.test.js +113 -0
  145. package/dist/src/ide/ide-installer.test.js.map +1 -0
  146. package/dist/src/ide/ideContext.d.ts +374 -0
  147. package/dist/src/ide/ideContext.js +147 -0
  148. package/dist/src/ide/ideContext.js.map +1 -0
  149. package/dist/src/ide/ideContext.test.d.ts +6 -0
  150. package/dist/src/ide/ideContext.test.js +265 -0
  151. package/dist/src/ide/ideContext.test.js.map +1 -0
  152. package/dist/src/ide/process-utils.d.ts +22 -0
  153. package/dist/src/ide/process-utils.js +153 -0
  154. package/dist/src/ide/process-utils.js.map +1 -0
  155. package/dist/src/ide/process-utils.test.d.ts +6 -0
  156. package/dist/src/ide/process-utils.test.js +72 -0
  157. package/dist/src/ide/process-utils.test.js.map +1 -0
  158. package/dist/src/index.d.ts +81 -0
  159. package/dist/src/index.js +90 -0
  160. package/dist/src/index.js.map +1 -0
  161. package/dist/src/index.test.d.ts +6 -0
  162. package/dist/src/index.test.js +12 -0
  163. package/dist/src/index.test.js.map +1 -0
  164. package/dist/src/mcp/google-auth-provider.d.ts +23 -0
  165. package/dist/src/mcp/google-auth-provider.js +72 -0
  166. package/dist/src/mcp/google-auth-provider.js.map +1 -0
  167. package/dist/src/mcp/google-auth-provider.test.d.ts +6 -0
  168. package/dist/src/mcp/google-auth-provider.test.js +89 -0
  169. package/dist/src/mcp/google-auth-provider.test.js.map +1 -0
  170. package/dist/src/mcp/oauth-provider.d.ts +146 -0
  171. package/dist/src/mcp/oauth-provider.js +601 -0
  172. package/dist/src/mcp/oauth-provider.js.map +1 -0
  173. package/dist/src/mcp/oauth-provider.test.d.ts +6 -0
  174. package/dist/src/mcp/oauth-provider.test.js +672 -0
  175. package/dist/src/mcp/oauth-provider.test.js.map +1 -0
  176. package/dist/src/mcp/oauth-token-storage.d.ts +61 -0
  177. package/dist/src/mcp/oauth-token-storage.js +148 -0
  178. package/dist/src/mcp/oauth-token-storage.js.map +1 -0
  179. package/dist/src/mcp/oauth-token-storage.test.d.ts +6 -0
  180. package/dist/src/mcp/oauth-token-storage.test.js +206 -0
  181. package/dist/src/mcp/oauth-token-storage.test.js.map +1 -0
  182. package/dist/src/mcp/oauth-utils.d.ts +119 -0
  183. package/dist/src/mcp/oauth-utils.js +235 -0
  184. package/dist/src/mcp/oauth-utils.js.map +1 -0
  185. package/dist/src/mcp/oauth-utils.test.d.ts +6 -0
  186. package/dist/src/mcp/oauth-utils.test.js +199 -0
  187. package/dist/src/mcp/oauth-utils.test.js.map +1 -0
  188. package/dist/src/mcp/token-storage/base-token-storage.d.ts +19 -0
  189. package/dist/src/mcp/token-storage/base-token-storage.js +36 -0
  190. package/dist/src/mcp/token-storage/base-token-storage.js.map +1 -0
  191. package/dist/src/mcp/token-storage/base-token-storage.test.d.ts +6 -0
  192. package/dist/src/mcp/token-storage/base-token-storage.test.js +160 -0
  193. package/dist/src/mcp/token-storage/base-token-storage.test.js.map +1 -0
  194. package/dist/src/mcp/token-storage/types.d.ts +34 -0
  195. package/dist/src/mcp/token-storage/types.js +7 -0
  196. package/dist/src/mcp/token-storage/types.js.map +1 -0
  197. package/dist/src/mocks/msw.d.ts +6 -0
  198. package/dist/src/mocks/msw.js +8 -0
  199. package/dist/src/mocks/msw.js.map +1 -0
  200. package/dist/src/prompts/mcp-prompts.d.ts +8 -0
  201. package/dist/src/prompts/mcp-prompts.js +13 -0
  202. package/dist/src/prompts/mcp-prompts.js.map +1 -0
  203. package/dist/src/prompts/prompt-registry.d.ts +34 -0
  204. package/dist/src/prompts/prompt-registry.js +63 -0
  205. package/dist/src/prompts/prompt-registry.js.map +1 -0
  206. package/dist/src/services/chatRecordingService.d.ts +150 -0
  207. package/dist/src/services/chatRecordingService.js +321 -0
  208. package/dist/src/services/chatRecordingService.js.map +1 -0
  209. package/dist/src/services/chatRecordingService.test.d.ts +6 -0
  210. package/dist/src/services/chatRecordingService.test.js +290 -0
  211. package/dist/src/services/chatRecordingService.test.js.map +1 -0
  212. package/dist/src/services/fileDiscoveryService.d.ts +35 -0
  213. package/dist/src/services/fileDiscoveryService.js +91 -0
  214. package/dist/src/services/fileDiscoveryService.js.map +1 -0
  215. package/dist/src/services/fileDiscoveryService.test.d.ts +6 -0
  216. package/dist/src/services/fileDiscoveryService.test.js +143 -0
  217. package/dist/src/services/fileDiscoveryService.test.js.map +1 -0
  218. package/dist/src/services/fileSystemService.d.ts +31 -0
  219. package/dist/src/services/fileSystemService.js +18 -0
  220. package/dist/src/services/fileSystemService.js.map +1 -0
  221. package/dist/src/services/fileSystemService.test.d.ts +6 -0
  222. package/dist/src/services/fileSystemService.test.js +41 -0
  223. package/dist/src/services/fileSystemService.test.js.map +1 -0
  224. package/dist/src/services/gitService.d.ts +23 -0
  225. package/dist/src/services/gitService.js +110 -0
  226. package/dist/src/services/gitService.js.map +1 -0
  227. package/dist/src/services/gitService.test.d.ts +6 -0
  228. package/dist/src/services/gitService.test.js +212 -0
  229. package/dist/src/services/gitService.test.js.map +1 -0
  230. package/dist/src/services/loopDetectionService.d.ts +98 -0
  231. package/dist/src/services/loopDetectionService.js +363 -0
  232. package/dist/src/services/loopDetectionService.js.map +1 -0
  233. package/dist/src/services/loopDetectionService.test.d.ts +6 -0
  234. package/dist/src/services/loopDetectionService.test.js +558 -0
  235. package/dist/src/services/loopDetectionService.test.js.map +1 -0
  236. package/dist/src/services/shellExecutionService.d.ts +68 -0
  237. package/dist/src/services/shellExecutionService.js +332 -0
  238. package/dist/src/services/shellExecutionService.js.map +1 -0
  239. package/dist/src/services/shellExecutionService.test.d.ts +6 -0
  240. package/dist/src/services/shellExecutionService.test.js +517 -0
  241. package/dist/src/services/shellExecutionService.test.js.map +1 -0
  242. package/dist/src/telemetry/clearcut-logger/clearcut-logger.d.ts +121 -0
  243. package/dist/src/telemetry/clearcut-logger/clearcut-logger.js +773 -0
  244. package/dist/src/telemetry/clearcut-logger/clearcut-logger.js.map +1 -0
  245. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.d.ts +17 -0
  246. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.js +407 -0
  247. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.js.map +1 -0
  248. package/dist/src/telemetry/clearcut-logger/event-metadata-key.d.ts +90 -0
  249. package/dist/src/telemetry/clearcut-logger/event-metadata-key.js +229 -0
  250. package/dist/src/telemetry/clearcut-logger/event-metadata-key.js.map +1 -0
  251. package/dist/src/telemetry/constants.d.ts +32 -0
  252. package/dist/src/telemetry/constants.js +33 -0
  253. package/dist/src/telemetry/constants.js.map +1 -0
  254. package/dist/src/telemetry/file-exporters.d.ts +29 -0
  255. package/dist/src/telemetry/file-exporters.js +62 -0
  256. package/dist/src/telemetry/file-exporters.js.map +1 -0
  257. package/dist/src/telemetry/index.d.ts +21 -0
  258. package/dist/src/telemetry/index.js +21 -0
  259. package/dist/src/telemetry/index.js.map +1 -0
  260. package/dist/src/telemetry/integration.test.circular.d.ts +6 -0
  261. package/dist/src/telemetry/integration.test.circular.js +54 -0
  262. package/dist/src/telemetry/integration.test.circular.js.map +1 -0
  263. package/dist/src/telemetry/loggers.d.ts +26 -0
  264. package/dist/src/telemetry/loggers.js +404 -0
  265. package/dist/src/telemetry/loggers.js.map +1 -0
  266. package/dist/src/telemetry/loggers.test.circular.d.ts +6 -0
  267. package/dist/src/telemetry/loggers.test.circular.js +107 -0
  268. package/dist/src/telemetry/loggers.test.circular.js.map +1 -0
  269. package/dist/src/telemetry/loggers.test.d.ts +6 -0
  270. package/dist/src/telemetry/loggers.test.js +658 -0
  271. package/dist/src/telemetry/loggers.test.js.map +1 -0
  272. package/dist/src/telemetry/metrics.d.ts +36 -0
  273. package/dist/src/telemetry/metrics.js +208 -0
  274. package/dist/src/telemetry/metrics.js.map +1 -0
  275. package/dist/src/telemetry/metrics.test.d.ts +6 -0
  276. package/dist/src/telemetry/metrics.test.js +242 -0
  277. package/dist/src/telemetry/metrics.test.js.map +1 -0
  278. package/dist/src/telemetry/sdk.d.ts +9 -0
  279. package/dist/src/telemetry/sdk.js +163 -0
  280. package/dist/src/telemetry/sdk.js.map +1 -0
  281. package/dist/src/telemetry/sdk.test.d.ts +6 -0
  282. package/dist/src/telemetry/sdk.test.js +82 -0
  283. package/dist/src/telemetry/sdk.test.js.map +1 -0
  284. package/dist/src/telemetry/telemetry-utils.d.ts +6 -0
  285. package/dist/src/telemetry/telemetry-utils.js +14 -0
  286. package/dist/src/telemetry/telemetry-utils.js.map +1 -0
  287. package/dist/src/telemetry/telemetry-utils.test.d.ts +6 -0
  288. package/dist/src/telemetry/telemetry-utils.test.js +40 -0
  289. package/dist/src/telemetry/telemetry-utils.test.js.map +1 -0
  290. package/dist/src/telemetry/telemetry.test.d.ts +6 -0
  291. package/dist/src/telemetry/telemetry.test.js +50 -0
  292. package/dist/src/telemetry/telemetry.test.js.map +1 -0
  293. package/dist/src/telemetry/tool-call-decision.d.ts +13 -0
  294. package/dist/src/telemetry/tool-call-decision.js +29 -0
  295. package/dist/src/telemetry/tool-call-decision.js.map +1 -0
  296. package/dist/src/telemetry/types.d.ts +220 -0
  297. package/dist/src/telemetry/types.js +383 -0
  298. package/dist/src/telemetry/types.js.map +1 -0
  299. package/dist/src/telemetry/uiTelemetry.d.ts +75 -0
  300. package/dist/src/telemetry/uiTelemetry.js +153 -0
  301. package/dist/src/telemetry/uiTelemetry.js.map +1 -0
  302. package/dist/src/telemetry/uiTelemetry.test.d.ts +6 -0
  303. package/dist/src/telemetry/uiTelemetry.test.js +558 -0
  304. package/dist/src/telemetry/uiTelemetry.test.js.map +1 -0
  305. package/dist/src/test-utils/config.d.ts +17 -0
  306. package/dist/src/test-utils/config.js +32 -0
  307. package/dist/src/test-utils/config.js.map +1 -0
  308. package/dist/src/test-utils/mockWorkspaceContext.d.ts +13 -0
  309. package/dist/src/test-utils/mockWorkspaceContext.js +24 -0
  310. package/dist/src/test-utils/mockWorkspaceContext.js.map +1 -0
  311. package/dist/src/test-utils/tools.d.ts +45 -0
  312. package/dist/src/test-utils/tools.js +105 -0
  313. package/dist/src/test-utils/tools.js.map +1 -0
  314. package/dist/src/tools/diffOptions.d.ts +9 -0
  315. package/dist/src/tools/diffOptions.js +38 -0
  316. package/dist/src/tools/diffOptions.js.map +1 -0
  317. package/dist/src/tools/diffOptions.test.d.ts +6 -0
  318. package/dist/src/tools/diffOptions.test.js +119 -0
  319. package/dist/src/tools/diffOptions.test.js.map +1 -0
  320. package/dist/src/tools/edit.d.ts +56 -0
  321. package/dist/src/tools/edit.js +423 -0
  322. package/dist/src/tools/edit.js.map +1 -0
  323. package/dist/src/tools/edit.test.d.ts +6 -0
  324. package/dist/src/tools/edit.test.js +713 -0
  325. package/dist/src/tools/edit.test.js.map +1 -0
  326. package/dist/src/tools/glob.d.ts +52 -0
  327. package/dist/src/tools/glob.js +236 -0
  328. package/dist/src/tools/glob.js.map +1 -0
  329. package/dist/src/tools/glob.test.d.ts +6 -0
  330. package/dist/src/tools/glob.test.js +375 -0
  331. package/dist/src/tools/glob.test.js.map +1 -0
  332. package/dist/src/tools/grep.d.ts +47 -0
  333. package/dist/src/tools/grep.js +517 -0
  334. package/dist/src/tools/grep.js.map +1 -0
  335. package/dist/src/tools/grep.test.d.ts +6 -0
  336. package/dist/src/tools/grep.test.js +295 -0
  337. package/dist/src/tools/grep.test.js.map +1 -0
  338. package/dist/src/tools/ls.d.ts +68 -0
  339. package/dist/src/tools/ls.js +227 -0
  340. package/dist/src/tools/ls.js.map +1 -0
  341. package/dist/src/tools/ls.test.d.ts +6 -0
  342. package/dist/src/tools/ls.test.js +389 -0
  343. package/dist/src/tools/ls.test.js.map +1 -0
  344. package/dist/src/tools/mcp-client-manager.d.ts +38 -0
  345. package/dist/src/tools/mcp-client-manager.js +74 -0
  346. package/dist/src/tools/mcp-client-manager.js.map +1 -0
  347. package/dist/src/tools/mcp-client-manager.test.d.ts +6 -0
  348. package/dist/src/tools/mcp-client-manager.test.js +39 -0
  349. package/dist/src/tools/mcp-client-manager.test.js.map +1 -0
  350. package/dist/src/tools/mcp-client.d.ts +199 -0
  351. package/dist/src/tools/mcp-client.js +995 -0
  352. package/dist/src/tools/mcp-client.js.map +1 -0
  353. package/dist/src/tools/mcp-client.test.d.ts +6 -0
  354. package/dist/src/tools/mcp-client.test.js +454 -0
  355. package/dist/src/tools/mcp-client.test.js.map +1 -0
  356. package/dist/src/tools/mcp-tool.d.ts +23 -0
  357. package/dist/src/tools/mcp-tool.js +240 -0
  358. package/dist/src/tools/mcp-tool.js.map +1 -0
  359. package/dist/src/tools/mcp-tool.test.d.ts +6 -0
  360. package/dist/src/tools/mcp-tool.test.js +576 -0
  361. package/dist/src/tools/mcp-tool.test.js.map +1 -0
  362. package/dist/src/tools/memoryTool.d.ts +40 -0
  363. package/dist/src/tools/memoryTool.js +296 -0
  364. package/dist/src/tools/memoryTool.js.map +1 -0
  365. package/dist/src/tools/memoryTool.test.d.ts +6 -0
  366. package/dist/src/tools/memoryTool.test.js +298 -0
  367. package/dist/src/tools/memoryTool.test.js.map +1 -0
  368. package/dist/src/tools/modifiable-tool.d.ts +32 -0
  369. package/dist/src/tools/modifiable-tool.js +88 -0
  370. package/dist/src/tools/modifiable-tool.js.map +1 -0
  371. package/dist/src/tools/modifiable-tool.test.d.ts +6 -0
  372. package/dist/src/tools/modifiable-tool.test.js +193 -0
  373. package/dist/src/tools/modifiable-tool.test.js.map +1 -0
  374. package/dist/src/tools/read-file.d.ts +35 -0
  375. package/dist/src/tools/read-file.js +127 -0
  376. package/dist/src/tools/read-file.js.map +1 -0
  377. package/dist/src/tools/read-file.test.d.ts +6 -0
  378. package/dist/src/tools/read-file.test.js +311 -0
  379. package/dist/src/tools/read-file.test.js.map +1 -0
  380. package/dist/src/tools/read-many-files.d.ts +60 -0
  381. package/dist/src/tools/read-many-files.js +414 -0
  382. package/dist/src/tools/read-many-files.js.map +1 -0
  383. package/dist/src/tools/read-many-files.test.d.ts +6 -0
  384. package/dist/src/tools/read-many-files.test.js +565 -0
  385. package/dist/src/tools/read-many-files.test.js.map +1 -0
  386. package/dist/src/tools/ripGrep.d.ts +47 -0
  387. package/dist/src/tools/ripGrep.js +368 -0
  388. package/dist/src/tools/ripGrep.js.map +1 -0
  389. package/dist/src/tools/ripGrep.test.d.ts +6 -0
  390. package/dist/src/tools/ripGrep.test.js +874 -0
  391. package/dist/src/tools/ripGrep.test.js.map +1 -0
  392. package/dist/src/tools/shell.d.ts +22 -0
  393. package/dist/src/tools/shell.js +320 -0
  394. package/dist/src/tools/shell.js.map +1 -0
  395. package/dist/src/tools/shell.test.d.ts +6 -0
  396. package/dist/src/tools/shell.test.js +336 -0
  397. package/dist/src/tools/shell.test.js.map +1 -0
  398. package/dist/src/tools/tool-error.d.ts +43 -0
  399. package/dist/src/tools/tool-error.js +58 -0
  400. package/dist/src/tools/tool-error.js.map +1 -0
  401. package/dist/src/tools/tool-registry.d.ts +86 -0
  402. package/dist/src/tools/tool-registry.js +369 -0
  403. package/dist/src/tools/tool-registry.js.map +1 -0
  404. package/dist/src/tools/tool-registry.test.d.ts +6 -0
  405. package/dist/src/tools/tool-registry.test.js +332 -0
  406. package/dist/src/tools/tool-registry.test.js.map +1 -0
  407. package/dist/src/tools/tools.d.ts +274 -0
  408. package/dist/src/tools/tools.js +250 -0
  409. package/dist/src/tools/tools.js.map +1 -0
  410. package/dist/src/tools/tools.test.d.ts +6 -0
  411. package/dist/src/tools/tools.test.js +205 -0
  412. package/dist/src/tools/tools.test.js.map +1 -0
  413. package/dist/src/tools/web-fetch.d.ts +27 -0
  414. package/dist/src/tools/web-fetch.js +243 -0
  415. package/dist/src/tools/web-fetch.js.map +1 -0
  416. package/dist/src/tools/web-fetch.test.d.ts +6 -0
  417. package/dist/src/tools/web-fetch.test.js +114 -0
  418. package/dist/src/tools/web-fetch.test.js.map +1 -0
  419. package/dist/src/tools/web-search.d.ts +49 -0
  420. package/dist/src/tools/web-search.js +137 -0
  421. package/dist/src/tools/web-search.js.map +1 -0
  422. package/dist/src/tools/web-search.test.d.ts +6 -0
  423. package/dist/src/tools/web-search.test.js +207 -0
  424. package/dist/src/tools/web-search.test.js.map +1 -0
  425. package/dist/src/tools/write-file.d.ts +52 -0
  426. package/dist/src/tools/write-file.js +314 -0
  427. package/dist/src/tools/write-file.js.map +1 -0
  428. package/dist/src/tools/write-file.test.d.ts +6 -0
  429. package/dist/src/tools/write-file.test.js +531 -0
  430. package/dist/src/tools/write-file.test.js.map +1 -0
  431. package/dist/src/utils/LruCache.d.ts +13 -0
  432. package/dist/src/utils/LruCache.js +38 -0
  433. package/dist/src/utils/LruCache.js.map +1 -0
  434. package/dist/src/utils/bfsFileSearch.d.ts +24 -0
  435. package/dist/src/utils/bfsFileSearch.js +89 -0
  436. package/dist/src/utils/bfsFileSearch.js.map +1 -0
  437. package/dist/src/utils/bfsFileSearch.test.d.ts +6 -0
  438. package/dist/src/utils/bfsFileSearch.test.js +163 -0
  439. package/dist/src/utils/bfsFileSearch.test.js.map +1 -0
  440. package/dist/src/utils/browser.d.ts +13 -0
  441. package/dist/src/utils/browser.js +50 -0
  442. package/dist/src/utils/browser.js.map +1 -0
  443. package/dist/src/utils/editCorrector.d.ts +53 -0
  444. package/dist/src/utils/editCorrector.js +545 -0
  445. package/dist/src/utils/editCorrector.js.map +1 -0
  446. package/dist/src/utils/editCorrector.test.d.ts +6 -0
  447. package/dist/src/utils/editCorrector.test.js +564 -0
  448. package/dist/src/utils/editCorrector.test.js.map +1 -0
  449. package/dist/src/utils/editor.d.ts +28 -0
  450. package/dist/src/utils/editor.js +186 -0
  451. package/dist/src/utils/editor.js.map +1 -0
  452. package/dist/src/utils/editor.test.d.ts +6 -0
  453. package/dist/src/utils/editor.test.js +445 -0
  454. package/dist/src/utils/editor.test.js.map +1 -0
  455. package/dist/src/utils/environmentContext.d.ts +21 -0
  456. package/dist/src/utils/environmentContext.js +90 -0
  457. package/dist/src/utils/environmentContext.js.map +1 -0
  458. package/dist/src/utils/environmentContext.test.d.ts +6 -0
  459. package/dist/src/utils/environmentContext.test.js +140 -0
  460. package/dist/src/utils/environmentContext.test.js.map +1 -0
  461. package/dist/src/utils/errorParsing.d.ts +8 -0
  462. package/dist/src/utils/errorParsing.js +93 -0
  463. package/dist/src/utils/errorParsing.js.map +1 -0
  464. package/dist/src/utils/errorParsing.test.d.ts +6 -0
  465. package/dist/src/utils/errorParsing.test.js +172 -0
  466. package/dist/src/utils/errorParsing.test.js.map +1 -0
  467. package/dist/src/utils/errorReporting.d.ts +14 -0
  468. package/dist/src/utils/errorReporting.js +88 -0
  469. package/dist/src/utils/errorReporting.js.map +1 -0
  470. package/dist/src/utils/errorReporting.test.d.ts +6 -0
  471. package/dist/src/utils/errorReporting.test.js +130 -0
  472. package/dist/src/utils/errorReporting.test.js.map +1 -0
  473. package/dist/src/utils/errors.d.ts +33 -0
  474. package/dist/src/utils/errors.js +86 -0
  475. package/dist/src/utils/errors.js.map +1 -0
  476. package/dist/src/utils/fetch.d.ts +11 -0
  477. package/dist/src/utils/fetch.js +51 -0
  478. package/dist/src/utils/fetch.js.map +1 -0
  479. package/dist/src/utils/fileUtils.d.ts +52 -0
  480. package/dist/src/utils/fileUtils.js +283 -0
  481. package/dist/src/utils/fileUtils.js.map +1 -0
  482. package/dist/src/utils/fileUtils.test.d.ts +6 -0
  483. package/dist/src/utils/fileUtils.test.js +364 -0
  484. package/dist/src/utils/fileUtils.test.js.map +1 -0
  485. package/dist/src/utils/filesearch/crawlCache.d.ts +25 -0
  486. package/dist/src/utils/filesearch/crawlCache.js +57 -0
  487. package/dist/src/utils/filesearch/crawlCache.js.map +1 -0
  488. package/dist/src/utils/filesearch/crawlCache.test.d.ts +6 -0
  489. package/dist/src/utils/filesearch/crawlCache.test.js +103 -0
  490. package/dist/src/utils/filesearch/crawlCache.test.js.map +1 -0
  491. package/dist/src/utils/filesearch/crawler.d.ts +15 -0
  492. package/dist/src/utils/filesearch/crawler.js +50 -0
  493. package/dist/src/utils/filesearch/crawler.js.map +1 -0
  494. package/dist/src/utils/filesearch/crawler.test.d.ts +6 -0
  495. package/dist/src/utils/filesearch/crawler.test.js +468 -0
  496. package/dist/src/utils/filesearch/crawler.test.js.map +1 -0
  497. package/dist/src/utils/filesearch/fileSearch.d.ts +38 -0
  498. package/dist/src/utils/filesearch/fileSearch.js +191 -0
  499. package/dist/src/utils/filesearch/fileSearch.js.map +1 -0
  500. package/dist/src/utils/filesearch/fileSearch.test.d.ts +6 -0
  501. package/dist/src/utils/filesearch/fileSearch.test.js +642 -0
  502. package/dist/src/utils/filesearch/fileSearch.test.js.map +1 -0
  503. package/dist/src/utils/filesearch/ignore.d.ts +42 -0
  504. package/dist/src/utils/filesearch/ignore.js +106 -0
  505. package/dist/src/utils/filesearch/ignore.js.map +1 -0
  506. package/dist/src/utils/filesearch/ignore.test.d.ts +6 -0
  507. package/dist/src/utils/filesearch/ignore.test.js +144 -0
  508. package/dist/src/utils/filesearch/ignore.test.js.map +1 -0
  509. package/dist/src/utils/filesearch/result-cache.d.ts +33 -0
  510. package/dist/src/utils/filesearch/result-cache.js +59 -0
  511. package/dist/src/utils/filesearch/result-cache.js.map +1 -0
  512. package/dist/src/utils/filesearch/result-cache.test.d.ts +6 -0
  513. package/dist/src/utils/filesearch/result-cache.test.js +46 -0
  514. package/dist/src/utils/filesearch/result-cache.test.js.map +1 -0
  515. package/dist/src/utils/flashFallback.integration.test.d.ts +6 -0
  516. package/dist/src/utils/flashFallback.integration.test.js +118 -0
  517. package/dist/src/utils/flashFallback.integration.test.js.map +1 -0
  518. package/dist/src/utils/formatters.d.ts +6 -0
  519. package/dist/src/utils/formatters.js +16 -0
  520. package/dist/src/utils/formatters.js.map +1 -0
  521. package/dist/src/utils/generateContentResponseUtilities.d.ts +13 -0
  522. package/dist/src/utils/generateContentResponseUtilities.js +80 -0
  523. package/dist/src/utils/generateContentResponseUtilities.js.map +1 -0
  524. package/dist/src/utils/generateContentResponseUtilities.test.d.ts +6 -0
  525. package/dist/src/utils/generateContentResponseUtilities.test.js +235 -0
  526. package/dist/src/utils/generateContentResponseUtilities.test.js.map +1 -0
  527. package/dist/src/utils/getFolderStructure.d.ts +31 -0
  528. package/dist/src/utils/getFolderStructure.js +246 -0
  529. package/dist/src/utils/getFolderStructure.js.map +1 -0
  530. package/dist/src/utils/getFolderStructure.test.d.ts +6 -0
  531. package/dist/src/utils/getFolderStructure.test.js +282 -0
  532. package/dist/src/utils/getFolderStructure.test.js.map +1 -0
  533. package/dist/src/utils/getPty.d.ts +19 -0
  534. package/dist/src/utils/getPty.js +23 -0
  535. package/dist/src/utils/getPty.js.map +1 -0
  536. package/dist/src/utils/gitIgnoreParser.d.ts +20 -0
  537. package/dist/src/utils/gitIgnoreParser.js +61 -0
  538. package/dist/src/utils/gitIgnoreParser.js.map +1 -0
  539. package/dist/src/utils/gitIgnoreParser.test.d.ts +6 -0
  540. package/dist/src/utils/gitIgnoreParser.test.js +154 -0
  541. package/dist/src/utils/gitIgnoreParser.test.js.map +1 -0
  542. package/dist/src/utils/gitUtils.d.ts +17 -0
  543. package/dist/src/utils/gitUtils.js +61 -0
  544. package/dist/src/utils/gitUtils.js.map +1 -0
  545. package/dist/src/utils/ignorePatterns.d.ts +103 -0
  546. package/dist/src/utils/ignorePatterns.js +220 -0
  547. package/dist/src/utils/ignorePatterns.js.map +1 -0
  548. package/dist/src/utils/ignorePatterns.test.d.ts +6 -0
  549. package/dist/src/utils/ignorePatterns.test.js +250 -0
  550. package/dist/src/utils/ignorePatterns.test.js.map +1 -0
  551. package/dist/src/utils/installationManager.d.ts +16 -0
  552. package/dist/src/utils/installationManager.js +50 -0
  553. package/dist/src/utils/installationManager.js.map +1 -0
  554. package/dist/src/utils/installationManager.test.d.ts +6 -0
  555. package/dist/src/utils/installationManager.test.js +83 -0
  556. package/dist/src/utils/installationManager.test.js.map +1 -0
  557. package/dist/src/utils/language-detection.d.ts +6 -0
  558. package/dist/src/utils/language-detection.js +101 -0
  559. package/dist/src/utils/language-detection.js.map +1 -0
  560. package/dist/src/utils/memoryDiscovery.d.ts +15 -0
  561. package/dist/src/utils/memoryDiscovery.js +253 -0
  562. package/dist/src/utils/memoryDiscovery.js.map +1 -0
  563. package/dist/src/utils/memoryDiscovery.test.d.ts +6 -0
  564. package/dist/src/utils/memoryDiscovery.test.js +219 -0
  565. package/dist/src/utils/memoryDiscovery.test.js.map +1 -0
  566. package/dist/src/utils/memoryImportProcessor.d.ts +42 -0
  567. package/dist/src/utils/memoryImportProcessor.js +296 -0
  568. package/dist/src/utils/memoryImportProcessor.js.map +1 -0
  569. package/dist/src/utils/memoryImportProcessor.test.d.ts +6 -0
  570. package/dist/src/utils/memoryImportProcessor.test.js +573 -0
  571. package/dist/src/utils/memoryImportProcessor.test.js.map +1 -0
  572. package/dist/src/utils/messageInspectors.d.ts +8 -0
  573. package/dist/src/utils/messageInspectors.js +16 -0
  574. package/dist/src/utils/messageInspectors.js.map +1 -0
  575. package/dist/src/utils/nextSpeakerChecker.d.ts +12 -0
  576. package/dist/src/utils/nextSpeakerChecker.js +91 -0
  577. package/dist/src/utils/nextSpeakerChecker.js.map +1 -0
  578. package/dist/src/utils/nextSpeakerChecker.test.d.ts +6 -0
  579. package/dist/src/utils/nextSpeakerChecker.test.js +168 -0
  580. package/dist/src/utils/nextSpeakerChecker.test.js.map +1 -0
  581. package/dist/src/utils/partUtils.d.ts +35 -0
  582. package/dist/src/utils/partUtils.js +133 -0
  583. package/dist/src/utils/partUtils.js.map +1 -0
  584. package/dist/src/utils/partUtils.test.d.ts +6 -0
  585. package/dist/src/utils/partUtils.test.js +241 -0
  586. package/dist/src/utils/partUtils.test.js.map +1 -0
  587. package/dist/src/utils/pathReader.d.ts +17 -0
  588. package/dist/src/utils/pathReader.js +92 -0
  589. package/dist/src/utils/pathReader.js.map +1 -0
  590. package/dist/src/utils/pathReader.test.d.ts +6 -0
  591. package/dist/src/utils/pathReader.test.js +363 -0
  592. package/dist/src/utils/pathReader.test.js.map +1 -0
  593. package/dist/src/utils/paths.d.ts +58 -0
  594. package/dist/src/utils/paths.js +159 -0
  595. package/dist/src/utils/paths.js.map +1 -0
  596. package/dist/src/utils/paths.test.d.ts +6 -0
  597. package/dist/src/utils/paths.test.js +225 -0
  598. package/dist/src/utils/paths.test.js.map +1 -0
  599. package/dist/src/utils/quotaErrorDetection.d.ts +18 -0
  600. package/dist/src/utils/quotaErrorDetection.js +65 -0
  601. package/dist/src/utils/quotaErrorDetection.js.map +1 -0
  602. package/dist/src/utils/retry.d.ts +30 -0
  603. package/dist/src/utils/retry.js +276 -0
  604. package/dist/src/utils/retry.js.map +1 -0
  605. package/dist/src/utils/retry.test.d.ts +6 -0
  606. package/dist/src/utils/retry.test.js +325 -0
  607. package/dist/src/utils/retry.test.js.map +1 -0
  608. package/dist/src/utils/safeJsonStringify.d.ts +13 -0
  609. package/dist/src/utils/safeJsonStringify.js +25 -0
  610. package/dist/src/utils/safeJsonStringify.js.map +1 -0
  611. package/dist/src/utils/safeJsonStringify.test.d.ts +6 -0
  612. package/dist/src/utils/safeJsonStringify.test.js +61 -0
  613. package/dist/src/utils/safeJsonStringify.test.js.map +1 -0
  614. package/dist/src/utils/schemaValidator.d.ts +15 -0
  615. package/dist/src/utils/schemaValidator.js +38 -0
  616. package/dist/src/utils/schemaValidator.js.map +1 -0
  617. package/dist/src/utils/secure-browser-launcher.d.ts +23 -0
  618. package/dist/src/utils/secure-browser-launcher.js +165 -0
  619. package/dist/src/utils/secure-browser-launcher.js.map +1 -0
  620. package/dist/src/utils/secure-browser-launcher.test.d.ts +6 -0
  621. package/dist/src/utils/secure-browser-launcher.test.js +149 -0
  622. package/dist/src/utils/secure-browser-launcher.test.js.map +1 -0
  623. package/dist/src/utils/session.d.ts +6 -0
  624. package/dist/src/utils/session.js +8 -0
  625. package/dist/src/utils/session.js.map +1 -0
  626. package/dist/src/utils/shell-utils.d.ts +117 -0
  627. package/dist/src/utils/shell-utils.js +370 -0
  628. package/dist/src/utils/shell-utils.js.map +1 -0
  629. package/dist/src/utils/shell-utils.test.d.ts +6 -0
  630. package/dist/src/utils/shell-utils.test.js +332 -0
  631. package/dist/src/utils/shell-utils.test.js.map +1 -0
  632. package/dist/src/utils/summarizer.d.ts +25 -0
  633. package/dist/src/utils/summarizer.js +51 -0
  634. package/dist/src/utils/summarizer.js.map +1 -0
  635. package/dist/src/utils/summarizer.test.d.ts +6 -0
  636. package/dist/src/utils/summarizer.test.js +131 -0
  637. package/dist/src/utils/summarizer.test.js.map +1 -0
  638. package/dist/src/utils/systemEncoding.d.ts +40 -0
  639. package/dist/src/utils/systemEncoding.js +149 -0
  640. package/dist/src/utils/systemEncoding.js.map +1 -0
  641. package/dist/src/utils/systemEncoding.test.d.ts +6 -0
  642. package/dist/src/utils/systemEncoding.test.js +368 -0
  643. package/dist/src/utils/systemEncoding.test.js.map +1 -0
  644. package/dist/src/utils/testUtils.d.ts +29 -0
  645. package/dist/src/utils/testUtils.js +70 -0
  646. package/dist/src/utils/testUtils.js.map +1 -0
  647. package/dist/src/utils/textUtils.d.ts +13 -0
  648. package/dist/src/utils/textUtils.js +28 -0
  649. package/dist/src/utils/textUtils.js.map +1 -0
  650. package/dist/src/utils/tool-utils.d.ts +19 -0
  651. package/dist/src/utils/tool-utils.js +58 -0
  652. package/dist/src/utils/tool-utils.js.map +1 -0
  653. package/dist/src/utils/tool-utils.test.d.ts +6 -0
  654. package/dist/src/utils/tool-utils.test.js +61 -0
  655. package/dist/src/utils/tool-utils.test.js.map +1 -0
  656. package/dist/src/utils/userAccountManager.d.ts +20 -0
  657. package/dist/src/utils/userAccountManager.js +114 -0
  658. package/dist/src/utils/userAccountManager.js.map +1 -0
  659. package/dist/src/utils/userAccountManager.test.d.ts +6 -0
  660. package/dist/src/utils/userAccountManager.test.js +223 -0
  661. package/dist/src/utils/userAccountManager.test.js.map +1 -0
  662. package/dist/src/utils/workspaceContext.d.ts +66 -0
  663. package/dist/src/utils/workspaceContext.js +171 -0
  664. package/dist/src/utils/workspaceContext.js.map +1 -0
  665. package/dist/src/utils/workspaceContext.test.d.ts +6 -0
  666. package/dist/src/utils/workspaceContext.test.js +318 -0
  667. package/dist/src/utils/workspaceContext.test.js.map +1 -0
  668. package/dist/tsconfig.tsbuildinfo +1 -0
  669. package/package.json +85 -0
@@ -0,0 +1,1857 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { describe, it, expect, vi, beforeEach, afterEach, } from 'vitest';
7
+ import { GoogleGenAI } from '@google/genai';
8
+ import { findIndexAfterFraction, GeminiClient } from './client.js';
9
+ import { AuthType, } from './contentGenerator.js';
10
+ import {} from './geminiChat.js';
11
+ import { Config } from '../config/config.js';
12
+ import { CompressionStatus, GeminiEventType, Turn, } from './turn.js';
13
+ import { getCoreSystemPrompt } from './prompts.js';
14
+ import { DEFAULT_GEMINI_FLASH_MODEL } from '../config/models.js';
15
+ import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
16
+ import { setSimulate429 } from '../utils/testUtils.js';
17
+ import { tokenLimit } from './tokenLimits.js';
18
+ import { ideContext } from '../ide/ideContext.js';
19
+ import { ClearcutLogger } from '../telemetry/clearcut-logger/clearcut-logger.js';
20
+ // --- Mocks ---
21
+ const mockChatCreateFn = vi.fn();
22
+ const mockGenerateContentFn = vi.fn();
23
+ const mockEmbedContentFn = vi.fn();
24
+ const mockTurnRunFn = vi.fn();
25
+ vi.mock('@google/genai');
26
+ vi.mock('./turn', async (importOriginal) => {
27
+ const actual = await importOriginal();
28
+ // Define a mock class that has the same shape as the real Turn
29
+ class MockTurn {
30
+ pendingToolCalls = [];
31
+ // The run method is a property that holds our mock function
32
+ run = mockTurnRunFn;
33
+ constructor() {
34
+ // The constructor can be empty or do some mock setup
35
+ }
36
+ }
37
+ // Export the mock class as 'Turn'
38
+ return {
39
+ ...actual,
40
+ Turn: MockTurn,
41
+ };
42
+ });
43
+ vi.mock('../config/config.js');
44
+ vi.mock('./prompts');
45
+ vi.mock('../utils/getFolderStructure', () => ({
46
+ getFolderStructure: vi.fn().mockResolvedValue('Mock Folder Structure'),
47
+ }));
48
+ vi.mock('../utils/errorReporting', () => ({ reportError: vi.fn() }));
49
+ vi.mock('../utils/nextSpeakerChecker', () => ({
50
+ checkNextSpeaker: vi.fn().mockResolvedValue(null),
51
+ }));
52
+ vi.mock('../utils/generateContentResponseUtilities', () => ({
53
+ getResponseText: (result) => result.candidates?.[0]?.content?.parts?.map((part) => part.text).join('') ||
54
+ undefined,
55
+ }));
56
+ vi.mock('../telemetry/index.js', () => ({
57
+ logApiRequest: vi.fn(),
58
+ logApiResponse: vi.fn(),
59
+ logApiError: vi.fn(),
60
+ }));
61
+ vi.mock('../ide/ideContext.js');
62
+ /**
63
+ * Array.fromAsync ponyfill, which will be available in es 2024.
64
+ *
65
+ * Buffers an async generator into an array and returns the result.
66
+ */
67
+ async function fromAsync(promise) {
68
+ const results = [];
69
+ for await (const result of promise) {
70
+ results.push(result);
71
+ }
72
+ return results;
73
+ }
74
+ describe('findIndexAfterFraction', () => {
75
+ const history = [
76
+ { role: 'user', parts: [{ text: 'This is the first message.' }] }, // JSON length: 66
77
+ { role: 'model', parts: [{ text: 'This is the second message.' }] }, // JSON length: 68
78
+ { role: 'user', parts: [{ text: 'This is the third message.' }] }, // JSON length: 66
79
+ { role: 'model', parts: [{ text: 'This is the fourth message.' }] }, // JSON length: 68
80
+ { role: 'user', parts: [{ text: 'This is the fifth message.' }] }, // JSON length: 65
81
+ ];
82
+ // Total length: 333
83
+ it('should throw an error for non-positive numbers', () => {
84
+ expect(() => findIndexAfterFraction(history, 0)).toThrow('Fraction must be between 0 and 1');
85
+ });
86
+ it('should throw an error for a fraction greater than or equal to 1', () => {
87
+ expect(() => findIndexAfterFraction(history, 1)).toThrow('Fraction must be between 0 and 1');
88
+ });
89
+ it('should handle a fraction in the middle', () => {
90
+ // 333 * 0.5 = 166.5
91
+ // 0: 66
92
+ // 1: 66 + 68 = 134
93
+ // 2: 134 + 66 = 200
94
+ // 200 >= 166.5, so index is 2
95
+ expect(findIndexAfterFraction(history, 0.5)).toBe(2);
96
+ });
97
+ it('should handle a fraction that results in the last index', () => {
98
+ // 333 * 0.9 = 299.7
99
+ // ...
100
+ // 3: 200 + 68 = 268
101
+ // 4: 268 + 65 = 333
102
+ // 333 >= 299.7, so index is 4
103
+ expect(findIndexAfterFraction(history, 0.9)).toBe(4);
104
+ });
105
+ it('should handle an empty history', () => {
106
+ expect(findIndexAfterFraction([], 0.5)).toBe(0);
107
+ });
108
+ it('should handle a history with only one item', () => {
109
+ expect(findIndexAfterFraction(history.slice(0, 1), 0.5)).toBe(0);
110
+ });
111
+ it('should handle history with weird parts', () => {
112
+ const historyWithEmptyParts = [
113
+ { role: 'user', parts: [{ text: 'Message 1' }] },
114
+ { role: 'model', parts: [{ fileData: { fileUri: 'derp' } }] },
115
+ { role: 'user', parts: [{ text: 'Message 2' }] },
116
+ ];
117
+ expect(findIndexAfterFraction(historyWithEmptyParts, 0.5)).toBe(1);
118
+ });
119
+ });
120
+ describe('Gemini Client (client.ts)', () => {
121
+ let client;
122
+ beforeEach(async () => {
123
+ vi.resetAllMocks();
124
+ // Disable 429 simulation for tests
125
+ setSimulate429(false);
126
+ // Set up the mock for GoogleGenAI constructor and its methods
127
+ const MockedGoogleGenAI = vi.mocked(GoogleGenAI);
128
+ MockedGoogleGenAI.mockImplementation(() => {
129
+ const mock = {
130
+ chats: { create: mockChatCreateFn },
131
+ models: {
132
+ generateContent: mockGenerateContentFn,
133
+ embedContent: mockEmbedContentFn,
134
+ },
135
+ };
136
+ return mock;
137
+ });
138
+ mockChatCreateFn.mockResolvedValue({});
139
+ mockGenerateContentFn.mockResolvedValue({
140
+ candidates: [
141
+ {
142
+ content: {
143
+ parts: [{ text: '{"key": "value"}' }],
144
+ },
145
+ },
146
+ ],
147
+ });
148
+ // Because the GeminiClient constructor kicks off an async process (startChat)
149
+ // that depends on a fully-formed Config object, we need to mock the
150
+ // entire implementation of Config for these tests.
151
+ const mockToolRegistry = {
152
+ getFunctionDeclarations: vi.fn().mockReturnValue([]),
153
+ getTool: vi.fn().mockReturnValue(null),
154
+ };
155
+ const fileService = new FileDiscoveryService('/test/dir');
156
+ const contentGeneratorConfig = {
157
+ model: 'test-model',
158
+ apiKey: 'test-key',
159
+ vertexai: false,
160
+ authType: AuthType.USE_GEMINI,
161
+ };
162
+ const mockConfigObject = {
163
+ getContentGeneratorConfig: vi
164
+ .fn()
165
+ .mockReturnValue(contentGeneratorConfig),
166
+ getToolRegistry: vi.fn().mockReturnValue(mockToolRegistry),
167
+ getModel: vi.fn().mockReturnValue('test-model'),
168
+ getEmbeddingModel: vi.fn().mockReturnValue('test-embedding-model'),
169
+ getApiKey: vi.fn().mockReturnValue('test-key'),
170
+ getVertexAI: vi.fn().mockReturnValue(false),
171
+ getUserAgent: vi.fn().mockReturnValue('test-agent'),
172
+ getUserMemory: vi.fn().mockReturnValue(''),
173
+ getFullContext: vi.fn().mockReturnValue(false),
174
+ getSessionId: vi.fn().mockReturnValue('test-session-id'),
175
+ getProxy: vi.fn().mockReturnValue(undefined),
176
+ getWorkingDir: vi.fn().mockReturnValue('/test/dir'),
177
+ getFileService: vi.fn().mockReturnValue(fileService),
178
+ getMaxSessionTurns: vi.fn().mockReturnValue(0),
179
+ getQuotaErrorOccurred: vi.fn().mockReturnValue(false),
180
+ setQuotaErrorOccurred: vi.fn(),
181
+ getNoBrowser: vi.fn().mockReturnValue(false),
182
+ getUsageStatisticsEnabled: vi.fn().mockReturnValue(true),
183
+ getIdeModeFeature: vi.fn().mockReturnValue(false),
184
+ getIdeMode: vi.fn().mockReturnValue(true),
185
+ getDebugMode: vi.fn().mockReturnValue(false),
186
+ getWorkspaceContext: vi.fn().mockReturnValue({
187
+ getDirectories: vi.fn().mockReturnValue(['/test/dir']),
188
+ }),
189
+ getGeminiClient: vi.fn(),
190
+ setFallbackMode: vi.fn(),
191
+ getChatCompression: vi.fn().mockReturnValue(undefined),
192
+ getSkipNextSpeakerCheck: vi.fn().mockReturnValue(false),
193
+ };
194
+ const MockedConfig = vi.mocked(Config, true);
195
+ MockedConfig.mockImplementation(() => mockConfigObject);
196
+ // We can instantiate the client here since Config is mocked
197
+ // and the constructor will use the mocked GoogleGenAI
198
+ client = new GeminiClient(new Config({ sessionId: 'test-session-id' }));
199
+ mockConfigObject.getGeminiClient.mockReturnValue(client);
200
+ await client.initialize(contentGeneratorConfig);
201
+ });
202
+ afterEach(() => {
203
+ vi.restoreAllMocks();
204
+ });
205
+ // NOTE: The following tests for startChat were removed due to persistent issues with
206
+ // the @google/genai mock. Specifically, the mockChatCreateFn (representing instance.chats.create)
207
+ // was not being detected as called by the GeminiClient instance.
208
+ // This likely points to a subtle issue in how the GoogleGenerativeAI class constructor
209
+ // and its instance methods are mocked and then used by the class under test.
210
+ // For future debugging, ensure that the `this.client` in `GeminiClient` (which is an
211
+ // instance of the mocked GoogleGenerativeAI) correctly has its `chats.create` method
212
+ // pointing to `mockChatCreateFn`.
213
+ // it('startChat should call getCoreSystemPrompt with userMemory and pass to chats.create', async () => { ... });
214
+ // it('startChat should call getCoreSystemPrompt with empty string if userMemory is empty', async () => { ... });
215
+ // NOTE: The following tests for generateJson were removed due to persistent issues with
216
+ // the @google/genai mock, similar to the startChat tests. The mockGenerateContentFn
217
+ // (representing instance.models.generateContent) was not being detected as called, or the mock
218
+ // was not preventing an actual API call (leading to API key errors).
219
+ // For future debugging, ensure `this.client.models.generateContent` in `GeminiClient` correctly
220
+ // uses the `mockGenerateContentFn`.
221
+ // it('generateJson should call getCoreSystemPrompt with userMemory and pass to generateContent', async () => { ... });
222
+ // it('generateJson should call getCoreSystemPrompt with empty string if userMemory is empty', async () => { ... });
223
+ describe('generateEmbedding', () => {
224
+ const texts = ['hello world', 'goodbye world'];
225
+ const testEmbeddingModel = 'test-embedding-model';
226
+ it('should call embedContent with correct parameters and return embeddings', async () => {
227
+ const mockEmbeddings = [
228
+ [0.1, 0.2, 0.3],
229
+ [0.4, 0.5, 0.6],
230
+ ];
231
+ const mockResponse = {
232
+ embeddings: [
233
+ { values: mockEmbeddings[0] },
234
+ { values: mockEmbeddings[1] },
235
+ ],
236
+ };
237
+ mockEmbedContentFn.mockResolvedValue(mockResponse);
238
+ const result = await client.generateEmbedding(texts);
239
+ expect(mockEmbedContentFn).toHaveBeenCalledTimes(1);
240
+ expect(mockEmbedContentFn).toHaveBeenCalledWith({
241
+ model: testEmbeddingModel,
242
+ contents: texts,
243
+ });
244
+ expect(result).toEqual(mockEmbeddings);
245
+ });
246
+ it('should return an empty array if an empty array is passed', async () => {
247
+ const result = await client.generateEmbedding([]);
248
+ expect(result).toEqual([]);
249
+ expect(mockEmbedContentFn).not.toHaveBeenCalled();
250
+ });
251
+ it('should throw an error if API response has no embeddings array', async () => {
252
+ mockEmbedContentFn.mockResolvedValue({}); // No `embeddings` key
253
+ await expect(client.generateEmbedding(texts)).rejects.toThrow('No embeddings found in API response.');
254
+ });
255
+ it('should throw an error if API response has an empty embeddings array', async () => {
256
+ const mockResponse = {
257
+ embeddings: [],
258
+ };
259
+ mockEmbedContentFn.mockResolvedValue(mockResponse);
260
+ await expect(client.generateEmbedding(texts)).rejects.toThrow('No embeddings found in API response.');
261
+ });
262
+ it('should throw an error if API returns a mismatched number of embeddings', async () => {
263
+ const mockResponse = {
264
+ embeddings: [{ values: [1, 2, 3] }], // Only one for two texts
265
+ };
266
+ mockEmbedContentFn.mockResolvedValue(mockResponse);
267
+ await expect(client.generateEmbedding(texts)).rejects.toThrow('API returned a mismatched number of embeddings. Expected 2, got 1.');
268
+ });
269
+ it('should throw an error if any embedding has nullish values', async () => {
270
+ const mockResponse = {
271
+ embeddings: [{ values: [1, 2, 3] }, { values: undefined }], // Second one is bad
272
+ };
273
+ mockEmbedContentFn.mockResolvedValue(mockResponse);
274
+ await expect(client.generateEmbedding(texts)).rejects.toThrow('API returned an empty embedding for input text at index 1: "goodbye world"');
275
+ });
276
+ it('should throw an error if any embedding has an empty values array', async () => {
277
+ const mockResponse = {
278
+ embeddings: [{ values: [] }, { values: [1, 2, 3] }], // First one is bad
279
+ };
280
+ mockEmbedContentFn.mockResolvedValue(mockResponse);
281
+ await expect(client.generateEmbedding(texts)).rejects.toThrow('API returned an empty embedding for input text at index 0: "hello world"');
282
+ });
283
+ it('should propagate errors from the API call', async () => {
284
+ const apiError = new Error('API Failure');
285
+ mockEmbedContentFn.mockRejectedValue(apiError);
286
+ await expect(client.generateEmbedding(texts)).rejects.toThrow('API Failure');
287
+ });
288
+ });
289
+ describe('generateJson', () => {
290
+ it('should call generateContent with the correct parameters', async () => {
291
+ const contents = [{ role: 'user', parts: [{ text: 'hello' }] }];
292
+ const schema = { type: 'string' };
293
+ const abortSignal = new AbortController().signal;
294
+ // Mock countTokens
295
+ const mockGenerator = {
296
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 1 }),
297
+ generateContent: mockGenerateContentFn,
298
+ };
299
+ client['contentGenerator'] = mockGenerator;
300
+ await client.generateJson(contents, schema, abortSignal);
301
+ expect(mockGenerateContentFn).toHaveBeenCalledWith({
302
+ model: 'test-model', // Should use current model from config
303
+ config: {
304
+ abortSignal,
305
+ systemInstruction: getCoreSystemPrompt(''),
306
+ temperature: 0,
307
+ topP: 1,
308
+ responseJsonSchema: schema,
309
+ responseMimeType: 'application/json',
310
+ },
311
+ contents,
312
+ }, 'test-session-id');
313
+ });
314
+ it('should allow overriding model and config', async () => {
315
+ const contents = [
316
+ { role: 'user', parts: [{ text: 'hello' }] },
317
+ ];
318
+ const schema = { type: 'string' };
319
+ const abortSignal = new AbortController().signal;
320
+ const customModel = 'custom-json-model';
321
+ const customConfig = { temperature: 0.9, topK: 20 };
322
+ const mockGenerator = {
323
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 1 }),
324
+ generateContent: mockGenerateContentFn,
325
+ };
326
+ client['contentGenerator'] = mockGenerator;
327
+ await client.generateJson(contents, schema, abortSignal, customModel, customConfig);
328
+ expect(mockGenerateContentFn).toHaveBeenCalledWith({
329
+ model: customModel,
330
+ config: {
331
+ abortSignal,
332
+ systemInstruction: getCoreSystemPrompt(''),
333
+ temperature: 0.9,
334
+ topP: 1, // from default
335
+ topK: 20,
336
+ responseJsonSchema: schema,
337
+ responseMimeType: 'application/json',
338
+ },
339
+ contents,
340
+ }, 'test-session-id');
341
+ });
342
+ });
343
+ describe('addHistory', () => {
344
+ it('should call chat.addHistory with the provided content', async () => {
345
+ const mockChat = {
346
+ addHistory: vi.fn(),
347
+ };
348
+ client['chat'] = mockChat;
349
+ const newContent = {
350
+ role: 'user',
351
+ parts: [{ text: 'New history item' }],
352
+ };
353
+ await client.addHistory(newContent);
354
+ expect(mockChat.addHistory).toHaveBeenCalledWith(newContent);
355
+ });
356
+ });
357
+ describe('resetChat', () => {
358
+ it('should create a new chat session, clearing the old history', async () => {
359
+ // 1. Get the initial chat instance and add some history.
360
+ const initialChat = client.getChat();
361
+ const initialHistory = await client.getHistory();
362
+ await client.addHistory({
363
+ role: 'user',
364
+ parts: [{ text: 'some old message' }],
365
+ });
366
+ const historyWithOldMessage = await client.getHistory();
367
+ expect(historyWithOldMessage.length).toBeGreaterThan(initialHistory.length);
368
+ // 2. Call resetChat.
369
+ await client.resetChat();
370
+ // 3. Get the new chat instance and its history.
371
+ const newChat = client.getChat();
372
+ const newHistory = await client.getHistory();
373
+ // 4. Assert that the chat instance is new and the history is reset.
374
+ expect(newChat).not.toBe(initialChat);
375
+ expect(newHistory.length).toBe(initialHistory.length);
376
+ expect(JSON.stringify(newHistory)).not.toContain('some old message');
377
+ });
378
+ });
379
+ describe('tryCompressChat', () => {
380
+ const mockCountTokens = vi.fn();
381
+ const mockSendMessage = vi.fn();
382
+ const mockGetHistory = vi.fn();
383
+ beforeEach(() => {
384
+ vi.mock('./tokenLimits', () => ({
385
+ tokenLimit: vi.fn(),
386
+ }));
387
+ client['contentGenerator'] = {
388
+ countTokens: mockCountTokens,
389
+ };
390
+ client['chat'] = {
391
+ getHistory: mockGetHistory,
392
+ addHistory: vi.fn(),
393
+ setHistory: vi.fn(),
394
+ sendMessage: mockSendMessage,
395
+ };
396
+ });
397
+ function setup({ chatHistory = [
398
+ { role: 'user', parts: [{ text: 'Long conversation' }] },
399
+ { role: 'model', parts: [{ text: 'Long response' }] },
400
+ ], } = {}) {
401
+ const mockChat = {
402
+ getHistory: vi.fn().mockReturnValue(chatHistory),
403
+ setHistory: vi.fn(),
404
+ sendMessage: vi.fn().mockResolvedValue({ text: 'Summary' }),
405
+ };
406
+ const mockCountTokens = vi
407
+ .fn()
408
+ .mockResolvedValueOnce({ totalTokens: 1000 })
409
+ .mockResolvedValueOnce({ totalTokens: 5000 });
410
+ const mockGenerator = {
411
+ countTokens: mockCountTokens,
412
+ };
413
+ client['chat'] = mockChat;
414
+ client['contentGenerator'] = mockGenerator;
415
+ client['startChat'] = vi.fn().mockResolvedValue({ ...mockChat });
416
+ return { client, mockChat, mockGenerator };
417
+ }
418
+ describe('when compression inflates the token count', () => {
419
+ it('uses the truncated history for compression');
420
+ it('allows compression to be forced/manual after a failure', async () => {
421
+ const { client, mockGenerator } = setup();
422
+ mockGenerator.countTokens?.mockResolvedValue({
423
+ totalTokens: 1000,
424
+ });
425
+ await client.tryCompressChat('prompt-id-4'); // Fails
426
+ const result = await client.tryCompressChat('prompt-id-4', true);
427
+ expect(result).toEqual({
428
+ compressionStatus: CompressionStatus.COMPRESSED,
429
+ newTokenCount: 1000,
430
+ originalTokenCount: 1000,
431
+ });
432
+ });
433
+ it('yields the result even if the compression inflated the tokens', async () => {
434
+ const { client } = setup();
435
+ const result = await client.tryCompressChat('prompt-id-4', true);
436
+ expect(result).toEqual({
437
+ compressionStatus: CompressionStatus.COMPRESSION_FAILED_INFLATED_TOKEN_COUNT,
438
+ newTokenCount: 5000,
439
+ originalTokenCount: 1000,
440
+ });
441
+ });
442
+ it('does not manipulate the source chat', async () => {
443
+ const { client, mockChat } = setup();
444
+ await client.tryCompressChat('prompt-id-4', true);
445
+ expect(client['chat']).toBe(mockChat); // a new chat session was not created
446
+ });
447
+ it('restores the history back to the original', async () => {
448
+ vi.mocked(tokenLimit).mockReturnValue(1000);
449
+ mockCountTokens.mockResolvedValue({
450
+ totalTokens: 999,
451
+ });
452
+ const originalHistory = [
453
+ { role: 'user', parts: [{ text: 'what is your wisdom?' }] },
454
+ { role: 'model', parts: [{ text: 'some wisdom' }] },
455
+ { role: 'user', parts: [{ text: 'ahh that is a good a wisdom' }] },
456
+ ];
457
+ const { client } = setup({
458
+ chatHistory: originalHistory,
459
+ });
460
+ const { compressionStatus } = await client.tryCompressChat('prompt-id-4');
461
+ expect(compressionStatus).toBe(CompressionStatus.COMPRESSION_FAILED_INFLATED_TOKEN_COUNT);
462
+ expect(client['chat']?.setHistory).toHaveBeenCalledWith(originalHistory);
463
+ });
464
+ it('will not attempt to compress context after a failure', async () => {
465
+ const { client, mockGenerator } = setup();
466
+ await client.tryCompressChat('prompt-id-4');
467
+ const result = await client.tryCompressChat('prompt-id-5');
468
+ // it counts tokens for {original, compressed} and then never again
469
+ expect(mockGenerator.countTokens).toHaveBeenCalledTimes(2);
470
+ expect(result).toEqual({
471
+ compressionStatus: CompressionStatus.NOOP,
472
+ newTokenCount: 0,
473
+ originalTokenCount: 0,
474
+ });
475
+ });
476
+ });
477
+ it('attempts to compress with a maxOutputTokens set to the original token count', async () => {
478
+ vi.mocked(tokenLimit).mockReturnValue(1000);
479
+ mockCountTokens.mockResolvedValue({
480
+ totalTokens: 999,
481
+ });
482
+ mockGetHistory.mockReturnValue([
483
+ { role: 'user', parts: [{ text: '...history...' }] },
484
+ ]);
485
+ // Mock the summary response from the chat
486
+ mockSendMessage.mockResolvedValue({
487
+ role: 'model',
488
+ parts: [{ text: 'This is a summary.' }],
489
+ });
490
+ await client.tryCompressChat('prompt-id-2', true);
491
+ expect(mockSendMessage).toHaveBeenCalledWith(expect.objectContaining({
492
+ config: expect.objectContaining({
493
+ maxOutputTokens: 999,
494
+ }),
495
+ }), 'prompt-id-2');
496
+ });
497
+ it('should not trigger summarization if token count is below threshold', async () => {
498
+ const MOCKED_TOKEN_LIMIT = 1000;
499
+ vi.mocked(tokenLimit).mockReturnValue(MOCKED_TOKEN_LIMIT);
500
+ mockGetHistory.mockReturnValue([
501
+ { role: 'user', parts: [{ text: '...history...' }] },
502
+ ]);
503
+ mockCountTokens.mockResolvedValue({
504
+ totalTokens: MOCKED_TOKEN_LIMIT * 0.699, // TOKEN_THRESHOLD_FOR_SUMMARIZATION = 0.7
505
+ });
506
+ const initialChat = client.getChat();
507
+ const result = await client.tryCompressChat('prompt-id-2');
508
+ const newChat = client.getChat();
509
+ expect(tokenLimit).toHaveBeenCalled();
510
+ expect(result).toEqual({
511
+ compressionStatus: CompressionStatus.NOOP,
512
+ newTokenCount: 699,
513
+ originalTokenCount: 699,
514
+ });
515
+ expect(newChat).toBe(initialChat);
516
+ });
517
+ it('logs a telemetry event when compressing', async () => {
518
+ vi.spyOn(ClearcutLogger.prototype, 'logChatCompressionEvent');
519
+ const MOCKED_TOKEN_LIMIT = 1000;
520
+ const MOCKED_CONTEXT_PERCENTAGE_THRESHOLD = 0.5;
521
+ vi.mocked(tokenLimit).mockReturnValue(MOCKED_TOKEN_LIMIT);
522
+ vi.spyOn(client['config'], 'getChatCompression').mockReturnValue({
523
+ contextPercentageThreshold: MOCKED_CONTEXT_PERCENTAGE_THRESHOLD,
524
+ });
525
+ mockGetHistory.mockReturnValue([
526
+ { role: 'user', parts: [{ text: '...history...' }] },
527
+ ]);
528
+ const originalTokenCount = MOCKED_TOKEN_LIMIT * MOCKED_CONTEXT_PERCENTAGE_THRESHOLD;
529
+ const newTokenCount = 100;
530
+ mockCountTokens
531
+ .mockResolvedValueOnce({ totalTokens: originalTokenCount }) // First call for the check
532
+ .mockResolvedValueOnce({ totalTokens: newTokenCount }); // Second call for the new history
533
+ // Mock the summary response from the chat
534
+ mockSendMessage.mockResolvedValue({
535
+ role: 'model',
536
+ parts: [{ text: 'This is a summary.' }],
537
+ });
538
+ await client.tryCompressChat('prompt-id-3');
539
+ expect(ClearcutLogger.prototype.logChatCompressionEvent).toHaveBeenCalledWith(expect.objectContaining({
540
+ tokens_before: originalTokenCount,
541
+ tokens_after: newTokenCount,
542
+ }));
543
+ });
544
+ it('should trigger summarization if token count is at threshold with contextPercentageThreshold setting', async () => {
545
+ const MOCKED_TOKEN_LIMIT = 1000;
546
+ const MOCKED_CONTEXT_PERCENTAGE_THRESHOLD = 0.5;
547
+ vi.mocked(tokenLimit).mockReturnValue(MOCKED_TOKEN_LIMIT);
548
+ vi.spyOn(client['config'], 'getChatCompression').mockReturnValue({
549
+ contextPercentageThreshold: MOCKED_CONTEXT_PERCENTAGE_THRESHOLD,
550
+ });
551
+ mockGetHistory.mockReturnValue([
552
+ { role: 'user', parts: [{ text: '...history...' }] },
553
+ ]);
554
+ const originalTokenCount = MOCKED_TOKEN_LIMIT * MOCKED_CONTEXT_PERCENTAGE_THRESHOLD;
555
+ const newTokenCount = 100;
556
+ mockCountTokens
557
+ .mockResolvedValueOnce({ totalTokens: originalTokenCount }) // First call for the check
558
+ .mockResolvedValueOnce({ totalTokens: newTokenCount }); // Second call for the new history
559
+ // Mock the summary response from the chat
560
+ mockSendMessage.mockResolvedValue({
561
+ role: 'model',
562
+ parts: [{ text: 'This is a summary.' }],
563
+ });
564
+ const initialChat = client.getChat();
565
+ const result = await client.tryCompressChat('prompt-id-3');
566
+ const newChat = client.getChat();
567
+ expect(tokenLimit).toHaveBeenCalled();
568
+ expect(mockSendMessage).toHaveBeenCalled();
569
+ // Assert that summarization happened and returned the correct stats
570
+ expect(result).toEqual({
571
+ compressionStatus: CompressionStatus.COMPRESSED,
572
+ originalTokenCount,
573
+ newTokenCount,
574
+ });
575
+ // Assert that the chat was reset
576
+ expect(newChat).not.toBe(initialChat);
577
+ });
578
+ it('should not compress across a function call response', async () => {
579
+ const MOCKED_TOKEN_LIMIT = 1000;
580
+ vi.mocked(tokenLimit).mockReturnValue(MOCKED_TOKEN_LIMIT);
581
+ mockGetHistory.mockReturnValue([
582
+ { role: 'user', parts: [{ text: '...history 1...' }] },
583
+ { role: 'model', parts: [{ text: '...history 2...' }] },
584
+ { role: 'user', parts: [{ text: '...history 3...' }] },
585
+ { role: 'model', parts: [{ text: '...history 4...' }] },
586
+ { role: 'user', parts: [{ text: '...history 5...' }] },
587
+ { role: 'model', parts: [{ text: '...history 6...' }] },
588
+ { role: 'user', parts: [{ text: '...history 7...' }] },
589
+ { role: 'model', parts: [{ text: '...history 8...' }] },
590
+ // Normally we would break here, but we have a function response.
591
+ {
592
+ role: 'user',
593
+ parts: [{ functionResponse: { name: '...history 8...' } }],
594
+ },
595
+ { role: 'model', parts: [{ text: '...history 10...' }] },
596
+ // Instead we will break here.
597
+ { role: 'user', parts: [{ text: '...history 10...' }] },
598
+ ]);
599
+ const originalTokenCount = 1000 * 0.7;
600
+ const newTokenCount = 100;
601
+ mockCountTokens
602
+ .mockResolvedValueOnce({ totalTokens: originalTokenCount }) // First call for the check
603
+ .mockResolvedValueOnce({ totalTokens: newTokenCount }); // Second call for the new history
604
+ // Mock the summary response from the chat
605
+ mockSendMessage.mockResolvedValue({
606
+ role: 'model',
607
+ parts: [{ text: 'This is a summary.' }],
608
+ });
609
+ const initialChat = client.getChat();
610
+ const result = await client.tryCompressChat('prompt-id-3');
611
+ const newChat = client.getChat();
612
+ expect(tokenLimit).toHaveBeenCalled();
613
+ expect(mockSendMessage).toHaveBeenCalled();
614
+ // Assert that summarization happened and returned the correct stats
615
+ expect(result).toEqual({
616
+ compressionStatus: CompressionStatus.COMPRESSED,
617
+ originalTokenCount,
618
+ newTokenCount,
619
+ });
620
+ // Assert that the chat was reset
621
+ expect(newChat).not.toBe(initialChat);
622
+ // 1. standard start context message
623
+ // 2. standard canned user start message
624
+ // 3. compressed summary message
625
+ // 4. standard canned user summary message
626
+ // 5. The last user message (not the last 3 because that would start with a function response)
627
+ expect(newChat.getHistory().length).toEqual(5);
628
+ });
629
+ it('should always trigger summarization when force is true, regardless of token count', async () => {
630
+ mockGetHistory.mockReturnValue([
631
+ { role: 'user', parts: [{ text: '...history...' }] },
632
+ ]);
633
+ const originalTokenCount = 10; // Well below threshold
634
+ const newTokenCount = 5;
635
+ mockCountTokens
636
+ .mockResolvedValueOnce({ totalTokens: originalTokenCount })
637
+ .mockResolvedValueOnce({ totalTokens: newTokenCount });
638
+ // Mock the summary response from the chat
639
+ mockSendMessage.mockResolvedValue({
640
+ role: 'model',
641
+ parts: [{ text: 'This is a summary.' }],
642
+ });
643
+ const initialChat = client.getChat();
644
+ const result = await client.tryCompressChat('prompt-id-1', true); // force = true
645
+ const newChat = client.getChat();
646
+ expect(mockSendMessage).toHaveBeenCalled();
647
+ expect(result).toEqual({
648
+ compressionStatus: CompressionStatus.COMPRESSED,
649
+ originalTokenCount,
650
+ newTokenCount,
651
+ });
652
+ // Assert that the chat was reset
653
+ expect(newChat).not.toBe(initialChat);
654
+ });
655
+ it('should use current model from config for token counting after sendMessage', async () => {
656
+ const initialModel = client['config'].getModel();
657
+ const mockCountTokens = vi
658
+ .fn()
659
+ .mockResolvedValueOnce({ totalTokens: 100000 })
660
+ .mockResolvedValueOnce({ totalTokens: 5000 });
661
+ const mockSendMessage = vi.fn().mockResolvedValue({ text: 'Summary' });
662
+ const mockChatHistory = [
663
+ { role: 'user', parts: [{ text: 'Long conversation' }] },
664
+ { role: 'model', parts: [{ text: 'Long response' }] },
665
+ ];
666
+ const mockChat = {
667
+ getHistory: vi.fn().mockReturnValue(mockChatHistory),
668
+ setHistory: vi.fn(),
669
+ sendMessage: mockSendMessage,
670
+ };
671
+ const mockGenerator = {
672
+ countTokens: mockCountTokens,
673
+ };
674
+ // mock the model has been changed between calls of `countTokens`
675
+ const firstCurrentModel = initialModel + '-changed-1';
676
+ const secondCurrentModel = initialModel + '-changed-2';
677
+ vi.spyOn(client['config'], 'getModel')
678
+ .mockReturnValueOnce(firstCurrentModel)
679
+ .mockReturnValueOnce(secondCurrentModel);
680
+ client['chat'] = mockChat;
681
+ client['contentGenerator'] = mockGenerator;
682
+ client['startChat'] = vi.fn().mockResolvedValue(mockChat);
683
+ const result = await client.tryCompressChat('prompt-id-4', true);
684
+ expect(mockCountTokens).toHaveBeenCalledTimes(2);
685
+ expect(mockCountTokens).toHaveBeenNthCalledWith(1, {
686
+ model: firstCurrentModel,
687
+ contents: mockChatHistory,
688
+ });
689
+ expect(mockCountTokens).toHaveBeenNthCalledWith(2, {
690
+ model: secondCurrentModel,
691
+ contents: expect.any(Array),
692
+ });
693
+ expect(result).toEqual({
694
+ compressionStatus: CompressionStatus.COMPRESSED,
695
+ originalTokenCount: 100000,
696
+ newTokenCount: 5000,
697
+ });
698
+ });
699
+ });
700
+ describe('sendMessageStream', () => {
701
+ it('emits a compression event when the context was automatically compressed', async () => {
702
+ // Arrange
703
+ const mockStream = (async function* () {
704
+ yield { type: 'content', value: 'Hello' };
705
+ })();
706
+ mockTurnRunFn.mockReturnValue(mockStream);
707
+ const mockChat = {
708
+ addHistory: vi.fn(),
709
+ getHistory: vi.fn().mockReturnValue([]),
710
+ };
711
+ client['chat'] = mockChat;
712
+ const mockGenerator = {
713
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
714
+ generateContent: mockGenerateContentFn,
715
+ };
716
+ client['contentGenerator'] = mockGenerator;
717
+ const compressionInfo = {
718
+ compressionStatus: CompressionStatus.COMPRESSED,
719
+ originalTokenCount: 1000,
720
+ newTokenCount: 500,
721
+ };
722
+ vi.spyOn(client, 'tryCompressChat').mockResolvedValueOnce(compressionInfo);
723
+ // Act
724
+ const stream = client.sendMessageStream([{ text: 'Hi' }], new AbortController().signal, 'prompt-id-1');
725
+ const events = await fromAsync(stream);
726
+ // Assert
727
+ expect(events).toContainEqual({
728
+ type: GeminiEventType.ChatCompressed,
729
+ value: compressionInfo,
730
+ });
731
+ });
732
+ it.each([
733
+ {
734
+ compressionStatus: CompressionStatus.COMPRESSION_FAILED_INFLATED_TOKEN_COUNT,
735
+ },
736
+ { compressionStatus: CompressionStatus.NOOP },
737
+ {
738
+ compressionStatus: CompressionStatus.COMPRESSION_FAILED_TOKEN_COUNT_ERROR,
739
+ },
740
+ ])('does not emit a compression event when the status is $compressionStatus', async ({ compressionStatus }) => {
741
+ // Arrange
742
+ const mockStream = (async function* () {
743
+ yield { type: 'content', value: 'Hello' };
744
+ })();
745
+ mockTurnRunFn.mockReturnValue(mockStream);
746
+ const mockChat = {
747
+ addHistory: vi.fn(),
748
+ getHistory: vi.fn().mockReturnValue([]),
749
+ };
750
+ client['chat'] = mockChat;
751
+ const mockGenerator = {
752
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
753
+ generateContent: mockGenerateContentFn,
754
+ };
755
+ client['contentGenerator'] = mockGenerator;
756
+ const compressionInfo = {
757
+ compressionStatus,
758
+ originalTokenCount: 1000,
759
+ newTokenCount: 500,
760
+ };
761
+ vi.spyOn(client, 'tryCompressChat').mockResolvedValueOnce(compressionInfo);
762
+ // Act
763
+ const stream = client.sendMessageStream([{ text: 'Hi' }], new AbortController().signal, 'prompt-id-1');
764
+ const events = await fromAsync(stream);
765
+ // Assert
766
+ expect(events).not.toContainEqual({
767
+ type: GeminiEventType.ChatCompressed,
768
+ value: expect.anything(),
769
+ });
770
+ });
771
+ it('should include editor context when ideMode is enabled', async () => {
772
+ // Arrange
773
+ vi.mocked(ideContext.getIdeContext).mockReturnValue({
774
+ workspaceState: {
775
+ openFiles: [
776
+ {
777
+ path: '/path/to/active/file.ts',
778
+ timestamp: Date.now(),
779
+ isActive: true,
780
+ selectedText: 'hello',
781
+ cursor: { line: 5, character: 10 },
782
+ },
783
+ {
784
+ path: '/path/to/recent/file1.ts',
785
+ timestamp: Date.now(),
786
+ },
787
+ {
788
+ path: '/path/to/recent/file2.ts',
789
+ timestamp: Date.now(),
790
+ },
791
+ ],
792
+ },
793
+ });
794
+ vi.spyOn(client['config'], 'getIdeMode').mockReturnValue(true);
795
+ const mockStream = (async function* () {
796
+ yield { type: 'content', value: 'Hello' };
797
+ })();
798
+ mockTurnRunFn.mockReturnValue(mockStream);
799
+ const mockChat = {
800
+ addHistory: vi.fn(),
801
+ getHistory: vi.fn().mockReturnValue([]),
802
+ };
803
+ client['chat'] = mockChat;
804
+ const mockGenerator = {
805
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
806
+ generateContent: mockGenerateContentFn,
807
+ };
808
+ client['contentGenerator'] = mockGenerator;
809
+ const initialRequest = [{ text: 'Hi' }];
810
+ // Act
811
+ const stream = client.sendMessageStream(initialRequest, new AbortController().signal, 'prompt-id-ide');
812
+ for await (const _ of stream) {
813
+ // consume stream
814
+ }
815
+ // Assert
816
+ expect(ideContext.getIdeContext).toHaveBeenCalled();
817
+ const expectedContext = `
818
+ Here is the user's editor context as a JSON object. This is for your information only.
819
+ \`\`\`json
820
+ ${JSON.stringify({
821
+ activeFile: {
822
+ path: '/path/to/active/file.ts',
823
+ cursor: {
824
+ line: 5,
825
+ character: 10,
826
+ },
827
+ selectedText: 'hello',
828
+ },
829
+ otherOpenFiles: ['/path/to/recent/file1.ts', '/path/to/recent/file2.ts'],
830
+ }, null, 2)}
831
+ \`\`\`
832
+ `.trim();
833
+ const expectedRequest = [{ text: expectedContext }];
834
+ expect(mockChat.addHistory).toHaveBeenCalledWith({
835
+ role: 'user',
836
+ parts: expectedRequest,
837
+ });
838
+ });
839
+ it('should not add context if ideMode is enabled but no open files', async () => {
840
+ // Arrange
841
+ vi.mocked(ideContext.getIdeContext).mockReturnValue({
842
+ workspaceState: {
843
+ openFiles: [],
844
+ },
845
+ });
846
+ vi.spyOn(client['config'], 'getIdeMode').mockReturnValue(true);
847
+ const mockStream = (async function* () {
848
+ yield { type: 'content', value: 'Hello' };
849
+ })();
850
+ mockTurnRunFn.mockReturnValue(mockStream);
851
+ const mockChat = {
852
+ addHistory: vi.fn(),
853
+ getHistory: vi.fn().mockReturnValue([]),
854
+ };
855
+ client['chat'] = mockChat;
856
+ const mockGenerator = {
857
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
858
+ generateContent: mockGenerateContentFn,
859
+ };
860
+ client['contentGenerator'] = mockGenerator;
861
+ const initialRequest = [{ text: 'Hi' }];
862
+ // Act
863
+ const stream = client.sendMessageStream(initialRequest, new AbortController().signal, 'prompt-id-ide');
864
+ for await (const _ of stream) {
865
+ // consume stream
866
+ }
867
+ // Assert
868
+ expect(ideContext.getIdeContext).toHaveBeenCalled();
869
+ expect(mockTurnRunFn).toHaveBeenCalledWith(initialRequest, expect.any(Object));
870
+ });
871
+ it('should add context if ideMode is enabled and there is one active file', async () => {
872
+ // Arrange
873
+ vi.mocked(ideContext.getIdeContext).mockReturnValue({
874
+ workspaceState: {
875
+ openFiles: [
876
+ {
877
+ path: '/path/to/active/file.ts',
878
+ timestamp: Date.now(),
879
+ isActive: true,
880
+ selectedText: 'hello',
881
+ cursor: { line: 5, character: 10 },
882
+ },
883
+ ],
884
+ },
885
+ });
886
+ vi.spyOn(client['config'], 'getIdeMode').mockReturnValue(true);
887
+ const mockStream = (async function* () {
888
+ yield { type: 'content', value: 'Hello' };
889
+ })();
890
+ mockTurnRunFn.mockReturnValue(mockStream);
891
+ const mockChat = {
892
+ addHistory: vi.fn(),
893
+ getHistory: vi.fn().mockReturnValue([]),
894
+ };
895
+ client['chat'] = mockChat;
896
+ const mockGenerator = {
897
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
898
+ generateContent: mockGenerateContentFn,
899
+ };
900
+ client['contentGenerator'] = mockGenerator;
901
+ const initialRequest = [{ text: 'Hi' }];
902
+ // Act
903
+ const stream = client.sendMessageStream(initialRequest, new AbortController().signal, 'prompt-id-ide');
904
+ for await (const _ of stream) {
905
+ // consume stream
906
+ }
907
+ // Assert
908
+ expect(ideContext.getIdeContext).toHaveBeenCalled();
909
+ const expectedContext = `
910
+ Here is the user's editor context as a JSON object. This is for your information only.
911
+ \`\`\`json
912
+ ${JSON.stringify({
913
+ activeFile: {
914
+ path: '/path/to/active/file.ts',
915
+ cursor: {
916
+ line: 5,
917
+ character: 10,
918
+ },
919
+ selectedText: 'hello',
920
+ },
921
+ }, null, 2)}
922
+ \`\`\`
923
+ `.trim();
924
+ const expectedRequest = [{ text: expectedContext }];
925
+ expect(mockChat.addHistory).toHaveBeenCalledWith({
926
+ role: 'user',
927
+ parts: expectedRequest,
928
+ });
929
+ });
930
+ it('should add context if ideMode is enabled and there are open files but no active file', async () => {
931
+ // Arrange
932
+ vi.mocked(ideContext.getIdeContext).mockReturnValue({
933
+ workspaceState: {
934
+ openFiles: [
935
+ {
936
+ path: '/path/to/recent/file1.ts',
937
+ timestamp: Date.now(),
938
+ },
939
+ {
940
+ path: '/path/to/recent/file2.ts',
941
+ timestamp: Date.now(),
942
+ },
943
+ ],
944
+ },
945
+ });
946
+ vi.spyOn(client['config'], 'getIdeMode').mockReturnValue(true);
947
+ const mockStream = (async function* () {
948
+ yield { type: 'content', value: 'Hello' };
949
+ })();
950
+ mockTurnRunFn.mockReturnValue(mockStream);
951
+ const mockChat = {
952
+ addHistory: vi.fn(),
953
+ getHistory: vi.fn().mockReturnValue([]),
954
+ };
955
+ client['chat'] = mockChat;
956
+ const mockGenerator = {
957
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
958
+ generateContent: mockGenerateContentFn,
959
+ };
960
+ client['contentGenerator'] = mockGenerator;
961
+ const initialRequest = [{ text: 'Hi' }];
962
+ // Act
963
+ const stream = client.sendMessageStream(initialRequest, new AbortController().signal, 'prompt-id-ide');
964
+ for await (const _ of stream) {
965
+ // consume stream
966
+ }
967
+ // Assert
968
+ expect(ideContext.getIdeContext).toHaveBeenCalled();
969
+ const expectedContext = `
970
+ Here is the user's editor context as a JSON object. This is for your information only.
971
+ \`\`\`json
972
+ ${JSON.stringify({
973
+ otherOpenFiles: ['/path/to/recent/file1.ts', '/path/to/recent/file2.ts'],
974
+ }, null, 2)}
975
+ \`\`\`
976
+ `.trim();
977
+ const expectedRequest = [{ text: expectedContext }];
978
+ expect(mockChat.addHistory).toHaveBeenCalledWith({
979
+ role: 'user',
980
+ parts: expectedRequest,
981
+ });
982
+ });
983
+ it('should return the turn instance after the stream is complete', async () => {
984
+ // Arrange
985
+ const mockStream = (async function* () {
986
+ yield { type: 'content', value: 'Hello' };
987
+ })();
988
+ mockTurnRunFn.mockReturnValue(mockStream);
989
+ const mockChat = {
990
+ addHistory: vi.fn(),
991
+ getHistory: vi.fn().mockReturnValue([]),
992
+ };
993
+ client['chat'] = mockChat;
994
+ const mockGenerator = {
995
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
996
+ generateContent: mockGenerateContentFn,
997
+ };
998
+ client['contentGenerator'] = mockGenerator;
999
+ // Act
1000
+ const stream = client.sendMessageStream([{ text: 'Hi' }], new AbortController().signal, 'prompt-id-1');
1001
+ // Consume the stream manually to get the final return value.
1002
+ let finalResult;
1003
+ while (true) {
1004
+ const result = await stream.next();
1005
+ if (result.done) {
1006
+ finalResult = result.value;
1007
+ break;
1008
+ }
1009
+ }
1010
+ // Assert
1011
+ expect(finalResult).toBeInstanceOf(Turn);
1012
+ });
1013
+ it('should stop infinite loop after MAX_TURNS when nextSpeaker always returns model', async () => {
1014
+ // Get the mocked checkNextSpeaker function and configure it to trigger infinite loop
1015
+ const { checkNextSpeaker } = await import('../utils/nextSpeakerChecker.js');
1016
+ const mockCheckNextSpeaker = vi.mocked(checkNextSpeaker);
1017
+ mockCheckNextSpeaker.mockResolvedValue({
1018
+ next_speaker: 'model',
1019
+ reasoning: 'Test case - always continue',
1020
+ });
1021
+ // Mock Turn to have no pending tool calls (which would allow nextSpeaker check)
1022
+ const mockStream = (async function* () {
1023
+ yield { type: 'content', value: 'Continue...' };
1024
+ })();
1025
+ mockTurnRunFn.mockReturnValue(mockStream);
1026
+ const mockChat = {
1027
+ addHistory: vi.fn(),
1028
+ getHistory: vi.fn().mockReturnValue([]),
1029
+ };
1030
+ client['chat'] = mockChat;
1031
+ const mockGenerator = {
1032
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
1033
+ generateContent: mockGenerateContentFn,
1034
+ };
1035
+ client['contentGenerator'] = mockGenerator;
1036
+ // Use a signal that never gets aborted
1037
+ const abortController = new AbortController();
1038
+ const signal = abortController.signal;
1039
+ // Act - Start the stream that should loop
1040
+ const stream = client.sendMessageStream([{ text: 'Start conversation' }], signal, 'prompt-id-2');
1041
+ // Count how many stream events we get
1042
+ let eventCount = 0;
1043
+ let finalResult;
1044
+ // Consume the stream and count iterations
1045
+ while (true) {
1046
+ const result = await stream.next();
1047
+ if (result.done) {
1048
+ finalResult = result.value;
1049
+ break;
1050
+ }
1051
+ eventCount++;
1052
+ // Safety check to prevent actual infinite loop in test
1053
+ if (eventCount > 200) {
1054
+ abortController.abort();
1055
+ throw new Error('Test exceeded expected event limit - possible actual infinite loop');
1056
+ }
1057
+ }
1058
+ // Assert
1059
+ expect(finalResult).toBeInstanceOf(Turn);
1060
+ // Debug: Check how many times checkNextSpeaker was called
1061
+ const callCount = mockCheckNextSpeaker.mock.calls.length;
1062
+ // If infinite loop protection is working, checkNextSpeaker should be called many times
1063
+ // but stop at MAX_TURNS (100). Since each recursive call should trigger checkNextSpeaker,
1064
+ // we expect it to be called multiple times before hitting the limit
1065
+ expect(mockCheckNextSpeaker).toHaveBeenCalled();
1066
+ // The test should demonstrate that the infinite loop protection works:
1067
+ // - If checkNextSpeaker is called many times (close to MAX_TURNS), it shows the loop was happening
1068
+ // - If it's only called once, the recursive behavior might not be triggered
1069
+ if (callCount === 0) {
1070
+ throw new Error('checkNextSpeaker was never called - the recursive condition was not met');
1071
+ }
1072
+ else if (callCount === 1) {
1073
+ // This might be expected behavior if the turn has pending tool calls or other conditions prevent recursion
1074
+ console.log('checkNextSpeaker called only once - no infinite loop occurred');
1075
+ }
1076
+ else {
1077
+ console.log(`checkNextSpeaker called ${callCount} times - infinite loop protection worked`);
1078
+ // If called multiple times, we expect it to be stopped before MAX_TURNS
1079
+ expect(callCount).toBeLessThanOrEqual(100); // Should not exceed MAX_TURNS
1080
+ }
1081
+ // The stream should produce events and eventually terminate
1082
+ expect(eventCount).toBeGreaterThanOrEqual(1);
1083
+ expect(eventCount).toBeLessThan(200); // Should not exceed our safety limit
1084
+ });
1085
+ it('should yield MaxSessionTurns and stop when session turn limit is reached', async () => {
1086
+ // Arrange
1087
+ const MAX_SESSION_TURNS = 5;
1088
+ vi.spyOn(client['config'], 'getMaxSessionTurns').mockReturnValue(MAX_SESSION_TURNS);
1089
+ const mockStream = (async function* () {
1090
+ yield { type: 'content', value: 'Hello' };
1091
+ })();
1092
+ mockTurnRunFn.mockReturnValue(mockStream);
1093
+ const mockChat = {
1094
+ addHistory: vi.fn(),
1095
+ getHistory: vi.fn().mockReturnValue([]),
1096
+ };
1097
+ client['chat'] = mockChat;
1098
+ const mockGenerator = {
1099
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
1100
+ generateContent: mockGenerateContentFn,
1101
+ };
1102
+ client['contentGenerator'] = mockGenerator;
1103
+ // Act & Assert
1104
+ // Run up to the limit
1105
+ for (let i = 0; i < MAX_SESSION_TURNS; i++) {
1106
+ const stream = client.sendMessageStream([{ text: 'Hi' }], new AbortController().signal, 'prompt-id-4');
1107
+ // consume stream
1108
+ for await (const _event of stream) {
1109
+ // do nothing
1110
+ }
1111
+ }
1112
+ // This call should exceed the limit
1113
+ const stream = client.sendMessageStream([{ text: 'Hi' }], new AbortController().signal, 'prompt-id-5');
1114
+ const events = [];
1115
+ for await (const event of stream) {
1116
+ events.push(event);
1117
+ }
1118
+ expect(events).toEqual([{ type: GeminiEventType.MaxSessionTurns }]);
1119
+ expect(mockTurnRunFn).toHaveBeenCalledTimes(MAX_SESSION_TURNS);
1120
+ });
1121
+ it('should respect MAX_TURNS limit even when turns parameter is set to a large value', async () => {
1122
+ // This test verifies that the infinite loop protection works even when
1123
+ // someone tries to bypass it by calling with a very large turns value
1124
+ // Get the mocked checkNextSpeaker function and configure it to trigger infinite loop
1125
+ const { checkNextSpeaker } = await import('../utils/nextSpeakerChecker.js');
1126
+ const mockCheckNextSpeaker = vi.mocked(checkNextSpeaker);
1127
+ mockCheckNextSpeaker.mockResolvedValue({
1128
+ next_speaker: 'model',
1129
+ reasoning: 'Test case - always continue',
1130
+ });
1131
+ // Mock Turn to have no pending tool calls (which would allow nextSpeaker check)
1132
+ const mockStream = (async function* () {
1133
+ yield { type: 'content', value: 'Continue...' };
1134
+ })();
1135
+ mockTurnRunFn.mockReturnValue(mockStream);
1136
+ const mockChat = {
1137
+ addHistory: vi.fn(),
1138
+ getHistory: vi.fn().mockReturnValue([]),
1139
+ };
1140
+ client['chat'] = mockChat;
1141
+ const mockGenerator = {
1142
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
1143
+ generateContent: mockGenerateContentFn,
1144
+ };
1145
+ client['contentGenerator'] = mockGenerator;
1146
+ // Use a signal that never gets aborted
1147
+ const abortController = new AbortController();
1148
+ const signal = abortController.signal;
1149
+ // Act - Start the stream with an extremely high turns value
1150
+ // This simulates a case where the turns protection is bypassed
1151
+ const stream = client.sendMessageStream([{ text: 'Start conversation' }], signal, 'prompt-id-3', Number.MAX_SAFE_INTEGER);
1152
+ // Count how many stream events we get
1153
+ let eventCount = 0;
1154
+ const maxTestIterations = 1000; // Higher limit to show the loop continues
1155
+ // Consume the stream and count iterations
1156
+ try {
1157
+ while (true) {
1158
+ const result = await stream.next();
1159
+ if (result.done) {
1160
+ break;
1161
+ }
1162
+ eventCount++;
1163
+ // This test should hit this limit, demonstrating the infinite loop
1164
+ if (eventCount > maxTestIterations) {
1165
+ abortController.abort();
1166
+ // This is the expected behavior - we hit the infinite loop
1167
+ break;
1168
+ }
1169
+ }
1170
+ }
1171
+ catch (error) {
1172
+ // If the test framework times out, that also demonstrates the infinite loop
1173
+ console.error('Test timed out or errored:', error);
1174
+ }
1175
+ // Assert that the fix works - the loop should stop at MAX_TURNS
1176
+ const callCount = mockCheckNextSpeaker.mock.calls.length;
1177
+ // With the fix: even when turns is set to a very high value,
1178
+ // the loop should stop at MAX_TURNS (100)
1179
+ expect(callCount).toBeLessThanOrEqual(100); // Should not exceed MAX_TURNS
1180
+ expect(eventCount).toBeLessThanOrEqual(200); // Should have reasonable number of events
1181
+ console.log(`Infinite loop protection working: checkNextSpeaker called ${callCount} times, ` +
1182
+ `${eventCount} events generated (properly bounded by MAX_TURNS)`);
1183
+ });
1184
+ describe('Editor context delta', () => {
1185
+ const mockStream = (async function* () {
1186
+ yield { type: 'content', value: 'Hello' };
1187
+ })();
1188
+ beforeEach(() => {
1189
+ client['forceFullIdeContext'] = false; // Reset before each delta test
1190
+ vi.spyOn(client, 'tryCompressChat').mockResolvedValue({
1191
+ originalTokenCount: 0,
1192
+ newTokenCount: 0,
1193
+ compressionStatus: CompressionStatus.COMPRESSED,
1194
+ });
1195
+ vi.spyOn(client['config'], 'getIdeMode').mockReturnValue(true);
1196
+ mockTurnRunFn.mockReturnValue(mockStream);
1197
+ const mockChat = {
1198
+ addHistory: vi.fn(),
1199
+ setHistory: vi.fn(),
1200
+ sendMessage: vi.fn().mockResolvedValue({ text: 'summary' }),
1201
+ // Assume history is not empty for delta checks
1202
+ getHistory: vi
1203
+ .fn()
1204
+ .mockReturnValue([
1205
+ { role: 'user', parts: [{ text: 'previous message' }] },
1206
+ ]),
1207
+ };
1208
+ client['chat'] = mockChat;
1209
+ const mockGenerator = {
1210
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
1211
+ generateContent: mockGenerateContentFn,
1212
+ };
1213
+ client['contentGenerator'] = mockGenerator;
1214
+ });
1215
+ const testCases = [
1216
+ {
1217
+ description: 'sends delta when active file changes',
1218
+ previousActiveFile: {
1219
+ path: '/path/to/old/file.ts',
1220
+ cursor: { line: 5, character: 10 },
1221
+ selectedText: 'hello',
1222
+ },
1223
+ currentActiveFile: {
1224
+ path: '/path/to/active/file.ts',
1225
+ cursor: { line: 5, character: 10 },
1226
+ selectedText: 'hello',
1227
+ },
1228
+ shouldSendContext: true,
1229
+ },
1230
+ {
1231
+ description: 'sends delta when cursor line changes',
1232
+ previousActiveFile: {
1233
+ path: '/path/to/active/file.ts',
1234
+ cursor: { line: 1, character: 10 },
1235
+ selectedText: 'hello',
1236
+ },
1237
+ currentActiveFile: {
1238
+ path: '/path/to/active/file.ts',
1239
+ cursor: { line: 5, character: 10 },
1240
+ selectedText: 'hello',
1241
+ },
1242
+ shouldSendContext: true,
1243
+ },
1244
+ {
1245
+ description: 'sends delta when cursor character changes',
1246
+ previousActiveFile: {
1247
+ path: '/path/to/active/file.ts',
1248
+ cursor: { line: 5, character: 1 },
1249
+ selectedText: 'hello',
1250
+ },
1251
+ currentActiveFile: {
1252
+ path: '/path/to/active/file.ts',
1253
+ cursor: { line: 5, character: 10 },
1254
+ selectedText: 'hello',
1255
+ },
1256
+ shouldSendContext: true,
1257
+ },
1258
+ {
1259
+ description: 'sends delta when selected text changes',
1260
+ previousActiveFile: {
1261
+ path: '/path/to/active/file.ts',
1262
+ cursor: { line: 5, character: 10 },
1263
+ selectedText: 'world',
1264
+ },
1265
+ currentActiveFile: {
1266
+ path: '/path/to/active/file.ts',
1267
+ cursor: { line: 5, character: 10 },
1268
+ selectedText: 'hello',
1269
+ },
1270
+ shouldSendContext: true,
1271
+ },
1272
+ {
1273
+ description: 'sends delta when selected text is added',
1274
+ previousActiveFile: {
1275
+ path: '/path/to/active/file.ts',
1276
+ cursor: { line: 5, character: 10 },
1277
+ },
1278
+ currentActiveFile: {
1279
+ path: '/path/to/active/file.ts',
1280
+ cursor: { line: 5, character: 10 },
1281
+ selectedText: 'hello',
1282
+ },
1283
+ shouldSendContext: true,
1284
+ },
1285
+ {
1286
+ description: 'sends delta when selected text is removed',
1287
+ previousActiveFile: {
1288
+ path: '/path/to/active/file.ts',
1289
+ cursor: { line: 5, character: 10 },
1290
+ selectedText: 'hello',
1291
+ },
1292
+ currentActiveFile: {
1293
+ path: '/path/to/active/file.ts',
1294
+ cursor: { line: 5, character: 10 },
1295
+ },
1296
+ shouldSendContext: true,
1297
+ },
1298
+ {
1299
+ description: 'does not send context when nothing changes',
1300
+ previousActiveFile: {
1301
+ path: '/path/to/active/file.ts',
1302
+ cursor: { line: 5, character: 10 },
1303
+ selectedText: 'hello',
1304
+ },
1305
+ currentActiveFile: {
1306
+ path: '/path/to/active/file.ts',
1307
+ cursor: { line: 5, character: 10 },
1308
+ selectedText: 'hello',
1309
+ },
1310
+ shouldSendContext: false,
1311
+ },
1312
+ ];
1313
+ it.each(testCases)('$description', async ({ previousActiveFile, currentActiveFile, shouldSendContext, }) => {
1314
+ // Setup previous context
1315
+ client['lastSentIdeContext'] = {
1316
+ workspaceState: {
1317
+ openFiles: [
1318
+ {
1319
+ path: previousActiveFile.path,
1320
+ cursor: previousActiveFile.cursor,
1321
+ selectedText: previousActiveFile.selectedText,
1322
+ isActive: true,
1323
+ timestamp: Date.now() - 1000,
1324
+ },
1325
+ ],
1326
+ },
1327
+ };
1328
+ // Setup current context
1329
+ vi.mocked(ideContext.getIdeContext).mockReturnValue({
1330
+ workspaceState: {
1331
+ openFiles: [
1332
+ { ...currentActiveFile, isActive: true, timestamp: Date.now() },
1333
+ ],
1334
+ },
1335
+ });
1336
+ const stream = client.sendMessageStream([{ text: 'Hi' }], new AbortController().signal, 'prompt-id-delta');
1337
+ for await (const _ of stream) {
1338
+ // consume stream
1339
+ }
1340
+ const mockChat = client['chat'];
1341
+ if (shouldSendContext) {
1342
+ expect(mockChat.addHistory).toHaveBeenCalledWith(expect.objectContaining({
1343
+ parts: expect.arrayContaining([
1344
+ expect.objectContaining({
1345
+ text: expect.stringContaining("Here is a summary of changes in the user's editor context"),
1346
+ }),
1347
+ ]),
1348
+ }));
1349
+ }
1350
+ else {
1351
+ expect(mockChat.addHistory).not.toHaveBeenCalled();
1352
+ }
1353
+ });
1354
+ it('sends full context when history is cleared, even if editor state is unchanged', async () => {
1355
+ const activeFile = {
1356
+ path: '/path/to/active/file.ts',
1357
+ cursor: { line: 5, character: 10 },
1358
+ selectedText: 'hello',
1359
+ };
1360
+ // Setup previous context
1361
+ client['lastSentIdeContext'] = {
1362
+ workspaceState: {
1363
+ openFiles: [
1364
+ {
1365
+ path: activeFile.path,
1366
+ cursor: activeFile.cursor,
1367
+ selectedText: activeFile.selectedText,
1368
+ isActive: true,
1369
+ timestamp: Date.now() - 1000,
1370
+ },
1371
+ ],
1372
+ },
1373
+ };
1374
+ // Setup current context (same as previous)
1375
+ vi.mocked(ideContext.getIdeContext).mockReturnValue({
1376
+ workspaceState: {
1377
+ openFiles: [
1378
+ { ...activeFile, isActive: true, timestamp: Date.now() },
1379
+ ],
1380
+ },
1381
+ });
1382
+ // Make history empty
1383
+ const mockChat = client['chat'];
1384
+ mockChat.getHistory.mockReturnValue([]);
1385
+ const stream = client.sendMessageStream([{ text: 'Hi' }], new AbortController().signal, 'prompt-id-history-cleared');
1386
+ for await (const _ of stream) {
1387
+ // consume stream
1388
+ }
1389
+ expect(mockChat.addHistory).toHaveBeenCalledWith(expect.objectContaining({
1390
+ parts: expect.arrayContaining([
1391
+ expect.objectContaining({
1392
+ text: expect.stringContaining("Here is the user's editor context"),
1393
+ }),
1394
+ ]),
1395
+ }));
1396
+ // Also verify it's the full context, not a delta.
1397
+ const call = mockChat.addHistory.mock.calls[0][0];
1398
+ const contextText = call.parts[0].text;
1399
+ const contextJson = JSON.parse(contextText.match(/```json\n(.*)\n```/s)[1]);
1400
+ expect(contextJson).toHaveProperty('activeFile');
1401
+ expect(contextJson.activeFile.path).toBe('/path/to/active/file.ts');
1402
+ });
1403
+ });
1404
+ describe('IDE context with pending tool calls', () => {
1405
+ let mockChat;
1406
+ beforeEach(() => {
1407
+ vi.spyOn(client, 'tryCompressChat').mockResolvedValue({
1408
+ originalTokenCount: 0,
1409
+ newTokenCount: 0,
1410
+ compressionStatus: CompressionStatus.COMPRESSED,
1411
+ });
1412
+ const mockStream = (async function* () {
1413
+ yield { type: 'content', value: 'response' };
1414
+ })();
1415
+ mockTurnRunFn.mockReturnValue(mockStream);
1416
+ mockChat = {
1417
+ addHistory: vi.fn(),
1418
+ getHistory: vi.fn().mockReturnValue([]), // Default empty history
1419
+ setHistory: vi.fn(),
1420
+ sendMessage: vi.fn().mockResolvedValue({ text: 'summary' }),
1421
+ };
1422
+ client['chat'] = mockChat;
1423
+ const mockGenerator = {
1424
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
1425
+ };
1426
+ client['contentGenerator'] = mockGenerator;
1427
+ vi.spyOn(client['config'], 'getIdeMode').mockReturnValue(true);
1428
+ vi.mocked(ideContext.getIdeContext).mockReturnValue({
1429
+ workspaceState: {
1430
+ openFiles: [{ path: '/path/to/file.ts', timestamp: Date.now() }],
1431
+ },
1432
+ });
1433
+ });
1434
+ it('should NOT add IDE context when a tool call is pending', async () => {
1435
+ // Arrange: History ends with a functionCall from the model
1436
+ const historyWithPendingCall = [
1437
+ { role: 'user', parts: [{ text: 'Please use a tool.' }] },
1438
+ {
1439
+ role: 'model',
1440
+ parts: [{ functionCall: { name: 'some_tool', args: {} } }],
1441
+ },
1442
+ ];
1443
+ vi.mocked(mockChat.getHistory).mockReturnValue(historyWithPendingCall);
1444
+ // Act: Simulate sending the tool's response back
1445
+ const stream = client.sendMessageStream([
1446
+ {
1447
+ functionResponse: {
1448
+ name: 'some_tool',
1449
+ response: { success: true },
1450
+ },
1451
+ },
1452
+ ], new AbortController().signal, 'prompt-id-tool-response');
1453
+ for await (const _ of stream) {
1454
+ // consume stream to complete the call
1455
+ }
1456
+ // Assert: The IDE context message should NOT have been added to the history.
1457
+ expect(mockChat.addHistory).not.toHaveBeenCalledWith(expect.objectContaining({
1458
+ parts: expect.arrayContaining([
1459
+ expect.objectContaining({
1460
+ text: expect.stringContaining("user's editor context"),
1461
+ }),
1462
+ ]),
1463
+ }));
1464
+ });
1465
+ it('should add IDE context when no tool call is pending', async () => {
1466
+ // Arrange: History is normal, no pending calls
1467
+ const normalHistory = [
1468
+ { role: 'user', parts: [{ text: 'A normal message.' }] },
1469
+ { role: 'model', parts: [{ text: 'A normal response.' }] },
1470
+ ];
1471
+ vi.mocked(mockChat.getHistory).mockReturnValue(normalHistory);
1472
+ // Act
1473
+ const stream = client.sendMessageStream([{ text: 'Another normal message' }], new AbortController().signal, 'prompt-id-normal');
1474
+ for await (const _ of stream) {
1475
+ // consume stream
1476
+ }
1477
+ // Assert: The IDE context message SHOULD have been added.
1478
+ expect(mockChat.addHistory).toHaveBeenCalledWith(expect.objectContaining({
1479
+ role: 'user',
1480
+ parts: expect.arrayContaining([
1481
+ expect.objectContaining({
1482
+ text: expect.stringContaining("user's editor context"),
1483
+ }),
1484
+ ]),
1485
+ }));
1486
+ });
1487
+ it('should send the latest IDE context on the next message after a skipped context', async () => {
1488
+ // --- Step 1: A tool call is pending, context should be skipped ---
1489
+ // Arrange: History ends with a functionCall
1490
+ const historyWithPendingCall = [
1491
+ { role: 'user', parts: [{ text: 'Please use a tool.' }] },
1492
+ {
1493
+ role: 'model',
1494
+ parts: [{ functionCall: { name: 'some_tool', args: {} } }],
1495
+ },
1496
+ ];
1497
+ vi.mocked(mockChat.getHistory).mockReturnValue(historyWithPendingCall);
1498
+ // Arrange: Set the initial IDE context
1499
+ const initialIdeContext = {
1500
+ workspaceState: {
1501
+ openFiles: [{ path: '/path/to/fileA.ts', timestamp: Date.now() }],
1502
+ },
1503
+ };
1504
+ vi.mocked(ideContext.getIdeContext).mockReturnValue(initialIdeContext);
1505
+ // Act: Send the tool response
1506
+ let stream = client.sendMessageStream([
1507
+ {
1508
+ functionResponse: {
1509
+ name: 'some_tool',
1510
+ response: { success: true },
1511
+ },
1512
+ },
1513
+ ], new AbortController().signal, 'prompt-id-tool-response');
1514
+ for await (const _ of stream) {
1515
+ /* consume */
1516
+ }
1517
+ // Assert: The initial context was NOT sent
1518
+ expect(mockChat.addHistory).not.toHaveBeenCalledWith(expect.objectContaining({
1519
+ parts: expect.arrayContaining([
1520
+ expect.objectContaining({
1521
+ text: expect.stringContaining("user's editor context"),
1522
+ }),
1523
+ ]),
1524
+ }));
1525
+ // --- Step 2: A new message is sent, latest context should be included ---
1526
+ // Arrange: The model has responded to the tool, and the user is sending a new message.
1527
+ const historyAfterToolResponse = [
1528
+ ...historyWithPendingCall,
1529
+ {
1530
+ role: 'user',
1531
+ parts: [
1532
+ {
1533
+ functionResponse: {
1534
+ name: 'some_tool',
1535
+ response: { success: true },
1536
+ },
1537
+ },
1538
+ ],
1539
+ },
1540
+ { role: 'model', parts: [{ text: 'The tool ran successfully.' }] },
1541
+ ];
1542
+ vi.mocked(mockChat.getHistory).mockReturnValue(historyAfterToolResponse);
1543
+ vi.mocked(mockChat.addHistory).mockClear(); // Clear previous calls for the next assertion
1544
+ // Arrange: The IDE context has now changed
1545
+ const newIdeContext = {
1546
+ workspaceState: {
1547
+ openFiles: [{ path: '/path/to/fileB.ts', timestamp: Date.now() }],
1548
+ },
1549
+ };
1550
+ vi.mocked(ideContext.getIdeContext).mockReturnValue(newIdeContext);
1551
+ // Act: Send a new, regular user message
1552
+ stream = client.sendMessageStream([{ text: 'Thanks!' }], new AbortController().signal, 'prompt-id-final');
1553
+ for await (const _ of stream) {
1554
+ /* consume */
1555
+ }
1556
+ // Assert: The NEW context was sent as a FULL context because there was no previously sent context.
1557
+ const addHistoryCalls = vi.mocked(mockChat.addHistory).mock.calls;
1558
+ const contextCall = addHistoryCalls.find((call) => JSON.stringify(call[0]).includes("user's editor context"));
1559
+ expect(contextCall).toBeDefined();
1560
+ expect(JSON.stringify(contextCall[0])).toContain("Here is the user's editor context as a JSON object");
1561
+ // Check that the sent context is the new one (fileB.ts)
1562
+ expect(JSON.stringify(contextCall[0])).toContain('fileB.ts');
1563
+ // Check that the sent context is NOT the old one (fileA.ts)
1564
+ expect(JSON.stringify(contextCall[0])).not.toContain('fileA.ts');
1565
+ });
1566
+ it('should send a context DELTA on the next message after a skipped context', async () => {
1567
+ // --- Step 0: Establish an initial context ---
1568
+ vi.mocked(mockChat.getHistory).mockReturnValue([]); // Start with empty history
1569
+ const contextA = {
1570
+ workspaceState: {
1571
+ openFiles: [
1572
+ {
1573
+ path: '/path/to/fileA.ts',
1574
+ isActive: true,
1575
+ timestamp: Date.now(),
1576
+ },
1577
+ ],
1578
+ },
1579
+ };
1580
+ vi.mocked(ideContext.getIdeContext).mockReturnValue(contextA);
1581
+ // Act: Send a regular message to establish the initial context
1582
+ let stream = client.sendMessageStream([{ text: 'Initial message' }], new AbortController().signal, 'prompt-id-initial');
1583
+ for await (const _ of stream) {
1584
+ /* consume */
1585
+ }
1586
+ // Assert: Full context for fileA.ts was sent and stored.
1587
+ const initialCall = vi.mocked(mockChat.addHistory).mock.calls[0][0];
1588
+ expect(JSON.stringify(initialCall)).toContain("user's editor context as a JSON object");
1589
+ expect(JSON.stringify(initialCall)).toContain('fileA.ts');
1590
+ // This implicitly tests that `lastSentIdeContext` is now set internally by the client.
1591
+ vi.mocked(mockChat.addHistory).mockClear();
1592
+ // --- Step 1: A tool call is pending, context should be skipped ---
1593
+ const historyWithPendingCall = [
1594
+ { role: 'user', parts: [{ text: 'Please use a tool.' }] },
1595
+ {
1596
+ role: 'model',
1597
+ parts: [{ functionCall: { name: 'some_tool', args: {} } }],
1598
+ },
1599
+ ];
1600
+ vi.mocked(mockChat.getHistory).mockReturnValue(historyWithPendingCall);
1601
+ // Arrange: IDE context changes, but this should be skipped
1602
+ const contextB = {
1603
+ workspaceState: {
1604
+ openFiles: [
1605
+ {
1606
+ path: '/path/to/fileB.ts',
1607
+ isActive: true,
1608
+ timestamp: Date.now(),
1609
+ },
1610
+ ],
1611
+ },
1612
+ };
1613
+ vi.mocked(ideContext.getIdeContext).mockReturnValue(contextB);
1614
+ // Act: Send the tool response
1615
+ stream = client.sendMessageStream([
1616
+ {
1617
+ functionResponse: {
1618
+ name: 'some_tool',
1619
+ response: { success: true },
1620
+ },
1621
+ },
1622
+ ], new AbortController().signal, 'prompt-id-tool-response');
1623
+ for await (const _ of stream) {
1624
+ /* consume */
1625
+ }
1626
+ // Assert: No context was sent
1627
+ expect(mockChat.addHistory).not.toHaveBeenCalled();
1628
+ // --- Step 2: A new message is sent, latest context DELTA should be included ---
1629
+ const historyAfterToolResponse = [
1630
+ ...historyWithPendingCall,
1631
+ {
1632
+ role: 'user',
1633
+ parts: [
1634
+ {
1635
+ functionResponse: {
1636
+ name: 'some_tool',
1637
+ response: { success: true },
1638
+ },
1639
+ },
1640
+ ],
1641
+ },
1642
+ { role: 'model', parts: [{ text: 'The tool ran successfully.' }] },
1643
+ ];
1644
+ vi.mocked(mockChat.getHistory).mockReturnValue(historyAfterToolResponse);
1645
+ // Arrange: The IDE context has changed again
1646
+ const contextC = {
1647
+ workspaceState: {
1648
+ openFiles: [
1649
+ // fileA is now closed, fileC is open
1650
+ {
1651
+ path: '/path/to/fileC.ts',
1652
+ isActive: true,
1653
+ timestamp: Date.now(),
1654
+ },
1655
+ ],
1656
+ },
1657
+ };
1658
+ vi.mocked(ideContext.getIdeContext).mockReturnValue(contextC);
1659
+ // Act: Send a new, regular user message
1660
+ stream = client.sendMessageStream([{ text: 'Thanks!' }], new AbortController().signal, 'prompt-id-final');
1661
+ for await (const _ of stream) {
1662
+ /* consume */
1663
+ }
1664
+ // Assert: The DELTA context was sent
1665
+ const finalCall = vi.mocked(mockChat.addHistory).mock.calls[0][0];
1666
+ expect(JSON.stringify(finalCall)).toContain('summary of changes');
1667
+ // The delta should reflect fileA being closed and fileC being opened.
1668
+ expect(JSON.stringify(finalCall)).toContain('filesClosed');
1669
+ expect(JSON.stringify(finalCall)).toContain('fileA.ts');
1670
+ expect(JSON.stringify(finalCall)).toContain('activeFileChanged');
1671
+ expect(JSON.stringify(finalCall)).toContain('fileC.ts');
1672
+ });
1673
+ });
1674
+ it('should not call checkNextSpeaker when turn.run() yields an error', async () => {
1675
+ // Arrange
1676
+ const { checkNextSpeaker } = await import('../utils/nextSpeakerChecker.js');
1677
+ const mockCheckNextSpeaker = vi.mocked(checkNextSpeaker);
1678
+ const mockStream = (async function* () {
1679
+ yield {
1680
+ type: GeminiEventType.Error,
1681
+ value: { error: { message: 'test error' } },
1682
+ };
1683
+ })();
1684
+ mockTurnRunFn.mockReturnValue(mockStream);
1685
+ const mockChat = {
1686
+ addHistory: vi.fn(),
1687
+ getHistory: vi.fn().mockReturnValue([]),
1688
+ };
1689
+ client['chat'] = mockChat;
1690
+ const mockGenerator = {
1691
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
1692
+ generateContent: mockGenerateContentFn,
1693
+ };
1694
+ client['contentGenerator'] = mockGenerator;
1695
+ // Act
1696
+ const stream = client.sendMessageStream([{ text: 'Hi' }], new AbortController().signal, 'prompt-id-error');
1697
+ for await (const _ of stream) {
1698
+ // consume stream
1699
+ }
1700
+ // Assert
1701
+ expect(mockCheckNextSpeaker).not.toHaveBeenCalled();
1702
+ });
1703
+ it('should not call checkNextSpeaker when turn.run() yields a value then an error', async () => {
1704
+ // Arrange
1705
+ const { checkNextSpeaker } = await import('../utils/nextSpeakerChecker.js');
1706
+ const mockCheckNextSpeaker = vi.mocked(checkNextSpeaker);
1707
+ const mockStream = (async function* () {
1708
+ yield { type: GeminiEventType.Content, value: 'some content' };
1709
+ yield {
1710
+ type: GeminiEventType.Error,
1711
+ value: { error: { message: 'test error' } },
1712
+ };
1713
+ })();
1714
+ mockTurnRunFn.mockReturnValue(mockStream);
1715
+ const mockChat = {
1716
+ addHistory: vi.fn(),
1717
+ getHistory: vi.fn().mockReturnValue([]),
1718
+ };
1719
+ client['chat'] = mockChat;
1720
+ const mockGenerator = {
1721
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
1722
+ generateContent: mockGenerateContentFn,
1723
+ };
1724
+ client['contentGenerator'] = mockGenerator;
1725
+ // Act
1726
+ const stream = client.sendMessageStream([{ text: 'Hi' }], new AbortController().signal, 'prompt-id-error');
1727
+ for await (const _ of stream) {
1728
+ // consume stream
1729
+ }
1730
+ // Assert
1731
+ expect(mockCheckNextSpeaker).not.toHaveBeenCalled();
1732
+ });
1733
+ });
1734
+ describe('generateContent', () => {
1735
+ it('should call generateContent with the correct parameters', async () => {
1736
+ const contents = [{ role: 'user', parts: [{ text: 'hello' }] }];
1737
+ const generationConfig = { temperature: 0.5 };
1738
+ const abortSignal = new AbortController().signal;
1739
+ // Mock countTokens
1740
+ const mockGenerator = {
1741
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 1 }),
1742
+ generateContent: mockGenerateContentFn,
1743
+ };
1744
+ client['contentGenerator'] = mockGenerator;
1745
+ await client.generateContent(contents, generationConfig, abortSignal);
1746
+ expect(mockGenerateContentFn).toHaveBeenCalledWith({
1747
+ model: 'test-model',
1748
+ config: {
1749
+ abortSignal,
1750
+ systemInstruction: getCoreSystemPrompt(''),
1751
+ temperature: 0.5,
1752
+ topP: 1,
1753
+ },
1754
+ contents,
1755
+ }, 'test-session-id');
1756
+ });
1757
+ it('should use current model from config for content generation', async () => {
1758
+ const initialModel = client['config'].getModel();
1759
+ const contents = [{ role: 'user', parts: [{ text: 'test' }] }];
1760
+ const currentModel = initialModel + '-changed';
1761
+ vi.spyOn(client['config'], 'getModel').mockReturnValueOnce(currentModel);
1762
+ const mockGenerator = {
1763
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 1 }),
1764
+ generateContent: mockGenerateContentFn,
1765
+ };
1766
+ client['contentGenerator'] = mockGenerator;
1767
+ await client.generateContent(contents, {}, new AbortController().signal);
1768
+ expect(mockGenerateContentFn).not.toHaveBeenCalledWith({
1769
+ model: initialModel,
1770
+ config: expect.any(Object),
1771
+ contents,
1772
+ });
1773
+ expect(mockGenerateContentFn).toHaveBeenCalledWith({
1774
+ model: currentModel,
1775
+ config: expect.any(Object),
1776
+ contents,
1777
+ }, 'test-session-id');
1778
+ });
1779
+ });
1780
+ describe('handleFlashFallback', () => {
1781
+ it('should use current model from config when checking for fallback', async () => {
1782
+ const initialModel = client['config'].getModel();
1783
+ const fallbackModel = DEFAULT_GEMINI_FLASH_MODEL;
1784
+ // mock config been changed
1785
+ const currentModel = initialModel + '-changed';
1786
+ const getModelSpy = vi.spyOn(client['config'], 'getModel');
1787
+ getModelSpy.mockReturnValue(currentModel);
1788
+ const mockFallbackHandler = vi.fn().mockResolvedValue(true);
1789
+ client['config'].flashFallbackHandler = mockFallbackHandler;
1790
+ client['config'].setModel = vi.fn();
1791
+ const result = await client['handleFlashFallback'](AuthType.LOGIN_WITH_GOOGLE);
1792
+ expect(result).toBe(fallbackModel);
1793
+ expect(mockFallbackHandler).toHaveBeenCalledWith(currentModel, fallbackModel, undefined);
1794
+ });
1795
+ });
1796
+ describe('setHistory', () => {
1797
+ it('should strip thought signatures when stripThoughts is true', () => {
1798
+ const mockChat = {
1799
+ setHistory: vi.fn(),
1800
+ };
1801
+ client['chat'] = mockChat;
1802
+ const historyWithThoughts = [
1803
+ {
1804
+ role: 'user',
1805
+ parts: [{ text: 'hello' }],
1806
+ },
1807
+ {
1808
+ role: 'model',
1809
+ parts: [
1810
+ { text: 'thinking...', thoughtSignature: 'thought-123' },
1811
+ {
1812
+ functionCall: { name: 'test', args: {} },
1813
+ thoughtSignature: 'thought-456',
1814
+ },
1815
+ ],
1816
+ },
1817
+ ];
1818
+ client.setHistory(historyWithThoughts, { stripThoughts: true });
1819
+ const expectedHistory = [
1820
+ {
1821
+ role: 'user',
1822
+ parts: [{ text: 'hello' }],
1823
+ },
1824
+ {
1825
+ role: 'model',
1826
+ parts: [
1827
+ { text: 'thinking...' },
1828
+ { functionCall: { name: 'test', args: {} } },
1829
+ ],
1830
+ },
1831
+ ];
1832
+ expect(mockChat.setHistory).toHaveBeenCalledWith(expectedHistory);
1833
+ });
1834
+ it('should not strip thought signatures when stripThoughts is false', () => {
1835
+ const mockChat = {
1836
+ setHistory: vi.fn(),
1837
+ };
1838
+ client['chat'] = mockChat;
1839
+ const historyWithThoughts = [
1840
+ {
1841
+ role: 'user',
1842
+ parts: [{ text: 'hello' }],
1843
+ },
1844
+ {
1845
+ role: 'model',
1846
+ parts: [
1847
+ { text: 'thinking...', thoughtSignature: 'thought-123' },
1848
+ { text: 'ok', thoughtSignature: 'thought-456' },
1849
+ ],
1850
+ },
1851
+ ];
1852
+ client.setHistory(historyWithThoughts, { stripThoughts: false });
1853
+ expect(mockChat.setHistory).toHaveBeenCalledWith(historyWithThoughts);
1854
+ });
1855
+ });
1856
+ });
1857
+ //# sourceMappingURL=client.test.js.map