wind-agent-cli 1.37.2 → 1.37.3

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 (374) hide show
  1. package/LICENSE +718 -718
  2. package/README.md +1 -1
  3. package/dist/api-docs.html +901 -901
  4. package/dist/assets/{CodeEditor-B2Wf7Fg0.js → CodeEditor-BqmxpZ_D.js} +1 -1
  5. package/dist/assets/{FileTree-N2IkkHlv.js → FileTree-DLE7Ioai.js} +1 -1
  6. package/dist/assets/{GitPanel-DZCeuFZ2.js → GitPanel-f8RMRa8D.js} +1 -1
  7. package/dist/assets/{MarkdownPreview-C0tqYnVu.js → MarkdownPreview-93h_1tJa.js} +1 -1
  8. package/dist/assets/{PluginTabContent-Bnuf-fb8.js → PluginTabContent-DU1jjkXP.js} +1 -1
  9. package/dist/assets/{Shell-BfFnMZ-f.js → Shell-CN_2MRIM.js} +1 -1
  10. package/dist/assets/{StandaloneShell-QmyYwNAl.js → StandaloneShell-D0avS8UE.js} +1 -1
  11. package/dist/assets/{TaskMasterPanel-fMsmvN9L.js → TaskMasterPanel-Cpf1Q5Ph.js} +3 -3
  12. package/dist/assets/{abnfDiagram-N423BO3Z-DjPU7HLs.js → abnfDiagram-N423BO3Z-p3aJIm4T.js} +1 -1
  13. package/dist/assets/{arc-Pdq6Tvr3.js → arc-CTeud6Fl.js} +1 -1
  14. package/dist/assets/{architectureDiagram-T3A2C74G-D0JnT0Vh.js → architectureDiagram-T3A2C74G-CG7kRCJU.js} +1 -1
  15. package/dist/assets/{blockDiagram-VBNYF7ZC-DpaEf3mv.js → blockDiagram-VBNYF7ZC-oSjQ1SgE.js} +1 -1
  16. package/dist/assets/{c4Diagram-5PPSVZJV-MpqlPGFi.js → c4Diagram-5PPSVZJV-RkzF0DJV.js} +1 -1
  17. package/dist/assets/channel-BfQbarn9.js +1 -0
  18. package/dist/assets/{chunk-2GRJ4B5K-DoSdNo8u.js → chunk-2GRJ4B5K-B07uZ07O.js} +1 -1
  19. package/dist/assets/{chunk-2Q5K7J3B-CE7I3uMn.js → chunk-2Q5K7J3B-DNSfO7xS.js} +1 -1
  20. package/dist/assets/{chunk-5RXB4S5H-B4UQ8snD.js → chunk-5RXB4S5H-BTeYcgyb.js} +1 -1
  21. package/dist/assets/{chunk-5VM5RSS4-B55XgqHZ.js → chunk-5VM5RSS4-B7vZV0zC.js} +1 -1
  22. package/dist/assets/{chunk-6Q2QTUOP-BS1KpefW.js → chunk-6Q2QTUOP-DuS_xUGG.js} +1 -1
  23. package/dist/assets/{chunk-GF5L2VYU-DkEPedJP.js → chunk-GF5L2VYU-CKLZ3iVD.js} +1 -1
  24. package/dist/assets/{chunk-JWPE2WC7-DOtkNhMm.js → chunk-JWPE2WC7-DD2hcXvs.js} +1 -1
  25. package/dist/assets/{chunk-KBJHAD2P-BXLjviqM.js → chunk-KBJHAD2P-Cz-l38qp.js} +1 -1
  26. package/dist/assets/{chunk-RYQCIY6F-C50fjNNz.js → chunk-RYQCIY6F-DGFIU1YM.js} +1 -1
  27. package/dist/assets/{chunk-XXDRQBXY-QBYqCkb7.js → chunk-XXDRQBXY-CmfzoYFl.js} +1 -1
  28. package/dist/assets/classDiagram-JCYQIIEL-Bpfe3kq7.js +1 -0
  29. package/dist/assets/classDiagram-v2-OCEON4UE-Bpfe3kq7.js +1 -0
  30. package/dist/assets/{code-xml-VK1YfShP.js → code-xml-CLpHzEOP.js} +1 -1
  31. package/dist/assets/{cose-bilkent-JH36ORCC-DrVTo1Nh.js → cose-bilkent-JH36ORCC-DlFcLXCB.js} +1 -1
  32. package/dist/assets/{cynefin-VYW2F7L2-DnJa_OlQ.js → cynefin-VYW2F7L2-P1HecReO.js} +1 -1
  33. package/dist/assets/{cynefinDiagram-MW4NZA55-CCxBjw9E.js → cynefinDiagram-MW4NZA55-COgduz5P.js} +1 -1
  34. package/dist/assets/{dagre-VZM6K2ZE-C_GvE4lu.js → dagre-VZM6K2ZE-Bbb-siGp.js} +1 -1
  35. package/dist/assets/{diagram-7IWD3JNH-pFzs9HEu.js → diagram-7IWD3JNH-9CWGFMYR.js} +1 -1
  36. package/dist/assets/{diagram-B4RE2ZJO-CcehQC7x.js → diagram-B4RE2ZJO-TWK59T6V.js} +1 -1
  37. package/dist/assets/{diagram-LBJQPF4R-hfKcrrxe.js → diagram-LBJQPF4R-ErMC9yaa.js} +1 -1
  38. package/dist/assets/{diagram-Q27KOJAE-C1semJfK.js → diagram-Q27KOJAE-Dt_-C7hV.js} +1 -1
  39. package/dist/assets/{diagram-UB23O5K3-57hvXQXO.js → diagram-UB23O5K3-BJ1DnRAF.js} +1 -1
  40. package/dist/assets/{ebnfDiagram-BXEA7PRR-9KIAlAVw.js → ebnfDiagram-BXEA7PRR-CE1YaQ9s.js} +1 -1
  41. package/dist/assets/{erDiagram-JOGREHBK-B7OzJ767.js → erDiagram-JOGREHBK-Bqk7N9aY.js} +1 -1
  42. package/dist/assets/{flowDiagram-UKHOOZJN-CJV8fQPR.js → flowDiagram-UKHOOZJN-DEr2II5V.js} +1 -1
  43. package/dist/assets/{ganttDiagram-PKOTCBZU-CbMNWWQu.js → ganttDiagram-PKOTCBZU-CWYAUeYN.js} +1 -1
  44. package/dist/assets/{gitGraphDiagram-DS77QQ5N-I_vZ5waO.js → gitGraphDiagram-DS77QQ5N-tdEcEIM6.js} +1 -1
  45. package/dist/assets/{index-ZHwIojzi.js → index-B-sTfSZq.js} +1 -1
  46. package/dist/assets/{index-GFhXZyl2.js → index-BSe3UiFA.js} +1 -1
  47. package/dist/assets/{index-DFnVoqpx.js → index-B_FDMWar.js} +5 -5
  48. package/dist/assets/{index-DlSeAkw_.js → index-CWJtg2pR.js} +1 -1
  49. package/dist/assets/{infoDiagram-6WML65LV-Dh20Tsbq.js → infoDiagram-6WML65LV-A3IqRUnO.js} +1 -1
  50. package/dist/assets/{ishikawaDiagram-WSZJBQD7-DH2Sm3ko.js → ishikawaDiagram-WSZJBQD7-B2uL6bkK.js} +1 -1
  51. package/dist/assets/{journeyDiagram-NVQOT4AX-BNFQqlVu.js → journeyDiagram-NVQOT4AX-D9JB-hRW.js} +1 -1
  52. package/dist/assets/{kanban-definition-27J2QSJJ-B3iL0ztJ.js → kanban-definition-27J2QSJJ-DmlgiV7K.js} +1 -1
  53. package/dist/assets/{linear-Cwe9dEKA.js → linear-Ct_eoJQk.js} +1 -1
  54. package/dist/assets/{mermaid.core-BYRQSshi.js → mermaid.core-CQ698HNn.js} +5 -5
  55. package/dist/assets/{mindmap-definition-FAOFIHXS-BgfBYMzr.js → mindmap-definition-FAOFIHXS-DGtMgQhf.js} +1 -1
  56. package/dist/assets/{pegDiagram-VL7TDLO6-CNYpECr8.js → pegDiagram-VL7TDLO6-CO6vP4n9.js} +1 -1
  57. package/dist/assets/{pieDiagram-7S7Q4E2Y-DeSrxc4I.js → pieDiagram-7S7Q4E2Y-DMkt_Zfr.js} +1 -1
  58. package/dist/assets/{quadrantDiagram-CIZ2JOQS-BXVVQsa6.js → quadrantDiagram-CIZ2JOQS-DgNxRz6t.js} +1 -1
  59. package/dist/assets/{railroadDiagram-AXF67PYL-JTroIW8F.js → railroadDiagram-AXF67PYL-DKz9UqA9.js} +1 -1
  60. package/dist/assets/{requirementDiagram-LRYGKXZP-C1Z_inLz.js → requirementDiagram-LRYGKXZP-L84XyGgV.js} +1 -1
  61. package/dist/assets/{sankeyDiagram-W5VNT64P-DCJgKFUk.js → sankeyDiagram-W5VNT64P-CQqWbJ3j.js} +1 -1
  62. package/dist/assets/{sequenceDiagram-SI44F4Z6-D8Wrx5Vc.js → sequenceDiagram-SI44F4Z6--tnzS2tb.js} +1 -1
  63. package/dist/assets/{sizeCapture-X5ZJPWSS-CXqD68vD.js → sizeCapture-X5ZJPWSS-DujwEOtm.js} +1 -1
  64. package/dist/assets/{stateDiagram-OKZ733FA-CF0Ekqjo.js → stateDiagram-OKZ733FA-BK3TcZY2.js} +1 -1
  65. package/dist/assets/stateDiagram-v2-UEYNNEHI-_medyomK.js +1 -0
  66. package/dist/assets/{swimlanes-SLNWSIFB-DVIax_k4.js → swimlanes-SLNWSIFB-naX-Uv1B.js} +2 -2
  67. package/dist/assets/swimlanesDiagram-ULZ7WXOC-DstIv3TC.js +8 -0
  68. package/dist/assets/{timeline-definition-Z64GVDOM-DSqk3ApG.js → timeline-definition-Z64GVDOM-C-vP_ddU.js} +1 -1
  69. package/dist/assets/{vennDiagram-T6HMQDX7-DNbTqyG5.js → vennDiagram-T6HMQDX7-DN-I7o-7.js} +1 -1
  70. package/dist/assets/{wardleyDiagram-T6FBY63Y-BNCpsFZV.js → wardleyDiagram-T6FBY63Y-Db9dsaXv.js} +1 -1
  71. package/dist/assets/{xychartDiagram-ELKLHX3M-XsVZphHr.js → xychartDiagram-ELKLHX3M-DE6OxW_p.js} +1 -1
  72. package/dist/clear-cache.html +85 -85
  73. package/dist/convert-icons.md +52 -52
  74. package/dist/favicon.svg +8 -8
  75. package/dist/generate-icons.js +48 -48
  76. package/dist/icons/codex-white.svg +3 -3
  77. package/dist/icons/codex.svg +3 -3
  78. package/dist/icons/cursor-white.svg +11 -11
  79. package/dist/icons/icon-128x128.svg +11 -11
  80. package/dist/icons/icon-144x144.svg +11 -11
  81. package/dist/icons/icon-152x152.svg +11 -11
  82. package/dist/icons/icon-192x192.svg +11 -11
  83. package/dist/icons/icon-384x384.svg +11 -11
  84. package/dist/icons/icon-512x512.svg +11 -11
  85. package/dist/icons/icon-72x72.svg +11 -11
  86. package/dist/icons/icon-96x96.svg +11 -11
  87. package/dist/icons/icon-template.svg +11 -11
  88. package/dist/index.html +56 -56
  89. package/dist/logo.svg +17 -17
  90. package/dist/manifest.json +60 -60
  91. package/dist/sw.js +124 -124
  92. package/dist-server/server/modules/cli/cli.service.js +36 -36
  93. package/dist-server/server/modules/cli/sandbox.service.js +38 -38
  94. package/dist-server/server/modules/cli/tests/cli-environment-bootstrap.test.js +74 -74
  95. package/dist-server/server/modules/commands/commands.routes.js +24 -24
  96. package/dist-server/server/modules/database/migrations.js +190 -190
  97. package/dist-server/server/modules/database/repositories/api-keys.js +3 -3
  98. package/dist-server/server/modules/database/repositories/github-tokens.js +2 -2
  99. package/dist-server/server/modules/database/repositories/notification-channel-endpoints.js +28 -28
  100. package/dist-server/server/modules/database/repositories/notification-preferences.js +4 -4
  101. package/dist-server/server/modules/database/repositories/projects.db.js +61 -61
  102. package/dist-server/server/modules/database/repositories/provider-models.js +35 -35
  103. package/dist-server/server/modules/database/repositories/push-subscriptions.js +5 -5
  104. package/dist-server/server/modules/database/repositories/scan-state.db.js +5 -5
  105. package/dist-server/server/modules/database/repositories/sessions.db.js +92 -92
  106. package/dist-server/server/modules/database/schema.js +177 -177
  107. package/dist-server/server/modules/database/tests/provider-models.db.integration.test.js +6 -6
  108. package/dist-server/server/modules/git/git.routes.js +17 -17
  109. package/dist-server/server/modules/providers/list/opencode/opencode-models.provider.js +12 -12
  110. package/dist-server/server/modules/providers/list/opencode/opencode-runtime.provider.js +9 -9
  111. package/dist-server/server/modules/providers/list/opencode/opencode-runtime.provider.test.js +17 -17
  112. package/dist-server/server/modules/providers/list/opencode/opencode-session-synchronizer.provider.js +25 -25
  113. package/dist-server/server/modules/providers/list/opencode/opencode-sessions.provider.js +27 -27
  114. package/dist-server/server/modules/providers/services/provider-token-usage.service.js +9 -9
  115. package/dist-server/server/modules/providers/tests/mcp.test.js +3 -3
  116. package/dist-server/server/modules/providers/tests/opencode-sessions.test.js +96 -96
  117. package/dist-server/server/modules/providers/tests/provider-token-usage.service.test.js +18 -18
  118. package/dist-server/server/modules/taskmaster/taskmaster.routes.js +419 -419
  119. package/electron/cloud.js +260 -260
  120. package/electron/desktopNotifications.js +378 -378
  121. package/electron/desktopWindow.js +766 -766
  122. package/electron/launcher/index.html +14 -14
  123. package/electron/launcher/launcher.css +801 -801
  124. package/electron/launcher/launcher.js +687 -687
  125. package/electron/localServer.js +549 -549
  126. package/electron/main.js +944 -944
  127. package/electron/preload.cjs +60 -60
  128. package/electron/scripts/generate-macos-icon.js +62 -62
  129. package/electron/serverInstaller.js +277 -277
  130. package/electron/tabs.js +87 -87
  131. package/electron/viewHost.js +331 -331
  132. package/package.json +250 -247
  133. package/public/api-docs.html +901 -901
  134. package/scripts/fix-node-pty.js +67 -67
  135. package/scripts/promote-dist-server.mjs +50 -50
  136. package/scripts/release/build-server-bundle.js +176 -176
  137. package/scripts/release/prepare-desktop-app.js +152 -152
  138. package/server/index.ts +399 -399
  139. package/server/load-env.ts +47 -47
  140. package/server/modules/agent/agent.module.ts +52 -52
  141. package/server/modules/agent/agent.routes.ts +1287 -1287
  142. package/server/modules/agent/index.ts +2 -2
  143. package/server/modules/agent/tests/agent.routes.test.ts +205 -205
  144. package/server/modules/assets/assets.routes.ts +150 -150
  145. package/server/modules/assets/index.ts +3 -3
  146. package/server/modules/assets/services/image-assets.service.ts +127 -127
  147. package/server/modules/assets/tests/image-assets.service.test.ts +74 -74
  148. package/server/modules/auth/auth.middleware.ts +163 -163
  149. package/server/modules/auth/auth.module.ts +38 -38
  150. package/server/modules/auth/auth.routes.ts +57 -57
  151. package/server/modules/auth/auth.service.ts +155 -155
  152. package/server/modules/auth/index.ts +9 -9
  153. package/server/modules/auth/tests/auth.service.test.ts +95 -95
  154. package/server/modules/browser-use/browser-use-mcp.routes.ts +120 -120
  155. package/server/modules/browser-use/browser-use-mcp.ts +386 -386
  156. package/server/modules/browser-use/browser-use-runtime.ts +10 -10
  157. package/server/modules/browser-use/browser-use.routes.ts +96 -96
  158. package/server/modules/browser-use/browser-use.service.ts +836 -836
  159. package/server/modules/browser-use/index.ts +11 -11
  160. package/server/modules/browser-use/tests/browser-use.service.test.ts +10 -10
  161. package/server/modules/cli/cli.module.ts +93 -93
  162. package/server/modules/cli/cli.service.ts +248 -248
  163. package/server/modules/cli/cli.ts +19 -19
  164. package/server/modules/cli/index.ts +2 -2
  165. package/server/modules/cli/sandbox.service.ts +398 -398
  166. package/server/modules/cli/tests/cli-environment-bootstrap.test.ts +186 -186
  167. package/server/modules/cli/tests/cli.service.test.ts +86 -86
  168. package/server/modules/cli/tests/sandbox.service.test.ts +58 -58
  169. package/server/modules/commands/commands.module.ts +22 -22
  170. package/server/modules/commands/commands.routes.ts +586 -586
  171. package/server/modules/commands/index.ts +2 -2
  172. package/server/modules/commands/tests/commands.test.ts +109 -109
  173. package/server/modules/database/connection.ts +143 -143
  174. package/server/modules/database/index.ts +17 -17
  175. package/server/modules/database/init-db.ts +17 -17
  176. package/server/modules/database/migrations.ts +515 -515
  177. package/server/modules/database/repositories/api-keys.ts +119 -119
  178. package/server/modules/database/repositories/app-config.ts +53 -53
  179. package/server/modules/database/repositories/credentials.ts +106 -106
  180. package/server/modules/database/repositories/github-tokens.ts +100 -100
  181. package/server/modules/database/repositories/notification-channel-endpoints.ts +153 -153
  182. package/server/modules/database/repositories/notification-preferences.ts +117 -117
  183. package/server/modules/database/repositories/projects.db.ts +196 -196
  184. package/server/modules/database/repositories/provider-models.ts +168 -168
  185. package/server/modules/database/repositories/push-subscriptions.ts +80 -80
  186. package/server/modules/database/repositories/scan-state.db.ts +42 -42
  187. package/server/modules/database/repositories/sessions.db.ts +524 -524
  188. package/server/modules/database/repositories/users.ts +140 -140
  189. package/server/modules/database/repositories/vapid-keys.ts +57 -57
  190. package/server/modules/database/schema.ts +210 -210
  191. package/server/modules/database/tests/projects.db.integration.test.ts +72 -72
  192. package/server/modules/database/tests/provider-models.db.integration.test.ts +125 -125
  193. package/server/modules/database/tests/sessions-provider-mapping.test.ts +109 -109
  194. package/server/modules/database/tests/sessions.db.integration.test.ts +116 -116
  195. package/server/modules/file-tree/file-tree.module.ts +116 -116
  196. package/server/modules/file-tree/file-tree.routes.ts +258 -258
  197. package/server/modules/file-tree/file-tree.service.ts +675 -675
  198. package/server/modules/file-tree/index.ts +2 -2
  199. package/server/modules/file-tree/tests/file-tree.routes.test.ts +157 -157
  200. package/server/modules/file-tree/tests/file-tree.service.test.ts +371 -371
  201. package/server/modules/git/git-branch.service.ts +43 -43
  202. package/server/modules/git/git-parsing.service.ts +66 -66
  203. package/server/modules/git/git.module.ts +22 -22
  204. package/server/modules/git/git.routes.ts +1596 -1596
  205. package/server/modules/git/index.ts +2 -2
  206. package/server/modules/git/tests/git-branch.service.test.ts +60 -60
  207. package/server/modules/git/tests/git-init.routes.test.ts +132 -132
  208. package/server/modules/git/tests/git.test.ts +106 -106
  209. package/server/modules/notifications/index.ts +24 -24
  210. package/server/modules/notifications/notifications.routes.ts +127 -127
  211. package/server/modules/notifications/services/desktop-notification-clients.service.ts +124 -124
  212. package/server/modules/notifications/services/notification-orchestrator.service.js +310 -310
  213. package/server/modules/notifications/tests/notification-orchestrator.integration.test.ts +55 -55
  214. package/server/modules/notifications/vapid-keys.service.ts +38 -38
  215. package/server/modules/notifications/websocket/desktop-notifications-websocket.service.ts +109 -109
  216. package/server/modules/plugins/index.ts +9 -9
  217. package/server/modules/plugins/plugin-process.service.ts +217 -217
  218. package/server/modules/plugins/plugin-registry.service.ts +459 -459
  219. package/server/modules/plugins/plugins.module.ts +33 -33
  220. package/server/modules/plugins/plugins.routes.ts +66 -66
  221. package/server/modules/plugins/plugins.service.ts +147 -147
  222. package/server/modules/plugins/tests/plugins.service.test.ts +32 -32
  223. package/server/modules/projects/index.ts +11 -11
  224. package/server/modules/projects/projects.routes.ts +273 -273
  225. package/server/modules/projects/services/project-clone.service.ts +323 -323
  226. package/server/modules/projects/services/project-delete.service.ts +90 -90
  227. package/server/modules/projects/services/project-management.service.ts +144 -144
  228. package/server/modules/projects/services/project-star.service.ts +78 -78
  229. package/server/modules/projects/services/projects-has-taskmaster.service.ts +248 -248
  230. package/server/modules/projects/services/projects-with-sessions-fetch.service.ts +314 -314
  231. package/server/modules/projects/tests/project-clone.service.test.ts +183 -183
  232. package/server/modules/projects/tests/project-management.service.test.ts +117 -117
  233. package/server/modules/projects/tests/project-star.service.test.ts +123 -123
  234. package/server/modules/projects/tests/projects-has-taskmaster.service.test.ts +105 -105
  235. package/server/modules/providers/README.md +380 -380
  236. package/server/modules/providers/index.ts +10 -10
  237. package/server/modules/providers/list/claude/claude-auth.provider.ts +160 -160
  238. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  239. package/server/modules/providers/list/claude/claude-models.provider.ts +294 -294
  240. package/server/modules/providers/list/claude/claude-runtime.provider.js +1068 -1068
  241. package/server/modules/providers/list/claude/claude-session-synchronizer.provider.ts +203 -203
  242. package/server/modules/providers/list/claude/claude-sessions.provider.ts +684 -684
  243. package/server/modules/providers/list/claude/claude-skills.provider.ts +265 -265
  244. package/server/modules/providers/list/claude/claude.provider.ts +30 -30
  245. package/server/modules/providers/list/codex/codex-auth.provider.ts +100 -100
  246. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  247. package/server/modules/providers/list/codex/codex-models.provider.ts +123 -123
  248. package/server/modules/providers/list/codex/codex-runtime.provider.js +533 -533
  249. package/server/modules/providers/list/codex/codex-session-synchronizer.provider.ts +203 -203
  250. package/server/modules/providers/list/codex/codex-sessions.provider.ts +938 -938
  251. package/server/modules/providers/list/codex/codex-skills.provider.ts +73 -73
  252. package/server/modules/providers/list/codex/codex.provider.ts +28 -28
  253. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +143 -143
  254. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  255. package/server/modules/providers/list/cursor/cursor-models.provider.ts +119 -119
  256. package/server/modules/providers/list/cursor/cursor-runtime.provider.js +385 -385
  257. package/server/modules/providers/list/cursor/cursor-session-synchronizer.provider.ts +159 -159
  258. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +654 -654
  259. package/server/modules/providers/list/cursor/cursor-skills.provider.ts +39 -39
  260. package/server/modules/providers/list/cursor/cursor.provider.ts +30 -30
  261. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +110 -110
  262. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +228 -228
  263. package/server/modules/providers/list/opencode/opencode-models.provider.ts +203 -203
  264. package/server/modules/providers/list/opencode/opencode-runtime.provider.js +434 -434
  265. package/server/modules/providers/list/opencode/opencode-runtime.provider.test.js +261 -261
  266. package/server/modules/providers/list/opencode/opencode-session-synchronizer.provider.ts +179 -179
  267. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +500 -500
  268. package/server/modules/providers/list/opencode/opencode-skills.provider.ts +78 -78
  269. package/server/modules/providers/list/opencode/opencode.provider.ts +30 -30
  270. package/server/modules/providers/provider.registry.ts +36 -36
  271. package/server/modules/providers/provider.routes.ts +877 -877
  272. package/server/modules/providers/services/mcp.service.ts +109 -109
  273. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  274. package/server/modules/providers/services/provider-capabilities.service.ts +97 -97
  275. package/server/modules/providers/services/provider-models.service.ts +401 -401
  276. package/server/modules/providers/services/provider-runtime.service.ts +108 -108
  277. package/server/modules/providers/services/provider-token-usage.service.ts +357 -357
  278. package/server/modules/providers/services/session-conversations-search.service.ts +1321 -1321
  279. package/server/modules/providers/services/session-synchronizer.service.ts +74 -74
  280. package/server/modules/providers/services/sessions-watcher.service.ts +247 -247
  281. package/server/modules/providers/services/sessions.service.ts +471 -471
  282. package/server/modules/providers/services/skills.service.ts +39 -39
  283. package/server/modules/providers/shared/base/abstract.provider.ts +32 -32
  284. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  285. package/server/modules/providers/shared/skills/skills.provider.ts +287 -287
  286. package/server/modules/providers/tests/claude-auth.test.ts +150 -150
  287. package/server/modules/providers/tests/claude-sessions.test.ts +61 -61
  288. package/server/modules/providers/tests/codex-sessions.test.ts +231 -231
  289. package/server/modules/providers/tests/mcp.test.ts +349 -349
  290. package/server/modules/providers/tests/opencode-models.test.ts +41 -41
  291. package/server/modules/providers/tests/opencode-sessions.test.ts +522 -522
  292. package/server/modules/providers/tests/provider-attachment-history.test.ts +247 -247
  293. package/server/modules/providers/tests/provider-models.service.test.ts +353 -353
  294. package/server/modules/providers/tests/provider-runtime.service.test.ts +138 -138
  295. package/server/modules/providers/tests/provider-token-usage.service.test.ts +186 -186
  296. package/server/modules/providers/tests/provider.routes.test.ts +244 -244
  297. package/server/modules/providers/tests/sessions-details.test.ts +73 -73
  298. package/server/modules/providers/tests/sessions.service.test.ts +127 -127
  299. package/server/modules/providers/tests/skills.test.ts +692 -692
  300. package/server/modules/settings/index.ts +2 -2
  301. package/server/modules/settings/settings.module.ts +50 -50
  302. package/server/modules/settings/settings.routes.ts +51 -51
  303. package/server/modules/settings/settings.service.ts +186 -186
  304. package/server/modules/settings/tests/settings.service.test.ts +54 -54
  305. package/server/modules/system/index.ts +2 -2
  306. package/server/modules/system/system.module.ts +62 -62
  307. package/server/modules/system/system.routes.ts +21 -21
  308. package/server/modules/system/system.service.ts +76 -76
  309. package/server/modules/system/tests/system.service.test.ts +118 -118
  310. package/server/modules/taskmaster/index.ts +2 -2
  311. package/server/modules/taskmaster/taskmaster.module.ts +24 -24
  312. package/server/modules/taskmaster/taskmaster.routes.ts +1482 -1482
  313. package/server/modules/taskmaster/taskmaster.service.ts +132 -132
  314. package/server/modules/taskmaster/tests/taskmaster.routes.test.ts +144 -144
  315. package/server/modules/taskmaster/tests/taskmaster.service.test.ts +97 -97
  316. package/server/modules/user/index.ts +2 -2
  317. package/server/modules/user/tests/user.service.test.ts +61 -61
  318. package/server/modules/user/user.module.ts +58 -58
  319. package/server/modules/user/user.routes.ts +50 -50
  320. package/server/modules/user/user.service.ts +85 -85
  321. package/server/modules/voice/index.ts +2 -2
  322. package/server/modules/voice/tests/voice.service.test.ts +98 -98
  323. package/server/modules/voice/voice.module.ts +47 -47
  324. package/server/modules/voice/voice.routes.ts +113 -113
  325. package/server/modules/voice/voice.service.ts +192 -192
  326. package/server/modules/websocket/README.md +273 -273
  327. package/server/modules/websocket/index.ts +3 -3
  328. package/server/modules/websocket/services/chat-run-registry.service.ts +343 -343
  329. package/server/modules/websocket/services/chat-session-writer.service.ts +145 -145
  330. package/server/modules/websocket/services/chat-websocket.service.ts +425 -425
  331. package/server/modules/websocket/services/plugin-websocket-proxy.service.ts +65 -65
  332. package/server/modules/websocket/services/shell-websocket.service.ts +502 -502
  333. package/server/modules/websocket/services/websocket-auth.service.ts +59 -59
  334. package/server/modules/websocket/services/websocket-server.service.ts +124 -124
  335. package/server/modules/websocket/services/websocket-state.service.ts +16 -16
  336. package/server/modules/websocket/services/websocket-writer.service.ts +38 -38
  337. package/server/modules/websocket/tests/chat-attachment-filter.test.ts +59 -59
  338. package/server/modules/websocket/tests/chat-run-registry.test.ts +282 -282
  339. package/server/modules/websocket/tests/shell-websocket.service.test.ts +100 -100
  340. package/server/modules/websocket/tests/websocket-heartbeat.service.test.ts +78 -78
  341. package/server/modules/worktrees/index.ts +2 -2
  342. package/server/modules/worktrees/services/worktree-create-and-open.service.ts +53 -53
  343. package/server/modules/worktrees/services/worktree-create.service.ts +104 -104
  344. package/server/modules/worktrees/services/worktree-git.service.ts +207 -207
  345. package/server/modules/worktrees/services/worktree-list.service.ts +143 -143
  346. package/server/modules/worktrees/services/worktree-merge.service.ts +157 -157
  347. package/server/modules/worktrees/services/worktree-open.service.ts +85 -85
  348. package/server/modules/worktrees/services/worktree-remove.service.ts +88 -88
  349. package/server/modules/worktrees/tests/worktree-create-and-open.service.test.ts +68 -68
  350. package/server/modules/worktrees/tests/worktree-create.service.test.ts +142 -142
  351. package/server/modules/worktrees/tests/worktree-git.service.test.ts +84 -84
  352. package/server/modules/worktrees/tests/worktree-list.service.test.ts +45 -45
  353. package/server/modules/worktrees/tests/worktree-merge.service.test.ts +213 -213
  354. package/server/modules/worktrees/tests/worktree-open.service.test.ts +122 -122
  355. package/server/modules/worktrees/tests/worktree-remove.service.test.ts +227 -227
  356. package/server/modules/worktrees/tests/worktrees.routes.test.ts +199 -199
  357. package/server/modules/worktrees/worktrees.module.ts +113 -113
  358. package/server/modules/worktrees/worktrees.routes.ts +116 -116
  359. package/server/shared/claude-cli-path.ts +139 -139
  360. package/server/shared/frontmatter.ts +18 -18
  361. package/server/shared/image-attachments.ts +435 -435
  362. package/server/shared/interfaces.ts +179 -179
  363. package/server/shared/tests/claude-cli-path.test.ts +61 -61
  364. package/server/shared/tests/image-attachments.test.ts +353 -353
  365. package/server/shared/tests/slice-tail-page.test.ts +42 -42
  366. package/server/shared/types.ts +1226 -1226
  367. package/server/shared/utils.ts +1161 -1161
  368. package/server/tsconfig.json +40 -40
  369. package/shared/networkHosts.js +22 -22
  370. package/dist/assets/channel-Bm0ZLE4z.js +0 -1
  371. package/dist/assets/classDiagram-JCYQIIEL-DqEOcNxw.js +0 -1
  372. package/dist/assets/classDiagram-v2-OCEON4UE-DqEOcNxw.js +0 -1
  373. package/dist/assets/stateDiagram-v2-UEYNNEHI-DARLpEFJ.js +0 -1
  374. package/dist/assets/swimlanesDiagram-ULZ7WXOC-CrgDgaY8.js +0 -8
