@vybestack/llxprt-code-core 0.1.18-nightly.250811.b0db22c6 → 0.1.18-nightly.250812.12fa8ad2

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 (485) hide show
  1. package/README.md +49 -2
  2. package/dist/index.d.ts +3 -0
  3. package/dist/index.js +2 -0
  4. package/dist/index.js.map +1 -1
  5. package/dist/src/auth/anthropic-device-flow.d.ts +53 -0
  6. package/dist/src/auth/anthropic-device-flow.js +208 -0
  7. package/dist/src/auth/anthropic-device-flow.js.map +1 -0
  8. package/dist/src/auth/token-store.js +11 -7
  9. package/dist/src/auth/token-store.js.map +1 -1
  10. package/dist/src/config/config.d.ts +7 -1
  11. package/dist/src/config/config.js +42 -4
  12. package/dist/src/config/config.js.map +1 -1
  13. package/dist/src/config/profileManager.d.ts +14 -4
  14. package/dist/src/config/profileManager.js +90 -11
  15. package/dist/src/config/profileManager.js.map +1 -1
  16. package/dist/src/core/contentGenerator.d.ts +2 -1
  17. package/dist/src/core/contentGenerator.js +1 -0
  18. package/dist/src/core/contentGenerator.js.map +1 -1
  19. package/dist/src/index.d.ts +6 -0
  20. package/dist/src/index.js +5 -0
  21. package/dist/src/index.js.map +1 -1
  22. package/dist/src/providers/BaseProvider.d.ts +51 -0
  23. package/dist/src/providers/BaseProvider.js +136 -1
  24. package/dist/src/providers/BaseProvider.js.map +1 -1
  25. package/dist/src/providers/IProvider.d.ts +1 -0
  26. package/dist/src/providers/LoggingProviderWrapper.d.ts +1 -0
  27. package/dist/src/providers/LoggingProviderWrapper.js +3 -0
  28. package/dist/src/providers/LoggingProviderWrapper.js.map +1 -1
  29. package/dist/src/providers/ProviderManager.d.ts +0 -1
  30. package/dist/src/providers/ProviderManager.js +23 -14
  31. package/dist/src/providers/ProviderManager.js.map +1 -1
  32. package/dist/src/providers/anthropic/AnthropicProvider.d.ts +20 -6
  33. package/dist/src/providers/anthropic/AnthropicProvider.js +172 -26
  34. package/dist/src/providers/anthropic/AnthropicProvider.js.map +1 -1
  35. package/dist/src/providers/gemini/GeminiProvider.d.ts +4 -0
  36. package/dist/src/providers/gemini/GeminiProvider.js +33 -1
  37. package/dist/src/providers/gemini/GeminiProvider.js.map +1 -1
  38. package/dist/src/providers/openai/OpenAIProvider.d.ts +32 -0
  39. package/dist/src/providers/openai/OpenAIProvider.js +200 -13
  40. package/dist/src/providers/openai/OpenAIProvider.js.map +1 -1
  41. package/dist/src/providers/openai/RESPONSES_API_MODELS.d.ts +1 -1
  42. package/dist/src/providers/openai/RESPONSES_API_MODELS.js +1 -0
  43. package/dist/src/providers/openai/RESPONSES_API_MODELS.js.map +1 -1
  44. package/dist/src/providers/openai/syntheticToolResponses.d.ts +52 -0
  45. package/dist/src/providers/openai/syntheticToolResponses.js +129 -0
  46. package/dist/src/providers/openai/syntheticToolResponses.js.map +1 -0
  47. package/dist/src/settings/SettingsService.d.ts +32 -0
  48. package/dist/src/settings/SettingsService.js +204 -0
  49. package/dist/src/settings/SettingsService.js.map +1 -0
  50. package/dist/src/settings/settingsServiceInstance.d.ts +12 -0
  51. package/dist/src/settings/settingsServiceInstance.js +24 -0
  52. package/dist/src/settings/settingsServiceInstance.js.map +1 -0
  53. package/dist/src/settings/types.d.ts +141 -0
  54. package/dist/src/settings/types.js +5 -0
  55. package/dist/src/settings/types.js.map +1 -0
  56. package/package.json +4 -2
  57. package/dist/src/auth/auth-integration.spec.d.ts +0 -6
  58. package/dist/src/auth/auth-integration.spec.js +0 -384
  59. package/dist/src/auth/auth-integration.spec.js.map +0 -1
  60. package/dist/src/auth/precedence.test.d.ts +0 -6
  61. package/dist/src/auth/precedence.test.js +0 -374
  62. package/dist/src/auth/precedence.test.js.map +0 -1
  63. package/dist/src/auth/qwen-device-flow.spec.d.ts +0 -6
  64. package/dist/src/auth/qwen-device-flow.spec.js +0 -793
  65. package/dist/src/auth/qwen-device-flow.spec.js.map +0 -1
  66. package/dist/src/auth/token-store.spec.d.ts +0 -6
  67. package/dist/src/auth/token-store.spec.js +0 -405
  68. package/dist/src/auth/token-store.spec.js.map +0 -1
  69. package/dist/src/code_assist/converter.test.d.ts +0 -6
  70. package/dist/src/code_assist/converter.test.js +0 -279
  71. package/dist/src/code_assist/converter.test.js.map +0 -1
  72. package/dist/src/code_assist/oauth2.test.d.ts +0 -6
  73. package/dist/src/code_assist/oauth2.test.js +0 -370
  74. package/dist/src/code_assist/oauth2.test.js.map +0 -1
  75. package/dist/src/code_assist/server.test.d.ts +0 -6
  76. package/dist/src/code_assist/server.test.js +0 -134
  77. package/dist/src/code_assist/server.test.js.map +0 -1
  78. package/dist/src/code_assist/setup.test.d.ts +0 -6
  79. package/dist/src/code_assist/setup.test.js +0 -65
  80. package/dist/src/code_assist/setup.test.js.map +0 -1
  81. package/dist/src/config/config.alwaysAllow.test.d.ts +0 -6
  82. package/dist/src/config/config.alwaysAllow.test.js +0 -84
  83. package/dist/src/config/config.alwaysAllow.test.js.map +0 -1
  84. package/dist/src/config/config.ephemeral.test.d.ts +0 -6
  85. package/dist/src/config/config.ephemeral.test.js +0 -152
  86. package/dist/src/config/config.ephemeral.test.js.map +0 -1
  87. package/dist/src/config/config.test.d.ts +0 -6
  88. package/dist/src/config/config.test.js +0 -369
  89. package/dist/src/config/config.test.js.map +0 -1
  90. package/dist/src/config/endpoints.test.d.ts +0 -6
  91. package/dist/src/config/endpoints.test.js +0 -196
  92. package/dist/src/config/endpoints.test.js.map +0 -1
  93. package/dist/src/config/flashFallback.test.d.ts +0 -6
  94. package/dist/src/config/flashFallback.test.js +0 -91
  95. package/dist/src/config/flashFallback.test.js.map +0 -1
  96. package/dist/src/core/client.test.d.ts +0 -6
  97. package/dist/src/core/client.test.js +0 -1323
  98. package/dist/src/core/client.test.js.map +0 -1
  99. package/dist/src/core/contentGenerator.test.d.ts +0 -6
  100. package/dist/src/core/contentGenerator.test.js +0 -103
  101. package/dist/src/core/contentGenerator.test.js.map +0 -1
  102. package/dist/src/core/coreToolScheduler.test.d.ts +0 -6
  103. package/dist/src/core/coreToolScheduler.test.js +0 -637
  104. package/dist/src/core/coreToolScheduler.test.js.map +0 -1
  105. package/dist/src/core/geminiChat.test.d.ts +0 -6
  106. package/dist/src/core/geminiChat.test.js +0 -425
  107. package/dist/src/core/geminiChat.test.js.map +0 -1
  108. package/dist/src/core/googleGenAIWrapper.test.d.ts +0 -6
  109. package/dist/src/core/googleGenAIWrapper.test.js +0 -104
  110. package/dist/src/core/googleGenAIWrapper.test.js.map +0 -1
  111. package/dist/src/core/logger.test.d.ts +0 -6
  112. package/dist/src/core/logger.test.js +0 -467
  113. package/dist/src/core/logger.test.js.map +0 -1
  114. package/dist/src/core/nonInteractiveToolExecutor.test.d.ts +0 -6
  115. package/dist/src/core/nonInteractiveToolExecutor.test.js +0 -165
  116. package/dist/src/core/nonInteractiveToolExecutor.test.js.map +0 -1
  117. package/dist/src/core/prompts-async.test.d.ts +0 -6
  118. package/dist/src/core/prompts-async.test.js +0 -115
  119. package/dist/src/core/prompts-async.test.js.map +0 -1
  120. package/dist/src/core/prompts.test.d.ts +0 -6
  121. package/dist/src/core/prompts.test.js +0 -68
  122. package/dist/src/core/prompts.test.js.map +0 -1
  123. package/dist/src/core/subagent.test.d.ts +0 -6
  124. package/dist/src/core/subagent.test.js +0 -510
  125. package/dist/src/core/subagent.test.js.map +0 -1
  126. package/dist/src/core/tokenLimits.test.d.ts +0 -6
  127. package/dist/src/core/tokenLimits.test.js +0 -66
  128. package/dist/src/core/tokenLimits.test.js.map +0 -1
  129. package/dist/src/core/turn.test.d.ts +0 -6
  130. package/dist/src/core/turn.test.js +0 -366
  131. package/dist/src/core/turn.test.js.map +0 -1
  132. package/dist/src/hooks/tool-render-suppression-hook.test.d.ts +0 -6
  133. package/dist/src/hooks/tool-render-suppression-hook.test.js +0 -59
  134. package/dist/src/hooks/tool-render-suppression-hook.test.js.map +0 -1
  135. package/dist/src/ide/ide-installer.test.d.ts +0 -6
  136. package/dist/src/ide/ide-installer.test.js +0 -55
  137. package/dist/src/ide/ide-installer.test.js.map +0 -1
  138. package/dist/src/ide/ideContext.test.d.ts +0 -6
  139. package/dist/src/ide/ideContext.test.js +0 -265
  140. package/dist/src/ide/ideContext.test.js.map +0 -1
  141. package/dist/src/index.test.d.ts +0 -6
  142. package/dist/src/index.test.js +0 -12
  143. package/dist/src/index.test.js.map +0 -1
  144. package/dist/src/integration-tests/oauth-integration.spec.d.ts +0 -6
  145. package/dist/src/integration-tests/oauth-integration.spec.js +0 -518
  146. package/dist/src/integration-tests/oauth-integration.spec.js.map +0 -1
  147. package/dist/src/integration-tests/oauth-simple-test.spec.d.ts +0 -1
  148. package/dist/src/integration-tests/oauth-simple-test.spec.js +0 -88
  149. package/dist/src/integration-tests/oauth-simple-test.spec.js.map +0 -1
  150. package/dist/src/integration-tests/todo-system.test.d.ts +0 -6
  151. package/dist/src/integration-tests/todo-system.test.js +0 -46
  152. package/dist/src/integration-tests/todo-system.test.js.map +0 -1
  153. package/dist/src/mcp/google-auth-provider.test.d.ts +0 -6
  154. package/dist/src/mcp/google-auth-provider.test.js +0 -54
  155. package/dist/src/mcp/google-auth-provider.test.js.map +0 -1
  156. package/dist/src/mcp/oauth-provider.test.d.ts +0 -6
  157. package/dist/src/mcp/oauth-provider.test.js +0 -602
  158. package/dist/src/mcp/oauth-provider.test.js.map +0 -1
  159. package/dist/src/mcp/oauth-token-storage.test.d.ts +0 -6
  160. package/dist/src/mcp/oauth-token-storage.test.js +0 -205
  161. package/dist/src/mcp/oauth-token-storage.test.js.map +0 -1
  162. package/dist/src/mcp/oauth-utils.test.d.ts +0 -6
  163. package/dist/src/mcp/oauth-utils.test.js +0 -144
  164. package/dist/src/mcp/oauth-utils.test.js.map +0 -1
  165. package/dist/src/parsers/TextToolCallParser.multibyte.test.d.ts +0 -1
  166. package/dist/src/parsers/TextToolCallParser.multibyte.test.js +0 -42
  167. package/dist/src/parsers/TextToolCallParser.multibyte.test.js.map +0 -1
  168. package/dist/src/parsers/TextToolCallParser.test.d.ts +0 -1
  169. package/dist/src/parsers/TextToolCallParser.test.js +0 -225
  170. package/dist/src/parsers/TextToolCallParser.test.js.map +0 -1
  171. package/dist/src/prompt-config/TemplateEngine.test.d.ts +0 -1
  172. package/dist/src/prompt-config/TemplateEngine.test.js +0 -494
  173. package/dist/src/prompt-config/TemplateEngine.test.js.map +0 -1
  174. package/dist/src/prompt-config/prompt-cache.test.d.ts +0 -6
  175. package/dist/src/prompt-config/prompt-cache.test.js +0 -437
  176. package/dist/src/prompt-config/prompt-cache.test.js.map +0 -1
  177. package/dist/src/prompt-config/prompt-installer.test.d.ts +0 -7
  178. package/dist/src/prompt-config/prompt-installer.test.js +0 -503
  179. package/dist/src/prompt-config/prompt-installer.test.js.map +0 -1
  180. package/dist/src/prompt-config/prompt-loader.test.d.ts +0 -5
  181. package/dist/src/prompt-config/prompt-loader.test.js +0 -413
  182. package/dist/src/prompt-config/prompt-loader.test.js.map +0 -1
  183. package/dist/src/prompt-config/prompt-resolver.test.d.ts +0 -1
  184. package/dist/src/prompt-config/prompt-resolver.test.js +0 -529
  185. package/dist/src/prompt-config/prompt-resolver.test.js.map +0 -1
  186. package/dist/src/prompt-config/prompt-service.test.d.ts +0 -1
  187. package/dist/src/prompt-config/prompt-service.test.js +0 -811
  188. package/dist/src/prompt-config/prompt-service.test.js.map +0 -1
  189. package/dist/src/providers/BaseProvider.test.d.ts +0 -6
  190. package/dist/src/providers/BaseProvider.test.js +0 -472
  191. package/dist/src/providers/BaseProvider.test.js.map +0 -1
  192. package/dist/src/providers/ProviderManager.gemini-switch.test.d.ts +0 -6
  193. package/dist/src/providers/ProviderManager.gemini-switch.test.js +0 -57
  194. package/dist/src/providers/ProviderManager.gemini-switch.test.js.map +0 -1
  195. package/dist/src/providers/ProviderManager.test.d.ts +0 -6
  196. package/dist/src/providers/ProviderManager.test.js +0 -284
  197. package/dist/src/providers/ProviderManager.test.js.map +0 -1
  198. package/dist/src/providers/adapters/GeminiCompatibleWrapper.test.d.ts +0 -6
  199. package/dist/src/providers/adapters/GeminiCompatibleWrapper.test.js +0 -273
  200. package/dist/src/providers/adapters/GeminiCompatibleWrapper.test.js.map +0 -1
  201. package/dist/src/providers/anthropic/AnthropicProvider.modelParams.test.d.ts +0 -1
  202. package/dist/src/providers/anthropic/AnthropicProvider.modelParams.test.js +0 -48
  203. package/dist/src/providers/anthropic/AnthropicProvider.modelParams.test.js.map +0 -1
  204. package/dist/src/providers/anthropic/AnthropicProvider.test.d.ts +0 -1
  205. package/dist/src/providers/anthropic/AnthropicProvider.test.js +0 -487
  206. package/dist/src/providers/anthropic/AnthropicProvider.test.js.map +0 -1
  207. package/dist/src/providers/gemini/GeminiProvider.integration.test.d.ts +0 -6
  208. package/dist/src/providers/gemini/GeminiProvider.integration.test.js +0 -126
  209. package/dist/src/providers/gemini/GeminiProvider.integration.test.js.map +0 -1
  210. package/dist/src/providers/gemini/GeminiProvider.test.d.ts +0 -6
  211. package/dist/src/providers/gemini/GeminiProvider.test.js +0 -136
  212. package/dist/src/providers/gemini/GeminiProvider.test.js.map +0 -1
  213. package/dist/src/providers/integration/multi-provider.integration.test.d.ts +0 -6
  214. package/dist/src/providers/integration/multi-provider.integration.test.js +0 -308
  215. package/dist/src/providers/integration/multi-provider.integration.test.js.map +0 -1
  216. package/dist/src/providers/openai/ConversationCache.accumTokens.test.d.ts +0 -1
  217. package/dist/src/providers/openai/ConversationCache.accumTokens.test.js +0 -97
  218. package/dist/src/providers/openai/ConversationCache.accumTokens.test.js.map +0 -1
  219. package/dist/src/providers/openai/ConversationCache.test.d.ts +0 -1
  220. package/dist/src/providers/openai/ConversationCache.test.js +0 -113
  221. package/dist/src/providers/openai/ConversationCache.test.js.map +0 -1
  222. package/dist/src/providers/openai/OpenAIProvider.callResponses.stateless.test.d.ts +0 -1
  223. package/dist/src/providers/openai/OpenAIProvider.callResponses.stateless.test.js +0 -189
  224. package/dist/src/providers/openai/OpenAIProvider.callResponses.stateless.test.js.map +0 -1
  225. package/dist/src/providers/openai/OpenAIProvider.integration.test.d.ts +0 -6
  226. package/dist/src/providers/openai/OpenAIProvider.integration.test.js +0 -125
  227. package/dist/src/providers/openai/OpenAIProvider.integration.test.js.map +0 -1
  228. package/dist/src/providers/openai/OpenAIProvider.responses.test.d.ts +0 -1
  229. package/dist/src/providers/openai/OpenAIProvider.responses.test.js +0 -350
  230. package/dist/src/providers/openai/OpenAIProvider.responses.test.js.map +0 -1
  231. package/dist/src/providers/openai/OpenAIProvider.responsesIntegration.test.d.ts +0 -1
  232. package/dist/src/providers/openai/OpenAIProvider.responsesIntegration.test.js +0 -213
  233. package/dist/src/providers/openai/OpenAIProvider.responsesIntegration.test.js.map +0 -1
  234. package/dist/src/providers/openai/OpenAIProvider.shouldUseResponses.test.d.ts +0 -1
  235. package/dist/src/providers/openai/OpenAIProvider.shouldUseResponses.test.js +0 -59
  236. package/dist/src/providers/openai/OpenAIProvider.shouldUseResponses.test.js.map +0 -1
  237. package/dist/src/providers/openai/OpenAIProvider.stateful.integration.test.d.ts +0 -6
  238. package/dist/src/providers/openai/OpenAIProvider.stateful.integration.test.js +0 -105
  239. package/dist/src/providers/openai/OpenAIProvider.stateful.integration.test.js.map +0 -1
  240. package/dist/src/providers/openai/OpenAIProvider.switch.test.d.ts +0 -1
  241. package/dist/src/providers/openai/OpenAIProvider.switch.test.js +0 -256
  242. package/dist/src/providers/openai/OpenAIProvider.switch.test.js.map +0 -1
  243. package/dist/src/providers/openai/OpenAIProvider.test.d.ts +0 -16
  244. package/dist/src/providers/openai/OpenAIProvider.test.js +0 -621
  245. package/dist/src/providers/openai/OpenAIProvider.test.js.map +0 -1
  246. package/dist/src/providers/openai/ResponsesContextTrim.integration.test.d.ts +0 -1
  247. package/dist/src/providers/openai/ResponsesContextTrim.integration.test.js +0 -210
  248. package/dist/src/providers/openai/ResponsesContextTrim.integration.test.js.map +0 -1
  249. package/dist/src/providers/openai/__tests__/formatArrayResponse.test.d.ts +0 -1
  250. package/dist/src/providers/openai/__tests__/formatArrayResponse.test.js +0 -65
  251. package/dist/src/providers/openai/__tests__/formatArrayResponse.test.js.map +0 -1
  252. package/dist/src/providers/openai/buildResponsesRequest.stripToolCalls.test.d.ts +0 -1
  253. package/dist/src/providers/openai/buildResponsesRequest.stripToolCalls.test.js +0 -129
  254. package/dist/src/providers/openai/buildResponsesRequest.stripToolCalls.test.js.map +0 -1
  255. package/dist/src/providers/openai/buildResponsesRequest.test.d.ts +0 -1
  256. package/dist/src/providers/openai/buildResponsesRequest.test.js +0 -406
  257. package/dist/src/providers/openai/buildResponsesRequest.test.js.map +0 -1
  258. package/dist/src/providers/openai/buildResponsesRequest.undefined.test.d.ts +0 -1
  259. package/dist/src/providers/openai/buildResponsesRequest.undefined.test.js +0 -50
  260. package/dist/src/providers/openai/buildResponsesRequest.undefined.test.js.map +0 -1
  261. package/dist/src/providers/openai/estimateRemoteTokens.test.d.ts +0 -1
  262. package/dist/src/providers/openai/estimateRemoteTokens.test.js +0 -125
  263. package/dist/src/providers/openai/estimateRemoteTokens.test.js.map +0 -1
  264. package/dist/src/providers/openai/openai-oauth.spec.d.ts +0 -16
  265. package/dist/src/providers/openai/openai-oauth.spec.js +0 -544
  266. package/dist/src/providers/openai/openai-oauth.spec.js.map +0 -1
  267. package/dist/src/providers/openai/parseResponsesStream.responsesToolCalls.test.d.ts +0 -1
  268. package/dist/src/providers/openai/parseResponsesStream.responsesToolCalls.test.js +0 -192
  269. package/dist/src/providers/openai/parseResponsesStream.responsesToolCalls.test.js.map +0 -1
  270. package/dist/src/providers/openai/parseResponsesStream.test.d.ts +0 -1
  271. package/dist/src/providers/openai/parseResponsesStream.test.js +0 -151
  272. package/dist/src/providers/openai/parseResponsesStream.test.js.map +0 -1
  273. package/dist/src/services/fileDiscoveryService.test.d.ts +0 -6
  274. package/dist/src/services/fileDiscoveryService.test.js +0 -143
  275. package/dist/src/services/fileDiscoveryService.test.js.map +0 -1
  276. package/dist/src/services/gitService.test.d.ts +0 -6
  277. package/dist/src/services/gitService.test.js +0 -209
  278. package/dist/src/services/gitService.test.js.map +0 -1
  279. package/dist/src/services/loopDetectionService.test.d.ts +0 -6
  280. package/dist/src/services/loopDetectionService.test.js +0 -484
  281. package/dist/src/services/loopDetectionService.test.js.map +0 -1
  282. package/dist/src/services/shellExecutionService.multibyte.test.d.ts +0 -6
  283. package/dist/src/services/shellExecutionService.multibyte.test.js +0 -72
  284. package/dist/src/services/shellExecutionService.multibyte.test.js.map +0 -1
  285. package/dist/src/services/shellExecutionService.test.d.ts +0 -6
  286. package/dist/src/services/shellExecutionService.test.js +0 -272
  287. package/dist/src/services/shellExecutionService.test.js.map +0 -1
  288. package/dist/src/services/shellExecutionService.windows.multibyte.test.d.ts +0 -6
  289. package/dist/src/services/shellExecutionService.windows.multibyte.test.js +0 -98
  290. package/dist/src/services/shellExecutionService.windows.multibyte.test.js.map +0 -1
  291. package/dist/src/services/shellExecutionService.windows.test.d.ts +0 -6
  292. package/dist/src/services/shellExecutionService.windows.test.js +0 -79
  293. package/dist/src/services/shellExecutionService.windows.test.js.map +0 -1
  294. package/dist/src/services/tool-call-tracker-service.test.d.ts +0 -6
  295. package/dist/src/services/tool-call-tracker-service.test.js +0 -99
  296. package/dist/src/services/tool-call-tracker-service.test.js.map +0 -1
  297. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.d.ts +0 -6
  298. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.js +0 -187
  299. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.js.map +0 -1
  300. package/dist/src/telemetry/loggers.test.d.ts +0 -6
  301. package/dist/src/telemetry/loggers.test.js +0 -573
  302. package/dist/src/telemetry/loggers.test.js.map +0 -1
  303. package/dist/src/telemetry/metrics.test.d.ts +0 -6
  304. package/dist/src/telemetry/metrics.test.js +0 -212
  305. package/dist/src/telemetry/metrics.test.js.map +0 -1
  306. package/dist/src/telemetry/telemetry.test.d.ts +0 -6
  307. package/dist/src/telemetry/telemetry.test.js +0 -54
  308. package/dist/src/telemetry/telemetry.test.js.map +0 -1
  309. package/dist/src/telemetry/uiTelemetry.test.d.ts +0 -6
  310. package/dist/src/telemetry/uiTelemetry.test.js +0 -518
  311. package/dist/src/telemetry/uiTelemetry.test.js.map +0 -1
  312. package/dist/src/tools/ToolFormatter.test.d.ts +0 -16
  313. package/dist/src/tools/ToolFormatter.test.js +0 -349
  314. package/dist/src/tools/ToolFormatter.test.js.map +0 -1
  315. package/dist/src/tools/ToolFormatter.toResponsesTool.test.d.ts +0 -1
  316. package/dist/src/tools/ToolFormatter.toResponsesTool.test.js +0 -241
  317. package/dist/src/tools/ToolFormatter.toResponsesTool.test.js.map +0 -1
  318. package/dist/src/tools/diffOptions.test.d.ts +0 -6
  319. package/dist/src/tools/diffOptions.test.js +0 -119
  320. package/dist/src/tools/diffOptions.test.js.map +0 -1
  321. package/dist/src/tools/edit.test.d.ts +0 -6
  322. package/dist/src/tools/edit.test.js +0 -689
  323. package/dist/src/tools/edit.test.js.map +0 -1
  324. package/dist/src/tools/glob.test.d.ts +0 -6
  325. package/dist/src/tools/glob.test.js +0 -332
  326. package/dist/src/tools/glob.test.js.map +0 -1
  327. package/dist/src/tools/grep.test.d.ts +0 -6
  328. package/dist/src/tools/grep.test.js +0 -272
  329. package/dist/src/tools/grep.test.js.map +0 -1
  330. package/dist/src/tools/ls.test.d.ts +0 -6
  331. package/dist/src/tools/ls.test.js +0 -357
  332. package/dist/src/tools/ls.test.js.map +0 -1
  333. package/dist/src/tools/mcp-client.test.d.ts +0 -6
  334. package/dist/src/tools/mcp-client.test.js +0 -617
  335. package/dist/src/tools/mcp-client.test.js.map +0 -1
  336. package/dist/src/tools/mcp-tool.test.d.ts +0 -6
  337. package/dist/src/tools/mcp-tool.test.js +0 -501
  338. package/dist/src/tools/mcp-tool.test.js.map +0 -1
  339. package/dist/src/tools/memoryTool.test.d.ts +0 -6
  340. package/dist/src/tools/memoryTool.test.js +0 -266
  341. package/dist/src/tools/memoryTool.test.js.map +0 -1
  342. package/dist/src/tools/modifiable-tool.test.d.ts +0 -6
  343. package/dist/src/tools/modifiable-tool.test.js +0 -193
  344. package/dist/src/tools/modifiable-tool.test.js.map +0 -1
  345. package/dist/src/tools/read-file.test.d.ts +0 -6
  346. package/dist/src/tools/read-file.test.js +0 -319
  347. package/dist/src/tools/read-file.test.js.map +0 -1
  348. package/dist/src/tools/read-many-files.test.d.ts +0 -6
  349. package/dist/src/tools/read-many-files.test.js +0 -644
  350. package/dist/src/tools/read-many-files.test.js.map +0 -1
  351. package/dist/src/tools/shell.multibyte.test.d.ts +0 -6
  352. package/dist/src/tools/shell.multibyte.test.js +0 -75
  353. package/dist/src/tools/shell.multibyte.test.js.map +0 -1
  354. package/dist/src/tools/shell.test.d.ts +0 -6
  355. package/dist/src/tools/shell.test.js +0 -367
  356. package/dist/src/tools/shell.test.js.map +0 -1
  357. package/dist/src/tools/todo-pause.spec.d.ts +0 -6
  358. package/dist/src/tools/todo-pause.spec.js +0 -287
  359. package/dist/src/tools/todo-pause.spec.js.map +0 -1
  360. package/dist/src/tools/todo-read.test.d.ts +0 -6
  361. package/dist/src/tools/todo-read.test.js +0 -162
  362. package/dist/src/tools/todo-read.test.js.map +0 -1
  363. package/dist/src/tools/todo-schemas.test.d.ts +0 -6
  364. package/dist/src/tools/todo-schemas.test.js +0 -341
  365. package/dist/src/tools/todo-schemas.test.js.map +0 -1
  366. package/dist/src/tools/todo-store.test.d.ts +0 -6
  367. package/dist/src/tools/todo-store.test.js +0 -169
  368. package/dist/src/tools/todo-store.test.js.map +0 -1
  369. package/dist/src/tools/todo-write.test.d.ts +0 -6
  370. package/dist/src/tools/todo-write.test.js +0 -226
  371. package/dist/src/tools/todo-write.test.js.map +0 -1
  372. package/dist/src/tools/tool-registry.test.d.ts +0 -6
  373. package/dist/src/tools/tool-registry.test.js +0 -468
  374. package/dist/src/tools/tool-registry.test.js.map +0 -1
  375. package/dist/src/tools/tools.test.d.ts +0 -6
  376. package/dist/src/tools/tools.test.js +0 -117
  377. package/dist/src/tools/tools.test.js.map +0 -1
  378. package/dist/src/tools/web-fetch.integration.test.d.ts +0 -6
  379. package/dist/src/tools/web-fetch.integration.test.js +0 -532
  380. package/dist/src/tools/web-fetch.integration.test.js.map +0 -1
  381. package/dist/src/tools/web-search.test.d.ts +0 -6
  382. package/dist/src/tools/web-search.test.js +0 -230
  383. package/dist/src/tools/web-search.test.js.map +0 -1
  384. package/dist/src/tools/write-file.test.d.ts +0 -6
  385. package/dist/src/tools/write-file.test.js +0 -465
  386. package/dist/src/tools/write-file.test.js.map +0 -1
  387. package/dist/src/utils/bfsFileSearch.test.d.ts +0 -6
  388. package/dist/src/utils/bfsFileSearch.test.js +0 -191
  389. package/dist/src/utils/bfsFileSearch.test.js.map +0 -1
  390. package/dist/src/utils/editCorrector.test.d.ts +0 -6
  391. package/dist/src/utils/editCorrector.test.js +0 -564
  392. package/dist/src/utils/editCorrector.test.js.map +0 -1
  393. package/dist/src/utils/editor.test.d.ts +0 -6
  394. package/dist/src/utils/editor.test.js +0 -445
  395. package/dist/src/utils/editor.test.js.map +0 -1
  396. package/dist/src/utils/environmentContext.test.d.ts +0 -6
  397. package/dist/src/utils/environmentContext.test.js +0 -139
  398. package/dist/src/utils/environmentContext.test.js.map +0 -1
  399. package/dist/src/utils/errorReporting.test.d.ts +0 -6
  400. package/dist/src/utils/errorReporting.test.js +0 -130
  401. package/dist/src/utils/errorReporting.test.js.map +0 -1
  402. package/dist/src/utils/fileUtils.test.d.ts +0 -6
  403. package/dist/src/utils/fileUtils.test.js +0 -363
  404. package/dist/src/utils/fileUtils.test.js.map +0 -1
  405. package/dist/src/utils/filesearch/crawlCache.test.d.ts +0 -6
  406. package/dist/src/utils/filesearch/crawlCache.test.js +0 -103
  407. package/dist/src/utils/filesearch/crawlCache.test.js.map +0 -1
  408. package/dist/src/utils/filesearch/fileSearch.test.d.ts +0 -6
  409. package/dist/src/utils/filesearch/fileSearch.test.js +0 -654
  410. package/dist/src/utils/filesearch/fileSearch.test.js.map +0 -1
  411. package/dist/src/utils/filesearch/ignore.test.d.ts +0 -6
  412. package/dist/src/utils/filesearch/ignore.test.js +0 -57
  413. package/dist/src/utils/filesearch/ignore.test.js.map +0 -1
  414. package/dist/src/utils/filesearch/result-cache.test.d.ts +0 -6
  415. package/dist/src/utils/filesearch/result-cache.test.js +0 -47
  416. package/dist/src/utils/filesearch/result-cache.test.js.map +0 -1
  417. package/dist/src/utils/flashFallback.integration.test.d.ts +0 -6
  418. package/dist/src/utils/flashFallback.integration.test.js +0 -120
  419. package/dist/src/utils/flashFallback.integration.test.js.map +0 -1
  420. package/dist/src/utils/generateContentResponseUtilities.test.d.ts +0 -6
  421. package/dist/src/utils/generateContentResponseUtilities.test.js +0 -273
  422. package/dist/src/utils/generateContentResponseUtilities.test.js.map +0 -1
  423. package/dist/src/utils/getFolderStructure.test.d.ts +0 -6
  424. package/dist/src/utils/getFolderStructure.test.js +0 -282
  425. package/dist/src/utils/getFolderStructure.test.js.map +0 -1
  426. package/dist/src/utils/gitIgnoreParser.test.d.ts +0 -6
  427. package/dist/src/utils/gitIgnoreParser.test.js +0 -154
  428. package/dist/src/utils/gitIgnoreParser.test.js.map +0 -1
  429. package/dist/src/utils/memoryDiscovery.test.d.ts +0 -6
  430. package/dist/src/utils/memoryDiscovery.test.js +0 -181
  431. package/dist/src/utils/memoryDiscovery.test.js.map +0 -1
  432. package/dist/src/utils/memoryImportProcessor.test.d.ts +0 -6
  433. package/dist/src/utils/memoryImportProcessor.test.js +0 -715
  434. package/dist/src/utils/memoryImportProcessor.test.js.map +0 -1
  435. package/dist/src/utils/nextSpeakerChecker.test.d.ts +0 -6
  436. package/dist/src/utils/nextSpeakerChecker.test.js +0 -172
  437. package/dist/src/utils/nextSpeakerChecker.test.js.map +0 -1
  438. package/dist/src/utils/partUtils.test.d.ts +0 -6
  439. package/dist/src/utils/partUtils.test.js +0 -130
  440. package/dist/src/utils/partUtils.test.js.map +0 -1
  441. package/dist/src/utils/paths.test.d.ts +0 -6
  442. package/dist/src/utils/paths.test.js +0 -153
  443. package/dist/src/utils/paths.test.js.map +0 -1
  444. package/dist/src/utils/retry.test.d.ts +0 -6
  445. package/dist/src/utils/retry.test.js +0 -322
  446. package/dist/src/utils/retry.test.js.map +0 -1
  447. package/dist/src/utils/safeJsonStringify.test.d.ts +0 -6
  448. package/dist/src/utils/safeJsonStringify.test.js +0 -61
  449. package/dist/src/utils/safeJsonStringify.test.js.map +0 -1
  450. package/dist/src/utils/sanitization.test.d.ts +0 -6
  451. package/dist/src/utils/sanitization.test.js +0 -81
  452. package/dist/src/utils/sanitization.test.js.map +0 -1
  453. package/dist/src/utils/schemaValidator.test.d.ts +0 -6
  454. package/dist/src/utils/schemaValidator.test.js +0 -146
  455. package/dist/src/utils/schemaValidator.test.js.map +0 -1
  456. package/dist/src/utils/secure-browser-launcher.test.d.ts +0 -6
  457. package/dist/src/utils/secure-browser-launcher.test.js +0 -149
  458. package/dist/src/utils/secure-browser-launcher.test.js.map +0 -1
  459. package/dist/src/utils/shell-utils.shellReplacement.test.d.ts +0 -6
  460. package/dist/src/utils/shell-utils.shellReplacement.test.js +0 -149
  461. package/dist/src/utils/shell-utils.shellReplacement.test.js.map +0 -1
  462. package/dist/src/utils/shell-utils.test.d.ts +0 -6
  463. package/dist/src/utils/shell-utils.test.js +0 -200
  464. package/dist/src/utils/shell-utils.test.js.map +0 -1
  465. package/dist/src/utils/summarizer.test.d.ts +0 -6
  466. package/dist/src/utils/summarizer.test.js +0 -131
  467. package/dist/src/utils/summarizer.test.js.map +0 -1
  468. package/dist/src/utils/systemEncoding.test.d.ts +0 -6
  469. package/dist/src/utils/systemEncoding.test.js +0 -368
  470. package/dist/src/utils/systemEncoding.test.js.map +0 -1
  471. package/dist/src/utils/toolOutputLimiter.test.d.ts +0 -6
  472. package/dist/src/utils/toolOutputLimiter.test.js +0 -164
  473. package/dist/src/utils/toolOutputLimiter.test.js.map +0 -1
  474. package/dist/src/utils/unicodeUtils.test.d.ts +0 -6
  475. package/dist/src/utils/unicodeUtils.test.js +0 -120
  476. package/dist/src/utils/unicodeUtils.test.js.map +0 -1
  477. package/dist/src/utils/user_account.test.d.ts +0 -6
  478. package/dist/src/utils/user_account.test.js +0 -153
  479. package/dist/src/utils/user_account.test.js.map +0 -1
  480. package/dist/src/utils/user_id.test.d.ts +0 -6
  481. package/dist/src/utils/user_id.test.js +0 -21
  482. package/dist/src/utils/user_id.test.js.map +0 -1
  483. package/dist/src/utils/workspaceContext.test.d.ts +0 -6
  484. package/dist/src/utils/workspaceContext.test.js +0 -209
  485. package/dist/src/utils/workspaceContext.test.js.map +0 -1
