texlite 0.22.0 → 0.24.0

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 (261) hide show
  1. package/DESIGN.md +75 -15
  2. package/OPERATIONS.md +21 -1
  3. package/README.md +1 -0
  4. package/README.zh-CN.md +1 -0
  5. package/addon.md +76 -0
  6. package/dist/client/assets/AdminUsers-C-8tXzvj.js +1 -0
  7. package/dist/client/assets/AdminUsers-C-8tXzvj.js.br +0 -0
  8. package/dist/client/assets/AdminUsers-C-8tXzvj.js.gz +0 -0
  9. package/dist/client/assets/{AgentIcon-DeoZDwgh.css → AgentIcon-_B7xXJpJ.css} +1 -1
  10. package/dist/client/assets/AgentIcon-_B7xXJpJ.css.br +0 -0
  11. package/dist/client/assets/AgentIcon-_B7xXJpJ.css.gz +0 -0
  12. package/dist/client/assets/{AgentManagement-DlV6tHez.js → AgentManagement-DXgfP7l_.js} +1 -1
  13. package/dist/client/assets/AgentManagement-DXgfP7l_.js.br +0 -0
  14. package/dist/client/assets/AgentManagement-DXgfP7l_.js.gz +0 -0
  15. package/dist/client/assets/AgentTerminal-DD4sskCS.js +2 -0
  16. package/dist/client/assets/AgentTerminal-DD4sskCS.js.br +0 -0
  17. package/dist/client/assets/AgentTerminal-DD4sskCS.js.gz +0 -0
  18. package/dist/client/assets/AgentTerminalSurface-DliOcop5.js +16 -0
  19. package/dist/client/assets/AgentTerminalSurface-DliOcop5.js.br +0 -0
  20. package/dist/client/assets/AgentTerminalSurface-DliOcop5.js.gz +0 -0
  21. package/dist/client/assets/{AvatarSettingsDialog-C8WQhZBK.js → AvatarSettingsDialog-iuEbMO4a.js} +1 -1
  22. package/dist/client/assets/AvatarSettingsDialog-iuEbMO4a.js.br +0 -0
  23. package/dist/client/assets/AvatarSettingsDialog-iuEbMO4a.js.gz +0 -0
  24. package/dist/client/assets/CitationBibtexEditor-CDiYDj3M.js +1 -0
  25. package/dist/client/assets/{CitationLibraryDialog-DgOIkLwK.js → CitationLibraryDialog-CJlL-Ytx.js} +3 -3
  26. package/dist/client/assets/CitationLibraryDialog-CJlL-Ytx.js.br +0 -0
  27. package/dist/client/assets/CitationLibraryDialog-CJlL-Ytx.js.gz +0 -0
  28. package/dist/client/assets/Dashboard-DqwGd9wd.js +5 -0
  29. package/dist/client/assets/Dashboard-DqwGd9wd.js.br +0 -0
  30. package/dist/client/assets/Dashboard-DqwGd9wd.js.gz +0 -0
  31. package/dist/client/assets/{GitDialog-DGzZ3GRj.js → GitDialog-DUGAigLx.js} +1 -1
  32. package/dist/client/assets/GitDialog-DUGAigLx.js.br +0 -0
  33. package/dist/client/assets/GitDialog-DUGAigLx.js.gz +0 -0
  34. package/dist/client/assets/{GitHubAccountDialog-CGZl3mcY.js → GitHubAccountDialog-B4eD622i.js} +1 -1
  35. package/dist/client/assets/GitHubAccountDialog-B4eD622i.js.br +0 -0
  36. package/dist/client/assets/GitHubAccountDialog-B4eD622i.js.gz +0 -0
  37. package/dist/client/assets/HistoryDialog-upkR8E0L.js +8 -0
  38. package/dist/client/assets/HistoryDialog-upkR8E0L.js.br +0 -0
  39. package/dist/client/assets/HistoryDialog-upkR8E0L.js.gz +0 -0
  40. package/dist/client/assets/{InfoPopover-Ba7GvcuW.js → InfoPopover-CQ3Q10tN.js} +1 -1
  41. package/dist/client/assets/LatexEditor-DvDYTc0r.js +25 -0
  42. package/dist/client/assets/LatexEditor-DvDYTc0r.js.br +0 -0
  43. package/dist/client/assets/LatexEditor-DvDYTc0r.js.gz +0 -0
  44. package/dist/client/assets/{MarkdownPreview-BH2iwvle.js → MarkdownPreview-_AXp5G7f.js} +1 -1
  45. package/dist/client/assets/MarkdownPreview-_AXp5G7f.js.br +0 -0
  46. package/dist/client/assets/MarkdownPreview-_AXp5G7f.js.gz +0 -0
  47. package/dist/client/assets/{ProjectIconPickerDialog-Bfkaxcnh.js → ProjectIconPickerDialog-BxjEYsau.js} +1 -1
  48. package/dist/client/assets/ProjectIconPickerDialog-BxjEYsau.js.br +0 -0
  49. package/dist/client/assets/ProjectIconPickerDialog-BxjEYsau.js.gz +0 -0
  50. package/dist/client/assets/ProjectSearchDialog-BB8thfK9.js +1 -0
  51. package/dist/client/assets/ProjectSearchDialog-BB8thfK9.js.br +0 -0
  52. package/dist/client/assets/ProjectSearchDialog-BB8thfK9.js.gz +0 -0
  53. package/dist/client/assets/ProjectSettings-Dx-b26uN.js +4 -0
  54. package/dist/client/assets/ProjectSettings-Dx-b26uN.js.br +0 -0
  55. package/dist/client/assets/ProjectSettings-Dx-b26uN.js.gz +0 -0
  56. package/dist/client/assets/ProjectWorkspace-DiurYeU1.js +25 -0
  57. package/dist/client/assets/ProjectWorkspace-DiurYeU1.js.br +0 -0
  58. package/dist/client/assets/ProjectWorkspace-DiurYeU1.js.gz +0 -0
  59. package/dist/client/assets/{QuickOpenDialog-CHjPlBu2.js → QuickOpenDialog-HlkWqVR9.js} +1 -1
  60. package/dist/client/assets/QuickOpenDialog-HlkWqVR9.js.br +0 -0
  61. package/dist/client/assets/QuickOpenDialog-HlkWqVR9.js.gz +0 -0
  62. package/dist/client/assets/ReadOnlySource-BIdN1YP_.js +2 -0
  63. package/dist/client/assets/SelectionHistoryDialog-Cb8I-G6m.js +3 -0
  64. package/dist/client/assets/SelectionHistoryDialog-Cb8I-G6m.js.br +0 -0
  65. package/dist/client/assets/SelectionHistoryDialog-Cb8I-G6m.js.gz +0 -0
  66. package/dist/client/assets/SharedProjectPage-BBLOLjnD.js +2 -0
  67. package/dist/client/assets/SharedProjectPage-BBLOLjnD.js.br +0 -0
  68. package/dist/client/assets/SharedProjectPage-BBLOLjnD.js.gz +0 -0
  69. package/dist/client/assets/{SystemMetricsDialog-DkmBA4o4.js → SystemMetricsDialog-Dr4pYWG6.js} +1 -1
  70. package/dist/client/assets/SystemMetricsDialog-Dr4pYWG6.js.br +0 -0
  71. package/dist/client/assets/SystemMetricsDialog-Dr4pYWG6.js.gz +0 -0
  72. package/dist/client/assets/{TagManagementDialog-BM1MRuwh.js → TagManagementDialog-D4fYVboy.js} +1 -1
  73. package/dist/client/assets/TagManagementDialog-D4fYVboy.js.br +0 -0
  74. package/dist/client/assets/TagManagementDialog-D4fYVboy.js.gz +0 -0
  75. package/dist/client/assets/{ThemeSwitcher-dcvtWVCO.js → ThemeSwitcher-BgzkYTeA.js} +1 -1
  76. package/dist/client/assets/TikzGalleryDialog-Bqzl2256.css +1 -0
  77. package/dist/client/assets/TikzGalleryDialog-Bqzl2256.css.br +0 -0
  78. package/dist/client/assets/TikzGalleryDialog-Bqzl2256.css.gz +0 -0
  79. package/dist/client/assets/TikzGalleryDialog-cPUDQ5Wj.js +1 -0
  80. package/dist/client/assets/TikzGalleryDialog-cPUDQ5Wj.js.br +0 -0
  81. package/dist/client/assets/TikzGalleryDialog-cPUDQ5Wj.js.gz +0 -0
  82. package/dist/client/assets/WordCountDialog-AiuR3rra.js +1 -0
  83. package/dist/client/assets/WordCountDialog-AiuR3rra.js.br +0 -0
  84. package/dist/client/assets/WordCountDialog-AiuR3rra.js.gz +0 -0
  85. package/dist/client/assets/{chktex-BrzPYHey.js → chktex--32C-Pkl.js} +1 -1
  86. package/dist/client/assets/{citationLibrary-DxGdbZEQ.js → citationLibrary-BJRzAgaV.js} +1 -1
  87. package/dist/client/assets/citationLibrary-BJRzAgaV.js.br +0 -0
  88. package/dist/client/assets/citationLibrary-BJRzAgaV.js.gz +0 -0
  89. package/dist/client/assets/editor-CSq7NymY.js +14 -0
  90. package/dist/client/assets/editor-CSq7NymY.js.br +0 -0
  91. package/dist/client/assets/editor-CSq7NymY.js.gz +0 -0
  92. package/dist/client/assets/editor-languages-CKP1xVf6.js +36 -0
  93. package/dist/client/assets/editor-languages-CKP1xVf6.js.br +0 -0
  94. package/dist/client/assets/editor-languages-CKP1xVf6.js.gz +0 -0
  95. package/dist/client/assets/editorThemeExtension-CjBD77yn.js +1 -0
  96. package/dist/client/assets/editorThemeExtension-CjBD77yn.js.br +0 -0
  97. package/dist/client/assets/editorThemeExtension-CjBD77yn.js.gz +0 -0
  98. package/dist/client/assets/file-cog-D_mhAnBe.js +1 -0
  99. package/dist/client/assets/{generatedParser-CZa2vsK6.js → generatedParser-2izSCuvk.js} +1 -1
  100. package/dist/client/assets/generatedParser-2izSCuvk.js.br +0 -0
  101. package/dist/client/assets/generatedParser-2izSCuvk.js.gz +0 -0
  102. package/dist/client/assets/i18n-Dpk6KCs6.js +13 -0
  103. package/dist/client/assets/i18n-Dpk6KCs6.js.br +0 -0
  104. package/dist/client/assets/i18n-Dpk6KCs6.js.gz +0 -0
  105. package/dist/client/assets/index-B1vejuOw.js +2 -0
  106. package/dist/client/assets/index-B1vejuOw.js.br +0 -0
  107. package/dist/client/assets/index-B1vejuOw.js.gz +0 -0
  108. package/dist/client/assets/index-Blr4J_Pq.css +1 -0
  109. package/dist/client/assets/index-Blr4J_Pq.css.br +0 -0
  110. package/dist/client/assets/index-Blr4J_Pq.css.gz +0 -0
  111. package/dist/client/assets/{relativeTime-mmWGtWRR.js → relativeTime-CcP1IEvr.js} +1 -1
  112. package/dist/client/assets/relativeTime-CcP1IEvr.js.br +0 -0
  113. package/dist/client/assets/relativeTime-CcP1IEvr.js.gz +0 -0
  114. package/dist/client/assets/sourceCursorStore-EycYBVxj.js +1 -0
  115. package/dist/client/assets/sourceCursorStore-EycYBVxj.js.br +0 -0
  116. package/dist/client/assets/sourceCursorStore-EycYBVxj.js.gz +0 -0
  117. package/dist/client/assets/{spellCheck-BTyLQAFH.js → spellCheck-DpWPgtM7.js} +1 -1
  118. package/dist/client/assets/spellCheck-DpWPgtM7.js.br +0 -0
  119. package/dist/client/assets/spellCheck-DpWPgtM7.js.gz +0 -0
  120. package/dist/client/assets/textLanguageSupport-tGXUsMU9.js +1 -0
  121. package/dist/client/assets/textLanguages-BpqiXyQi.js +78 -0
  122. package/dist/client/assets/textLanguages-BpqiXyQi.js.br +0 -0
  123. package/dist/client/assets/textLanguages-BpqiXyQi.js.gz +0 -0
  124. package/dist/client/assets/useDeletionTransitions-DvxVkRuo.js +1 -0
  125. package/dist/client/assets/useDeletionTransitions-DvxVkRuo.js.br +0 -0
  126. package/dist/client/assets/useDeletionTransitions-DvxVkRuo.js.gz +0 -0
  127. package/dist/client/assets/{vimSupport-C-WiMLjc.js → vimSupport-DMVGjr9R.js} +6 -6
  128. package/dist/client/assets/vimSupport-DMVGjr9R.js.br +0 -0
  129. package/dist/client/assets/vimSupport-DMVGjr9R.js.gz +0 -0
  130. package/dist/client/index.html +3 -3
  131. package/dist/server/agentChanges.js +95 -7
  132. package/dist/server/agents/outputBuffer.js +105 -0
  133. package/dist/server/agents/sessions.js +33 -16
  134. package/dist/server/agents/workspaces.js +14 -1
  135. package/dist/server/app.js +2 -0
  136. package/dist/server/cli.js +12 -1
  137. package/dist/server/collaboration.js +9 -0
  138. package/dist/server/config.js +10 -0
  139. package/dist/server/db.js +64 -0
  140. package/dist/server/editHistory.js +68 -20
  141. package/dist/server/git.js +9 -7
  142. package/dist/server/history.js +160 -69
  143. package/dist/server/i18n.js +8 -0
  144. package/dist/server/locales/zh-Hant.js +4 -0
  145. package/dist/server/projectMutations.js +4 -0
  146. package/dist/server/routes/comments.js +7 -2
  147. package/dist/server/routes/compile.js +56 -4
  148. package/dist/server/routes/projectFiles.js +54 -0
  149. package/dist/server/routes/projectGit.js +1 -1
  150. package/dist/server/routes/projectHistory.js +19 -5
  151. package/dist/server/routes/system.js +1 -0
  152. package/dist/server/routes/tikzGallery.js +38 -0
  153. package/dist/server/tikzEditorAddon.js +115 -0
  154. package/dist/server/tikzEditorRelease.js +9 -0
  155. package/dist/server/tikzGallery.js +63 -0
  156. package/dist/shared/agentMessages.js +3 -0
  157. package/dist/shared/tikzStandalone.js +15 -0
  158. package/package.json +2 -1
  159. package/templates/agents/AGENTS.md +12 -0
  160. package/texlite.config.example.json +4 -0
  161. package/dist/client/assets/AdminUsers-DepqkT6m.js +0 -1
  162. package/dist/client/assets/AdminUsers-DepqkT6m.js.br +0 -0
  163. package/dist/client/assets/AdminUsers-DepqkT6m.js.gz +0 -0
  164. package/dist/client/assets/AgentIcon-DeoZDwgh.css.br +0 -0
  165. package/dist/client/assets/AgentIcon-DeoZDwgh.css.gz +0 -0
  166. package/dist/client/assets/AgentManagement-DlV6tHez.js.br +0 -0
  167. package/dist/client/assets/AgentManagement-DlV6tHez.js.gz +0 -0
  168. package/dist/client/assets/AgentTerminal-CvOz5X_j.js +0 -2
  169. package/dist/client/assets/AgentTerminal-CvOz5X_j.js.br +0 -0
  170. package/dist/client/assets/AgentTerminal-CvOz5X_j.js.gz +0 -0
  171. package/dist/client/assets/AgentTerminalSurface-COqg_GdK.js +0 -16
  172. package/dist/client/assets/AgentTerminalSurface-COqg_GdK.js.br +0 -0
  173. package/dist/client/assets/AgentTerminalSurface-COqg_GdK.js.gz +0 -0
  174. package/dist/client/assets/AvatarSettingsDialog-C8WQhZBK.js.br +0 -0
  175. package/dist/client/assets/AvatarSettingsDialog-C8WQhZBK.js.gz +0 -0
  176. package/dist/client/assets/CitationBibtexEditor-SpudGDwi.js +0 -1
  177. package/dist/client/assets/CitationLibraryDialog-DgOIkLwK.js.br +0 -0
  178. package/dist/client/assets/CitationLibraryDialog-DgOIkLwK.js.gz +0 -0
  179. package/dist/client/assets/Dashboard-CD1w42mA.js +0 -5
  180. package/dist/client/assets/Dashboard-CD1w42mA.js.br +0 -0
  181. package/dist/client/assets/Dashboard-CD1w42mA.js.gz +0 -0
  182. package/dist/client/assets/GitDialog-DGzZ3GRj.js.br +0 -0
  183. package/dist/client/assets/GitDialog-DGzZ3GRj.js.gz +0 -0
  184. package/dist/client/assets/GitHubAccountDialog-CGZl3mcY.js.br +0 -0
  185. package/dist/client/assets/GitHubAccountDialog-CGZl3mcY.js.gz +0 -0
  186. package/dist/client/assets/HistoryDialog-DTZxCgyT.js +0 -8
  187. package/dist/client/assets/HistoryDialog-DTZxCgyT.js.br +0 -0
  188. package/dist/client/assets/HistoryDialog-DTZxCgyT.js.gz +0 -0
  189. package/dist/client/assets/LatexEditor-Boc-45KL.js +0 -25
  190. package/dist/client/assets/LatexEditor-Boc-45KL.js.br +0 -0
  191. package/dist/client/assets/LatexEditor-Boc-45KL.js.gz +0 -0
  192. package/dist/client/assets/MarkdownPreview-BH2iwvle.js.br +0 -0
  193. package/dist/client/assets/MarkdownPreview-BH2iwvle.js.gz +0 -0
  194. package/dist/client/assets/ProjectIconPickerDialog-Bfkaxcnh.js.br +0 -0
  195. package/dist/client/assets/ProjectIconPickerDialog-Bfkaxcnh.js.gz +0 -0
  196. package/dist/client/assets/ProjectSearchDialog-DPIzxVYj.js +0 -1
  197. package/dist/client/assets/ProjectSearchDialog-DPIzxVYj.js.br +0 -0
  198. package/dist/client/assets/ProjectSearchDialog-DPIzxVYj.js.gz +0 -0
  199. package/dist/client/assets/ProjectSettings-ChXx_cmP.js +0 -4
  200. package/dist/client/assets/ProjectSettings-ChXx_cmP.js.br +0 -0
  201. package/dist/client/assets/ProjectSettings-ChXx_cmP.js.gz +0 -0
  202. package/dist/client/assets/ProjectWorkspace-B-w2ix8N.js +0 -25
  203. package/dist/client/assets/ProjectWorkspace-B-w2ix8N.js.br +0 -0
  204. package/dist/client/assets/ProjectWorkspace-B-w2ix8N.js.gz +0 -0
  205. package/dist/client/assets/QuickOpenDialog-CHjPlBu2.js.br +0 -0
  206. package/dist/client/assets/QuickOpenDialog-CHjPlBu2.js.gz +0 -0
  207. package/dist/client/assets/ReadOnlySource-DKcmDg0e.js +0 -2
  208. package/dist/client/assets/SelectionHistoryDialog-Dnj22E8N.js +0 -3
  209. package/dist/client/assets/SelectionHistoryDialog-Dnj22E8N.js.br +0 -0
  210. package/dist/client/assets/SelectionHistoryDialog-Dnj22E8N.js.gz +0 -0
  211. package/dist/client/assets/SharedProjectPage-l8GSYTm-.js +0 -2
  212. package/dist/client/assets/SharedProjectPage-l8GSYTm-.js.br +0 -0
  213. package/dist/client/assets/SharedProjectPage-l8GSYTm-.js.gz +0 -0
  214. package/dist/client/assets/SystemMetricsDialog-DkmBA4o4.js.br +0 -0
  215. package/dist/client/assets/SystemMetricsDialog-DkmBA4o4.js.gz +0 -0
  216. package/dist/client/assets/TagManagementDialog-BM1MRuwh.js.br +0 -0
  217. package/dist/client/assets/TagManagementDialog-BM1MRuwh.js.gz +0 -0
  218. package/dist/client/assets/WordCountDialog-DI0Jv-fg.js +0 -1
  219. package/dist/client/assets/WordCountDialog-DI0Jv-fg.js.br +0 -0
  220. package/dist/client/assets/WordCountDialog-DI0Jv-fg.js.gz +0 -0
  221. package/dist/client/assets/citationLibrary-DxGdbZEQ.js.br +0 -0
  222. package/dist/client/assets/citationLibrary-DxGdbZEQ.js.gz +0 -0
  223. package/dist/client/assets/editor-CkUEg2La.js +0 -14
  224. package/dist/client/assets/editor-CkUEg2La.js.br +0 -0
  225. package/dist/client/assets/editor-CkUEg2La.js.gz +0 -0
  226. package/dist/client/assets/editor-languages-kcWr1Z3Q.js +0 -36
  227. package/dist/client/assets/editor-languages-kcWr1Z3Q.js.br +0 -0
  228. package/dist/client/assets/editor-languages-kcWr1Z3Q.js.gz +0 -0
  229. package/dist/client/assets/editorThemeExtension-BWtZV1Af.js +0 -1
  230. package/dist/client/assets/editorThemeExtension-BWtZV1Af.js.br +0 -0
  231. package/dist/client/assets/editorThemeExtension-BWtZV1Af.js.gz +0 -0
  232. package/dist/client/assets/generatedParser-CZa2vsK6.js.br +0 -0
  233. package/dist/client/assets/generatedParser-CZa2vsK6.js.gz +0 -0
  234. package/dist/client/assets/i18n-Dtn6w-qA.js +0 -13
  235. package/dist/client/assets/i18n-Dtn6w-qA.js.br +0 -0
  236. package/dist/client/assets/i18n-Dtn6w-qA.js.gz +0 -0
  237. package/dist/client/assets/index-BbU2fbRw.css +0 -1
  238. package/dist/client/assets/index-BbU2fbRw.css.br +0 -0
  239. package/dist/client/assets/index-BbU2fbRw.css.gz +0 -0
  240. package/dist/client/assets/index-CPR6YZEf.js +0 -2
  241. package/dist/client/assets/index-CPR6YZEf.js.br +0 -0
  242. package/dist/client/assets/index-CPR6YZEf.js.gz +0 -0
  243. package/dist/client/assets/relativeTime-mmWGtWRR.js.br +0 -0
  244. package/dist/client/assets/relativeTime-mmWGtWRR.js.gz +0 -0
  245. package/dist/client/assets/sourceCursorStore-BVDvDKeP.js +0 -1
  246. package/dist/client/assets/sourceCursorStore-BVDvDKeP.js.br +0 -0
  247. package/dist/client/assets/sourceCursorStore-BVDvDKeP.js.gz +0 -0
  248. package/dist/client/assets/spellCheck-BTyLQAFH.js.br +0 -0
  249. package/dist/client/assets/spellCheck-BTyLQAFH.js.gz +0 -0
  250. package/dist/client/assets/textLanguageSupport-Ck8lMOWz.js +0 -1
  251. package/dist/client/assets/textLanguages-CwWstpJ5.js +0 -78
  252. package/dist/client/assets/textLanguages-CwWstpJ5.js.br +0 -0
  253. package/dist/client/assets/textLanguages-CwWstpJ5.js.gz +0 -0
  254. package/dist/client/assets/useDeletionTransitions-Ba_yhkrl.js +0 -1
  255. package/dist/client/assets/useDeletionTransitions-Ba_yhkrl.js.br +0 -0
  256. package/dist/client/assets/useDeletionTransitions-Ba_yhkrl.js.gz +0 -0
  257. package/dist/client/assets/vimSupport-C-WiMLjc.js.br +0 -0
  258. package/dist/client/assets/vimSupport-C-WiMLjc.js.gz +0 -0
  259. /package/dist/client/assets/{AgentIcon-CA-PfOka.js → AgentIcon-CjaO3WzI.js} +0 -0
  260. /package/dist/client/assets/{AgentIcon-CA-PfOka.js.br → AgentIcon-CjaO3WzI.js.br} +0 -0
  261. /package/dist/client/assets/{AgentIcon-CA-PfOka.js.gz → AgentIcon-CjaO3WzI.js.gz} +0 -0