@@ -1,1321 +1,1321 @@
1
- import fsSync from 'node:fs';
2
- import path from 'node:path';
3
- import readline from 'node:readline';
4
-
5
- import { spawn } from 'cross-spawn';
6
- import { rgPath } from '@vscode/ripgrep';
7
-
8
- import { projectsDb, sessionsDb } from '@/modules/database/index.js';
9
-
10
- type AnyRecord = Record<string, any>;
11
- type SearchableProvider = 'claude' | 'codex';
12
-
13
- type SearchSnippetHighlight = {
14
- start: number;
15
- end: number;
16
- };
17
-
18
- type SessionConversationMatch = {
19
- role: string;
20
- snippet: string;
21
- highlights: SearchSnippetHighlight[];
22
- timestamp: string | null;
23
- provider: SearchableProvider;
24
- messageUuid?: string | null;
25
- };
26
-
27
- type SessionConversationResult = {
28
- sessionId: string;
29
- provider: SearchableProvider;
30
- sessionSummary: string;
31
- matches: SessionConversationMatch[];
32
- };
33
-
34
- type ProjectConversationResult = {
35
- projectId: string | null;
36
- projectName: string;
37
- projectDisplayName: string;
38
- sessions: SessionConversationResult[];
39
- };
40
-
41
- type SessionTitleSearchResult = {
42
- sessionId: string;
43
- provider: string;
44
- projectId: string | null;
45
- projectDisplayName: string;
46
- sessionTitle: string;
47
- lastActivity: string | null;
48
- };
49
-
50
- export type SessionConversationSearchProgressUpdate = {
51
- projectResult: ProjectConversationResult | null;
52
- totalMatches: number;
53
- scannedProjects: number;
54
- totalProjects: number;
55
- };
56
-
57
- type SearchSessionConversationsInput = {
58
- query: string;
59
- limit: number;
60
- signal?: AbortSignal;
61
- onTitleResults?: (results: SessionTitleSearchResult[]) => void;
62
- onProgress?: (update: SessionConversationSearchProgressUpdate) => void;
63
- };
64
-
65
- type SessionRepositoryRow = ReturnType<typeof sessionsDb.getAllSessions>[number];
66
- type SearchableSessionRow = SessionRepositoryRow & {
67
- provider: SearchableProvider;
68
- jsonl_path: string;
69
- };
70
-
71
- type SearchRuntime = {
72
- matchesQuery: (text: string) => boolean;
73
- buildSnippet: (text: string) => { snippet: string; highlights: SearchSnippetHighlight[] };
74
- limit: number;
75
- totalMatches: number;
76
- isAborted: () => boolean;
77
- matchedSessionKeys: Set<string>;
78
- claudeSessionsByFileKey: Map<string, SearchableSessionRow[]>;
79
- claudeFileResultsCache: Map<string, Map<string, SessionConversationResult>>;
80
- };
81
-
82
- type SearchablePathEntry = {
83
- normalizedPath: string;
84
- absolutePath: string;
85
- };
86
-
87
- type ProjectBucket = {
88
- key: string;
89
- projectId: string | null;
90
- projectName: string;
91
- projectDisplayName: string;
92
- sessions: SearchableSessionRow[];
93
- };
94
-
95
- const SUPPORTED_PROVIDERS = new Set<SearchableProvider>(['claude', 'codex']);
96
- const MAX_MATCHES_PER_SESSION = 2;
97
- const RIPGREP_FILE_CHUNK_SIZE = 40;
98
- const RIPGREP_CHUNK_CONCURRENCY = 6;
99
- const UNKNOWN_PROJECT_KEY = '__unknown_project__';
100
-
101
- const INTERNAL_CONTENT_PREFIXES = [
102
- '<system-reminder>',
103
- 'Caveat:',
104
- 'Invalid API key',
105
- '[Request interrupted',
106
- ] as const;
107
-
108
- /**
109
- * Codex includes extra internal metadata tags that should not surface as
110
- * user-facing searchable conversation content.
111
- */
112
- const CODEX_INTERNAL_CONTENT_PREFIXES = [
113
- '<environment_context>',
114
- '<cwd>',
115
- ] as const;
116
-
117
- function normalizeComparablePath(inputPath: string): string {
118
- if (!inputPath || typeof inputPath !== 'string') {
119
- return '';
120
- }
121
-
122
- const withoutLongPathPrefix = inputPath.startsWith('\\\\?\\')
123
- ? inputPath.slice(4)
124
- : inputPath;
125
- const normalized = path.normalize(withoutLongPathPrefix.trim());
126
- if (!normalized) {
127
- return '';
128
- }
129
-
130
- const resolved = path.resolve(normalized);
131
- return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
132
- }
133
-
134
- function chunkArray<TItem>(items: TItem[], size: number): TItem[][] {
135
- if (size <= 0) {
136
- return [items];
137
- }
138
-
139
- const chunks: TItem[][] = [];
140
- for (let idx = 0; idx < items.length; idx += size) {
141
- chunks.push(items.slice(idx, idx + size));
142
- }
143
- return chunks;
144
- }
145
-
146
- function getSessionKey(session: Pick<SessionRepositoryRow, 'provider' | 'session_id'>): string {
147
- return `${session.provider}:${session.session_id}`;
148
- }
149
-
150
- function makeProjectKey(projectPath: string | null): string {
151
- const normalized = typeof projectPath === 'string' ? projectPath.trim() : '';
152
- return normalized.length > 0 ? normalized : UNKNOWN_PROJECT_KEY;
153
- }
154
-
155
- function toSummaryText(customName: string | null, fallback: string | null | undefined, emptyLabel: string): string {
156
- const trimmedCustomName = typeof customName === 'string' ? customName.trim() : '';
157
- if (trimmedCustomName) {
158
- return trimmedCustomName;
159
- }
160
-
161
- const trimmedFallback = typeof fallback === 'string' ? fallback.trim() : '';
162
- if (!trimmedFallback) {
163
- return emptyLabel;
164
- }
165
-
166
- return trimmedFallback.length > 50 ? `${trimmedFallback.slice(0, 50)}...` : trimmedFallback;
167
- }
168
-
169
- /**
170
- * Finds visible sessions whose displayed title contains the query. Title
171
- * matches are resolved from the database before transcript scanning so the UI
172
- * can always present them first, including sessions without a transcript yet.
173
- */
174
- function findSessionTitleResults(
175
- sessions: SessionRepositoryRow[],
176
- query: string,
177
- limit: number,
178
- ): SessionTitleSearchResult[] {
179
- const normalizedQuery = query.toLocaleLowerCase().replace(/\s+/g, ' ');
180
- const projectCache = new Map<string, ReturnType<typeof projectsDb.getProjectPath>>();
181
-
182
- return sessions
183
- .flatMap((session) => {
184
- const sessionTitle = toSummaryText(session.custom_name, session.session_id, session.session_id);
185
- const normalizedTitle = sessionTitle.toLocaleLowerCase().replace(/\s+/g, ' ');
186
- const matchIndex = normalizedTitle.indexOf(normalizedQuery);
187
- if (matchIndex === -1) {
188
- return [];
189
- }
190
-
191
- const projectPath = typeof session.project_path === 'string' && session.project_path.trim()
192
- ? session.project_path.trim()
193
- : null;
194
- const projectKey = projectPath ?? UNKNOWN_PROJECT_KEY;
195
- if (!projectCache.has(projectKey)) {
196
- projectCache.set(
197
- projectKey,
198
- projectPath ? projectsDb.getProjectPath(projectPath) : null,
199
- );
200
- }
201
-
202
- const project = projectCache.get(projectKey) ?? null;
203
- if (project?.isArchived) {
204
- return [];
205
- }
206
-
207
- return [{
208
- sessionId: session.session_id,
209
- provider: session.provider,
210
- projectId: project?.project_id ?? null,
211
- projectDisplayName: projectPath
212
- ? (project?.custom_project_name?.trim() || path.basename(projectPath) || projectPath)
213
- : 'Unknown Project',
214
- sessionTitle,
215
- lastActivity: session.updated_at || session.created_at || null,
216
- matchIndex,
217
- }];
218
- })
219
- .sort((left, right) => {
220
- if (left.matchIndex !== right.matchIndex) {
221
- return left.matchIndex - right.matchIndex;
222
- }
223
-
224
- return new Date(right.lastActivity ?? 0).getTime() - new Date(left.lastActivity ?? 0).getTime();
225
- })
226
- .slice(0, limit)
227
- .map(({ matchIndex: _matchIndex, ...result }) => result);
228
- }
229
-
230
- function isInternalContent(content: string): boolean {
231
- return INTERNAL_CONTENT_PREFIXES.some((prefix) => content.startsWith(prefix));
232
- }
233
-
234
- function isInternalCodexContent(content: string): boolean {
235
- const normalized = content.trimStart();
236
- return CODEX_INTERNAL_CONTENT_PREFIXES.some((prefix) => normalized.startsWith(prefix));
237
- }
238
-
239
- function escapeRegex(value: string): string {
240
- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
241
- }
242
-
243
- function createWordMatcher(
244
- rawQuery: string,
245
- words: string[],
246
- ): Pick<SearchRuntime, 'matchesQuery' | 'buildSnippet'> {
247
- const normalizedQuery = rawQuery.trim().replace(/\s+/g, ' ');
248
- const requireExactPhrase = words.length > 1 && normalizedQuery.length > 0;
249
- const wordPatterns = words.map((word) => new RegExp(`(?<!\\p{L})${escapeRegex(word)}(?!\\p{L})`, 'u'));
250
- const phrasePattern = words.map((word) => escapeRegex(word)).join('\\s+');
251
- const phraseRegex = new RegExp(phrasePattern, 'iu');
252
-
253
- const allWordsMatch = (textLower: string): boolean =>
254
- wordPatterns.every((pattern) => pattern.test(textLower));
255
-
256
- const matchesQuery = (text: string): boolean => {
257
- if (typeof text !== 'string' || text.length === 0) {
258
- return false;
259
- }
260
-
261
- if (requireExactPhrase) {
262
- return phraseRegex.test(text);
263
- }
264
-
265
- if (phraseRegex.test(text)) {
266
- return true;
267
- }
268
-
269
- if (words.length === 1) {
270
- return allWordsMatch(text.toLowerCase());
271
- }
272
-
273
- return allWordsMatch(text.toLowerCase());
274
- };
275
-
276
- const buildSnippet = (
277
- text: string,
278
- snippetLen = 150,
279
- ): { snippet: string; highlights: SearchSnippetHighlight[] } => {
280
- const textLower = text.toLowerCase();
281
- let firstIndex = -1;
282
- let firstWordLen = 0;
283
- let phraseStart = -1;
284
- let phraseLength = 0;
285
-
286
- const phraseMatch = phraseRegex.exec(text);
287
- if (phraseMatch) {
288
- phraseStart = phraseMatch.index;
289
- phraseLength = phraseMatch[0].length;
290
- firstIndex = phraseStart;
291
- firstWordLen = phraseLength;
292
- }
293
-
294
- if (firstIndex === -1) {
295
- for (const word of words) {
296
- const regex = new RegExp(`(?<!\\p{L})${escapeRegex(word)}(?!\\p{L})`, 'u');
297
- const match = regex.exec(textLower);
298
- if (match && (firstIndex === -1 || match.index < firstIndex)) {
299
- firstIndex = match.index;
300
- firstWordLen = word.length;
301
- }
302
- }
303
- }
304
-
305
- if (firstIndex === -1) {
306
- firstIndex = 0;
307
- }
308
-
309
- const halfLen = Math.floor(snippetLen / 2);
310
- const start = Math.max(0, firstIndex - halfLen);
311
- const end = Math.min(text.length, firstIndex + halfLen + firstWordLen);
312
- const prefix = start > 0 ? '...' : '';
313
- const suffix = end < text.length ? '...' : '';
314
- const snippetBody = text.slice(start, end).replace(/\n/g, ' ');
315
- const snippet = `${prefix}${snippetBody}${suffix}`;
316
-
317
- const snippetLower = snippet.toLowerCase();
318
- const highlights: SearchSnippetHighlight[] = [];
319
-
320
- if (phraseStart >= start && phraseStart + phraseLength <= end) {
321
- const phraseOffset = prefix.length + (phraseStart - start);
322
- highlights.push({
323
- start: phraseOffset,
324
- end: phraseOffset + phraseLength,
325
- });
326
- }
327
-
328
- if (!requireExactPhrase) {
329
- for (const word of words) {
330
- const regex = new RegExp(`(?<!\\p{L})${escapeRegex(word)}(?!\\p{L})`, 'gu');
331
- let match = regex.exec(snippetLower);
332
- while (match) {
333
- highlights.push({ start: match.index, end: match.index + word.length });
334
- match = regex.exec(snippetLower);
335
- }
336
- }
337
- }
338
-
339
- highlights.sort((left, right) => left.start - right.start);
340
- const merged: SearchSnippetHighlight[] = [];
341
- for (const highlight of highlights) {
342
- const previous = merged[merged.length - 1];
343
- if (previous && highlight.start <= previous.end) {
344
- previous.end = Math.max(previous.end, highlight.end);
345
- } else {
346
- merged.push({ ...highlight });
347
- }
348
- }
349
-
350
- return { snippet, highlights: merged };
351
- };
352
-
353
- return { matchesQuery, buildSnippet };
354
- }
355
-
356
- function extractClaudeText(content: unknown): string {
357
- if (typeof content === 'string') {
358
- return content;
359
- }
360
-
361
- if (!Array.isArray(content)) {
362
- return '';
363
- }
364
-
365
- return content
366
- .filter((part: AnyRecord) => part?.type === 'text' && typeof part?.text === 'string')
367
- .map((part: AnyRecord) => String(part.text))
368
- .join(' ');
369
- }
370
-
371
- function extractTaggedContent(content: string, tagName: string): string | null {
372
- const escapedTagName = tagName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
373
- const match = new RegExp(`<${escapedTagName}>([\\s\\S]*?)<\\/${escapedTagName}>`).exec(content);
374
- return match ? match[1] : null;
375
- }
376
-
377
- type ClaudeLocalCommandPayload = {
378
- commandName: string;
379
- commandMessage: string;
380
- commandArgs: string;
381
- };
382
-
383
- function parseClaudeLocalCommandPayload(content: string): ClaudeLocalCommandPayload | null {
384
- const commandName = extractTaggedContent(content, 'command-name');
385
- const commandMessage = extractTaggedContent(content, 'command-message');
386
- const commandArgs = extractTaggedContent(content, 'command-args');
387
-
388
- if (commandName === null && commandMessage === null && commandArgs === null) {
389
- return null;
390
- }
391
-
392
- return {
393
- commandName: commandName ?? '',
394
- commandMessage: commandMessage ?? '',
395
- commandArgs: commandArgs ?? '',
396
- };
397
- }
398
-
399
- function buildClaudeLocalCommandDisplayText(payload: ClaudeLocalCommandPayload): string {
400
- const commandName = payload.commandName.trim();
401
- const commandMessage = payload.commandMessage.trim();
402
- const commandArgs = payload.commandArgs.trim();
403
- const baseCommand = commandName || commandMessage;
404
-
405
- if (!baseCommand) {
406
- return '';
407
- }
408
-
409
- return commandArgs ? `${baseCommand} ${commandArgs}` : baseCommand;
410
- }
411
-
412
- function stripAnsiFormatting(text: string): string {
413
- return text.replace(/\u001B\[[0-9;?]*[ -/]*[@-~]/g, '');
414
- }
415
-
416
- type ClaudeSearchableMessage = {
417
- text: string;
418
- role: 'user' | 'assistant';
419
- };
420
-
421
- /**
422
- * Claude mixes visible chat, compact summaries, and local command wrappers into
423
- * the same transcript stream. Search should operate on the user-visible meaning
424
- * of those rows rather than the raw wrapper syntax.
425
- */
426
- function extractClaudeSearchableMessage(entry: AnyRecord): ClaudeSearchableMessage | null {
427
- if (!entry.message?.content || entry.isApiErrorMessage) {
428
- return null;
429
- }
430
-
431
- const rawRole = entry.message.role;
432
- if (rawRole !== 'user' && rawRole !== 'assistant') {
433
- return null;
434
- }
435
-
436
- if (typeof entry.message.content === 'string') {
437
- const content = String(entry.message.content);
438
-
439
- if (entry.isCompactSummary === true && content.trim()) {
440
- return {
441
- text: content,
442
- role: 'assistant',
443
- };
444
- }
445
-
446
- const localCommand = parseClaudeLocalCommandPayload(content);
447
- if (localCommand) {
448
- const displayText = buildClaudeLocalCommandDisplayText(localCommand);
449
- return displayText
450
- ? {
451
- text: displayText,
452
- role: 'user',
453
- }
454
- : null;
455
- }
456
-
457
- const localCommandStdout = extractTaggedContent(content, 'local-command-stdout');
458
- if (localCommandStdout !== null) {
459
- const stdoutText = stripAnsiFormatting(localCommandStdout).trim();
460
- return stdoutText
461
- ? {
462
- text: stdoutText,
463
- role: 'assistant',
464
- }
465
- : null;
466
- }
467
-
468
- if (!content || isInternalContent(content)) {
469
- return null;
470
- }
471
-
472
- return {
473
- text: content,
474
- role: rawRole,
475
- };
476
- }
477
-
478
- const text = extractClaudeText(entry.message.content);
479
- if (!text) {
480
- return null;
481
- }
482
-
483
- if (entry.isCompactSummary === true) {
484
- return {
485
- text,
486
- role: 'assistant',
487
- };
488
- }
489
-
490
- if (isInternalContent(text)) {
491
- return null;
492
- }
493
-
494
- return {
495
- text,
496
- role: rawRole,
497
- };
498
- }
499
-
500
- function extractCodexText(content: unknown): string {
501
- if (typeof content === 'string') {
502
- return content;
503
- }
504
-
505
- if (!Array.isArray(content)) {
506
- return '';
507
- }
508
-
509
- return content
510
- .map((item) => {
511
- if (!item || typeof item !== 'object') {
512
- return '';
513
- }
514
-
515
- const record = item as AnyRecord;
516
- if (
517
- (record.type === 'input_text' || record.type === 'output_text' || record.type === 'text')
518
- && typeof record.text === 'string'
519
- ) {
520
- return record.text;
521
- }
522
-
523
- return '';
524
- })
525
- .filter(Boolean)
526
- .join(' ');
527
- }
528
-
529
- function normalizeSearchableSessions(rows: SessionRepositoryRow[]): SearchableSessionRow[] {
530
- const normalizedRows: SearchableSessionRow[] = [];
531
- const projectArchiveStateByPath = new Map<string, boolean>();
532
-
533
- for (const row of rows) {
534
- const provider = row.provider as SearchableProvider;
535
- if (!SUPPORTED_PROVIDERS.has(provider)) {
536
- continue;
537
- }
538
-
539
- const rawJsonlPath = typeof row.jsonl_path === 'string' ? row.jsonl_path.trim() : '';
540
- if (!rawJsonlPath) {
541
- continue;
542
- }
543
-
544
- const absoluteJsonlPath = path.resolve(rawJsonlPath);
545
- if (!fsSync.existsSync(absoluteJsonlPath)) {
546
- continue;
547
- }
548
-
549
- /**
550
- * Active session rows can still belong to an archived project because
551
- * project archiving intentionally preserves the underlying session data.
552
- * Global conversation search should follow the visible workspace model,
553
- * which means excluding any session whose owning project is archived.
554
- *
555
- * Cache the archive lookup per normalized project path so one search pass
556
- * does not re-query the same project row for every session in that folder.
557
- */
558
- const normalizedProjectPath = typeof row.project_path === 'string' ? row.project_path.trim() : '';
559
- if (normalizedProjectPath) {
560
- if (!projectArchiveStateByPath.has(normalizedProjectPath)) {
561
- const projectRow = projectsDb.getProjectPath(normalizedProjectPath);
562
- projectArchiveStateByPath.set(normalizedProjectPath, Boolean(projectRow?.isArchived));
563
- }
564
-
565
- if (projectArchiveStateByPath.get(normalizedProjectPath) === true) {
566
- continue;
567
- }
568
- }
569
-
570
- normalizedRows.push({
571
- ...row,
572
- provider,
573
- jsonl_path: absoluteJsonlPath,
574
- });
575
- }
576
-
577
- return normalizedRows;
578
- }
579
-
580
- function buildProjectBuckets(searchableSessions: SearchableSessionRow[]): ProjectBucket[] {
581
- const projectBuckets = new Map<string, ProjectBucket>();
582
- const projectMetadataCache = new Map<string, { projectId: string | null; projectDisplayName: string }>();
583
-
584
- for (const session of searchableSessions) {
585
- const key = makeProjectKey(session.project_path);
586
- if (!projectBuckets.has(key)) {
587
- if (!projectMetadataCache.has(key)) {
588
- if (key === UNKNOWN_PROJECT_KEY) {
589
- projectMetadataCache.set(key, {
590
- projectId: null,
591
- projectDisplayName: 'Unknown Project',
592
- });
593
- } else {
594
- const projectRow = projectsDb.getProjectPath(key);
595
- const customProjectName = typeof projectRow?.custom_project_name === 'string'
596
- ? projectRow.custom_project_name.trim()
597
- : '';
598
- const displayName = customProjectName || path.basename(key) || key;
599
-
600
- projectMetadataCache.set(key, {
601
- projectId: projectRow?.project_id ?? null,
602
- projectDisplayName: displayName,
603
- });
604
- }
605
- }
606
-
607
- const metadata = projectMetadataCache.get(key) as { projectId: string | null; projectDisplayName: string };
608
- projectBuckets.set(key, {
609
- key,
610
- projectId: metadata.projectId,
611
- projectName: key,
612
- projectDisplayName: metadata.projectDisplayName,
613
- sessions: [],
614
- });
615
- }
616
-
617
- const bucket = projectBuckets.get(key) as ProjectBucket;
618
- bucket.sessions.push(session);
619
- }
620
-
621
- const buckets = Array.from(projectBuckets.values());
622
- for (const bucket of buckets) {
623
- bucket.sessions.sort((left, right) => {
624
- const leftTs = new Date(left.updated_at || left.created_at || 0).getTime();
625
- const rightTs = new Date(right.updated_at || right.created_at || 0).getTime();
626
- return rightTs - leftTs;
627
- });
628
- }
629
-
630
- return buckets;
631
- }
632
-
633
- /**
634
- * Executes ripgrep with the file list explicitly provided from sessionsDb jsonl paths.
635
- *
636
- * This avoids recursive directory walks and uses a fixed known candidate list.
637
- */
638
- async function runRipgrepFilesWithMatches(
639
- pattern: string,
640
- filePaths: string[],
641
- signal?: AbortSignal,
642
- ): Promise<Set<string>> {
643
- if (!pattern || filePaths.length === 0 || signal?.aborted) {
644
- return new Set();
645
- }
646
-
647
- return new Promise((resolve, reject) => {
648
- const args = [
649
- '--files-with-matches',
650
- '--no-messages',
651
- '--ignore-case',
652
- '--fixed-strings',
653
- '--',
654
- pattern,
655
- ...filePaths,
656
- ];
657
- const rg = spawn(rgPath, args, {
658
- stdio: ['ignore', 'pipe', 'pipe'],
659
- windowsHide: true,
660
- });
661
-
662
- const stdoutChunks: Buffer[] = [];
663
- const stderrChunks: Buffer[] = [];
664
- let aborted = false;
665
-
666
- const abortListener = () => {
667
- aborted = true;
668
- rg.kill();
669
- };
670
-
671
- if (signal) {
672
- signal.addEventListener('abort', abortListener, { once: true });
673
- }
674
-
675
- rg.stdout.on('data', (chunk: Buffer) => {
676
- stdoutChunks.push(chunk);
677
- });
678
-
679
- rg.stderr.on('data', (chunk: Buffer) => {
680
- stderrChunks.push(chunk);
681
- });
682
-
683
- rg.on('error', (error) => {
684
- if (signal) {
685
- signal.removeEventListener('abort', abortListener);
686
- }
687
-
688
- if (aborted || signal?.aborted) {
689
- resolve(new Set());
690
- return;
691
- }
692
-
693
- reject(error);
694
- });
695
-
696
- rg.on('close', (code) => {
697
- if (signal) {
698
- signal.removeEventListener('abort', abortListener);
699
- }
700
-
701
- if (aborted || signal?.aborted) {
702
- resolve(new Set());
703
- return;
704
- }
705
-
706
- if (code !== 0 && code !== 1) {
707
- const stderr = Buffer.concat(stderrChunks).toString('utf8').trim();
708
- reject(new Error(`ripgrep failed with code ${String(code)}: ${stderr}`));
709
- return;
710
- }
711
-
712
- const stdout = Buffer.concat(stdoutChunks).toString('utf8');
713
- const matchedPaths = new Set<string>();
714
-
715
- for (const line of stdout.split(/\r?\n/)) {
716
- const trimmed = line.trim();
717
- if (!trimmed) {
718
- continue;
719
- }
720
-
721
- matchedPaths.add(normalizeComparablePath(trimmed));
722
- }
723
-
724
- resolve(matchedPaths);
725
- });
726
- });
727
- }
728
-
729
- async function findMatchedFileKeys(
730
- searchablePathEntries: SearchablePathEntry[],
731
- rawQuery: string,
732
- words: string[],
733
- signal?: AbortSignal,
734
- ): Promise<Set<string>> {
735
- if (searchablePathEntries.length === 0 || words.length === 0 || signal?.aborted) {
736
- return new Set();
737
- }
738
-
739
- const normalizedQuery = rawQuery.trim().replace(/\s+/g, ' ');
740
- const requireExactPhrase = words.length > 1 && normalizedQuery.length > 0;
741
-
742
- if (requireExactPhrase) {
743
- let matchedForPhrase = searchablePathEntries.slice();
744
-
745
- // Keep ripgrep as an over-approximation for exact phrase mode by requiring
746
- // each word to appear somewhere in the file, then defer strict phrase
747
- // validation to the in-memory matcher.
748
- for (const word of words) {
749
- if (signal?.aborted) {
750
- return new Set();
751
- }
752
-
753
- const matchedForWord = new Set<string>();
754
- const fileChunks = chunkArray(
755
- matchedForPhrase.map((entry) => entry.absolutePath),
756
- RIPGREP_FILE_CHUNK_SIZE,
757
- );
758
-
759
- let nextChunkIndex = 0;
760
- const workerCount = Math.min(RIPGREP_CHUNK_CONCURRENCY, fileChunks.length);
761
- const workers = Array.from({ length: workerCount }, async () => {
762
- while (nextChunkIndex < fileChunks.length && !signal?.aborted) {
763
- const currentIndex = nextChunkIndex;
764
- nextChunkIndex += 1;
765
- const chunkMatches = await runRipgrepFilesWithMatches(word, fileChunks[currentIndex], signal);
766
- for (const matchedPath of chunkMatches) {
767
- matchedForWord.add(matchedPath);
768
- }
769
- }
770
- });
771
-
772
- await Promise.all(workers);
773
- if (signal?.aborted) {
774
- return new Set();
775
- }
776
-
777
- matchedForPhrase = matchedForPhrase.filter((entry) => matchedForWord.has(entry.normalizedPath));
778
- if (matchedForPhrase.length === 0) {
779
- break;
780
- }
781
- }
782
-
783
- return new Set(matchedForPhrase.map((entry) => entry.normalizedPath));
784
- }
785
-
786
- let remainingEntries = searchablePathEntries.slice();
787
-
788
- // Run one ripgrep pass per term and intersect by keeping only files that
789
- // matched every query word.
790
- for (const word of words) {
791
- if (signal?.aborted) {
792
- return new Set();
793
- }
794
-
795
- const matchedForWord = new Set<string>();
796
- const fileChunks = chunkArray(
797
- remainingEntries.map((entry) => entry.absolutePath),
798
- RIPGREP_FILE_CHUNK_SIZE,
799
- );
800
-
801
- let nextChunkIndex = 0;
802
- const workerCount = Math.min(RIPGREP_CHUNK_CONCURRENCY, fileChunks.length);
803
-
804
- const workers = Array.from({ length: workerCount }, async () => {
805
- while (nextChunkIndex < fileChunks.length && !signal?.aborted) {
806
- const currentIndex = nextChunkIndex;
807
- nextChunkIndex += 1;
808
- const chunkMatches = await runRipgrepFilesWithMatches(word, fileChunks[currentIndex], signal);
809
- for (const matchedPath of chunkMatches) {
810
- matchedForWord.add(matchedPath);
811
- }
812
- }
813
- });
814
-
815
- await Promise.all(workers);
816
- if (signal?.aborted) {
817
- return new Set();
818
- }
819
-
820
- remainingEntries = remainingEntries.filter((entry) => matchedForWord.has(entry.normalizedPath));
821
- if (remainingEntries.length === 0) {
822
- break;
823
- }
824
- }
825
-
826
- return new Set(remainingEntries.map((entry) => entry.normalizedPath));
827
- }
828
-
829
- function addSessionMatch(
830
- runtime: SearchRuntime,
831
- matches: SessionConversationMatch[],
832
- match: SessionConversationMatch,
833
- ): void {
834
- if (runtime.totalMatches >= runtime.limit || matches.length >= MAX_MATCHES_PER_SESSION) {
835
- return;
836
- }
837
-
838
- matches.push(match);
839
- runtime.totalMatches += 1;
840
- }
841
-
842
- async function parseClaudeSessionMatches(
843
- session: SearchableSessionRow,
844
- runtime: SearchRuntime,
845
- ): Promise<SessionConversationResult | null> {
846
- const fileKey = normalizeComparablePath(session.jsonl_path);
847
- if (!fileKey) {
848
- return null;
849
- }
850
-
851
- if (!runtime.claudeFileResultsCache.has(fileKey)) {
852
- const sessionsForFile = runtime.claudeSessionsByFileKey.get(fileKey) || [];
853
- const matchedSessionsForFile = sessionsForFile.filter((candidate) =>
854
- runtime.matchedSessionKeys.has(getSessionKey(candidate)),
855
- );
856
-
857
- const targetSessions = matchedSessionsForFile.length > 0
858
- ? matchedSessionsForFile
859
- : [session];
860
-
861
- // Transcript lines are tagged with the provider session id (e.g. Claude's own
862
- // conversation UUID), which is not necessarily the app-facing `session_id`.
863
- // Match and attribute by the provider id, but map results back to the
864
- // internal `session_id` the rest of the app uses to identify sessions.
865
- const providerToInternalId = new Map<string, string>();
866
- const customNameBySessionId = new Map<string, string | null>();
867
- for (const candidate of targetSessions) {
868
- const providerId = candidate.provider_session_id || candidate.session_id;
869
- providerToInternalId.set(providerId, candidate.session_id);
870
- customNameBySessionId.set(providerId, candidate.custom_name ?? null);
871
- }
872
- const targetSessionIds = new Set(providerToInternalId.keys());
873
-
874
- type ClaudeSessionSearchState = {
875
- matches: SessionConversationMatch[];
876
- pendingSummaries: Map<string, string>;
877
- fallbackUserText: string | null;
878
- fallbackAssistantText: string | null;
879
- resolvedSummary: string | null;
880
- };
881
-
882
- const sessionStateById = new Map<string, ClaudeSessionSearchState>();
883
- const getSessionState = (sessionId: string): ClaudeSessionSearchState => {
884
- if (!sessionStateById.has(sessionId)) {
885
- sessionStateById.set(sessionId, {
886
- matches: [],
887
- pendingSummaries: new Map<string, string>(),
888
- fallbackUserText: null,
889
- fallbackAssistantText: null,
890
- resolvedSummary: null,
891
- });
892
- }
893
- return sessionStateById.get(sessionId) as ClaudeSessionSearchState;
894
- };
895
-
896
- let currentSessionId: string | null = null;
897
-
898
- try {
899
- const fileStream = fsSync.createReadStream(session.jsonl_path);
900
- const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity });
901
-
902
- for await (const line of rl) {
903
- if (runtime.totalMatches >= runtime.limit || runtime.isAborted()) {
904
- break;
905
- }
906
- if (!line.trim()) {
907
- continue;
908
- }
909
-
910
- let entry: AnyRecord;
911
- try {
912
- entry = JSON.parse(line) as AnyRecord;
913
- } catch {
914
- continue;
915
- }
916
-
917
- if (entry.sessionId) {
918
- currentSessionId = String(entry.sessionId);
919
- }
920
- const entrySessionId = entry.sessionId
921
- ? String(entry.sessionId)
922
- : currentSessionId;
923
- if (!entrySessionId || !targetSessionIds.has(entrySessionId)) {
924
- continue;
925
- }
926
-
927
- const state = getSessionState(entrySessionId);
928
-
929
- if (entry.type === 'summary' && entry.summary) {
930
- const summaryValue = String(entry.summary);
931
- if (entry.sessionId) {
932
- state.resolvedSummary = summaryValue;
933
- } else if (entry.leafUuid) {
934
- state.pendingSummaries.set(String(entry.leafUuid), summaryValue);
935
- }
936
- }
937
-
938
- if (!state.resolvedSummary && entry.parentUuid) {
939
- const pendingSummary = state.pendingSummaries.get(String(entry.parentUuid));
940
- if (pendingSummary) {
941
- state.resolvedSummary = pendingSummary;
942
- }
943
- }
944
-
945
- const searchableMessage = extractClaudeSearchableMessage(entry);
946
- if (!searchableMessage) {
947
- continue;
948
- }
949
-
950
- const { text, role } = searchableMessage;
951
-
952
- /**
953
- * Claude compact summaries are the most faithful session-summary source
954
- * after a `/compact` because they describe the post-compaction state that
955
- * the resumed session actually continues from. Prefer them over generic
956
- * fallback user text when present.
957
- */
958
- if (entry.isCompactSummary === true) {
959
- state.resolvedSummary = text;
960
- }
961
-
962
- if (role === 'user') {
963
- state.fallbackUserText = text;
964
- } else {
965
- state.fallbackAssistantText = text;
966
- }
967
-
968
- if (!runtime.matchesQuery(text)) {
969
- continue;
970
- }
971
-
972
- const { snippet, highlights } = runtime.buildSnippet(text);
973
- addSessionMatch(runtime, state.matches, {
974
- role,
975
- snippet,
976
- highlights,
977
- timestamp: entry.timestamp ? String(entry.timestamp) : null,
978
- provider: 'claude',
979
- messageUuid: entry.uuid ? String(entry.uuid) : null,
980
- });
981
- }
982
- } catch {
983
- runtime.claudeFileResultsCache.set(fileKey, new Map());
984
- return null;
985
- }
986
-
987
- const fileResults = new Map<string, SessionConversationResult>();
988
- for (const [sessionId, state] of sessionStateById.entries()) {
989
- if (state.matches.length === 0) {
990
- continue;
991
- }
992
-
993
- const internalSessionId = providerToInternalId.get(sessionId) ?? sessionId;
994
- fileResults.set(internalSessionId, {
995
- sessionId: internalSessionId,
996
- provider: 'claude',
997
- sessionSummary: toSummaryText(
998
- customNameBySessionId.get(sessionId) ?? null,
999
- state.resolvedSummary || state.fallbackUserText || state.fallbackAssistantText,
1000
- 'New Session',
1001
- ),
1002
- matches: state.matches,
1003
- });
1004
- }
1005
-
1006
- runtime.claudeFileResultsCache.set(fileKey, fileResults);
1007
- }
1008
-
1009
- return runtime.claudeFileResultsCache.get(fileKey)?.get(session.session_id) ?? null;
1010
- }
1011
-
1012
- function isVisibleCodexUserMessage(payload: AnyRecord | null | undefined): boolean {
1013
- if (!payload || payload.type !== 'user_message') {
1014
- return false;
1015
- }
1016
-
1017
- if (payload.kind && payload.kind !== 'plain') {
1018
- return false;
1019
- }
1020
-
1021
- return typeof payload.message === 'string' && payload.message.trim().length > 0;
1022
- }
1023
-
1024
- async function parseCodexSessionMatches(
1025
- session: SearchableSessionRow,
1026
- runtime: SearchRuntime,
1027
- ): Promise<SessionConversationResult | null> {
1028
- const matches: SessionConversationMatch[] = [];
1029
- let latestUserMessageText: string | null = null;
1030
- const seenMessageFingerprints = new Set<string>();
1031
-
1032
- try {
1033
- const fileStream = fsSync.createReadStream(session.jsonl_path);
1034
- const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity });
1035
-
1036
- for await (const line of rl) {
1037
- if (runtime.totalMatches >= runtime.limit || runtime.isAborted()) {
1038
- break;
1039
- }
1040
- if (!line.trim()) {
1041
- continue;
1042
- }
1043
-
1044
- let entry: AnyRecord;
1045
- try {
1046
- entry = JSON.parse(line) as AnyRecord;
1047
- } catch {
1048
- continue;
1049
- }
1050
-
1051
- let text: string | null = null;
1052
- let role: 'user' | 'assistant' | null = null;
1053
-
1054
- if (entry.type === 'event_msg' && isVisibleCodexUserMessage(entry.payload as AnyRecord)) {
1055
- text = String(entry.payload.message);
1056
- role = 'user';
1057
- } else if (
1058
- entry.type === 'event_msg'
1059
- && entry.payload?.type === 'agent_reasoning'
1060
- && typeof entry.payload?.text === 'string'
1061
- ) {
1062
- text = String(entry.payload.text);
1063
- role = 'assistant';
1064
- } else if (entry.type === 'response_item' && entry.payload?.type === 'message') {
1065
- const payload = entry.payload as AnyRecord;
1066
- if (payload.role === 'user') {
1067
- text = extractCodexText(payload.content);
1068
- role = 'user';
1069
- } else if (payload.role === 'assistant') {
1070
- text = extractCodexText(payload.content);
1071
- role = 'assistant';
1072
- }
1073
- } else if (entry.type === 'response_item' && entry.payload?.type === 'reasoning') {
1074
- const summaryText = Array.isArray(entry.payload.summary)
1075
- ? entry.payload.summary
1076
- .map((item: AnyRecord) => (typeof item?.text === 'string' ? item.text : ''))
1077
- .filter(Boolean)
1078
- .join('\n')
1079
- : '';
1080
-
1081
- if (summaryText.trim()) {
1082
- text = summaryText;
1083
- role = 'assistant';
1084
- }
1085
- }
1086
-
1087
- if (!text || !role) {
1088
- continue;
1089
- }
1090
- if (isInternalCodexContent(text)) {
1091
- continue;
1092
- }
1093
- if (role === 'user') {
1094
- latestUserMessageText = text;
1095
- }
1096
-
1097
- const fingerprint = `${role}:${text.trim().toLowerCase()}`;
1098
- if (seenMessageFingerprints.has(fingerprint)) {
1099
- continue;
1100
- }
1101
- seenMessageFingerprints.add(fingerprint);
1102
-
1103
- if (!runtime.matchesQuery(text)) {
1104
- continue;
1105
- }
1106
-
1107
- const { snippet, highlights } = runtime.buildSnippet(text);
1108
- addSessionMatch(runtime, matches, {
1109
- role,
1110
- snippet,
1111
- highlights,
1112
- timestamp: entry.timestamp ? String(entry.timestamp) : null,
1113
- provider: 'codex',
1114
- });
1115
- }
1116
- } catch {
1117
- return null;
1118
- }
1119
-
1120
- if (matches.length === 0) {
1121
- return null;
1122
- }
1123
-
1124
- return {
1125
- sessionId: session.session_id,
1126
- provider: 'codex',
1127
- sessionSummary: toSummaryText(session.custom_name, latestUserMessageText, 'Codex Session'),
1128
- matches,
1129
- };
1130
- }
1131
-
1132
- async function parseSessionMatches(
1133
- session: SearchableSessionRow,
1134
- runtime: SearchRuntime,
1135
- ): Promise<SessionConversationResult | null> {
1136
- if (session.provider === 'claude') {
1137
- return parseClaudeSessionMatches(session, runtime);
1138
- }
1139
- if (session.provider === 'codex') {
1140
- return parseCodexSessionMatches(session, runtime);
1141
- }
1142
- return null;
1143
- }
1144
-
1145
- /**
1146
- * Searches session titles and provider transcripts for the provider search
1147
- * service and its route-level integration tests.
1148
- */
1149
- export async function searchConversations(
1150
- query: string,
1151
- limit = 50,
1152
- onProjectResult: ((update: SessionConversationSearchProgressUpdate) => void) | null = null,
1153
- signal: AbortSignal | null = null,
1154
- onTitleResults: ((results: SessionTitleSearchResult[]) => void) | null = null,
1155
- ): Promise<{
1156
- results: ProjectConversationResult[];
1157
- titleResults: SessionTitleSearchResult[];
1158
- totalMatches: number;
1159
- query: string;
1160
- }> {
1161
- const safeQuery = typeof query === 'string' ? query.trim() : '';
1162
- const safeLimit = Math.max(1, Math.min(Number.isFinite(limit) ? limit : 50, 200));
1163
- const words = safeQuery.toLowerCase().split(/\s+/).filter((word) => word.length > 0);
1164
-
1165
- if (words.length === 0) {
1166
- return { results: [], titleResults: [], totalMatches: 0, query: safeQuery };
1167
- }
1168
-
1169
- const isAborted = () => signal?.aborted === true;
1170
- if (isAborted()) {
1171
- return { results: [], titleResults: [], totalMatches: 0, query: safeQuery };
1172
- }
1173
-
1174
- const activeSessions = sessionsDb.getAllSessions();
1175
- const titleResults = findSessionTitleResults(activeSessions, safeQuery, safeLimit);
1176
- onTitleResults?.(titleResults);
1177
-
1178
- const searchableSessions = normalizeSearchableSessions(activeSessions);
1179
- if (searchableSessions.length === 0) {
1180
- return { results: [], titleResults, totalMatches: 0, query: safeQuery };
1181
- }
1182
-
1183
- const sessionsByPathKey = new Map<string, SearchableSessionRow[]>();
1184
- const searchablePathEntries: SearchablePathEntry[] = [];
1185
-
1186
- for (const session of searchableSessions) {
1187
- const normalizedPath = normalizeComparablePath(session.jsonl_path);
1188
- if (!normalizedPath) {
1189
- continue;
1190
- }
1191
-
1192
- if (!sessionsByPathKey.has(normalizedPath)) {
1193
- sessionsByPathKey.set(normalizedPath, []);
1194
- searchablePathEntries.push({
1195
- normalizedPath,
1196
- absolutePath: session.jsonl_path,
1197
- });
1198
- }
1199
-
1200
- const pathSessions = sessionsByPathKey.get(normalizedPath) as SearchableSessionRow[];
1201
- pathSessions.push(session);
1202
- }
1203
-
1204
- const matchedFileKeys = await findMatchedFileKeys(
1205
- searchablePathEntries,
1206
- safeQuery,
1207
- words,
1208
- signal ?? undefined,
1209
- );
1210
- if (isAborted() || matchedFileKeys.size === 0) {
1211
- return { results: [], titleResults, totalMatches: 0, query: safeQuery };
1212
- }
1213
-
1214
- const matchedSessionKeys = new Set<string>();
1215
- for (const fileKey of matchedFileKeys) {
1216
- const sessions = sessionsByPathKey.get(fileKey);
1217
- if (!sessions) {
1218
- continue;
1219
- }
1220
-
1221
- for (const session of sessions) {
1222
- matchedSessionKeys.add(getSessionKey(session));
1223
- }
1224
- }
1225
-
1226
- const projectBuckets = buildProjectBuckets(searchableSessions);
1227
- const totalProjects = projectBuckets.length;
1228
- const results: ProjectConversationResult[] = [];
1229
- let scannedProjects = 0;
1230
-
1231
- const runtime: SearchRuntime = {
1232
- ...createWordMatcher(safeQuery, words),
1233
- limit: safeLimit,
1234
- totalMatches: 0,
1235
- isAborted,
1236
- matchedSessionKeys,
1237
- claudeSessionsByFileKey: new Map<string, SearchableSessionRow[]>(),
1238
- claudeFileResultsCache: new Map<string, Map<string, SessionConversationResult>>(),
1239
- };
1240
-
1241
- for (const [fileKey, sessions] of sessionsByPathKey.entries()) {
1242
- const claudeSessions = sessions.filter((session) => session.provider === 'claude');
1243
- if (claudeSessions.length > 0) {
1244
- runtime.claudeSessionsByFileKey.set(fileKey, claudeSessions);
1245
- }
1246
- }
1247
-
1248
- for (const bucket of projectBuckets) {
1249
- if (runtime.totalMatches >= runtime.limit || runtime.isAborted()) {
1250
- break;
1251
- }
1252
-
1253
- const projectResult: ProjectConversationResult = {
1254
- projectId: bucket.projectId,
1255
- projectName: bucket.projectName,
1256
- projectDisplayName: bucket.projectDisplayName,
1257
- sessions: [],
1258
- };
1259
-
1260
- for (const session of bucket.sessions) {
1261
- if (runtime.totalMatches >= runtime.limit || runtime.isAborted()) {
1262
- break;
1263
- }
1264
- if (!matchedSessionKeys.has(getSessionKey(session))) {
1265
- continue;
1266
- }
1267
-
1268
- const sessionResult = await parseSessionMatches(session, runtime);
1269
- if (sessionResult) {
1270
- projectResult.sessions.push(sessionResult);
1271
- }
1272
- }
1273
-
1274
- scannedProjects += 1;
1275
- if (projectResult.sessions.length > 0) {
1276
- results.push(projectResult);
1277
- onProjectResult?.({
1278
- projectResult,
1279
- totalMatches: runtime.totalMatches,
1280
- scannedProjects,
1281
- totalProjects,
1282
- });
1283
- } else if (onProjectResult && scannedProjects % 10 === 0) {
1284
- onProjectResult({
1285
- projectResult: null,
1286
- totalMatches: runtime.totalMatches,
1287
- scannedProjects,
1288
- totalProjects,
1289
- });
1290
- }
1291
- }
1292
-
1293
- return {
1294
- results,
1295
- titleResults,
1296
- totalMatches: runtime.totalMatches,
1297
- query: safeQuery,
1298
- };
1299
- }
1300
-
1301
- /**
1302
- * Application service for session-conversation search.
1303
- *
1304
- * Provider routes call this service so route handlers stay focused on
1305
- * request parsing/response formatting, while search execution remains
1306
- * centralized in one place.
1307
- */
1308
- export const sessionConversationsSearchService = {
1309
- /**
1310
- * Streams progress updates while the search scans provider session logs.
1311
- */
1312
- async search(input: SearchSessionConversationsInput): Promise<void> {
1313
- await searchConversations(
1314
- input.query,
1315
- input.limit,
1316
- input.onProgress ?? null,
1317
- input.signal ?? null,
1318
- input.onTitleResults ?? null,
1319
- );
1320
- },
1321
- };
1
+ import fsSync from 'node:fs';
2
+ import path from 'node:path';
3
+ import readline from 'node:readline';
4
+
5
+ import { spawn } from 'cross-spawn';
6
+ import { rgPath } from '@vscode/ripgrep';
7
+
8
+ import { projectsDb, sessionsDb } from '@/modules/database/index.js';
9
+
10
+ type AnyRecord = Record<string, any>;
11
+ type SearchableProvider = 'claude' | 'codex';
12
+
13
+ type SearchSnippetHighlight = {
14
+ start: number;
15
+ end: number;
16
+ };
17
+
18
+ type SessionConversationMatch = {
19
+ role: string;
20
+ snippet: string;
21
+ highlights: SearchSnippetHighlight[];
22
+ timestamp: string | null;
23
+ provider: SearchableProvider;
24
+ messageUuid?: string | null;
25
+ };
26
+
27
+ type SessionConversationResult = {
28
+ sessionId: string;
29
+ provider: SearchableProvider;
30
+ sessionSummary: string;
31
+ matches: SessionConversationMatch[];
32
+ };
33
+
34
+ type ProjectConversationResult = {
35
+ projectId: string | null;
36
+ projectName: string;
37
+ projectDisplayName: string;
38
+ sessions: SessionConversationResult[];
39
+ };
40
+
41
+ type SessionTitleSearchResult = {
42
+ sessionId: string;
43
+ provider: string;
44
+ projectId: string | null;
45
+ projectDisplayName: string;
46
+ sessionTitle: string;
47
+ lastActivity: string | null;
48
+ };
49
+
50
+ export type SessionConversationSearchProgressUpdate = {
51
+ projectResult: ProjectConversationResult | null;
52
+ totalMatches: number;
53
+ scannedProjects: number;
54
+ totalProjects: number;
55
+ };
56
+
57
+ type SearchSessionConversationsInput = {
58
+ query: string;
59
+ limit: number;
60
+ signal?: AbortSignal;
61
+ onTitleResults?: (results: SessionTitleSearchResult[]) => void;
62
+ onProgress?: (update: SessionConversationSearchProgressUpdate) => void;
63
+ };
64
+
65
+ type SessionRepositoryRow = ReturnType<typeof sessionsDb.getAllSessions>[number];
66
+ type SearchableSessionRow = SessionRepositoryRow & {
67
+ provider: SearchableProvider;
68
+ jsonl_path: string;
69
+ };
70
+
71
+ type SearchRuntime = {
72
+ matchesQuery: (text: string) => boolean;
73
+ buildSnippet: (text: string) => { snippet: string; highlights: SearchSnippetHighlight[] };
74
+ limit: number;
75
+ totalMatches: number;
76
+ isAborted: () => boolean;
77
+ matchedSessionKeys: Set<string>;
78
+ claudeSessionsByFileKey: Map<string, SearchableSessionRow[]>;
79
+ claudeFileResultsCache: Map<string, Map<string, SessionConversationResult>>;
80
+ };
81
+
82
+ type SearchablePathEntry = {
83
+ normalizedPath: string;
84
+ absolutePath: string;
85
+ };
86
+
87
+ type ProjectBucket = {
88
+ key: string;
89
+ projectId: string | null;
90
+ projectName: string;
91
+ projectDisplayName: string;
92
+ sessions: SearchableSessionRow[];
93
+ };
94
+
95
+ const SUPPORTED_PROVIDERS = new Set<SearchableProvider>(['claude', 'codex']);
96
+ const MAX_MATCHES_PER_SESSION = 2;
97
+ const RIPGREP_FILE_CHUNK_SIZE = 40;
98
+ const RIPGREP_CHUNK_CONCURRENCY = 6;
99
+ const UNKNOWN_PROJECT_KEY = '__unknown_project__';
100
+
101
+ const INTERNAL_CONTENT_PREFIXES = [
102
+ '<system-reminder>',
103
+ 'Caveat:',
104
+ 'Invalid API key',
105
+ '[Request interrupted',
106
+ ] as const;
107
+
108
+ /**
109
+ * Codex includes extra internal metadata tags that should not surface as
110
+ * user-facing searchable conversation content.
111
+ */
112
+ const CODEX_INTERNAL_CONTENT_PREFIXES = [
113
+ '<environment_context>',
114
+ '<cwd>',
115
+ ] as const;
116
+
117
+ function normalizeComparablePath(inputPath: string): string {
118
+ if (!inputPath || typeof inputPath !== 'string') {
119
+ return '';
120
+ }
121
+
122
+ const withoutLongPathPrefix = inputPath.startsWith('\\\\?\\')
123
+ ? inputPath.slice(4)
124
+ : inputPath;
125
+ const normalized = path.normalize(withoutLongPathPrefix.trim());
126
+ if (!normalized) {
127
+ return '';
128
+ }
129
+
130
+ const resolved = path.resolve(normalized);
131
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
132
+ }
133
+
134
+ function chunkArray<TItem>(items: TItem[], size: number): TItem[][] {
135
+ if (size <= 0) {
136
+ return [items];
137
+ }
138
+
139
+ const chunks: TItem[][] = [];
140
+ for (let idx = 0; idx < items.length; idx += size) {
141
+ chunks.push(items.slice(idx, idx + size));
142
+ }
143
+ return chunks;
144
+ }
145
+
146
+ function getSessionKey(session: Pick<SessionRepositoryRow, 'provider' | 'session_id'>): string {
147
+ return `${session.provider}:${session.session_id}`;
148
+ }
149
+
150
+ function makeProjectKey(projectPath: string | null): string {
151
+ const normalized = typeof projectPath === 'string' ? projectPath.trim() : '';
152
+ return normalized.length > 0 ? normalized : UNKNOWN_PROJECT_KEY;
153
+ }
154
+
155
+ function toSummaryText(customName: string | null, fallback: string | null | undefined, emptyLabel: string): string {
156
+ const trimmedCustomName = typeof customName === 'string' ? customName.trim() : '';
157
+ if (trimmedCustomName) {
158
+ return trimmedCustomName;
159
+ }
160
+
161
+ const trimmedFallback = typeof fallback === 'string' ? fallback.trim() : '';
162
+ if (!trimmedFallback) {
163
+ return emptyLabel;
164
+ }
165
+
166
+ return trimmedFallback.length > 50 ? `${trimmedFallback.slice(0, 50)}...` : trimmedFallback;
167
+ }
168
+
169
+ /**
170
+ * Finds visible sessions whose displayed title contains the query. Title
171
+ * matches are resolved from the database before transcript scanning so the UI
172
+ * can always present them first, including sessions without a transcript yet.
173
+ */
174
+ function findSessionTitleResults(
175
+ sessions: SessionRepositoryRow[],
176
+ query: string,
177
+ limit: number,
178
+ ): SessionTitleSearchResult[] {
179
+ const normalizedQuery = query.toLocaleLowerCase().replace(/\s+/g, ' ');
180
+ const projectCache = new Map<string, ReturnType<typeof projectsDb.getProjectPath>>();
181
+
182
+ return sessions
183
+ .flatMap((session) => {
184
+ const sessionTitle = toSummaryText(session.custom_name, session.session_id, session.session_id);
185
+ const normalizedTitle = sessionTitle.toLocaleLowerCase().replace(/\s+/g, ' ');
186
+ const matchIndex = normalizedTitle.indexOf(normalizedQuery);
187
+ if (matchIndex === -1) {
188
+ return [];
189
+ }
190
+
191
+ const projectPath = typeof session.project_path === 'string' && session.project_path.trim()
192
+ ? session.project_path.trim()
193
+ : null;
194
+ const projectKey = projectPath ?? UNKNOWN_PROJECT_KEY;
195
+ if (!projectCache.has(projectKey)) {
196
+ projectCache.set(
197
+ projectKey,
198
+ projectPath ? projectsDb.getProjectPath(projectPath) : null,
199
+ );
200
+ }
201
+
202
+ const project = projectCache.get(projectKey) ?? null;
203
+ if (project?.isArchived) {
204
+ return [];
205
+ }
206
+
207
+ return [{
208
+ sessionId: session.session_id,
209
+ provider: session.provider,
210
+ projectId: project?.project_id ?? null,
211
+ projectDisplayName: projectPath
212
+ ? (project?.custom_project_name?.trim() || path.basename(projectPath) || projectPath)
213
+ : 'Unknown Project',
214
+ sessionTitle,
215
+ lastActivity: session.updated_at || session.created_at || null,
216
+ matchIndex,
217
+ }];
218
+ })
219
+ .sort((left, right) => {
220
+ if (left.matchIndex !== right.matchIndex) {
221
+ return left.matchIndex - right.matchIndex;
222
+ }
223
+
224
+ return new Date(right.lastActivity ?? 0).getTime() - new Date(left.lastActivity ?? 0).getTime();
225
+ })
226
+ .slice(0, limit)
227
+ .map(({ matchIndex: _matchIndex, ...result }) => result);
228
+ }
229
+
230
+ function isInternalContent(content: string): boolean {
231
+ return INTERNAL_CONTENT_PREFIXES.some((prefix) => content.startsWith(prefix));
232
+ }
233
+
234
+ function isInternalCodexContent(content: string): boolean {
235
+ const normalized = content.trimStart();
236
+ return CODEX_INTERNAL_CONTENT_PREFIXES.some((prefix) => normalized.startsWith(prefix));
237
+ }
238
+
239
+ function escapeRegex(value: string): string {
240
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
241
+ }
242
+
243
+ function createWordMatcher(
244
+ rawQuery: string,
245
+ words: string[],
246
+ ): Pick<SearchRuntime, 'matchesQuery' | 'buildSnippet'> {
247
+ const normalizedQuery = rawQuery.trim().replace(/\s+/g, ' ');
248
+ const requireExactPhrase = words.length > 1 && normalizedQuery.length > 0;
249
+ const wordPatterns = words.map((word) => new RegExp(`(?<!\\p{L})${escapeRegex(word)}(?!\\p{L})`, 'u'));
250
+ const phrasePattern = words.map((word) => escapeRegex(word)).join('\\s+');
251
+ const phraseRegex = new RegExp(phrasePattern, 'iu');
252
+
253
+ const allWordsMatch = (textLower: string): boolean =>
254
+ wordPatterns.every((pattern) => pattern.test(textLower));
255
+
256
+ const matchesQuery = (text: string): boolean => {
257
+ if (typeof text !== 'string' || text.length === 0) {
258
+ return false;
259
+ }
260
+
261
+ if (requireExactPhrase) {
262
+ return phraseRegex.test(text);
263
+ }
264
+
265
+ if (phraseRegex.test(text)) {
266
+ return true;
267
+ }
268
+
269
+ if (words.length === 1) {
270
+ return allWordsMatch(text.toLowerCase());
271
+ }
272
+
273
+ return allWordsMatch(text.toLowerCase());
274
+ };
275
+
276
+ const buildSnippet = (
277
+ text: string,
278
+ snippetLen = 150,
279
+ ): { snippet: string; highlights: SearchSnippetHighlight[] } => {
280
+ const textLower = text.toLowerCase();
281
+ let firstIndex = -1;
282
+ let firstWordLen = 0;
283
+ let phraseStart = -1;
284
+ let phraseLength = 0;
285
+
286
+ const phraseMatch = phraseRegex.exec(text);
287
+ if (phraseMatch) {
288
+ phraseStart = phraseMatch.index;
289
+ phraseLength = phraseMatch[0].length;
290
+ firstIndex = phraseStart;
291
+ firstWordLen = phraseLength;
292
+ }
293
+
294
+ if (firstIndex === -1) {
295
+ for (const word of words) {
296
+ const regex = new RegExp(`(?<!\\p{L})${escapeRegex(word)}(?!\\p{L})`, 'u');
297
+ const match = regex.exec(textLower);
298
+ if (match && (firstIndex === -1 || match.index < firstIndex)) {
299
+ firstIndex = match.index;
300
+ firstWordLen = word.length;
301
+ }
302
+ }
303
+ }
304
+
305
+ if (firstIndex === -1) {
306
+ firstIndex = 0;
307
+ }
308
+
309
+ const halfLen = Math.floor(snippetLen / 2);
310
+ const start = Math.max(0, firstIndex - halfLen);
311
+ const end = Math.min(text.length, firstIndex + halfLen + firstWordLen);
312
+ const prefix = start > 0 ? '...' : '';
313
+ const suffix = end < text.length ? '...' : '';
314
+ const snippetBody = text.slice(start, end).replace(/\n/g, ' ');
315
+ const snippet = `${prefix}${snippetBody}${suffix}`;
316
+
317
+ const snippetLower = snippet.toLowerCase();
318
+ const highlights: SearchSnippetHighlight[] = [];
319
+
320
+ if (phraseStart >= start && phraseStart + phraseLength <= end) {
321
+ const phraseOffset = prefix.length + (phraseStart - start);
322
+ highlights.push({
323
+ start: phraseOffset,
324
+ end: phraseOffset + phraseLength,
325
+ });
326
+ }
327
+
328
+ if (!requireExactPhrase) {
329
+ for (const word of words) {
330
+ const regex = new RegExp(`(?<!\\p{L})${escapeRegex(word)}(?!\\p{L})`, 'gu');
331
+ let match = regex.exec(snippetLower);
332
+ while (match) {
333
+ highlights.push({ start: match.index, end: match.index + word.length });
334
+ match = regex.exec(snippetLower);
335
+ }
336
+ }
337
+ }
338
+
339
+ highlights.sort((left, right) => left.start - right.start);
340
+ const merged: SearchSnippetHighlight[] = [];
341
+ for (const highlight of highlights) {
342
+ const previous = merged[merged.length - 1];
343
+ if (previous && highlight.start <= previous.end) {
344
+ previous.end = Math.max(previous.end, highlight.end);
345
+ } else {
346
+ merged.push({ ...highlight });
347
+ }
348
+ }
349
+
350
+ return { snippet, highlights: merged };
351
+ };
352
+
353
+ return { matchesQuery, buildSnippet };
354
+ }
355
+
356
+ function extractClaudeText(content: unknown): string {
357
+ if (typeof content === 'string') {
358
+ return content;
359
+ }
360
+
361
+ if (!Array.isArray(content)) {
362
+ return '';
363
+ }
364
+
365
+ return content
366
+ .filter((part: AnyRecord) => part?.type === 'text' && typeof part?.text === 'string')
367
+ .map((part: AnyRecord) => String(part.text))
368
+ .join(' ');
369
+ }
370
+
371
+ function extractTaggedContent(content: string, tagName: string): string | null {
372
+ const escapedTagName = tagName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
373
+ const match = new RegExp(`<${escapedTagName}>([\\s\\S]*?)<\\/${escapedTagName}>`).exec(content);
374
+ return match ? match[1] : null;
375
+ }
376
+
377
+ type ClaudeLocalCommandPayload = {
378
+ commandName: string;
379
+ commandMessage: string;
380
+ commandArgs: string;
381
+ };
382
+
383
+ function parseClaudeLocalCommandPayload(content: string): ClaudeLocalCommandPayload | null {
384
+ const commandName = extractTaggedContent(content, 'command-name');
385
+ const commandMessage = extractTaggedContent(content, 'command-message');
386
+ const commandArgs = extractTaggedContent(content, 'command-args');
387
+
388
+ if (commandName === null && commandMessage === null && commandArgs === null) {
389
+ return null;
390
+ }
391
+
392
+ return {
393
+ commandName: commandName ?? '',
394
+ commandMessage: commandMessage ?? '',
395
+ commandArgs: commandArgs ?? '',
396
+ };
397
+ }
398
+
399
+ function buildClaudeLocalCommandDisplayText(payload: ClaudeLocalCommandPayload): string {
400
+ const commandName = payload.commandName.trim();
401
+ const commandMessage = payload.commandMessage.trim();
402
+ const commandArgs = payload.commandArgs.trim();
403
+ const baseCommand = commandName || commandMessage;
404
+
405
+ if (!baseCommand) {
406
+ return '';
407
+ }
408
+
409
+ return commandArgs ? `${baseCommand} ${commandArgs}` : baseCommand;
410
+ }
411
+
412
+ function stripAnsiFormatting(text: string): string {
413
+ return text.replace(/\u001B\[[0-9;?]*[ -/]*[@-~]/g, '');
414
+ }
415
+
416
+ type ClaudeSearchableMessage = {
417
+ text: string;
418
+ role: 'user' | 'assistant';
419
+ };
420
+
421
+ /**
422
+ * Claude mixes visible chat, compact summaries, and local command wrappers into
423
+ * the same transcript stream. Search should operate on the user-visible meaning
424
+ * of those rows rather than the raw wrapper syntax.
425
+ */
426
+ function extractClaudeSearchableMessage(entry: AnyRecord): ClaudeSearchableMessage | null {
427
+ if (!entry.message?.content || entry.isApiErrorMessage) {
428
+ return null;
429
+ }
430
+
431
+ const rawRole = entry.message.role;
432
+ if (rawRole !== 'user' && rawRole !== 'assistant') {
433
+ return null;
434
+ }
435
+
436
+ if (typeof entry.message.content === 'string') {
437
+ const content = String(entry.message.content);
438
+
439
+ if (entry.isCompactSummary === true && content.trim()) {
440
+ return {
441
+ text: content,
442
+ role: 'assistant',
443
+ };
444
+ }
445
+
446
+ const localCommand = parseClaudeLocalCommandPayload(content);
447
+ if (localCommand) {
448
+ const displayText = buildClaudeLocalCommandDisplayText(localCommand);
449
+ return displayText
450
+ ? {
451
+ text: displayText,
452
+ role: 'user',
453
+ }
454
+ : null;
455
+ }
456
+
457
+ const localCommandStdout = extractTaggedContent(content, 'local-command-stdout');
458
+ if (localCommandStdout !== null) {
459
+ const stdoutText = stripAnsiFormatting(localCommandStdout).trim();
460
+ return stdoutText
461
+ ? {
462
+ text: stdoutText,
463
+ role: 'assistant',
464
+ }
465
+ : null;
466
+ }
467
+
468
+ if (!content || isInternalContent(content)) {
469
+ return null;
470
+ }
471
+
472
+ return {
473
+ text: content,
474
+ role: rawRole,
475
+ };
476
+ }
477
+
478
+ const text = extractClaudeText(entry.message.content);
479
+ if (!text) {
480
+ return null;
481
+ }
482
+
483
+ if (entry.isCompactSummary === true) {
484
+ return {
485
+ text,
486
+ role: 'assistant',
487
+ };
488
+ }
489
+
490
+ if (isInternalContent(text)) {
491
+ return null;
492
+ }
493
+
494
+ return {
495
+ text,
496
+ role: rawRole,
497
+ };
498
+ }
499
+
500
+ function extractCodexText(content: unknown): string {
501
+ if (typeof content === 'string') {
502
+ return content;
503
+ }
504
+
505
+ if (!Array.isArray(content)) {
506
+ return '';
507
+ }
508
+
509
+ return content
510
+ .map((item) => {
511
+ if (!item || typeof item !== 'object') {
512
+ return '';
513
+ }
514
+
515
+ const record = item as AnyRecord;
516
+ if (
517
+ (record.type === 'input_text' || record.type === 'output_text' || record.type === 'text')
518
+ && typeof record.text === 'string'
519
+ ) {
520
+ return record.text;
521
+ }
522
+
523
+ return '';
524
+ })
525
+ .filter(Boolean)
526
+ .join(' ');
527
+ }
528
+
529
+ function normalizeSearchableSessions(rows: SessionRepositoryRow[]): SearchableSessionRow[] {
530
+ const normalizedRows: SearchableSessionRow[] = [];
531
+ const projectArchiveStateByPath = new Map<string, boolean>();
532
+
533
+ for (const row of rows) {
534
+ const provider = row.provider as SearchableProvider;
535
+ if (!SUPPORTED_PROVIDERS.has(provider)) {
536
+ continue;
537
+ }
538
+
539
+ const rawJsonlPath = typeof row.jsonl_path === 'string' ? row.jsonl_path.trim() : '';
540
+ if (!rawJsonlPath) {
541
+ continue;
542
+ }
543
+
544
+ const absoluteJsonlPath = path.resolve(rawJsonlPath);
545
+ if (!fsSync.existsSync(absoluteJsonlPath)) {
546
+ continue;
547
+ }
548
+
549
+ /**
550
+ * Active session rows can still belong to an archived project because
551
+ * project archiving intentionally preserves the underlying session data.
552
+ * Global conversation search should follow the visible workspace model,
553
+ * which means excluding any session whose owning project is archived.
554
+ *
555
+ * Cache the archive lookup per normalized project path so one search pass
556
+ * does not re-query the same project row for every session in that folder.
557
+ */
558
+ const normalizedProjectPath = typeof row.project_path === 'string' ? row.project_path.trim() : '';
559
+ if (normalizedProjectPath) {
560
+ if (!projectArchiveStateByPath.has(normalizedProjectPath)) {
561
+ const projectRow = projectsDb.getProjectPath(normalizedProjectPath);
562
+ projectArchiveStateByPath.set(normalizedProjectPath, Boolean(projectRow?.isArchived));
563
+ }
564
+
565
+ if (projectArchiveStateByPath.get(normalizedProjectPath) === true) {
566
+ continue;
567
+ }
568
+ }
569
+
570
+ normalizedRows.push({
571
+ ...row,
572
+ provider,
573
+ jsonl_path: absoluteJsonlPath,
574
+ });
575
+ }
576
+
577
+ return normalizedRows;
578
+ }
579
+
580
+ function buildProjectBuckets(searchableSessions: SearchableSessionRow[]): ProjectBucket[] {
581
+ const projectBuckets = new Map<string, ProjectBucket>();
582
+ const projectMetadataCache = new Map<string, { projectId: string | null; projectDisplayName: string }>();
583
+
584
+ for (const session of searchableSessions) {
585
+ const key = makeProjectKey(session.project_path);
586
+ if (!projectBuckets.has(key)) {
587
+ if (!projectMetadataCache.has(key)) {
588
+ if (key === UNKNOWN_PROJECT_KEY) {
589
+ projectMetadataCache.set(key, {
590
+ projectId: null,
591
+ projectDisplayName: 'Unknown Project',
592
+ });
593
+ } else {
594
+ const projectRow = projectsDb.getProjectPath(key);
595
+ const customProjectName = typeof projectRow?.custom_project_name === 'string'
596
+ ? projectRow.custom_project_name.trim()
597
+ : '';
598
+ const displayName = customProjectName || path.basename(key) || key;
599
+
600
+ projectMetadataCache.set(key, {
601
+ projectId: projectRow?.project_id ?? null,
602
+ projectDisplayName: displayName,
603
+ });
604
+ }
605
+ }
606
+
607
+ const metadata = projectMetadataCache.get(key) as { projectId: string | null; projectDisplayName: string };
608
+ projectBuckets.set(key, {
609
+ key,
610
+ projectId: metadata.projectId,
611
+ projectName: key,
612
+ projectDisplayName: metadata.projectDisplayName,
613
+ sessions: [],
614
+ });
615
+ }
616
+
617
+ const bucket = projectBuckets.get(key) as ProjectBucket;
618
+ bucket.sessions.push(session);
619
+ }
620
+
621
+ const buckets = Array.from(projectBuckets.values());
622
+ for (const bucket of buckets) {
623
+ bucket.sessions.sort((left, right) => {
624
+ const leftTs = new Date(left.updated_at || left.created_at || 0).getTime();
625
+ const rightTs = new Date(right.updated_at || right.created_at || 0).getTime();
626
+ return rightTs - leftTs;
627
+ });
628
+ }
629
+
630
+ return buckets;
631
+ }
632
+
633
+ /**
634
+ * Executes ripgrep with the file list explicitly provided from sessionsDb jsonl paths.
635
+ *
636
+ * This avoids recursive directory walks and uses a fixed known candidate list.
637
+ */
638
+ async function runRipgrepFilesWithMatches(
639
+ pattern: string,
640
+ filePaths: string[],
641
+ signal?: AbortSignal,
642
+ ): Promise<Set<string>> {
643
+ if (!pattern || filePaths.length === 0 || signal?.aborted) {
644
+ return new Set();
645
+ }
646
+
647
+ return new Promise((resolve, reject) => {
648
+ const args = [
649
+ '--files-with-matches',
650
+ '--no-messages',
651
+ '--ignore-case',
652
+ '--fixed-strings',
653
+ '--',
654
+ pattern,
655
+ ...filePaths,
656
+ ];
657
+ const rg = spawn(rgPath, args, {
658
+ stdio: ['ignore', 'pipe', 'pipe'],
659
+ windowsHide: true,
660
+ });
661
+
662
+ const stdoutChunks: Buffer[] = [];
663
+ const stderrChunks: Buffer[] = [];
664
+ let aborted = false;
665
+
666
+ const abortListener = () => {
667
+ aborted = true;
668
+ rg.kill();
669
+ };
670
+
671
+ if (signal) {
672
+ signal.addEventListener('abort', abortListener, { once: true });
673
+ }
674
+
675
+ rg.stdout.on('data', (chunk: Buffer) => {
676
+ stdoutChunks.push(chunk);
677
+ });
678
+
679
+ rg.stderr.on('data', (chunk: Buffer) => {
680
+ stderrChunks.push(chunk);
681
+ });
682
+
683
+ rg.on('error', (error) => {
684
+ if (signal) {
685
+ signal.removeEventListener('abort', abortListener);
686
+ }
687
+
688
+ if (aborted || signal?.aborted) {
689
+ resolve(new Set());
690
+ return;
691
+ }
692
+
693
+ reject(error);
694
+ });
695
+
696
+ rg.on('close', (code) => {
697
+ if (signal) {
698
+ signal.removeEventListener('abort', abortListener);
699
+ }
700
+
701
+ if (aborted || signal?.aborted) {
702
+ resolve(new Set());
703
+ return;
704
+ }
705
+
706
+ if (code !== 0 && code !== 1) {
707
+ const stderr = Buffer.concat(stderrChunks).toString('utf8').trim();
708
+ reject(new Error(`ripgrep failed with code ${String(code)}: ${stderr}`));
709
+ return;
710
+ }
711
+
712
+ const stdout = Buffer.concat(stdoutChunks).toString('utf8');
713
+ const matchedPaths = new Set<string>();
714
+
715
+ for (const line of stdout.split(/\r?\n/)) {
716
+ const trimmed = line.trim();
717
+ if (!trimmed) {
718
+ continue;
719
+ }
720
+
721
+ matchedPaths.add(normalizeComparablePath(trimmed));
722
+ }
723
+
724
+ resolve(matchedPaths);
725
+ });
726
+ });
727
+ }
728
+
729
+ async function findMatchedFileKeys(
730
+ searchablePathEntries: SearchablePathEntry[],
731
+ rawQuery: string,
732
+ words: string[],
733
+ signal?: AbortSignal,
734
+ ): Promise<Set<string>> {
735
+ if (searchablePathEntries.length === 0 || words.length === 0 || signal?.aborted) {
736
+ return new Set();
737
+ }
738
+
739
+ const normalizedQuery = rawQuery.trim().replace(/\s+/g, ' ');
740
+ const requireExactPhrase = words.length > 1 && normalizedQuery.length > 0;
741
+
742
+ if (requireExactPhrase) {
743
+ let matchedForPhrase = searchablePathEntries.slice();
744
+
745
+ // Keep ripgrep as an over-approximation for exact phrase mode by requiring
746
+ // each word to appear somewhere in the file, then defer strict phrase
747
+ // validation to the in-memory matcher.
748
+ for (const word of words) {
749
+ if (signal?.aborted) {
750
+ return new Set();
751
+ }
752
+
753
+ const matchedForWord = new Set<string>();
754
+ const fileChunks = chunkArray(
755
+ matchedForPhrase.map((entry) => entry.absolutePath),
756
+ RIPGREP_FILE_CHUNK_SIZE,
757
+ );
758
+
759
+ let nextChunkIndex = 0;
760
+ const workerCount = Math.min(RIPGREP_CHUNK_CONCURRENCY, fileChunks.length);
761
+ const workers = Array.from({ length: workerCount }, async () => {
762
+ while (nextChunkIndex < fileChunks.length && !signal?.aborted) {
763
+ const currentIndex = nextChunkIndex;
764
+ nextChunkIndex += 1;
765
+ const chunkMatches = await runRipgrepFilesWithMatches(word, fileChunks[currentIndex], signal);
766
+ for (const matchedPath of chunkMatches) {
767
+ matchedForWord.add(matchedPath);
768
+ }
769
+ }
770
+ });
771
+
772
+ await Promise.all(workers);
773
+ if (signal?.aborted) {
774
+ return new Set();
775
+ }
776
+
777
+ matchedForPhrase = matchedForPhrase.filter((entry) => matchedForWord.has(entry.normalizedPath));
778
+ if (matchedForPhrase.length === 0) {
779
+ break;
780
+ }
781
+ }
782
+
783
+ return new Set(matchedForPhrase.map((entry) => entry.normalizedPath));
784
+ }
785
+
786
+ let remainingEntries = searchablePathEntries.slice();
787
+
788
+ // Run one ripgrep pass per term and intersect by keeping only files that
789
+ // matched every query word.
790
+ for (const word of words) {
791
+ if (signal?.aborted) {
792
+ return new Set();
793
+ }
794
+
795
+ const matchedForWord = new Set<string>();
796
+ const fileChunks = chunkArray(
797
+ remainingEntries.map((entry) => entry.absolutePath),
798
+ RIPGREP_FILE_CHUNK_SIZE,
799
+ );
800
+
801
+ let nextChunkIndex = 0;
802
+ const workerCount = Math.min(RIPGREP_CHUNK_CONCURRENCY, fileChunks.length);
803
+
804
+ const workers = Array.from({ length: workerCount }, async () => {
805
+ while (nextChunkIndex < fileChunks.length && !signal?.aborted) {
806
+ const currentIndex = nextChunkIndex;
807
+ nextChunkIndex += 1;
808
+ const chunkMatches = await runRipgrepFilesWithMatches(word, fileChunks[currentIndex], signal);
809
+ for (const matchedPath of chunkMatches) {
810
+ matchedForWord.add(matchedPath);
811
+ }
812
+ }
813
+ });
814
+
815
+ await Promise.all(workers);
816
+ if (signal?.aborted) {
817
+ return new Set();
818
+ }
819
+
820
+ remainingEntries = remainingEntries.filter((entry) => matchedForWord.has(entry.normalizedPath));
821
+ if (remainingEntries.length === 0) {
822
+ break;
823
+ }
824
+ }
825
+
826
+ return new Set(remainingEntries.map((entry) => entry.normalizedPath));
827
+ }
828
+
829
+ function addSessionMatch(
830
+ runtime: SearchRuntime,
831
+ matches: SessionConversationMatch[],
832
+ match: SessionConversationMatch,
833
+ ): void {
834
+ if (runtime.totalMatches >= runtime.limit || matches.length >= MAX_MATCHES_PER_SESSION) {
835
+ return;
836
+ }
837
+
838
+ matches.push(match);
839
+ runtime.totalMatches += 1;
840
+ }
841
+
842
+ async function parseClaudeSessionMatches(
843
+ session: SearchableSessionRow,
844
+ runtime: SearchRuntime,
845
+ ): Promise<SessionConversationResult | null> {
846
+ const fileKey = normalizeComparablePath(session.jsonl_path);
847
+ if (!fileKey) {
848
+ return null;
849
+ }
850
+
851
+ if (!runtime.claudeFileResultsCache.has(fileKey)) {
852
+ const sessionsForFile = runtime.claudeSessionsByFileKey.get(fileKey) || [];
853
+ const matchedSessionsForFile = sessionsForFile.filter((candidate) =>
854
+ runtime.matchedSessionKeys.has(getSessionKey(candidate)),
855
+ );
856
+
857
+ const targetSessions = matchedSessionsForFile.length > 0
858
+ ? matchedSessionsForFile
859
+ : [session];
860
+
861
+ // Transcript lines are tagged with the provider session id (e.g. Claude's own
862
+ // conversation UUID), which is not necessarily the app-facing `session_id`.
863
+ // Match and attribute by the provider id, but map results back to the
864
+ // internal `session_id` the rest of the app uses to identify sessions.
865
+ const providerToInternalId = new Map<string, string>();
866
+ const customNameBySessionId = new Map<string, string | null>();
867
+ for (const candidate of targetSessions) {
868
+ const providerId = candidate.provider_session_id || candidate.session_id;
869
+ providerToInternalId.set(providerId, candidate.session_id);
870
+ customNameBySessionId.set(providerId, candidate.custom_name ?? null);
871
+ }
872
+ const targetSessionIds = new Set(providerToInternalId.keys());
873
+
874
+ type ClaudeSessionSearchState = {
875
+ matches: SessionConversationMatch[];
876
+ pendingSummaries: Map<string, string>;
877
+ fallbackUserText: string | null;
878
+ fallbackAssistantText: string | null;
879
+ resolvedSummary: string | null;
880
+ };
881
+
882
+ const sessionStateById = new Map<string, ClaudeSessionSearchState>();
883
+ const getSessionState = (sessionId: string): ClaudeSessionSearchState => {
884
+ if (!sessionStateById.has(sessionId)) {
885
+ sessionStateById.set(sessionId, {
886
+ matches: [],
887
+ pendingSummaries: new Map<string, string>(),
888
+ fallbackUserText: null,
889
+ fallbackAssistantText: null,
890
+ resolvedSummary: null,
891
+ });
892
+ }
893
+ return sessionStateById.get(sessionId) as ClaudeSessionSearchState;
894
+ };
895
+
896
+ let currentSessionId: string | null = null;
897
+
898
+ try {
899
+ const fileStream = fsSync.createReadStream(session.jsonl_path);
900
+ const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity });
901
+
902
+ for await (const line of rl) {
903
+ if (runtime.totalMatches >= runtime.limit || runtime.isAborted()) {
904
+ break;
905
+ }
906
+ if (!line.trim()) {
907
+ continue;
908
+ }
909
+
910
+ let entry: AnyRecord;
911
+ try {
912
+ entry = JSON.parse(line) as AnyRecord;
913
+ } catch {
914
+ continue;
915
+ }
916
+
917
+ if (entry.sessionId) {
918
+ currentSessionId = String(entry.sessionId);
919
+ }
920
+ const entrySessionId = entry.sessionId
921
+ ? String(entry.sessionId)
922
+ : currentSessionId;
923
+ if (!entrySessionId || !targetSessionIds.has(entrySessionId)) {
924
+ continue;
925
+ }
926
+
927
+ const state = getSessionState(entrySessionId);
928
+
929
+ if (entry.type === 'summary' && entry.summary) {
930
+ const summaryValue = String(entry.summary);
931
+ if (entry.sessionId) {
932
+ state.resolvedSummary = summaryValue;
933
+ } else if (entry.leafUuid) {
934
+ state.pendingSummaries.set(String(entry.leafUuid), summaryValue);
935
+ }
936
+ }
937
+
938
+ if (!state.resolvedSummary && entry.parentUuid) {
939
+ const pendingSummary = state.pendingSummaries.get(String(entry.parentUuid));
940
+ if (pendingSummary) {
941
+ state.resolvedSummary = pendingSummary;
942
+ }
943
+ }
944
+
945
+ const searchableMessage = extractClaudeSearchableMessage(entry);
946
+ if (!searchableMessage) {
947
+ continue;
948
+ }
949
+
950
+ const { text, role } = searchableMessage;
951
+
952
+ /**
953
+ * Claude compact summaries are the most faithful session-summary source
954
+ * after a `/compact` because they describe the post-compaction state that
955
+ * the resumed session actually continues from. Prefer them over generic
956
+ * fallback user text when present.
957
+ */
958
+ if (entry.isCompactSummary === true) {
959
+ state.resolvedSummary = text;
960
+ }
961
+
962
+ if (role === 'user') {
963
+ state.fallbackUserText = text;
964
+ } else {
965
+ state.fallbackAssistantText = text;
966
+ }
967
+
968
+ if (!runtime.matchesQuery(text)) {
969
+ continue;
970
+ }
971
+
972
+ const { snippet, highlights } = runtime.buildSnippet(text);
973
+ addSessionMatch(runtime, state.matches, {
974
+ role,
975
+ snippet,
976
+ highlights,
977
+ timestamp: entry.timestamp ? String(entry.timestamp) : null,
978
+ provider: 'claude',
979
+ messageUuid: entry.uuid ? String(entry.uuid) : null,
980
+ });
981
+ }
982
+ } catch {
983
+ runtime.claudeFileResultsCache.set(fileKey, new Map());
984
+ return null;
985
+ }
986
+
987
+ const fileResults = new Map<string, SessionConversationResult>();
988
+ for (const [sessionId, state] of sessionStateById.entries()) {
989
+ if (state.matches.length === 0) {
990
+ continue;
991
+ }
992
+
993
+ const internalSessionId = providerToInternalId.get(sessionId) ?? sessionId;
994
+ fileResults.set(internalSessionId, {
995
+ sessionId: internalSessionId,
996
+ provider: 'claude',
997
+ sessionSummary: toSummaryText(
998
+ customNameBySessionId.get(sessionId) ?? null,
999
+ state.resolvedSummary || state.fallbackUserText || state.fallbackAssistantText,
1000
+ 'New Session',
1001
+ ),
1002
+ matches: state.matches,
1003
+ });
1004
+ }
1005
+
1006
+ runtime.claudeFileResultsCache.set(fileKey, fileResults);
1007
+ }
1008
+
1009
+ return runtime.claudeFileResultsCache.get(fileKey)?.get(session.session_id) ?? null;
1010
+ }
1011
+
1012
+ function isVisibleCodexUserMessage(payload: AnyRecord | null | undefined): boolean {
1013
+ if (!payload || payload.type !== 'user_message') {
1014
+ return false;
1015
+ }
1016
+
1017
+ if (payload.kind && payload.kind !== 'plain') {
1018
+ return false;
1019
+ }
1020
+
1021
+ return typeof payload.message === 'string' && payload.message.trim().length > 0;
1022
+ }
1023
+
1024
+ async function parseCodexSessionMatches(
1025
+ session: SearchableSessionRow,
1026
+ runtime: SearchRuntime,
1027
+ ): Promise<SessionConversationResult | null> {
1028
+ const matches: SessionConversationMatch[] = [];
1029
+ let latestUserMessageText: string | null = null;
1030
+ const seenMessageFingerprints = new Set<string>();
1031
+
1032
+ try {
1033
+ const fileStream = fsSync.createReadStream(session.jsonl_path);
1034
+ const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity });
1035
+
1036
+ for await (const line of rl) {
1037
+ if (runtime.totalMatches >= runtime.limit || runtime.isAborted()) {
1038
+ break;
1039
+ }
1040
+ if (!line.trim()) {
1041
+ continue;
1042
+ }
1043
+
1044
+ let entry: AnyRecord;
1045
+ try {
1046
+ entry = JSON.parse(line) as AnyRecord;
1047
+ } catch {
1048
+ continue;
1049
+ }
1050
+
1051
+ let text: string | null = null;
1052
+ let role: 'user' | 'assistant' | null = null;
1053
+
1054
+ if (entry.type === 'event_msg' && isVisibleCodexUserMessage(entry.payload as AnyRecord)) {
1055
+ text = String(entry.payload.message);
1056
+ role = 'user';
1057
+ } else if (
1058
+ entry.type === 'event_msg'
1059
+ && entry.payload?.type === 'agent_reasoning'
1060
+ && typeof entry.payload?.text === 'string'
1061
+ ) {
1062
+ text = String(entry.payload.text);
1063
+ role = 'assistant';
1064
+ } else if (entry.type === 'response_item' && entry.payload?.type === 'message') {
1065
+ const payload = entry.payload as AnyRecord;
1066
+ if (payload.role === 'user') {
1067
+ text = extractCodexText(payload.content);
1068
+ role = 'user';
1069
+ } else if (payload.role === 'assistant') {
1070
+ text = extractCodexText(payload.content);
1071
+ role = 'assistant';
1072
+ }
1073
+ } else if (entry.type === 'response_item' && entry.payload?.type === 'reasoning') {
1074
+ const summaryText = Array.isArray(entry.payload.summary)
1075
+ ? entry.payload.summary
1076
+ .map((item: AnyRecord) => (typeof item?.text === 'string' ? item.text : ''))
1077
+ .filter(Boolean)
1078
+ .join('\n')
1079
+ : '';
1080
+
1081
+ if (summaryText.trim()) {
1082
+ text = summaryText;
1083
+ role = 'assistant';
1084
+ }
1085
+ }
1086
+
1087
+ if (!text || !role) {
1088
+ continue;
1089
+ }
1090
+ if (isInternalCodexContent(text)) {
1091
+ continue;
1092
+ }
1093
+ if (role === 'user') {
1094
+ latestUserMessageText = text;
1095
+ }
1096
+
1097
+ const fingerprint = `${role}:${text.trim().toLowerCase()}`;
1098
+ if (seenMessageFingerprints.has(fingerprint)) {
1099
+ continue;
1100
+ }
1101
+ seenMessageFingerprints.add(fingerprint);
1102
+
1103
+ if (!runtime.matchesQuery(text)) {
1104
+ continue;
1105
+ }
1106
+
1107
+ const { snippet, highlights } = runtime.buildSnippet(text);
1108
+ addSessionMatch(runtime, matches, {
1109
+ role,
1110
+ snippet,
1111
+ highlights,
1112
+ timestamp: entry.timestamp ? String(entry.timestamp) : null,
1113
+ provider: 'codex',
1114
+ });
1115
+ }
1116
+ } catch {
1117
+ return null;
1118
+ }
1119
+
1120
+ if (matches.length === 0) {
1121
+ return null;
1122
+ }
1123
+
1124
+ return {
1125
+ sessionId: session.session_id,
1126
+ provider: 'codex',
1127
+ sessionSummary: toSummaryText(session.custom_name, latestUserMessageText, 'Codex Session'),
1128
+ matches,
1129
+ };
1130
+ }
1131
+
1132
+ async function parseSessionMatches(
1133
+ session: SearchableSessionRow,
1134
+ runtime: SearchRuntime,
1135
+ ): Promise<SessionConversationResult | null> {
1136
+ if (session.provider === 'claude') {
1137
+ return parseClaudeSessionMatches(session, runtime);
1138
+ }
1139
+ if (session.provider === 'codex') {
1140
+ return parseCodexSessionMatches(session, runtime);
1141
+ }
1142
+ return null;
1143
+ }
1144
+
1145
+ /**
1146
+ * Searches session titles and provider transcripts for the provider search
1147
+ * service and its route-level integration tests.
1148
+ */
1149
+ export async function searchConversations(
1150
+ query: string,
1151
+ limit = 50,
1152
+ onProjectResult: ((update: SessionConversationSearchProgressUpdate) => void) | null = null,
1153
+ signal: AbortSignal | null = null,
1154
+ onTitleResults: ((results: SessionTitleSearchResult[]) => void) | null = null,
1155
+ ): Promise<{
1156
+ results: ProjectConversationResult[];
1157
+ titleResults: SessionTitleSearchResult[];
1158
+ totalMatches: number;
1159
+ query: string;
1160
+ }> {
1161
+ const safeQuery = typeof query === 'string' ? query.trim() : '';
1162
+ const safeLimit = Math.max(1, Math.min(Number.isFinite(limit) ? limit : 50, 200));
1163
+ const words = safeQuery.toLowerCase().split(/\s+/).filter((word) => word.length > 0);
1164
+
1165
+ if (words.length === 0) {
1166
+ return { results: [], titleResults: [], totalMatches: 0, query: safeQuery };
1167
+ }
1168
+
1169
+ const isAborted = () => signal?.aborted === true;
1170
+ if (isAborted()) {
1171
+ return { results: [], titleResults: [], totalMatches: 0, query: safeQuery };
1172
+ }
1173
+
1174
+ const activeSessions = sessionsDb.getAllSessions();
1175
+ const titleResults = findSessionTitleResults(activeSessions, safeQuery, safeLimit);
1176
+ onTitleResults?.(titleResults);
1177
+
1178
+ const searchableSessions = normalizeSearchableSessions(activeSessions);
1179
+ if (searchableSessions.length === 0) {
1180
+ return { results: [], titleResults, totalMatches: 0, query: safeQuery };
1181
+ }
1182
+
1183
+ const sessionsByPathKey = new Map<string, SearchableSessionRow[]>();
1184
+ const searchablePathEntries: SearchablePathEntry[] = [];
1185
+
1186
+ for (const session of searchableSessions) {
1187
+ const normalizedPath = normalizeComparablePath(session.jsonl_path);
1188
+ if (!normalizedPath) {
1189
+ continue;
1190
+ }
1191
+
1192
+ if (!sessionsByPathKey.has(normalizedPath)) {
1193
+ sessionsByPathKey.set(normalizedPath, []);
1194
+ searchablePathEntries.push({
1195
+ normalizedPath,
1196
+ absolutePath: session.jsonl_path,
1197
+ });
1198
+ }
1199
+
1200
+ const pathSessions = sessionsByPathKey.get(normalizedPath) as SearchableSessionRow[];
1201
+ pathSessions.push(session);
1202
+ }
1203
+
1204
+ const matchedFileKeys = await findMatchedFileKeys(
1205
+ searchablePathEntries,
1206
+ safeQuery,
1207
+ words,
1208
+ signal ?? undefined,
1209
+ );
1210
+ if (isAborted() || matchedFileKeys.size === 0) {
1211
+ return { results: [], titleResults, totalMatches: 0, query: safeQuery };
1212
+ }
1213
+
1214
+ const matchedSessionKeys = new Set<string>();
1215
+ for (const fileKey of matchedFileKeys) {
1216
+ const sessions = sessionsByPathKey.get(fileKey);
1217
+ if (!sessions) {
1218
+ continue;
1219
+ }
1220
+
1221
+ for (const session of sessions) {
1222
+ matchedSessionKeys.add(getSessionKey(session));
1223
+ }
1224
+ }
1225
+
1226
+ const projectBuckets = buildProjectBuckets(searchableSessions);
1227
+ const totalProjects = projectBuckets.length;
1228
+ const results: ProjectConversationResult[] = [];
1229
+ let scannedProjects = 0;
1230
+
1231
+ const runtime: SearchRuntime = {
1232
+ ...createWordMatcher(safeQuery, words),
1233
+ limit: safeLimit,
1234
+ totalMatches: 0,
1235
+ isAborted,
1236
+ matchedSessionKeys,
1237
+ claudeSessionsByFileKey: new Map<string, SearchableSessionRow[]>(),
1238
+ claudeFileResultsCache: new Map<string, Map<string, SessionConversationResult>>(),
1239
+ };
1240
+
1241
+ for (const [fileKey, sessions] of sessionsByPathKey.entries()) {
1242
+ const claudeSessions = sessions.filter((session) => session.provider === 'claude');
1243
+ if (claudeSessions.length > 0) {
1244
+ runtime.claudeSessionsByFileKey.set(fileKey, claudeSessions);
1245
+ }
1246
+ }
1247
+
1248
+ for (const bucket of projectBuckets) {
1249
+ if (runtime.totalMatches >= runtime.limit || runtime.isAborted()) {
1250
+ break;
1251
+ }
1252
+
1253
+ const projectResult: ProjectConversationResult = {
1254
+ projectId: bucket.projectId,
1255
+ projectName: bucket.projectName,
1256
+ projectDisplayName: bucket.projectDisplayName,
1257
+ sessions: [],
1258
+ };
1259
+
1260
+ for (const session of bucket.sessions) {
1261
+ if (runtime.totalMatches >= runtime.limit || runtime.isAborted()) {
1262
+ break;
1263
+ }
1264
+ if (!matchedSessionKeys.has(getSessionKey(session))) {
1265
+ continue;
1266
+ }
1267
+
1268
+ const sessionResult = await parseSessionMatches(session, runtime);
1269
+ if (sessionResult) {
1270
+ projectResult.sessions.push(sessionResult);
1271
+ }
1272
+ }
1273
+
1274
+ scannedProjects += 1;
1275
+ if (projectResult.sessions.length > 0) {
1276
+ results.push(projectResult);
1277
+ onProjectResult?.({
1278
+ projectResult,
1279
+ totalMatches: runtime.totalMatches,
1280
+ scannedProjects,
1281
+ totalProjects,
1282
+ });
1283
+ } else if (onProjectResult && scannedProjects % 10 === 0) {
1284
+ onProjectResult({
1285
+ projectResult: null,
1286
+ totalMatches: runtime.totalMatches,
1287
+ scannedProjects,
1288
+ totalProjects,
1289
+ });
1290
+ }
1291
+ }
1292
+
1293
+ return {
1294
+ results,
1295
+ titleResults,
1296
+ totalMatches: runtime.totalMatches,
1297
+ query: safeQuery,
1298
+ };
1299
+ }
1300
+
1301
+ /**
1302
+ * Application service for session-conversation search.
1303
+ *
1304
+ * Provider routes call this service so route handlers stay focused on
1305
+ * request parsing/response formatting, while search execution remains
1306
+ * centralized in one place.
1307
+ */
1308
+ export const sessionConversationsSearchService = {
1309
+ /**
1310
+ * Streams progress updates while the search scans provider session logs.
1311
+ */
1312
+ async search(input: SearchSessionConversationsInput): Promise<void> {
1313
+ await searchConversations(
1314
+ input.query,
1315
+ input.limit,
1316
+ input.onProgress ?? null,
1317
+ input.signal ?? null,
1318
+ input.onTitleResults ?? null,
1319
+ );
1320
+ },
1321
+ };