@@ -1,1323 +0,0 @@
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
- // Mock prompts module before imports
8
- vi.mock('./prompts.js', () => ({
9
- getCoreSystemPromptAsync: vi
10
- .fn()
11
- .mockResolvedValue('Test system instruction'),
12
- getCompressionPrompt: vi.fn().mockReturnValue('Test compression prompt'),
13
- initializePromptSystem: vi.fn().mockResolvedValue(undefined),
14
- }));
15
- import { GoogleGenAI, } from '@google/genai';
16
- import { findIndexAfterFraction, GeminiClient } from './client.js';
17
- import { getCoreSystemPromptAsync } from './prompts.js';
18
- import { AuthType, } from './contentGenerator.js';
19
- import { Config } from '../config/config.js';
20
- import { GeminiEventType, Turn } from './turn.js';
21
- import { DEFAULT_GEMINI_FLASH_MODEL } from '../config/models.js';
22
- import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
23
- import { setSimulate429 } from '../utils/testUtils.js';
24
- import { tokenLimit } from './tokenLimits.js';
25
- import { ideContext } from '../ide/ideContext.js';
26
- import { ComplexityAnalyzer } from '../services/complexity-analyzer.js';
27
- import { TodoReminderService } from '../services/todo-reminder-service.js';
28
- // --- Mocks ---
29
- const mockChatCreateFn = vi.fn();
30
- const mockGenerateContentFn = vi.fn();
31
- const mockEmbedContentFn = vi.fn();
32
- const mockTurnRunFn = vi.fn();
33
- vi.mock('@google/genai');
34
- vi.mock('../services/complexity-analyzer.js', () => ({
35
- ComplexityAnalyzer: vi.fn().mockImplementation(() => ({
36
- analyzeComplexity: vi.fn().mockReturnValue({
37
- complexityScore: 0.2,
38
- isComplex: false,
39
- detectedTasks: [],
40
- sequentialIndicators: [],
41
- questionCount: 0,
42
- shouldSuggestTodos: false,
43
- }),
44
- })),
45
- }));
46
- vi.mock('../services/todo-reminder-service.js', () => ({
47
- TodoReminderService: vi.fn().mockImplementation(() => ({
48
- getComplexTaskSuggestion: vi.fn(),
49
- })),
50
- }));
51
- vi.mock('./turn', () => {
52
- // Define a mock class that has the same shape as the real Turn
53
- class MockTurn {
54
- pendingToolCalls = [];
55
- // The run method is a property that holds our mock function
56
- run = mockTurnRunFn;
57
- constructor() {
58
- // The constructor can be empty or do some mock setup
59
- }
60
- }
61
- // Export the mock class as 'Turn'
62
- return {
63
- Turn: MockTurn,
64
- GeminiEventType: {
65
- MaxSessionTurns: 'MaxSessionTurns',
66
- ChatCompressed: 'ChatCompressed',
67
- },
68
- };
69
- });
70
- vi.mock('../config/config.js');
71
- vi.mock('../utils/getFolderStructure', () => ({
72
- getFolderStructure: vi.fn().mockResolvedValue('Mock Folder Structure'),
73
- }));
74
- vi.mock('../utils/errorReporting', () => ({ reportError: vi.fn() }));
75
- vi.mock('../utils/generateContentResponseUtilities', () => ({
76
- getResponseText: (result) => result.candidates?.[0]?.content?.parts?.map((part) => part.text).join('') ||
77
- undefined,
78
- }));
79
- vi.mock('../telemetry/index.js', () => ({
80
- logApiRequest: vi.fn(),
81
- logApiResponse: vi.fn(),
82
- logApiError: vi.fn(),
83
- }));
84
- vi.mock('../utils/retry.js', () => ({
85
- retryWithBackoff: vi.fn((apiCall) => apiCall()),
86
- }));
87
- vi.mock('../ide/ideContext.js');
88
- describe('findIndexAfterFraction', () => {
89
- const history = [
90
- { role: 'user', parts: [{ text: 'This is the first message.' }] }, // JSON length: 66
91
- { role: 'model', parts: [{ text: 'This is the second message.' }] }, // JSON length: 68
92
- { role: 'user', parts: [{ text: 'This is the third message.' }] }, // JSON length: 66
93
- { role: 'model', parts: [{ text: 'This is the fourth message.' }] }, // JSON length: 68
94
- { role: 'user', parts: [{ text: 'This is the fifth message.' }] }, // JSON length: 65
95
- ];
96
- // Total length: 333
97
- it('should throw an error for non-positive numbers', () => {
98
- expect(() => findIndexAfterFraction(history, 0)).toThrow('Fraction must be between 0 and 1');
99
- });
100
- it('should throw an error for a fraction greater than or equal to 1', () => {
101
- expect(() => findIndexAfterFraction(history, 1)).toThrow('Fraction must be between 0 and 1');
102
- });
103
- it('should handle a fraction in the middle', () => {
104
- // 333 * 0.5 = 166.5
105
- // 0: 66
106
- // 1: 66 + 68 = 134
107
- // 2: 134 + 66 = 200
108
- // 200 >= 166.5, so index is 2
109
- expect(findIndexAfterFraction(history, 0.5)).toBe(2);
110
- });
111
- it('should handle a fraction that results in the last index', () => {
112
- // 333 * 0.9 = 299.7
113
- // ...
114
- // 3: 200 + 68 = 268
115
- // 4: 268 + 65 = 333
116
- // 333 >= 299.7, so index is 4
117
- expect(findIndexAfterFraction(history, 0.9)).toBe(4);
118
- });
119
- it('should handle an empty history', () => {
120
- expect(findIndexAfterFraction([], 0.5)).toBe(0);
121
- });
122
- it('should handle a history with only one item', () => {
123
- expect(findIndexAfterFraction(history.slice(0, 1), 0.5)).toBe(0);
124
- });
125
- it('should handle history with weird parts', () => {
126
- const historyWithEmptyParts = [
127
- { role: 'user', parts: [{ text: 'Message 1' }] },
128
- { role: 'model', parts: [{ fileData: { fileUri: 'derp' } }] },
129
- { role: 'user', parts: [{ text: 'Message 2' }] },
130
- ];
131
- expect(findIndexAfterFraction(historyWithEmptyParts, 0.5)).toBe(1);
132
- });
133
- });
134
- describe('Gemini Client (client.ts)', () => {
135
- let client;
136
- beforeEach(async () => {
137
- vi.resetAllMocks();
138
- // Re-setup prompts mocks after reset
139
- vi.mocked(getCoreSystemPromptAsync).mockResolvedValue('Test system instruction');
140
- // Re-setup mocks after reset
141
- vi.mocked(ComplexityAnalyzer).mockImplementation(() => ({
142
- analyzeComplexity: vi.fn().mockReturnValue({
143
- complexityScore: 0.2,
144
- isComplex: false,
145
- detectedTasks: [],
146
- sequentialIndicators: [],
147
- questionCount: 0,
148
- shouldSuggestTodos: false,
149
- }),
150
- }));
151
- vi.mocked(TodoReminderService).mockImplementation(() => ({
152
- getComplexTaskSuggestion: vi.fn(),
153
- }));
154
- // Disable 429 simulation for tests
155
- setSimulate429(false);
156
- // Set up the mock for GoogleGenAI constructor and its methods
157
- const MockedGoogleGenAI = vi.mocked(GoogleGenAI);
158
- MockedGoogleGenAI.mockImplementation((..._args) => {
159
- const mockInstance = {
160
- chats: { create: mockChatCreateFn },
161
- models: {
162
- generateContent: mockGenerateContentFn,
163
- embedContent: mockEmbedContentFn,
164
- },
165
- };
166
- return mockInstance;
167
- });
168
- mockChatCreateFn.mockResolvedValue({});
169
- mockGenerateContentFn.mockResolvedValue({
170
- candidates: [
171
- {
172
- content: {
173
- parts: [{ text: '{"key": "value"}' }],
174
- },
175
- },
176
- ],
177
- });
178
- // Because the GeminiClient constructor kicks off an async process (startChat)
179
- // that depends on a fully-formed Config object, we need to mock the
180
- // entire implementation of Config for these tests.
181
- const mockToolRegistry = {
182
- getFunctionDeclarations: vi.fn().mockReturnValue([]),
183
- getTool: vi.fn().mockReturnValue(null),
184
- };
185
- const fileService = new FileDiscoveryService('/test/dir');
186
- const MockedConfig = vi.mocked(Config, true);
187
- const contentGeneratorConfig = {
188
- model: 'test-model',
189
- apiKey: 'test-key',
190
- vertexai: false,
191
- authType: AuthType.USE_GEMINI,
192
- };
193
- const mockConfigObject = {
194
- getContentGeneratorConfig: vi
195
- .fn()
196
- .mockReturnValue(contentGeneratorConfig),
197
- getToolRegistry: vi.fn().mockResolvedValue(mockToolRegistry),
198
- getModel: vi.fn().mockReturnValue('test-model'),
199
- getEmbeddingModel: vi.fn().mockReturnValue('test-embedding-model'),
200
- getApiKey: vi.fn().mockReturnValue('test-key'),
201
- getVertexAI: vi.fn().mockReturnValue(false),
202
- getUserAgent: vi.fn().mockReturnValue('test-agent'),
203
- getUserMemory: vi.fn().mockReturnValue(''),
204
- getFullContext: vi.fn().mockReturnValue(false),
205
- getSessionId: vi.fn().mockReturnValue('test-session-id'),
206
- getProxy: vi.fn().mockReturnValue(undefined),
207
- getWorkingDir: vi.fn().mockReturnValue('/test/dir'),
208
- getFileService: vi.fn().mockReturnValue(fileService),
209
- getMaxSessionTurns: vi.fn().mockReturnValue(0),
210
- getQuotaErrorOccurred: vi.fn().mockReturnValue(false),
211
- setQuotaErrorOccurred: vi.fn(),
212
- getNoBrowser: vi.fn().mockReturnValue(false),
213
- getUsageStatisticsEnabled: vi.fn().mockReturnValue(true),
214
- getIdeModeFeature: vi.fn().mockReturnValue(false),
215
- getIdeMode: vi.fn().mockReturnValue(true),
216
- getWorkspaceContext: vi.fn().mockReturnValue({
217
- getDirectories: vi.fn().mockReturnValue(['/test/dir']),
218
- }),
219
- getGeminiClient: vi.fn(),
220
- getDebugMode: vi.fn().mockReturnValue(false),
221
- setFallbackMode: vi.fn(),
222
- getComplexityAnalyzerSettings: vi.fn().mockReturnValue({
223
- complexityThreshold: 0.6,
224
- minTasksForSuggestion: 3,
225
- suggestionCooldownMs: 300000,
226
- }),
227
- getChatCompression: vi.fn().mockReturnValue(undefined),
228
- };
229
- MockedConfig.mockImplementation(() => mockConfigObject);
230
- // We can instantiate the client here since Config is mocked
231
- // and the constructor will use the mocked GoogleGenAI
232
- const mockConfig = new Config({
233
- sessionId: 'test-session-id',
234
- });
235
- client = new GeminiClient(mockConfig);
236
- await client.initialize(contentGeneratorConfig);
237
- // Update the mock to return the client
238
- mockConfigObject.getGeminiClient.mockReturnValue(client);
239
- // Add missing methods to the client instance for tests
240
- client.getHistory = vi.fn().mockReturnValue([]);
241
- });
242
- afterEach(() => {
243
- vi.restoreAllMocks();
244
- });
245
- // NOTE: The following tests for startChat were removed due to persistent issues with
246
- // the @google/genai mock. Specifically, the mockChatCreateFn (representing instance.chats.create)
247
- // was not being detected as called by the GeminiClient instance.
248
- // This likely points to a subtle issue in how the GoogleGenerativeAI class constructor
249
- // and its instance methods are mocked and then used by the class under test.
250
- // For future debugging, ensure that the `this.client` in `GeminiClient` (which is an
251
- // instance of the mocked GoogleGenerativeAI) correctly has its `chats.create` method
252
- // pointing to `mockChatCreateFn`.
253
- // it('startChat should call getCoreSystemPrompt with userMemory and pass to chats.create', async () => { ... });
254
- // it('startChat should call getCoreSystemPrompt with empty string if userMemory is empty', async () => { ... });
255
- // NOTE: The following tests for generateJson were removed due to persistent issues with
256
- // the @google/genai mock, similar to the startChat tests. The mockGenerateContentFn
257
- // (representing instance.models.generateContent) was not being detected as called, or the mock
258
- // was not preventing an actual API call (leading to API key errors).
259
- // For future debugging, ensure `this.client.models.generateContent` in `GeminiClient` correctly
260
- // uses the `mockGenerateContentFn`.
261
- // it('generateJson should call getCoreSystemPrompt with userMemory and pass to generateContent', async () => { ... });
262
- // it('generateJson should call getCoreSystemPrompt with empty string if userMemory is empty', async () => { ... });
263
- describe('generateEmbedding', () => {
264
- const texts = ['hello world', 'goodbye world'];
265
- const testEmbeddingModel = 'test-embedding-model';
266
- it('should call embedContent with correct parameters and return embeddings', async () => {
267
- const mockEmbeddings = [
268
- [0.1, 0.2, 0.3],
269
- [0.4, 0.5, 0.6],
270
- ];
271
- const mockResponse = {
272
- embeddings: [
273
- { values: mockEmbeddings[0] },
274
- { values: mockEmbeddings[1] },
275
- ],
276
- };
277
- mockEmbedContentFn.mockResolvedValue(mockResponse);
278
- const result = await client.generateEmbedding(texts);
279
- expect(mockEmbedContentFn).toHaveBeenCalledTimes(1);
280
- expect(mockEmbedContentFn).toHaveBeenCalledWith({
281
- model: testEmbeddingModel,
282
- contents: texts,
283
- });
284
- expect(result).toEqual(mockEmbeddings);
285
- });
286
- it('should return an empty array if an empty array is passed', async () => {
287
- const result = await client.generateEmbedding([]);
288
- expect(result).toEqual([]);
289
- expect(mockEmbedContentFn).not.toHaveBeenCalled();
290
- });
291
- it('should throw an error if API response has no embeddings array', async () => {
292
- mockEmbedContentFn.mockResolvedValue({}); // No `embeddings` key
293
- await expect(client.generateEmbedding(texts)).rejects.toThrow('No embeddings found in API response.');
294
- });
295
- it('should throw an error if API response has an empty embeddings array', async () => {
296
- const mockResponse = {
297
- embeddings: [],
298
- };
299
- mockEmbedContentFn.mockResolvedValue(mockResponse);
300
- await expect(client.generateEmbedding(texts)).rejects.toThrow('No embeddings found in API response.');
301
- });
302
- it('should throw an error if API returns a mismatched number of embeddings', async () => {
303
- const mockResponse = {
304
- embeddings: [{ values: [1, 2, 3] }], // Only one for two texts
305
- };
306
- mockEmbedContentFn.mockResolvedValue(mockResponse);
307
- await expect(client.generateEmbedding(texts)).rejects.toThrow('API returned a mismatched number of embeddings. Expected 2, got 1.');
308
- });
309
- it('should throw an error if any embedding has nullish values', async () => {
310
- const mockResponse = {
311
- embeddings: [{ values: [1, 2, 3] }, { values: undefined }], // Second one is bad
312
- };
313
- mockEmbedContentFn.mockResolvedValue(mockResponse);
314
- await expect(client.generateEmbedding(texts)).rejects.toThrow('API returned an empty embedding for input text at index 1: "goodbye world"');
315
- });
316
- it('should throw an error if any embedding has an empty values array', async () => {
317
- const mockResponse = {
318
- embeddings: [{ values: [] }, { values: [1, 2, 3] }], // First one is bad
319
- };
320
- mockEmbedContentFn.mockResolvedValue(mockResponse);
321
- await expect(client.generateEmbedding(texts)).rejects.toThrow('API returned an empty embedding for input text at index 0: "hello world"');
322
- });
323
- it('should propagate errors from the API call', async () => {
324
- const apiError = new Error('API Failure');
325
- mockEmbedContentFn.mockRejectedValue(apiError);
326
- await expect(client.generateEmbedding(texts)).rejects.toThrow('API Failure');
327
- });
328
- });
329
- describe('generateContent', () => {
330
- it('should call generateContent with the correct parameters', async () => {
331
- const contents = [{ role: 'user', parts: [{ text: 'hello' }] }];
332
- const generationConfig = { temperature: 0.5 };
333
- const abortSignal = new AbortController().signal;
334
- // Mock the retryWithBackoff to directly call the apiCall function
335
- vi.mock('../utils/retry.js', () => ({
336
- retryWithBackoff: vi.fn((apiCall) => apiCall()),
337
- }));
338
- // Mock countTokens with a fresh mock function
339
- const mockContentGeneratorGenerateContent = vi.fn().mockResolvedValue({
340
- candidates: [
341
- {
342
- content: {
343
- parts: [{ text: 'response' }],
344
- },
345
- },
346
- ],
347
- });
348
- const mockGenerator = {
349
- countTokens: vi.fn().mockResolvedValue({ totalTokens: 1 }),
350
- generateContent: mockContentGeneratorGenerateContent,
351
- generateContentStream: vi.fn(),
352
- embedContent: vi.fn(),
353
- };
354
- client['contentGenerator'] = mockGenerator;
355
- client['isInitialized'] = vi.fn().mockReturnValue(true);
356
- const { retryWithBackoff } = await import('../utils/retry.js');
357
- vi.mocked(retryWithBackoff).mockImplementation(async (apiCall) => await apiCall());
358
- await client.generateContent(contents, generationConfig, abortSignal);
359
- expect(mockContentGeneratorGenerateContent).toHaveBeenCalledWith({
360
- model: 'test-model',
361
- config: {
362
- abortSignal,
363
- systemInstruction: 'Test system instruction',
364
- temperature: 0.5,
365
- topP: 1,
366
- },
367
- contents,
368
- }, 'test-session-id');
369
- });
370
- });
371
- describe('generateJson', () => {
372
- it('should call generateContent with the correct parameters', async () => {
373
- const contents = [{ role: 'user', parts: [{ text: 'hello' }] }];
374
- const schema = { type: 'string' };
375
- const abortSignal = new AbortController().signal;
376
- // Mock lazyInitialize to prevent it from overriding our mock
377
- client['lazyInitialize'] = vi.fn().mockResolvedValue(undefined);
378
- // Track the arguments manually
379
- let capturedRequest;
380
- let capturedPromptId;
381
- const mockGenerator = {
382
- countTokens: vi.fn().mockResolvedValue({ totalTokens: 1 }),
383
- generateContent: vi.fn(async (request, promptId) => {
384
- capturedRequest = request;
385
- capturedPromptId = promptId;
386
- return {
387
- candidates: [
388
- {
389
- content: {
390
- parts: [{ text: '{"key": "value"}' }],
391
- },
392
- },
393
- ],
394
- };
395
- }),
396
- generateContentStream: vi.fn(),
397
- embedContent: vi.fn(),
398
- };
399
- client['contentGenerator'] = mockGenerator;
400
- try {
401
- await client.generateJson(contents, schema, abortSignal);
402
- }
403
- catch (error) {
404
- console.error('Error in generateJson:', error);
405
- throw error;
406
- }
407
- // Check the captured arguments
408
- expect(capturedRequest).toBeDefined();
409
- expect(capturedPromptId).toBe('test-session-id');
410
- expect(capturedRequest).toMatchObject({
411
- model: 'test-model', // Should use current model from config
412
- config: {
413
- abortSignal,
414
- systemInstruction: 'Test system instruction',
415
- temperature: 0,
416
- topP: 1,
417
- responseSchema: schema,
418
- responseMimeType: 'application/json',
419
- },
420
- contents,
421
- });
422
- });
423
- it('should allow overriding model and config', async () => {
424
- const contents = [{ role: 'user', parts: [{ text: 'hello' }] }];
425
- const schema = { type: 'string' };
426
- const abortSignal = new AbortController().signal;
427
- const customModel = 'custom-json-model';
428
- const customConfig = { temperature: 0.9, topK: 20 };
429
- // Mock lazyInitialize to prevent it from overriding our mock
430
- client['lazyInitialize'] = vi.fn().mockResolvedValue(undefined);
431
- // Track the arguments manually
432
- let capturedRequest;
433
- let capturedPromptId;
434
- const mockGenerator = {
435
- countTokens: vi.fn().mockResolvedValue({ totalTokens: 1 }),
436
- generateContent: vi.fn(async (request, promptId) => {
437
- capturedRequest = request;
438
- capturedPromptId = promptId;
439
- return {
440
- candidates: [
441
- {
442
- content: {
443
- parts: [{ text: '{"key": "value"}' }],
444
- },
445
- },
446
- ],
447
- };
448
- }),
449
- };
450
- client['contentGenerator'] = mockGenerator;
451
- await client.generateJson(contents, schema, abortSignal, customModel, customConfig);
452
- // Check the captured arguments
453
- expect(capturedRequest).toBeDefined();
454
- expect(capturedPromptId).toBe('test-session-id');
455
- expect(capturedRequest).toMatchObject({
456
- model: customModel,
457
- config: {
458
- abortSignal,
459
- systemInstruction: 'Test system instruction',
460
- temperature: 0.9,
461
- topP: 1, // from default
462
- topK: 20,
463
- responseSchema: schema,
464
- responseMimeType: 'application/json',
465
- },
466
- contents,
467
- });
468
- });
469
- });
470
- describe('addHistory', () => {
471
- it('should call chat.addHistory with the provided content', async () => {
472
- const mockChat = {
473
- addHistory: vi.fn(),
474
- };
475
- client['chat'] = mockChat;
476
- const newContent = {
477
- role: 'user',
478
- parts: [{ text: 'New history item' }],
479
- };
480
- await client.addHistory(newContent);
481
- expect(mockChat.addHistory).toHaveBeenCalledWith(newContent);
482
- });
483
- });
484
- describe('resetChat', () => {
485
- it('should create a new chat session, clearing the old history', async () => {
486
- // Create mock chats with distinct histories
487
- const initialChatHistory = [
488
- { role: 'user', parts: [{ text: 'initial context' }] },
489
- { role: 'model', parts: [{ text: 'acknowledged' }] },
490
- ];
491
- const mockInitialChat = {
492
- getHistory: vi.fn().mockReturnValue(initialChatHistory),
493
- addHistory: vi.fn().mockImplementation((content) => {
494
- // Update the history when addHistory is called
495
- initialChatHistory.push(content);
496
- }),
497
- setHistory: vi.fn(),
498
- };
499
- const mockNewChat = {
500
- getHistory: vi.fn().mockReturnValue([
501
- { role: 'user', parts: [{ text: 'fresh start' }] },
502
- { role: 'model', parts: [{ text: 'ready' }] },
503
- ]),
504
- addHistory: vi.fn(),
505
- setHistory: vi.fn(),
506
- };
507
- // Mock startChat to return the new chat when called
508
- const mockStartChat = vi.fn().mockResolvedValue(mockNewChat);
509
- client['startChat'] = mockStartChat;
510
- client['chat'] = mockInitialChat;
511
- // Mock that client is initialized
512
- client['contentGenerator'] = {};
513
- client['isInitialized'] = vi.fn().mockReturnValue(true);
514
- // Override the global getHistory mock for this test
515
- const getHistoryMock = vi.mocked(client.getHistory);
516
- getHistoryMock.mockImplementation(async () => client.getChat().getHistory());
517
- // 1. Get the initial chat instance and verify initial state
518
- const initialChat = client.getChat();
519
- expect(initialChat).toBe(mockInitialChat);
520
- const initialHistory = await client.getHistory();
521
- expect(initialHistory).toHaveLength(2); // initial context + acknowledged
522
- // Add a message to the initial chat
523
- await client.addHistory({
524
- role: 'user',
525
- parts: [{ text: 'some old message' }],
526
- });
527
- const historyWithOldMessage = await client.getHistory();
528
- expect(historyWithOldMessage).toHaveLength(3);
529
- expect(JSON.stringify(historyWithOldMessage)).toContain('some old message');
530
- // 2. Call resetChat
531
- await client.resetChat();
532
- // 3. Verify the chat was replaced
533
- const newChat = client.getChat();
534
- expect(mockStartChat).toHaveBeenCalledTimes(1);
535
- expect(client['chat']).toBe(mockNewChat);
536
- expect(newChat).toBe(mockNewChat);
537
- expect(newChat).not.toBe(initialChat);
538
- // 4. Verify the history is from the new chat
539
- const newHistory = await client.getHistory();
540
- expect(newHistory).toHaveLength(2); // fresh start + ready
541
- expect(JSON.stringify(newHistory)).not.toContain('some old message');
542
- expect(JSON.stringify(newHistory)).toContain('fresh start');
543
- });
544
- });
545
- describe('tryCompressChat', () => {
546
- const mockCountTokens = vi.fn();
547
- const mockSendMessage = vi.fn();
548
- const mockGetHistory = vi.fn();
549
- beforeEach(() => {
550
- vi.mock('./tokenLimits', () => ({
551
- tokenLimit: vi.fn(),
552
- }));
553
- client['contentGenerator'] = {
554
- countTokens: mockCountTokens,
555
- };
556
- client['chat'] = {
557
- getHistory: mockGetHistory,
558
- addHistory: vi.fn(),
559
- setHistory: vi.fn(),
560
- sendMessage: mockSendMessage,
561
- };
562
- });
563
- it('should not trigger summarization if token count is below threshold', async () => {
564
- const MOCKED_TOKEN_LIMIT = 1000;
565
- vi.mocked(tokenLimit).mockReturnValue(MOCKED_TOKEN_LIMIT);
566
- mockGetHistory.mockReturnValue([
567
- { role: 'user', parts: [{ text: '...history...' }] },
568
- ]);
569
- mockCountTokens.mockResolvedValue({
570
- totalTokens: MOCKED_TOKEN_LIMIT * 0.699, // TOKEN_THRESHOLD_FOR_SUMMARIZATION = 0.7
571
- });
572
- const initialChat = client.getChat();
573
- const result = await client.tryCompressChat('prompt-id-2');
574
- const newChat = client.getChat();
575
- expect(tokenLimit).toHaveBeenCalled();
576
- expect(result).toBeNull();
577
- expect(newChat).toBe(initialChat);
578
- });
579
- it('should trigger summarization if token count is at threshold with contextPercentageThreshold setting', async () => {
580
- const MOCKED_TOKEN_LIMIT = 1000;
581
- const MOCKED_CONTEXT_PERCENTAGE_THRESHOLD = 0.5;
582
- vi.mocked(tokenLimit).mockReturnValue(MOCKED_TOKEN_LIMIT);
583
- vi.spyOn(client['config'], 'getChatCompression').mockReturnValue({
584
- contextPercentageThreshold: MOCKED_CONTEXT_PERCENTAGE_THRESHOLD,
585
- });
586
- mockGetHistory.mockReturnValue([
587
- { role: 'user', parts: [{ text: '...history...' }] },
588
- ]);
589
- const originalTokenCount = MOCKED_TOKEN_LIMIT * MOCKED_CONTEXT_PERCENTAGE_THRESHOLD;
590
- const newTokenCount = 100;
591
- mockCountTokens
592
- .mockResolvedValueOnce({ totalTokens: originalTokenCount }) // First call for the check
593
- .mockResolvedValueOnce({ totalTokens: newTokenCount }); // Second call for the new history
594
- // Mock the summary response from the chat
595
- mockSendMessage.mockResolvedValue({
596
- role: 'model',
597
- parts: [{ text: 'This is a summary.' }],
598
- });
599
- const initialChat = client.getChat();
600
- const result = await client.tryCompressChat('prompt-id-3');
601
- const newChat = client.getChat();
602
- expect(tokenLimit).toHaveBeenCalled();
603
- expect(mockSendMessage).toHaveBeenCalled();
604
- // Assert that summarization happened and returned the correct stats
605
- expect(result).toEqual({
606
- originalTokenCount,
607
- newTokenCount,
608
- });
609
- // Assert that the chat was reset
610
- expect(newChat).not.toBe(initialChat);
611
- });
612
- it('should not compress across a function call response', async () => {
613
- const MOCKED_TOKEN_LIMIT = 1000;
614
- vi.mocked(tokenLimit).mockReturnValue(MOCKED_TOKEN_LIMIT);
615
- mockGetHistory.mockReturnValue([
616
- { role: 'user', parts: [{ text: '...history 1...' }] },
617
- { role: 'model', parts: [{ text: '...history 2...' }] },
618
- { role: 'user', parts: [{ text: '...history 3...' }] },
619
- { role: 'model', parts: [{ text: '...history 4...' }] },
620
- { role: 'user', parts: [{ text: '...history 5...' }] },
621
- { role: 'model', parts: [{ text: '...history 6...' }] },
622
- { role: 'user', parts: [{ text: '...history 7...' }] },
623
- { role: 'model', parts: [{ text: '...history 8...' }] },
624
- // Normally we would break here, but we have a function response.
625
- {
626
- role: 'user',
627
- parts: [{ functionResponse: { name: '...history 8...' } }],
628
- },
629
- { role: 'model', parts: [{ text: '...history 10...' }] },
630
- // Instead we will break here.
631
- { role: 'user', parts: [{ text: '...history 10...' }] },
632
- ]);
633
- const originalTokenCount = 1000 * 0.7;
634
- const newTokenCount = 100;
635
- mockCountTokens
636
- .mockResolvedValueOnce({ totalTokens: originalTokenCount }) // First call for the check
637
- .mockResolvedValueOnce({ totalTokens: newTokenCount }); // Second call for the new history
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-3');
645
- const newChat = client.getChat();
646
- expect(tokenLimit).toHaveBeenCalled();
647
- expect(mockSendMessage).toHaveBeenCalled();
648
- // Assert that summarization happened and returned the correct stats
649
- expect(result).toEqual({
650
- originalTokenCount,
651
- newTokenCount,
652
- });
653
- // Assert that the chat was reset
654
- expect(newChat).not.toBe(initialChat);
655
- // 1. standard start context message
656
- // After compression, we should have:
657
- // 1. compressed summary message
658
- // 2. standard canned user summary message
659
- // 3. The last user message (not the last 3 because that would start with a function response)
660
- // (No more environment context messages since they're in system instruction now)
661
- expect(newChat.getHistory().length).toEqual(3);
662
- });
663
- it('should always trigger summarization when force is true, regardless of token count', async () => {
664
- mockGetHistory.mockReturnValue([
665
- { role: 'user', parts: [{ text: '...history...' }] },
666
- ]);
667
- const originalTokenCount = 10; // Well below threshold
668
- const newTokenCount = 5;
669
- mockCountTokens
670
- .mockResolvedValueOnce({ totalTokens: originalTokenCount })
671
- .mockResolvedValueOnce({ totalTokens: newTokenCount });
672
- // Mock the summary response from the chat
673
- mockSendMessage.mockResolvedValue({
674
- role: 'model',
675
- parts: [{ text: 'This is a summary.' }],
676
- });
677
- const initialChat = client.getChat();
678
- const result = await client.tryCompressChat('prompt-id-1', true); // force = true
679
- const newChat = client.getChat();
680
- expect(mockSendMessage).toHaveBeenCalled();
681
- expect(result).toEqual({
682
- originalTokenCount,
683
- newTokenCount,
684
- });
685
- // Assert that the chat was reset
686
- expect(newChat).not.toBe(initialChat);
687
- });
688
- });
689
- describe('sendMessageStream', () => {
690
- it('should include IDE context when ideModeFeature is enabled', async () => {
691
- // Arrange
692
- vi.mocked(ideContext.getIdeContext).mockReturnValue({
693
- workspaceState: {
694
- openFiles: [
695
- {
696
- path: '/path/to/active/file.ts',
697
- timestamp: Date.now(),
698
- isActive: true,
699
- selectedText: 'hello',
700
- cursor: { line: 5, character: 10 },
701
- },
702
- {
703
- path: '/path/to/recent/file1.ts',
704
- timestamp: Date.now(),
705
- },
706
- {
707
- path: '/path/to/recent/file2.ts',
708
- timestamp: Date.now(),
709
- },
710
- ],
711
- },
712
- });
713
- vi.spyOn(client['config'], 'getIdeModeFeature').mockReturnValue(true);
714
- const mockStream = (async function* () {
715
- yield { type: 'content', value: 'Hello' };
716
- })();
717
- mockTurnRunFn.mockReturnValue(mockStream);
718
- const mockChat = {
719
- addHistory: vi.fn(),
720
- getHistory: vi.fn().mockReturnValue([]),
721
- };
722
- client['chat'] = mockChat;
723
- const mockGenerator = {
724
- countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
725
- generateContent: mockGenerateContentFn,
726
- };
727
- client['contentGenerator'] = mockGenerator;
728
- const initialRequest = [{ text: 'Hi' }];
729
- // Act
730
- const stream = client.sendMessageStream(initialRequest, new AbortController().signal, 'prompt-id-ide');
731
- for await (const _ of stream) {
732
- // consume stream
733
- }
734
- // Assert
735
- expect(ideContext.getIdeContext).toHaveBeenCalled();
736
- const expectedContext = `
737
- This is the file that the user is looking at:
738
- - Path: /path/to/active/file.ts
739
- This is the cursor position in the file:
740
- - Cursor Position: Line 5, Character 10
741
- This is the selected text in the file:
742
- - hello
743
- Here are some other files the user has open, with the most recent at the top:
744
- - /path/to/recent/file1.ts
745
- - /path/to/recent/file2.ts
746
- `.trim();
747
- const expectedRequest = [{ text: expectedContext }, ...initialRequest];
748
- expect(mockTurnRunFn).toHaveBeenCalledWith(expectedRequest, expect.any(Object));
749
- });
750
- it('should not add context if ideModeFeature is enabled but no open files', async () => {
751
- // Arrange
752
- vi.mocked(ideContext.getIdeContext).mockReturnValue({
753
- workspaceState: {
754
- openFiles: [],
755
- },
756
- });
757
- vi.spyOn(client['config'], 'getIdeModeFeature').mockReturnValue(true);
758
- const mockStream = (async function* () {
759
- yield { type: 'content', value: 'Hello' };
760
- })();
761
- mockTurnRunFn.mockReturnValue(mockStream);
762
- const mockChat = {
763
- addHistory: vi.fn(),
764
- getHistory: vi.fn().mockReturnValue([]),
765
- };
766
- client['chat'] = mockChat;
767
- const mockGenerator = {
768
- countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
769
- generateContent: mockGenerateContentFn,
770
- };
771
- client['contentGenerator'] = mockGenerator;
772
- const initialRequest = [{ text: 'Hi' }];
773
- // Act
774
- const stream = client.sendMessageStream(initialRequest, new AbortController().signal, 'prompt-id-ide');
775
- for await (const _ of stream) {
776
- // consume stream
777
- }
778
- // Assert
779
- expect(ideContext.getIdeContext).toHaveBeenCalled();
780
- expect(mockTurnRunFn).toHaveBeenCalledWith(initialRequest, expect.any(Object));
781
- });
782
- it('should add context if ideModeFeature is enabled and there is one active file', async () => {
783
- // Arrange
784
- vi.mocked(ideContext.getIdeContext).mockReturnValue({
785
- workspaceState: {
786
- openFiles: [
787
- {
788
- path: '/path/to/active/file.ts',
789
- timestamp: Date.now(),
790
- isActive: true,
791
- selectedText: 'hello',
792
- cursor: { line: 5, character: 10 },
793
- },
794
- ],
795
- },
796
- });
797
- vi.spyOn(client['config'], 'getIdeModeFeature').mockReturnValue(true);
798
- const mockStream = (async function* () {
799
- yield { type: 'content', value: 'Hello' };
800
- })();
801
- mockTurnRunFn.mockReturnValue(mockStream);
802
- const mockChat = {
803
- addHistory: vi.fn(),
804
- getHistory: vi.fn().mockReturnValue([]),
805
- };
806
- client['chat'] = mockChat;
807
- const mockGenerator = {
808
- countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
809
- generateContent: mockGenerateContentFn,
810
- };
811
- client['contentGenerator'] = mockGenerator;
812
- const initialRequest = [{ text: 'Hi' }];
813
- // Act
814
- const stream = client.sendMessageStream(initialRequest, new AbortController().signal, 'prompt-id-ide');
815
- for await (const _ of stream) {
816
- // consume stream
817
- }
818
- // Assert
819
- expect(ideContext.getIdeContext).toHaveBeenCalled();
820
- const expectedContext = `
821
- This is the file that the user is looking at:
822
- - Path: /path/to/active/file.ts
823
- This is the cursor position in the file:
824
- - Cursor Position: Line 5, Character 10
825
- This is the selected text in the file:
826
- - hello
827
- `.trim();
828
- const expectedRequest = [{ text: expectedContext }, ...initialRequest];
829
- expect(mockTurnRunFn).toHaveBeenCalledWith(expectedRequest, expect.any(Object));
830
- });
831
- it('should add context if ideModeFeature is enabled and there are open files but no active file', async () => {
832
- // Arrange
833
- vi.mocked(ideContext.getIdeContext).mockReturnValue({
834
- workspaceState: {
835
- openFiles: [
836
- {
837
- path: '/path/to/recent/file1.ts',
838
- timestamp: Date.now(),
839
- },
840
- {
841
- path: '/path/to/recent/file2.ts',
842
- timestamp: Date.now(),
843
- },
844
- ],
845
- },
846
- });
847
- vi.spyOn(client['config'], 'getIdeModeFeature').mockReturnValue(true);
848
- const mockStream = (async function* () {
849
- yield { type: 'content', value: 'Hello' };
850
- })();
851
- mockTurnRunFn.mockReturnValue(mockStream);
852
- const mockChat = {
853
- addHistory: vi.fn(),
854
- getHistory: vi.fn().mockReturnValue([]),
855
- };
856
- client['chat'] = mockChat;
857
- const mockGenerator = {
858
- countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
859
- generateContent: mockGenerateContentFn,
860
- };
861
- client['contentGenerator'] = mockGenerator;
862
- const initialRequest = [{ text: 'Hi' }];
863
- // Act
864
- const stream = client.sendMessageStream(initialRequest, new AbortController().signal, 'prompt-id-ide');
865
- for await (const _ of stream) {
866
- // consume stream
867
- }
868
- // Assert
869
- expect(ideContext.getIdeContext).toHaveBeenCalled();
870
- const expectedContext = `
871
- Here are some files the user has open, with the most recent at the top:
872
- - /path/to/recent/file1.ts
873
- - /path/to/recent/file2.ts
874
- `.trim();
875
- const expectedRequest = [{ text: expectedContext }, ...initialRequest];
876
- expect(mockTurnRunFn).toHaveBeenCalledWith(expectedRequest, expect.any(Object));
877
- });
878
- it('should return the turn instance after the stream is complete', async () => {
879
- // Arrange
880
- const mockStream = (async function* () {
881
- yield { type: 'content', value: 'Hello' };
882
- })();
883
- mockTurnRunFn.mockReturnValue(mockStream);
884
- const mockChat = {
885
- addHistory: vi.fn(),
886
- getHistory: vi.fn().mockReturnValue([]),
887
- };
888
- client['chat'] = mockChat;
889
- const mockGenerator = {
890
- countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
891
- generateContent: vi.fn(),
892
- generateContentStream: vi.fn(),
893
- embedContent: vi.fn(),
894
- };
895
- client['contentGenerator'] = mockGenerator;
896
- // Act
897
- const stream = client.sendMessageStream([{ text: 'Hi' }], new AbortController().signal, 'prompt-id-1');
898
- // Consume the stream manually to get the final return value.
899
- let finalResult;
900
- while (true) {
901
- const result = await stream.next();
902
- if (result.done) {
903
- finalResult = result.value;
904
- break;
905
- }
906
- }
907
- // Assert
908
- expect(finalResult).toBeInstanceOf(Turn);
909
- });
910
- it.skip('should stop infinite loop after MAX_TURNS when nextSpeaker always returns model', async () => {
911
- // Get the mocked checkNextSpeaker function and configure it to trigger infinite loop
912
- const { checkNextSpeaker } = await import('../utils/nextSpeakerChecker.js');
913
- const mockCheckNextSpeaker = vi.mocked(checkNextSpeaker);
914
- mockCheckNextSpeaker.mockResolvedValue({
915
- next_speaker: 'model',
916
- reasoning: 'Test case - always continue',
917
- });
918
- // Mock provider manager to return 'gemini' provider
919
- const mockProviderManager = {
920
- getActiveProviderName: vi.fn().mockReturnValue('gemini'),
921
- getActiveProvider: vi.fn().mockReturnValue(null),
922
- };
923
- const mockContentGenConfig = {
924
- model: 'test-model',
925
- providerManager: mockProviderManager,
926
- };
927
- vi.spyOn(client['config'], 'getContentGeneratorConfig').mockReturnValue(mockContentGenConfig);
928
- // Mock Turn to have no pending tool calls (which would allow nextSpeaker check)
929
- const mockStream = (async function* () {
930
- yield { type: 'content', value: 'Continue...' };
931
- })();
932
- mockTurnRunFn.mockReturnValue(mockStream);
933
- const mockChat = {
934
- addHistory: vi.fn(),
935
- getHistory: vi.fn().mockReturnValue([]),
936
- };
937
- client['chat'] = mockChat;
938
- const mockGenerator = {
939
- countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
940
- };
941
- client['contentGenerator'] = mockGenerator;
942
- // Use a signal that never gets aborted
943
- const abortController = new AbortController();
944
- const signal = abortController.signal;
945
- // Act - Start the stream that should loop
946
- const stream = client.sendMessageStream([{ text: 'Start conversation' }], signal, 'prompt-id-2');
947
- // Count how many stream events we get
948
- let eventCount = 0;
949
- let finalResult;
950
- // Consume the stream and count iterations
951
- while (true) {
952
- const result = await stream.next();
953
- if (result.done) {
954
- finalResult = result.value;
955
- break;
956
- }
957
- eventCount++;
958
- // Safety check to prevent actual infinite loop in test
959
- if (eventCount > 200) {
960
- abortController.abort();
961
- throw new Error('Test exceeded expected event limit - possible actual infinite loop');
962
- }
963
- }
964
- // Assert
965
- expect(finalResult).toBeInstanceOf(Turn);
966
- // Debug: Check how many times checkNextSpeaker was called
967
- const callCount = mockCheckNextSpeaker.mock.calls.length;
968
- // If infinite loop protection is working, checkNextSpeaker should be called many times
969
- // but stop at MAX_TURNS (100). Since each recursive call should trigger checkNextSpeaker,
970
- // we expect it to be called multiple times before hitting the limit
971
- expect(mockCheckNextSpeaker).toHaveBeenCalled();
972
- // The test should demonstrate that the infinite loop protection works:
973
- // - If checkNextSpeaker is called many times (close to MAX_TURNS), it shows the loop was happening
974
- // - If it's only called once, the recursive behavior might not be triggered
975
- if (callCount === 0) {
976
- throw new Error('checkNextSpeaker was never called - the recursive condition was not met');
977
- }
978
- else if (callCount === 1) {
979
- // This might be expected behavior if the turn has pending tool calls or other conditions prevent recursion
980
- console.log('checkNextSpeaker called only once - no infinite loop occurred');
981
- }
982
- else {
983
- console.log(`checkNextSpeaker called ${callCount} times - infinite loop protection worked`);
984
- // If called multiple times, we expect it to be stopped before MAX_TURNS
985
- expect(callCount).toBeLessThanOrEqual(100); // Should not exceed MAX_TURNS
986
- }
987
- // The stream should produce events and eventually terminate
988
- expect(eventCount).toBeGreaterThanOrEqual(1);
989
- expect(eventCount).toBeLessThan(200); // Should not exceed our safety limit
990
- });
991
- it('should yield MaxSessionTurns and stop when session turn limit is reached', async () => {
992
- // Arrange
993
- const MAX_SESSION_TURNS = 5;
994
- vi.spyOn(client['config'], 'getMaxSessionTurns').mockReturnValue(MAX_SESSION_TURNS);
995
- const mockStream = (async function* () {
996
- yield { type: 'content', value: 'Hello' };
997
- })();
998
- mockTurnRunFn.mockReturnValue(mockStream);
999
- const mockChat = {
1000
- addHistory: vi.fn(),
1001
- getHistory: vi.fn().mockReturnValue([]),
1002
- };
1003
- client['chat'] = mockChat;
1004
- const mockGenerator = {
1005
- countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
1006
- };
1007
- client['contentGenerator'] = mockGenerator;
1008
- // Act & Assert
1009
- // Run up to the limit
1010
- for (let i = 0; i < MAX_SESSION_TURNS; i++) {
1011
- const stream = client.sendMessageStream([{ text: 'Hi' }], new AbortController().signal, 'prompt-id-4');
1012
- // consume stream
1013
- for await (const _event of stream) {
1014
- // do nothing
1015
- }
1016
- }
1017
- // This call should exceed the limit
1018
- const stream = client.sendMessageStream([{ text: 'Hi' }], new AbortController().signal, 'prompt-id-5');
1019
- const events = [];
1020
- for await (const event of stream) {
1021
- events.push(event);
1022
- }
1023
- expect(events).toEqual([{ type: GeminiEventType.MaxSessionTurns }]);
1024
- expect(mockTurnRunFn).toHaveBeenCalledTimes(MAX_SESSION_TURNS);
1025
- });
1026
- it.skip('should respect MAX_TURNS limit even when turns parameter is set to a large value', async () => {
1027
- // This test verifies that the infinite loop protection works even when
1028
- // someone tries to bypass it by calling with a very large turns value
1029
- // Get the mocked checkNextSpeaker function and configure it to trigger infinite loop
1030
- const { checkNextSpeaker } = await import('../utils/nextSpeakerChecker.js');
1031
- const mockCheckNextSpeaker = vi.mocked(checkNextSpeaker);
1032
- mockCheckNextSpeaker.mockResolvedValue({
1033
- next_speaker: 'model',
1034
- reasoning: 'Test case - always continue',
1035
- });
1036
- // Mock Turn to have no pending tool calls (which would allow nextSpeaker check)
1037
- const mockStream = (async function* () {
1038
- yield { type: 'content', value: 'Continue...' };
1039
- })();
1040
- mockTurnRunFn.mockReturnValue(mockStream);
1041
- const mockChat = {
1042
- addHistory: vi.fn(),
1043
- getHistory: vi.fn().mockReturnValue([]),
1044
- };
1045
- client['chat'] = mockChat;
1046
- const mockGenerator = {
1047
- countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
1048
- };
1049
- client['contentGenerator'] = mockGenerator;
1050
- // Use a signal that never gets aborted
1051
- const abortController = new AbortController();
1052
- const signal = abortController.signal;
1053
- // Act - Start the stream with an extremely high turns value
1054
- // This simulates a case where the turns protection is bypassed
1055
- const stream = client.sendMessageStream([{ text: 'Start conversation' }], signal, 'prompt-id-3', Number.MAX_SAFE_INTEGER);
1056
- // Count how many stream events we get
1057
- let eventCount = 0;
1058
- const maxTestIterations = 1000; // Higher limit to show the loop continues
1059
- // Consume the stream and count iterations
1060
- try {
1061
- while (true) {
1062
- const result = await stream.next();
1063
- if (result.done) {
1064
- break;
1065
- }
1066
- eventCount++;
1067
- // This test should hit this limit, demonstrating the infinite loop
1068
- if (eventCount > maxTestIterations) {
1069
- abortController.abort();
1070
- // This is the expected behavior - we hit the infinite loop
1071
- break;
1072
- }
1073
- }
1074
- }
1075
- catch (error) {
1076
- // If the test framework times out, that also demonstrates the infinite loop
1077
- console.error('Test timed out or errored:', error);
1078
- }
1079
- // Assert that the fix works - the loop should stop at MAX_TURNS
1080
- const callCount = mockCheckNextSpeaker.mock.calls.length;
1081
- // With the fix: even when turns is set to a very high value,
1082
- // the loop should stop at MAX_TURNS (100)
1083
- expect(callCount).toBeLessThanOrEqual(100); // Should not exceed MAX_TURNS
1084
- expect(eventCount).toBeLessThanOrEqual(200); // Should have reasonable number of events
1085
- console.log(`Infinite loop protection working: checkNextSpeaker called ${callCount} times, ` +
1086
- `${eventCount} events generated (properly bounded by MAX_TURNS)`);
1087
- });
1088
- });
1089
- describe('generateContent model usage', () => {
1090
- it('should use current model from config for content generation', async () => {
1091
- const initialModel = client['config'].getModel();
1092
- const contents = [{ role: 'user', parts: [{ text: 'test' }] }];
1093
- const currentModel = initialModel + '-changed';
1094
- // Mock getModel to return the changed model when called during generateContent
1095
- vi.spyOn(client['config'], 'getModel').mockReturnValue(currentModel);
1096
- // Mock the retryWithBackoff to directly call the apiCall function
1097
- vi.mock('../utils/retry.js', () => ({
1098
- retryWithBackoff: vi.fn((apiCall) => apiCall()),
1099
- }));
1100
- const mockContentGeneratorGenerateContent = vi.fn().mockResolvedValue({
1101
- candidates: [
1102
- {
1103
- content: {
1104
- parts: [{ text: 'response' }],
1105
- },
1106
- },
1107
- ],
1108
- });
1109
- const mockGenerator = {
1110
- countTokens: vi.fn().mockResolvedValue({ totalTokens: 1 }),
1111
- generateContent: mockContentGeneratorGenerateContent,
1112
- };
1113
- client['contentGenerator'] = mockGenerator;
1114
- client['isInitialized'] = vi.fn().mockReturnValue(true);
1115
- const { retryWithBackoff } = await import('../utils/retry.js');
1116
- vi.mocked(retryWithBackoff).mockImplementation(async (apiCall) => await apiCall());
1117
- await client.generateContent(contents, {}, new AbortController().signal);
1118
- // Verify the mock was called
1119
- expect(mockContentGeneratorGenerateContent).toHaveBeenCalledTimes(1);
1120
- // Get the actual call arguments
1121
- const actualCall = mockContentGeneratorGenerateContent.mock.calls[0];
1122
- // Assert on the model specifically
1123
- expect(actualCall[0].model).toBe(currentModel);
1124
- expect(actualCall[0].model).not.toBe(initialModel);
1125
- // Verify other expected properties exist
1126
- expect(actualCall[0]).toHaveProperty('contents', contents);
1127
- expect(actualCall[0]).toHaveProperty('config');
1128
- expect(actualCall[0].config).toHaveProperty('abortSignal');
1129
- expect(actualCall[0].config).toHaveProperty('systemInstruction');
1130
- // Verify prompt_id was passed
1131
- expect(actualCall[1]).toBe('test-session-id');
1132
- });
1133
- });
1134
- describe('tryCompressChat model usage', () => {
1135
- it('should use current model from config for token counting after sendMessage', async () => {
1136
- const initialModel = client['config'].getModel();
1137
- const mockCountTokens = vi
1138
- .fn()
1139
- .mockResolvedValueOnce({ totalTokens: 100000 })
1140
- .mockResolvedValueOnce({ totalTokens: 5000 });
1141
- const mockSendMessage = vi.fn().mockResolvedValue({ text: 'Summary' });
1142
- const mockChatHistory = [
1143
- { role: 'user', parts: [{ text: 'Long conversation' }] },
1144
- { role: 'model', parts: [{ text: 'Long response' }] },
1145
- ];
1146
- const mockChat = {
1147
- getHistory: vi.fn().mockReturnValue(mockChatHistory),
1148
- setHistory: vi.fn(),
1149
- sendMessage: mockSendMessage,
1150
- };
1151
- const mockGenerator = {
1152
- countTokens: mockCountTokens,
1153
- };
1154
- // mock the model has been changed between calls of `countTokens`
1155
- const firstCurrentModel = initialModel + '-changed-1';
1156
- const secondCurrentModel = initialModel + '-changed-2';
1157
- vi.spyOn(client['config'], 'getModel')
1158
- .mockReturnValueOnce(firstCurrentModel)
1159
- .mockReturnValueOnce(secondCurrentModel);
1160
- client['chat'] = mockChat;
1161
- client['contentGenerator'] = mockGenerator;
1162
- client['startChat'] = vi.fn().mockResolvedValue(mockChat);
1163
- const result = await client.tryCompressChat('prompt-id-4', true);
1164
- expect(mockCountTokens).toHaveBeenCalledTimes(2);
1165
- expect(mockCountTokens).toHaveBeenNthCalledWith(1, {
1166
- model: firstCurrentModel,
1167
- contents: mockChatHistory,
1168
- });
1169
- expect(mockCountTokens).toHaveBeenNthCalledWith(2, {
1170
- model: secondCurrentModel,
1171
- contents: expect.any(Array),
1172
- });
1173
- expect(result).toEqual({
1174
- originalTokenCount: 100000,
1175
- newTokenCount: 5000,
1176
- });
1177
- });
1178
- });
1179
- describe('handleFlashFallback', () => {
1180
- it('should use current model from config when checking for fallback', async () => {
1181
- const initialModel = client['config'].getModel();
1182
- const fallbackModel = DEFAULT_GEMINI_FLASH_MODEL;
1183
- // mock config been changed
1184
- const currentModel = initialModel + '-changed';
1185
- const getModelSpy = vi.spyOn(client['config'], 'getModel');
1186
- getModelSpy.mockReturnValue(currentModel);
1187
- const mockFallbackHandler = vi.fn().mockResolvedValue(true);
1188
- client['config'].flashFallbackHandler = mockFallbackHandler;
1189
- client['config'].setModel = vi.fn();
1190
- const result = await client['handleFlashFallback'](AuthType.LOGIN_WITH_GOOGLE);
1191
- expect(result).toBe(fallbackModel);
1192
- expect(mockFallbackHandler).toHaveBeenCalledWith(currentModel, fallbackModel, undefined);
1193
- });
1194
- });
1195
- // TODO: Re-enable when updateModel method is implemented
1196
- describe.skip('updateModel', () => {
1197
- it('should update model in config and reinitialize chat', async () => {
1198
- // Arrange
1199
- const mockSetModel = vi.fn();
1200
- const mockConfig = {
1201
- getModel: vi.fn().mockReturnValue('gemini-2.5-pro'),
1202
- setModel: mockSetModel,
1203
- getProjectRoot: vi.fn().mockReturnValue('/test'),
1204
- getWorkingDir: vi.fn().mockReturnValue('/test'),
1205
- getFullContext: vi.fn().mockReturnValue(false),
1206
- getUserMemory: vi.fn().mockReturnValue(''),
1207
- getLlxprtMdFileCount: vi.fn().mockReturnValue(0),
1208
- getFileService: vi.fn().mockReturnValue(null),
1209
- getCheckpointingEnabled: vi.fn().mockReturnValue(false),
1210
- getToolRegistry: vi.fn().mockResolvedValue({
1211
- generateSchema: vi.fn().mockReturnValue([]),
1212
- getToolTelemetry: vi.fn().mockReturnValue([]),
1213
- getFunctionDeclarations: vi.fn().mockReturnValue([]),
1214
- }),
1215
- };
1216
- client['config'] = mockConfig;
1217
- // Mock the content generator and chat
1218
- const mockContentGenerator = {
1219
- generateContent: vi.fn(),
1220
- generateContentStream: vi.fn(),
1221
- countTokens: vi.fn(),
1222
- embedContent: vi.fn(),
1223
- };
1224
- client['contentGenerator'] = mockContentGenerator;
1225
- // const initialChat = client['chat'];
1226
- // Act
1227
- // await client.updateModel('gemini-2.5-flash');
1228
- // Assert
1229
- // expect(mockSetModel).toHaveBeenCalledWith('gemini-2.5-flash');
1230
- // expect(client['model']).toBe('gemini-2.5-flash');
1231
- // expect(client['chat']).not.toBe(initialChat); // Chat should be reinitialized
1232
- // Skip test - updateModel method not implemented yet
1233
- expect(true).toBe(true);
1234
- });
1235
- });
1236
- // TODO: Re-enable when listAvailableModels method is implemented
1237
- describe.skip('listAvailableModels', () => {
1238
- beforeEach(() => {
1239
- global.fetch = vi.fn();
1240
- });
1241
- afterEach(() => {
1242
- vi.restoreAllMocks();
1243
- });
1244
- it('should fetch models from API for GEMINI auth type', async () => {
1245
- // Arrange
1246
- const mockModels = [
1247
- { name: 'models/gemini-2.5-pro', displayName: 'Gemini 2.5 Pro' },
1248
- { name: 'models/gemini-2.5-flash', displayName: 'Gemini 2.5 Flash' },
1249
- ];
1250
- const mockConfig = {
1251
- getContentGeneratorConfig: vi.fn().mockReturnValue({
1252
- authType: AuthType.USE_GEMINI,
1253
- apiKey: 'test-api-key',
1254
- }),
1255
- };
1256
- client['config'] = mockConfig;
1257
- global.fetch.mockResolvedValue({
1258
- ok: true,
1259
- json: vi.fn().mockResolvedValue({ models: mockModels }),
1260
- });
1261
- // Act
1262
- // const models = await client.listAvailableModels();
1263
- const models = []; // Placeholder - listAvailableModels not implemented
1264
- // Assert
1265
- expect(global.fetch).toHaveBeenCalledWith('https://generativelanguage.googleapis.com/v1beta/models?key=test-api-key', expect.objectContaining({
1266
- method: 'GET',
1267
- headers: { 'Content-Type': 'application/json' },
1268
- }));
1269
- expect(models).toEqual(mockModels);
1270
- });
1271
- it('should return OAuth marker for OAuth auth types', async () => {
1272
- // Arrange
1273
- const mockConfig = {
1274
- getContentGeneratorConfig: vi.fn().mockReturnValue({
1275
- authType: AuthType.LOGIN_WITH_GOOGLE,
1276
- }),
1277
- };
1278
- client['config'] = mockConfig;
1279
- // Act
1280
- // const models = await client.listAvailableModels();
1281
- const models = []; // Placeholder - listAvailableModels not implemented
1282
- // Assert
1283
- expect(models).toEqual([
1284
- {
1285
- name: 'oauth-not-supported',
1286
- displayName: 'OAuth Authentication',
1287
- description: 'Model listing is not available with OAuth authentication',
1288
- },
1289
- ]);
1290
- });
1291
- it('should return empty array when API call fails', async () => {
1292
- // Arrange
1293
- const mockConfig = {
1294
- getContentGeneratorConfig: vi.fn().mockReturnValue({
1295
- authType: AuthType.USE_GEMINI,
1296
- apiKey: 'test-api-key',
1297
- }),
1298
- };
1299
- client['config'] = mockConfig;
1300
- global.fetch.mockRejectedValue(new Error('Network error'));
1301
- // Act
1302
- // const models = await client.listAvailableModels();
1303
- const models = []; // Placeholder - listAvailableModels not implemented
1304
- // Assert
1305
- expect(models).toEqual([]);
1306
- });
1307
- it('should return empty array for unsupported auth type', async () => {
1308
- // Arrange
1309
- const mockConfig = {
1310
- getContentGeneratorConfig: vi.fn().mockReturnValue({
1311
- authType: undefined,
1312
- }),
1313
- };
1314
- client['config'] = mockConfig;
1315
- // Act
1316
- // const models = await client.listAvailableModels();
1317
- const models = []; // Placeholder - listAvailableModels not implemented
1318
- // Assert
1319
- expect(models).toEqual([]);
1320
- });
1321
- });
1322
- });
1323
- //# sourceMappingURL=client.test.js.map