@@ -10,6 +10,7 @@ import { agentTaskRoot, AgentSourceSync, ensureAgentInstructions, writeAgentProj
10
10
  import { sourceRoot } from "../files.js";
11
11
  import { loadAgentPty, stopAgentPty } from "./terminal.js";
12
12
  import { clearAgentExecution, recoverAgentExecution } from "./execution.js";
13
+ import { AgentOutputBuffer } from "./outputBuffer.js";
13
14
  const now = () => new Date().toISOString();
14
15
  const taskNameCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-";
15
16
  function randomTaskName() {
@@ -39,7 +40,7 @@ export class AgentService {
39
40
  continue;
40
41
  this.db.prepare("UPDATE agent_tasks SET state = 'stopping', error_code = 'AGENT_RECOVERY_FAILED' WHERE id = ?").run(row.id);
41
42
  this.activeProjects.set(row.project_id, row.id);
42
- const releaseWriter = this.context.projectMutations.registerExternalWriter(row.project_id, async () => { await this.stop(row.id); });
43
+ const releaseWriter = this.context.projectMutations.registerExternalWriter(row.project_id, async () => { await this.stop(row.id, undefined, false, "AGENT_STOPPED_BY_PROJECT_OPERATION"); });
43
44
  this.recoveries.set(row.id, () => {
44
45
  if (this.activeProjects.get(row.project_id) === row.id)
45
46
  this.activeProjects.delete(row.project_id);
@@ -59,7 +60,8 @@ export class AgentService {
59
60
  COUNT(CASE WHEN state IN ('starting', 'running', 'stopping')
60
61
  AND (? IS NULL OR project_id = ?) THEN 1 END) AS activeCount
61
62
  FROM agent_tasks WHERE user_id = ?`).get(projectId ?? null, projectId ?? null, userId);
62
- return { visible: this.policy().allowed.length > 0 || total > 0, activeCount };
63
+ const enabled = this.policy().allowed.length > 0;
64
+ return { visible: enabled || total > 0, activeCount, enabled };
63
65
  }
64
66
  async catalog(refresh = false) {
65
67
  await this.recovery;
@@ -168,7 +170,7 @@ export class AgentService {
168
170
  // This applies to all users, agents and tasks in this project.
169
171
  if (this.activeProjects.has(row.project_id))
170
172
  throw httpError(409, "AGENT_PROJECT_BUSY");
171
- const releaseWriter = this.context.projectMutations.registerExternalWriter(row.project_id, async () => { await this.stop(id); });
173
+ const releaseWriter = this.context.projectMutations.registerExternalWriter(row.project_id, async () => { await this.stop(id, undefined, false, "AGENT_STOPPED_BY_PROJECT_OPERATION"); });
172
174
  if (!releaseWriter)
173
175
  throw httpError(409, "AGENT_PROJECT_BUSY");
174
176
  this.activeProjects.set(row.project_id, id);
@@ -221,7 +223,7 @@ export class AgentService {
221
223
  executionFile: this.executionFile(id),
222
224
  beforeStart: () => { this.db.prepare("UPDATE agent_tasks SET ever_started = 1 WHERE id = ?").run(id); } });
223
225
  let finish;
224
- const execution = { pty, attachments: new Set(), controller: null, output: "", stopping: false, termination: null, exitCode: null,
226
+ const execution = { pty, attachments: new Set(), controller: null, output: new AgentOutputBuffer(), permissionsCheckedAt: -Infinity, cols: 100, rows: 24, stopping: false, termination: null, exitCode: null,
225
227
  finished: new Promise((resolve) => { finish = resolve; }), finish: () => finish(), subscriptions: [], source, releaseProject };
226
228
  this.executions.set(id, execution);
227
229
  execution.subscriptions.push(pty.onData((data) => this.output(id, execution, data)));
@@ -261,11 +263,14 @@ export class AgentService {
261
263
  }
262
264
  });
263
265
  }
264
- async stop(id, user, administration = false) {
266
+ async stop(id, user, administration = false, reason) {
265
267
  return this.withTask(id, async () => {
266
268
  if (user)
267
269
  this.owned(id, user, administration);
268
- await this.stopExecution(id);
270
+ if (reason && (this.executions.has(id) || this.recoveries.has(id))) {
271
+ this.db.prepare("UPDATE agent_tasks SET error_code = ? WHERE id = ? AND error_code IS NULL").run(reason, id);
272
+ }
273
+ await this.stopExecution(id, reason);
269
274
  await this.captureContext(id);
270
275
  const row = this.row(id);
271
276
  if (user && row)
@@ -320,8 +325,10 @@ export class AgentService {
320
325
  if (!execution.controller)
321
326
  execution.controller = attachment;
322
327
  this.send(socket, { type: "state", task: this.json(row) });
323
- if (execution.output)
324
- this.send(socket, { type: "output", data: execution.output });
328
+ this.send(socket, { type: "size", cols: execution.cols, rows: execution.rows });
329
+ const replay = execution.output.replay();
330
+ if (replay)
331
+ this.send(socket, { type: "output", data: replay });
325
332
  this.controls(execution);
326
333
  socket.on("message", (raw) => {
327
334
  if (!authorized()) {
@@ -350,6 +357,10 @@ export class AgentService {
350
357
  execution.pty.write(message.data);
351
358
  if (message.type === "resize") {
352
359
  execution.pty.resize(message.cols, message.rows);
360
+ execution.cols = message.cols;
361
+ execution.rows = message.rows;
362
+ for (const peer of execution.attachments)
363
+ this.send(peer.socket, { type: "size", cols: message.cols, rows: message.rows });
353
364
  }
354
365
  });
355
366
  socket.on("close", () => {
@@ -408,9 +419,9 @@ export class AgentService {
408
419
  this.db.prepare("UPDATE agent_tasks SET native_session_id = ? WHERE id = ?").run(native.id, id);
409
420
  return native;
410
421
  }
411
- async stopExecution(id) {
422
+ async stopExecution(id, reason) {
412
423
  if (this.recoveries.has(id)) {
413
- await this.recoverExecution(id, "stopped");
424
+ await this.recoverExecution(id, "stopped", reason);
414
425
  return;
415
426
  }
416
427
  const execution = this.executions.get(id);
@@ -471,12 +482,18 @@ export class AgentService {
471
482
  return termination;
472
483
  }
473
484
  output(id, execution, data) {
474
- const row = this.row(id);
475
- if (!row || !this.editable(row)) {
476
- void this.stop(id).catch((error) => this.options.onError?.(error));
485
+ if (execution.stopping)
477
486
  return;
487
+ const checkedAt = performance.now();
488
+ if (checkedAt - execution.permissionsCheckedAt >= 1000) {
489
+ const row = this.row(id);
490
+ if (!row || !this.editable(row)) {
491
+ void this.stop(id).catch((error) => this.options.onError?.(error));
492
+ return;
493
+ }
494
+ execution.permissionsCheckedAt = checkedAt;
478
495
  }
479
- execution.output = (execution.output + data).slice(-256 * 1024);
496
+ execution.output.append(data);
480
497
  for (const attachment of execution.attachments) {
481
498
  if (!attachment.authorized()) {
482
499
  attachment.socket.close(1008, "Authentication expired");
@@ -538,7 +555,7 @@ export class AgentService {
538
555
  catch { /* Failure is logged and its task/claim remains available for retry. */ }
539
556
  }));
540
557
  }
541
- async recoverExecution(id, state) {
558
+ async recoverExecution(id, state, reason = null) {
542
559
  try {
543
560
  await recoverAgentExecution(this.executionFile(id));
544
561
  const row = this.row(id);
@@ -548,7 +565,7 @@ export class AgentService {
548
565
  const author = this.db.prepare("SELECT 1 FROM users WHERE id = ?").get(row.user_id) ? row.user_id : null;
549
566
  this.context.recordHistory(row.project_id, author, "file", undefined, { hasAgent: true });
550
567
  }
551
- this.db.prepare("UPDATE agent_tasks SET state = ?, error_code = NULL, ended_at = ?, updated_at = ? WHERE id = ?").run(state, now(), now(), id);
568
+ this.db.prepare("UPDATE agent_tasks SET state = ?, error_code = ?, ended_at = ?, updated_at = ? WHERE id = ?").run(state, reason, now(), now(), id);
552
569
  this.recoveries.get(id)?.();
553
570
  this.recoveries.delete(id);
554
571
  }
@@ -294,6 +294,19 @@ export class AgentSourceSync {
294
294
  }
295
295
  }
296
296
  }
297
+ /** The add-on's guide for figure work, when the add-on is enabled and ships one. */
298
+ async function tikzGuidePath(config) {
299
+ if (!config.tikzGalleryEnabled)
300
+ return null;
301
+ const guide = path.join(config.tikzGalleryDir, "TIKZ.md");
302
+ try {
303
+ await fs.promises.access(guide, fs.constants.R_OK);
304
+ return guide;
305
+ }
306
+ catch {
307
+ return null;
308
+ }
309
+ }
297
310
  /** Provide logs outside the source tree without introducing generated project files. */
298
311
  export async function writeAgentProjectContext(context, taskId, projectId) {
299
312
  const { config, db } = context;
@@ -306,7 +319,7 @@ export async function writeAgentProjectContext(context, taskId, projectId) {
306
319
  await fs.promises.writeFile(path.join(state, "project-context.json"), JSON.stringify({ sourceDirectory: sourceRoot(config, projectId),
307
320
  mainFile: project.main_file, outputDirectory: outputRoot(config, projectId),
308
321
  latestCompile: latest ? { runId: latest.id, status: latest.status } : null,
309
- compileLog: path.join(state, "compile.log") }, null, 2), { mode: 0o600 });
322
+ compileLog: path.join(state, "compile.log"), tikzGuide: await tikzGuidePath(config) }, null, 2), { mode: 0o600 });
310
323
  }
311
324
  function externalEdit(filePath, before, after, authorId) {
312
325
  const createdAt = new Date().toISOString();
@@ -40,6 +40,7 @@ import { registerProjectCatalogRoutes } from "./routes/projects.js";
40
40
  import { registerSystemRoutes } from "./routes/system.js";
41
41
  import { registerUserManagementRoutes } from "./routes/users.js";
42
42
  import { registerWordCountRoutes } from "./routes/wordCount.js";
43
+ import { registerTikzGalleryRoutes } from "./routes/tikzGallery.js";
43
44
  import { registerAgentRoutes } from "./routes/agents.js";
44
45
  import { AgentService } from "./agents/sessions.js";
45
46
  import { HarperService } from "./harper.js";
@@ -348,6 +349,7 @@ export async function buildApp(config, db, options = {}) {
348
349
  recordHistory
349
350
  });
350
351
  registerWordCountRoutes(routes, { config, db, projectMutations, texcount });
352
+ registerTikzGalleryRoutes(routes, { config, db });
351
353
  registerCompileRoutes(routes, { config, db, collaboration, projectMutations, compileCoordinator, metrics, pruneCompileRuns });
352
354
  // The factory owns shared services and lifecycle hooks; route modules own endpoint behavior.
353
355
  if (renderedIndex !== null) {
@@ -13,6 +13,7 @@ import { serve } from "./index.js";
13
13
  import { processStatus, restartManaged, startManaged, stopManaged, streamLogs, waitForOnline } from "./pm2.js";
14
14
  import { resolveConfigPath } from "./runtimePaths.js";
15
15
  import { basePathHref } from "../shared/basePath.js";
16
+ import { TikzGalleryLibrary } from "./tikzGallery.js";
16
17
  const HELP = `TexLite ${packageVersion()}
17
18
 
18
19
  Usage:
@@ -211,7 +212,8 @@ async function requirements(options) {
211
212
  function inspectDoctorApplication(config, configPath) {
212
213
  const checks = [
213
214
  { name: "Configuration", status: "passed", detail: `Valid: ${configPath}` },
214
- inspectClientAssets(config)
215
+ inspectClientAssets(config),
216
+ ...(config.tikzGalleryEnabled ? [inspectTikzGallery(config)] : [])
215
217
  ];
216
218
  let db = null;
217
219
  try {
@@ -242,6 +244,14 @@ function inspectClientAssets(config) {
242
244
  catch { /* Report a concise diagnostic below. */ }
243
245
  return { name: "Client assets", status: "failed", detail: `Missing ${entry}; run \`npm run build\` or reinstall TexLite.` };
244
246
  }
247
+ function inspectTikzGallery(config) {
248
+ const result = new TikzGalleryLibrary(config.tikzGalleryDir).catalog();
249
+ if (result.status === "ok")
250
+ return { name: "TikZ gallery", status: "passed", detail: `${result.catalog.items.length} figures: ${config.tikzGalleryDir}` };
251
+ return { name: "TikZ gallery", status: "failed", detail: result.status === "incompatible"
252
+ ? `${config.tikzGalleryDir} has a catalog this TexLite cannot read; update TexLite or the add-on.`
253
+ : `No catalog in ${config.tikzGalleryDir}; clone the add-on there or set tikzGallery.enabled to false.` };
254
+ }
245
255
  function errorMessage(error) {
246
256
  return error instanceof Error ? error.message.replace(/\s+/g, " ").slice(0, 240) : String(error).slice(0, 240);
247
257
  }
@@ -256,6 +266,7 @@ async function printConfig(options) {
256
266
  dataDir: config.dataDir,
257
267
  databasePath: config.databasePath,
258
268
  projectsDir: config.projectsDir,
269
+ tikzGallery: { enabled: config.tikzGalleryEnabled, path: config.tikzGalleryDir },
259
270
  clientDir: config.clientDir,
260
271
  sessionDays: config.sessionDays,
261
272
  compileTimeoutSeconds: config.compileTimeoutMs / 1000,
@@ -223,6 +223,10 @@ export class CollaborationService {
223
223
  return () => { if (this.externalSources.get(projectId) === observer)
224
224
  this.externalSources.delete(projectId); };
225
225
  }
226
+ /** Pull an active external writer's newest disk edits for these files into the room now. */
227
+ reconcileExternalSources(projectId, paths) {
228
+ this.externalSources.get(projectId)?.beforeFlush(paths);
229
+ }
226
230
  /** Apply disk edits as a real attributed Yjs delta, retaining pending human edits and anchors. */
227
231
  /** `agent` marks text written by a coding agent on behalf of `userId`; it is recorded in edit history. */
228
232
  importExternalText(projectId, filePath, content, userId, { agent = false } = {}) {
@@ -844,6 +848,7 @@ export class CollaborationService {
844
848
  textObservers: new Map(),
845
849
  saveTimer: null,
846
850
  stateSaveTimer: null,
851
+ stateDirty: true,
847
852
  cleanupTimer: null,
848
853
  lastModifiedUserId: null,
849
854
  epoch: bootstrap.epoch,
@@ -1515,6 +1520,7 @@ export class CollaborationService {
1515
1520
  }, SAVE_DELAY_MS);
1516
1521
  }
1517
1522
  scheduleStateSave(room) {
1523
+ room.stateDirty = true;
1518
1524
  if (room.stateSaveTimer)
1519
1525
  clearTimeout(room.stateSaveTimer);
1520
1526
  room.stateSaveTimer = setTimeout(() => {
@@ -1531,11 +1537,14 @@ export class CollaborationService {
1531
1537
  clearTimeout(room.stateSaveTimer);
1532
1538
  room.stateSaveTimer = null;
1533
1539
  this.rejectOversizedTexts(room);
1540
+ if (!room.stateDirty)
1541
+ return;
1534
1542
  const target = collaborationStatePath(this.config, room.projectId);
1535
1543
  const temporary = `${target}.tmp`;
1536
1544
  fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
1537
1545
  fs.writeFileSync(temporary, Y.encodeStateAsUpdate(room.doc), { mode: 0o600 });
1538
1546
  fs.renameSync(temporary, target);
1547
+ room.stateDirty = false;
1539
1548
  }
1540
1549
  flushRoom(room) {
1541
1550
  if (room.snapshotBarrierDepth > 0 || (this.snapshotBarriers.get(room.projectId) ?? 0) > 0) {
@@ -14,6 +14,9 @@ export const CONFIG_DEFAULTS = {
14
14
  basePath: ROOT_BASE_PATH,
15
15
  dataDir: defaultDataDirectory(),
16
16
  clientDir: packageClientDirectory(),
17
+ tikzGalleryEnabled: false,
18
+ /** Relative to the configuration file, like a relative storage.dataDir. */
19
+ tikzGalleryPath: path.join("addon", "texlite-tikz"),
17
20
  sessionDays: 14,
18
21
  compileTimeoutSeconds: 600,
19
22
  maxCompileJobs: 10,
@@ -93,6 +96,8 @@ export function loadConfig(configPathOverride) {
93
96
  databasePath: path.join(dataDir, "texlite.db"),
94
97
  projectsDir: path.join(dataDir, "projects"),
95
98
  clientDir,
99
+ tikzGalleryEnabled: fileConfig.tikzGallery?.enabled ?? CONFIG_DEFAULTS.tikzGalleryEnabled,
100
+ tikzGalleryDir: resolveConfiguredPath("tikzGallery.path", fileConfig.tikzGallery?.path ?? CONFIG_DEFAULTS.tikzGalleryPath, configDirectory),
96
101
  sessionDays: integerSetting("sessionDays", process.env.TEXLITE_SESSION_DAYS, fileConfig.sessionDays, CONFIG_DEFAULTS.sessionDays, CONFIG_LIMITS.sessionDays),
97
102
  compileTimeoutMs: compileTimeoutSeconds * 1000,
98
103
  maxCompileJobs,
@@ -210,6 +215,11 @@ function validateFileConfig(config) {
210
215
  optionalString(server?.basePath, "server.basePath", { min: 1, max: 1_024 });
211
216
  const storage = optionalSection(config.storage, "storage");
212
217
  optionalString(storage?.dataDir, "storage.dataDir", { min: 1, max: 4_096 });
218
+ const tikzGallery = optionalSection(config.tikzGallery, "tikzGallery");
219
+ if (tikzGallery && Object.prototype.hasOwnProperty.call(tikzGallery, "enabled") && typeof tikzGallery.enabled !== "boolean") {
220
+ throw configurationError("tikzGallery.enabled", "must be true or false");
221
+ }
222
+ optionalString(tikzGallery?.path, "tikzGallery.path", { min: 1, max: 4_096 });
213
223
  const uploads = optionalSection(config.uploads, "uploads");
214
224
  optionalInteger(uploads?.maxFileSizeMB, "uploads.maxFileSizeMB", CONFIG_LIMITS.maxFileSizeMB);
215
225
  const pdf = optionalSection(config.pdf, "pdf");
package/dist/server/db.js CHANGED
@@ -197,8 +197,72 @@ const databaseMigrations = [
197
197
  if (missingColumn(db, "project_edit_segments", "has_agent")) {
198
198
  db.exec("ALTER TABLE project_edit_segments ADD COLUMN has_agent INTEGER NOT NULL DEFAULT 0");
199
199
  }
200
+ } },
201
+ // Which stored file contents each snapshot uses, and how many snapshots use
202
+ // each content. Retention and storage statistics read these instead of
203
+ // parsing every manifest. Triggers keep both in step with the manifests;
204
+ // deleting a snapshot cascades and releases its references.
205
+ { version: 23, name: "add_history_version_objects", apply: createHistoryObjectIndex },
206
+ // Edit-history retention removes the oldest records first. This order lets
207
+ // it read just those rows instead of sorting the project's whole history.
208
+ { version: 24, name: "add_edit_segment_age_index", apply: (db) => {
209
+ db.exec(`CREATE INDEX IF NOT EXISTS project_edit_segments_project_updated
210
+ ON project_edit_segments(project_id, updated_at)`);
211
+ } },
212
+ // Development databases may have applied an unreleased draft of migration
213
+ // 23 that had only the per-snapshot rows. Complete the index and rebuild the
214
+ // reference counts from those rows; on any other database this is a no-op
215
+ // apart from recounting.
216
+ { version: 25, name: "complete_history_object_index", apply: (db) => {
217
+ createHistoryObjectIndex(db);
218
+ db.exec(`DROP INDEX IF EXISTS project_history_version_objects_digest;
219
+ DELETE FROM project_history_objects;
220
+ INSERT INTO project_history_objects (project_id, digest, size, refs)
221
+ SELECT project_id, digest, MAX(size), COUNT(*) FROM project_history_version_objects GROUP BY project_id, digest;`);
200
222
  } }
201
223
  ];
224
+ /** Create the snapshot object index and its triggers, and index existing snapshots. */
225
+ function createHistoryObjectIndex(db) {
226
+ const insertObjects = (version) => `INSERT OR IGNORE INTO project_history_version_objects (version_id, project_id, digest, size)
227
+ SELECT ${version}.id, ${version}.project_id, json_extract(file.value, '$.digest'), json_extract(file.value, '$.size')
228
+ FROM json_each(${version}.manifest_json, '$.files') AS file`;
229
+ db.exec(`
230
+ CREATE TABLE IF NOT EXISTS project_history_version_objects (
231
+ version_id TEXT NOT NULL REFERENCES project_history_versions(id) ON DELETE CASCADE,
232
+ project_id TEXT NOT NULL,
233
+ digest TEXT NOT NULL,
234
+ size INTEGER NOT NULL,
235
+ PRIMARY KEY (version_id, digest)
236
+ ) WITHOUT ROWID;
237
+ CREATE TABLE IF NOT EXISTS project_history_objects (
238
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
239
+ digest TEXT NOT NULL,
240
+ size INTEGER NOT NULL,
241
+ refs INTEGER NOT NULL,
242
+ PRIMARY KEY (project_id, digest)
243
+ ) WITHOUT ROWID;
244
+ CREATE TRIGGER IF NOT EXISTS project_history_version_objects_insert
245
+ AFTER INSERT ON project_history_version_objects BEGIN
246
+ INSERT INTO project_history_objects (project_id, digest, size, refs) VALUES (NEW.project_id, NEW.digest, NEW.size, 1)
247
+ ON CONFLICT(project_id, digest) DO UPDATE SET refs = refs + 1;
248
+ END;
249
+ CREATE TRIGGER IF NOT EXISTS project_history_version_objects_delete
250
+ AFTER DELETE ON project_history_version_objects BEGIN
251
+ UPDATE project_history_objects SET refs = refs - 1 WHERE project_id = OLD.project_id AND digest = OLD.digest;
252
+ DELETE FROM project_history_objects WHERE project_id = OLD.project_id AND digest = OLD.digest AND refs <= 0;
253
+ END;
254
+ CREATE TRIGGER IF NOT EXISTS project_history_versions_objects_insert
255
+ AFTER INSERT ON project_history_versions BEGIN
256
+ ${insertObjects("NEW")};
257
+ END;
258
+ CREATE TRIGGER IF NOT EXISTS project_history_versions_objects_update
259
+ AFTER UPDATE OF manifest_json ON project_history_versions BEGIN
260
+ DELETE FROM project_history_version_objects WHERE version_id = OLD.id;
261
+ ${insertObjects("NEW")};
262
+ END;
263
+ ${insertObjects("history").replace("FROM json_each(history.manifest_json", "FROM project_history_versions AS history, json_each(history.manifest_json")};
264
+ `);
265
+ }
202
266
  function migrateGitHubTokensToUsers(db) {
203
267
  db.exec(`
204
268
  CREATE TABLE IF NOT EXISTS user_github_settings (
@@ -13,7 +13,11 @@ export function createEditHistorySpan(beforeStart, afterStart, deleted, inserted
13
13
  }
14
14
  /** Agent-change mapping walks at most this many of a file's newest segments. */
15
15
  const MAX_AGENT_CHANGE_CHAIN_SEGMENTS = 2_000;
16
+ /** Files whose mapped agent changes stay in memory between requests. */
17
+ const MAX_CACHED_AGENT_CHANGE_FILES = 64;
16
18
  const DEFAULT_RESULT_LIMIT = 60;
19
+ /** Entries a "load older" request may skip; the walk itself is bounded by retention. */
20
+ export const MAX_SELECTION_HISTORY_OFFSET = 10_000;
17
21
  /** Edits separated by at most this pause belong to one displayed entry. */
18
22
  const EDIT_SESSION_GAP_MS = 5 * 60 * 1_000;
19
23
  /** A long continuous session is still split, so earlier states stay visible. */
@@ -29,6 +33,7 @@ export class ProjectEditHistoryService {
29
33
  db;
30
34
  maxSegments;
31
35
  maxStorageBytes;
36
+ agentChangeCache = new Map();
32
37
  constructor(db, maxStorageBytes = DEFAULT_EDIT_HISTORY_MAX_STORAGE_BYTES, maxSegments = CONFIG_DEFAULTS.editHistoryMaxSegments) {
33
38
  this.db = db;
34
39
  this.maxSegments = maxSegments;
@@ -85,28 +90,30 @@ export class ProjectEditHistoryService {
85
90
  }
86
91
  /** Keep the newest contiguous suffix within both record and payload limits. */
87
92
  prune(projectId) {
88
- const rows = this.db.prepare(`SELECT id, file_path, after_hash, updated_at, steps_bytes
93
+ // This runs on every saved edit batch. Removing the oldest records until
94
+ // both limits hold keeps exactly that suffix, and reads only the records
95
+ // being removed instead of sorting the project's whole history.
96
+ const totals = this.db.prepare(`SELECT COUNT(*) AS count, COALESCE(SUM(MAX(steps_bytes, 0)), 0) AS bytes
97
+ FROM project_edit_segments WHERE project_id = ?`).get(projectId);
98
+ let excessCount = totals.count - this.maxSegments;
99
+ let excessBytes = totals.bytes - this.maxStorageBytes;
100
+ if (excessCount <= 0 && excessBytes <= 0)
101
+ return;
102
+ const discarded = [];
103
+ for (const row of this.db.prepare(`SELECT id, file_path, after_hash, updated_at, steps_bytes
89
104
  FROM project_edit_segments WHERE project_id = ?
90
- ORDER BY updated_at DESC, rowid DESC`).all(projectId);
91
- let retainedBytes = 0;
92
- let retainedCount = 0;
93
- let firstDiscard = rows.length;
94
- for (let index = 0; index < rows.length; index += 1) {
95
- const size = Math.max(0, Number(rows[index].steps_bytes) || 0);
96
- if (retainedCount >= this.maxSegments || retainedBytes + size > this.maxStorageBytes) {
97
- firstDiscard = index;
105
+ ORDER BY updated_at ASC, rowid ASC`).iterate(projectId)) {
106
+ if (excessCount <= 0 && excessBytes <= 0)
98
107
  break;
99
- }
100
- retainedBytes += size;
101
- retainedCount += 1;
108
+ discarded.push(row);
109
+ excessCount -= 1;
110
+ excessBytes -= Math.max(0, Number(row.steps_bytes) || 0);
102
111
  }
103
- if (firstDiscard === rows.length)
104
- return;
105
112
  const remove = this.db.prepare("DELETE FROM project_edit_segments WHERE id = ?");
106
113
  const boundaryFiles = new Set();
107
- for (const row of rows.slice(firstDiscard)) {
108
- // Rows are newest first. The first discarded row for a source file is
109
- // precisely where a backward selection map must stop.
114
+ // The newest removed record of a source file is precisely where a
115
+ // backward selection map must stop.
116
+ for (const row of [...discarded].reverse()) {
110
117
  if (!boundaryFiles.has(row.file_path)) {
111
118
  boundaryFiles.add(row.file_path);
112
119
  this.recordRetentionBoundary(projectId, row.file_path, row.after_hash, row.updated_at);
@@ -120,7 +127,13 @@ export class ProjectEditHistoryService {
120
127
  ON CONFLICT(project_id, file_path) DO UPDATE SET after_hash = excluded.after_hash, updated_at = excluded.updated_at`)
121
128
  .run(projectId, filePath, afterHash, updatedAt);
122
129
  }
123
- selectionHistory(projectId, filePathInput, currentSource, startInput, endInput, resultLimit = DEFAULT_RESULT_LIMIT) {
130
+ selectionHistory(projectId, filePathInput, currentSource, startInput, endInput, resultLimit = DEFAULT_RESULT_LIMIT,
131
+ /**
132
+ * Entries the caller already shows. The passage can only be reconstructed
133
+ * by walking back from the current source, so a later page walks again
134
+ * and returns the entries after these.
135
+ */
136
+ offsetInput = 0) {
124
137
  const filePath = safeRelativePath(filePathInput);
125
138
  const start = clamp(Math.min(startInput, endInput), 0, currentSource.length);
126
139
  const end = clamp(Math.max(startInput, endInput), start, currentSource.length);
@@ -143,7 +156,8 @@ export class ProjectEditHistoryService {
143
156
  let chainComplete = true;
144
157
  let exhaustedRows = true;
145
158
  let baseline = null;
146
- const limit = clamp(resultLimit, 1, DEFAULT_RESULT_LIMIT);
159
+ const offset = clamp(offsetInput, 0, MAX_SELECTION_HISTORY_OFFSET);
160
+ const limit = offset + clamp(resultLimit, 1, DEFAULT_RESULT_LIMIT);
147
161
  for (const row of rows) {
148
162
  // A direct file replacement, restoration, import, or retained-history
149
163
  // pruning can intentionally create a gap. Never guess across it: doing
@@ -210,7 +224,7 @@ export class ProjectEditHistoryService {
210
224
  const preview = previewPassage(passage.exact ? passage.text : null);
211
225
  baseline = { content: preview.text, contentTruncated: preview.truncated };
212
226
  }
213
- return { entries, baseline, hasMore: !exhaustedRows, chainComplete };
227
+ return { entries: entries.slice(offset), baseline, hasMore: !exhaustedRows, chainComplete };
214
228
  }
215
229
  /**
216
230
  * Coding-agent changes made for `userId` in one file, mapped to `currentSource`.
@@ -221,6 +235,26 @@ export class ProjectEditHistoryService {
221
235
  */
222
236
  agentChanges(projectId, filePathInput, currentSource, userId) {
223
237
  const filePath = safeRelativePath(filePathInput);
238
+ // Browsers poll this while a task runs. The chain's shape and the source
239
+ // decide the result, and reading them avoids parsing every stored edit.
240
+ const shape = this.db.prepare(`SELECT COUNT(*) AS total, MAX(rowid) AS newest
241
+ FROM project_edit_segments WHERE project_id = ? AND file_path = ?`).get(projectId, filePath);
242
+ const cacheKey = JSON.stringify([projectId, filePath, userId]);
243
+ const signature = `${shape.total}:${shape.newest}:${hashText(currentSource)}`;
244
+ const cached = this.agentChangeCache.get(cacheKey);
245
+ if (cached?.signature === signature)
246
+ return cached.changes;
247
+ const changes = this.mapAgentChanges(projectId, filePath, currentSource, userId);
248
+ this.agentChangeCache.delete(cacheKey);
249
+ this.agentChangeCache.set(cacheKey, { signature, changes });
250
+ for (const key of this.agentChangeCache.keys()) {
251
+ if (this.agentChangeCache.size <= MAX_CACHED_AGENT_CHANGE_FILES)
252
+ break;
253
+ this.agentChangeCache.delete(key);
254
+ }
255
+ return changes;
256
+ }
257
+ mapAgentChanges(projectId, filePath, currentSource, userId) {
224
258
  const rows = this.db.prepare(`SELECT id, author_id, has_agent, before_hash, after_hash, steps_json
225
259
  FROM project_edit_segments WHERE project_id = ? AND file_path = ?
226
260
  ORDER BY updated_at DESC, rowid DESC LIMIT ?`)
@@ -355,6 +389,20 @@ function previewPassage(value) {
355
389
  const edge = Math.floor((MAX_PASSAGE_PREVIEW_CHARS - 1) / 2);
356
390
  return { text: `${value.slice(0, edge)}…${value.slice(value.length - edge)}`, truncated: true };
357
391
  }
392
+ /**
393
+ * Keep a file's edit chain with it through a rename or folder move. Run this in
394
+ * the transaction that moves the file; `movedPath` returns unaffected paths as is.
395
+ */
396
+ export function moveEditHistoryPaths(db, projectId, movedPath) {
397
+ for (const table of ["project_edit_segments", "project_edit_history_boundaries"]) {
398
+ const update = db.prepare(`UPDATE OR REPLACE ${table} SET file_path = ? WHERE project_id = ? AND file_path = ?`);
399
+ for (const { file_path: filePath } of db.prepare(`SELECT DISTINCT file_path FROM ${table} WHERE project_id = ?`).all(projectId)) {
400
+ const next = movedPath(filePath);
401
+ if (next !== filePath)
402
+ update.run(next, projectId, filePath);
403
+ }
404
+ }
405
+ }
358
406
  export function hashText(content) {
359
407
  return createHash("sha256").update(content).digest("hex");
360
408
  }
@@ -8,6 +8,8 @@ import { httpError } from "./http.js";
8
8
  import { detachedProcessGroup, killProcessGroup } from "./processTree.js";
9
9
  const MAX_COMMAND_OUTPUT = 8 * 1024 * 1024;
10
10
  const MAX_DIFF_OUTPUT = 1024 * 1024;
11
+ // Conflict recovery copies are local safety artifacts, never backup content.
12
+ const backupPaths = [".", ":(top,exclude).texlite-agent-conflicts"];
11
13
  export class ProjectGitService {
12
14
  config;
13
15
  db;
@@ -54,7 +56,7 @@ export class ProjectGitService {
54
56
  commitIdentity
55
57
  };
56
58
  const root = sourceRoot(this.config, project.id);
57
- const porcelain = (await this.git(root, ["status", "--porcelain=v1"])).stdout.trim();
59
+ const porcelain = (await this.git(root, ["status", "--porcelain=v1", "--", ...backupPaths])).stdout.trim();
58
60
  const branchResult = await this.git(root, ["symbolic-ref", "--quiet", "--short", "HEAD"], [1]);
59
61
  const branch = branchResult.code === 0 ? branchResult.stdout.trim() : null;
60
62
  const remoteResult = await this.git(root, ["remote", "get-url", "origin"], [2]);
@@ -173,8 +175,8 @@ export class ProjectGitService {
173
175
  const branch = await this.git(root, ["symbolic-ref", "--quiet", "--short", "HEAD"], [1]);
174
176
  if (branch.code !== 0)
175
177
  throw httpError(409, "GIT_DETACHED_HEAD");
176
- await this.git(root, ["add", "--all"]);
177
- const staged = await this.git(root, ["diff", "--cached", "--quiet"], [1]);
178
+ await this.git(root, ["add", "--all", "--", ...backupPaths]);
179
+ const staged = await this.git(root, ["diff", "--cached", "--quiet", "--", ...backupPaths], [1]);
178
180
  if (staged.code === 0)
179
181
  throw httpError(409, "GIT_NO_CHANGES");
180
182
  const identity = this.identityForUser(owner.id);
@@ -193,7 +195,7 @@ export class ProjectGitService {
193
195
  "-c", `user.email=${identity.email}`,
194
196
  "-c", "commit.gpgSign=false",
195
197
  "-c", "core.hooksPath=/dev/null",
196
- "commit", "-m", message
198
+ "commit", "--only", "-m", message, "--", ...backupPaths
197
199
  ], [], identityEnvironment);
198
200
  const result = await this.git(root, ["log", "-1", "--format=%H%x1f%h%x1f%an%x1f%ae%x1f%aI%x1f%s"]);
199
201
  return parseCommit(result.stdout.trim());
@@ -237,8 +239,8 @@ export class ProjectGitService {
237
239
  else {
238
240
  const hasHead = (await this.git(root, ["rev-parse", "--verify", "HEAD"], [128])).code === 0;
239
241
  if (hasHead)
240
- output = (await this.git(root, ["diff", "--no-ext-diff", "--unified=3", "HEAD", "--"])).stdout;
241
- const untracked = (await this.git(root, ["ls-files", "--others", "--exclude-standard", "-z"])).stdout
242
+ output = (await this.git(root, ["diff", "--no-ext-diff", "--unified=3", "HEAD", "--", ...backupPaths])).stdout;
243
+ const untracked = (await this.git(root, ["ls-files", "--others", "--exclude-standard", "-z", "--", ...backupPaths])).stdout
242
244
  .split("\0").filter(Boolean).slice(0, 100);
243
245
  for (const file of untracked) {
244
246
  const addition = await this.git(root, ["diff", "--no-index", "--", "/dev/null", file], [1]);
@@ -274,7 +276,7 @@ export class ProjectGitService {
274
276
  if (head.code !== 0)
275
277
  throw httpError(409, "GIT_NO_COMMIT");
276
278
  await this.assertRevisionHasNoSymlinks(root, head.stdout.trim());
277
- await this.git(root, ["restore", "--source=HEAD", "--staged", "--worktree", "--", "."]);
279
+ await this.git(root, ["restore", "--source=HEAD", "--staged", "--worktree", "--", ...backupPaths]);
278
280
  assertNoSourceSymlinks(this.config, project.id);
279
281
  }
280
282
  async ensureRepository(project) {