texlite 0.24.0 → 0.25.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 (241) hide show
  1. package/DESIGN.md +85 -2
  2. package/NPM_TESTING.md +46 -2
  3. package/OPERATIONS.md +136 -6
  4. package/README.md +1 -2
  5. package/README.zh-CN.md +2 -2
  6. package/THIRD_PARTY_NOTICES.md +12 -0
  7. package/dist/client/assets/AdminUsers-D4ljqr_D.js +1 -0
  8. package/dist/client/assets/AdminUsers-D4ljqr_D.js.br +0 -0
  9. package/dist/client/assets/AdminUsers-D4ljqr_D.js.gz +0 -0
  10. package/dist/client/assets/AgentManagement-DwRMP_nD.js +1 -0
  11. package/dist/client/assets/AgentManagement-DwRMP_nD.js.br +0 -0
  12. package/dist/client/assets/AgentManagement-DwRMP_nD.js.gz +0 -0
  13. package/dist/client/assets/AgentTerminal-CSsr21PC.js +2 -0
  14. package/dist/client/assets/AgentTerminal-CSsr21PC.js.br +0 -0
  15. package/dist/client/assets/AgentTerminal-CSsr21PC.js.gz +0 -0
  16. package/dist/client/assets/{AgentTerminalSurface-DliOcop5.js → AgentTerminalSurface-BLroKMGe.js} +1 -1
  17. package/dist/client/assets/{AgentTerminalSurface-DliOcop5.js.br → AgentTerminalSurface-BLroKMGe.js.br} +0 -0
  18. package/dist/client/assets/AgentTerminalSurface-BLroKMGe.js.gz +0 -0
  19. package/dist/client/assets/{AvatarSettingsDialog-iuEbMO4a.js → AvatarSettingsDialog-BgVGfSzn.js} +1 -1
  20. package/dist/client/assets/AvatarSettingsDialog-BgVGfSzn.js.br +0 -0
  21. package/dist/client/assets/AvatarSettingsDialog-BgVGfSzn.js.gz +0 -0
  22. package/dist/client/assets/CitationBibtexEditor-DLPom-qx.js +1 -0
  23. package/dist/client/assets/CitationLibraryDialog-Cn-kFi8E.js +3 -0
  24. package/dist/client/assets/CitationLibraryDialog-Cn-kFi8E.js.br +0 -0
  25. package/dist/client/assets/CitationLibraryDialog-Cn-kFi8E.js.gz +0 -0
  26. package/dist/client/assets/Dashboard-7JrR0t6C.js +5 -0
  27. package/dist/client/assets/Dashboard-7JrR0t6C.js.br +0 -0
  28. package/dist/client/assets/Dashboard-7JrR0t6C.js.gz +0 -0
  29. package/dist/client/assets/DrawioEditor-CYQnzKDd.js +1 -0
  30. package/dist/client/assets/DrawioEditor-CYQnzKDd.js.br +0 -0
  31. package/dist/client/assets/DrawioEditor-CYQnzKDd.js.gz +0 -0
  32. package/dist/client/assets/GitDialog-DMCVR8QK.js +4 -0
  33. package/dist/client/assets/GitDialog-DMCVR8QK.js.br +0 -0
  34. package/dist/client/assets/GitDialog-DMCVR8QK.js.gz +0 -0
  35. package/dist/client/assets/GitHubAccountDialog-BbJpR9Vq.js +1 -0
  36. package/dist/client/assets/GitHubAccountDialog-BbJpR9Vq.js.br +0 -0
  37. package/dist/client/assets/GitHubAccountDialog-BbJpR9Vq.js.gz +0 -0
  38. package/dist/client/assets/{HistoryDialog-upkR8E0L.js → HistoryDialog-CcPWpTLn.js} +3 -3
  39. package/dist/client/assets/HistoryDialog-CcPWpTLn.js.br +0 -0
  40. package/dist/client/assets/HistoryDialog-CcPWpTLn.js.gz +0 -0
  41. package/dist/client/assets/LatexEditor-D7C9jpJO.js +25 -0
  42. package/dist/client/assets/LatexEditor-D7C9jpJO.js.br +0 -0
  43. package/dist/client/assets/LatexEditor-D7C9jpJO.js.gz +0 -0
  44. package/dist/client/assets/{MarkdownPreview-_AXp5G7f.js → MarkdownPreview-Txs5upCY.js} +1 -1
  45. package/dist/client/assets/MarkdownPreview-Txs5upCY.js.br +0 -0
  46. package/dist/client/assets/MarkdownPreview-Txs5upCY.js.gz +0 -0
  47. package/dist/client/assets/{ProjectIconPickerDialog-BxjEYsau.js → ProjectIconPickerDialog-CUlPlfmL.js} +1 -1
  48. package/dist/client/assets/ProjectIconPickerDialog-CUlPlfmL.js.br +0 -0
  49. package/dist/client/assets/ProjectIconPickerDialog-CUlPlfmL.js.gz +0 -0
  50. package/dist/client/assets/ProjectSearchDialog-Bt6NyHIJ.js +1 -0
  51. package/dist/client/assets/ProjectSearchDialog-Bt6NyHIJ.js.br +0 -0
  52. package/dist/client/assets/ProjectSearchDialog-Bt6NyHIJ.js.gz +0 -0
  53. package/dist/client/assets/ProjectSettings-B6e7EAxq.js +4 -0
  54. package/dist/client/assets/ProjectSettings-B6e7EAxq.js.br +0 -0
  55. package/dist/client/assets/ProjectSettings-B6e7EAxq.js.gz +0 -0
  56. package/dist/client/assets/ProjectWorkspace-D0EMITec.js +25 -0
  57. package/dist/client/assets/ProjectWorkspace-D0EMITec.js.br +0 -0
  58. package/dist/client/assets/ProjectWorkspace-D0EMITec.js.gz +0 -0
  59. package/dist/client/assets/{QuickOpenDialog-HlkWqVR9.js → QuickOpenDialog-D6yjnquG.js} +1 -1
  60. package/dist/client/assets/QuickOpenDialog-D6yjnquG.js.br +0 -0
  61. package/dist/client/assets/QuickOpenDialog-D6yjnquG.js.gz +0 -0
  62. package/dist/client/assets/{ReadOnlySource-BIdN1YP_.js → ReadOnlySource-BOAnB5L0.js} +1 -1
  63. package/dist/client/assets/{SelectionHistoryDialog-Cb8I-G6m.js → SelectionHistoryDialog-D6ql9E0j.js} +2 -2
  64. package/dist/client/assets/SelectionHistoryDialog-D6ql9E0j.js.br +0 -0
  65. package/dist/client/assets/SelectionHistoryDialog-D6ql9E0j.js.gz +0 -0
  66. package/dist/client/assets/SharedProjectPage-DuscqDx5.js +2 -0
  67. package/dist/client/assets/SharedProjectPage-DuscqDx5.js.br +0 -0
  68. package/dist/client/assets/SharedProjectPage-DuscqDx5.js.gz +0 -0
  69. package/dist/client/assets/SystemMetricsDialog-KiKZOF2N.js +1 -0
  70. package/dist/client/assets/SystemMetricsDialog-KiKZOF2N.js.br +0 -0
  71. package/dist/client/assets/SystemMetricsDialog-KiKZOF2N.js.gz +0 -0
  72. package/dist/client/assets/TagManagementDialog-BHbqvu3K.js +1 -0
  73. package/dist/client/assets/TagManagementDialog-BHbqvu3K.js.br +0 -0
  74. package/dist/client/assets/TagManagementDialog-BHbqvu3K.js.gz +0 -0
  75. package/dist/client/assets/ThemeSwitcher-5cgNbWiG.js +1 -0
  76. package/dist/client/assets/{TikzGalleryDialog-cPUDQ5Wj.js → TikzGalleryDialog-CFbLjNTt.js} +1 -1
  77. package/dist/client/assets/TikzGalleryDialog-CFbLjNTt.js.br +0 -0
  78. package/dist/client/assets/TikzGalleryDialog-CFbLjNTt.js.gz +0 -0
  79. package/dist/client/assets/{WordCountDialog-AiuR3rra.js → WordCountDialog-hXC-cpPs.js} +1 -1
  80. package/dist/client/assets/WordCountDialog-hXC-cpPs.js.br +0 -0
  81. package/dist/client/assets/WordCountDialog-hXC-cpPs.js.gz +0 -0
  82. package/dist/client/assets/{chktex--32C-Pkl.js → chktex-CLzMD_9a.js} +1 -1
  83. package/dist/client/assets/file-down-DA4jGFrF.js +1 -0
  84. package/dist/client/assets/i18n-B8sR-BXw.js +13 -0
  85. package/dist/client/assets/i18n-B8sR-BXw.js.br +0 -0
  86. package/dist/client/assets/i18n-B8sR-BXw.js.gz +0 -0
  87. package/dist/client/assets/index-D6faTuJe.css +1 -0
  88. package/dist/client/assets/index-D6faTuJe.css.br +0 -0
  89. package/dist/client/assets/index-D6faTuJe.css.gz +0 -0
  90. package/dist/client/assets/index-dScQ5LCu.js +2 -0
  91. package/dist/client/assets/index-dScQ5LCu.js.br +0 -0
  92. package/dist/client/assets/index-dScQ5LCu.js.gz +0 -0
  93. package/dist/client/assets/relativeTime-zIVNCN0k.js +1 -0
  94. package/dist/client/assets/relativeTime-zIVNCN0k.js.br +0 -0
  95. package/dist/client/assets/relativeTime-zIVNCN0k.js.gz +0 -0
  96. package/dist/client/assets/sourceCursorStore-DWCXVKvp.js +2 -0
  97. package/dist/client/assets/sourceCursorStore-DWCXVKvp.js.br +0 -0
  98. package/dist/client/assets/sourceCursorStore-DWCXVKvp.js.gz +0 -0
  99. package/dist/client/assets/{spellCheck-DpWPgtM7.js → spellCheck-DpyzDbmq.js} +1 -1
  100. package/dist/client/assets/spellCheck-DpyzDbmq.js.br +0 -0
  101. package/dist/client/assets/spellCheck-DpyzDbmq.js.gz +0 -0
  102. package/dist/client/assets/useDeletionTransitions-Bm4I5qej.js +1 -0
  103. package/dist/client/assets/useDeletionTransitions-Bm4I5qej.js.br +0 -0
  104. package/dist/client/assets/useDeletionTransitions-Bm4I5qej.js.gz +0 -0
  105. package/dist/client/index.html +3 -4
  106. package/dist/server/agents/adapters/claude.js +5 -2
  107. package/dist/server/agents/adapters/common.js +18 -5
  108. package/dist/server/agents/execution.js +25 -4
  109. package/dist/server/agents/launcher.js +5 -2
  110. package/dist/server/agents/processIdentity.js +1 -1
  111. package/dist/server/agents/terminal.js +5 -2
  112. package/dist/server/agents/windowsJob.js +141 -0
  113. package/dist/server/app.js +24 -6
  114. package/dist/server/auth.js +3 -2
  115. package/dist/server/browserOrigin.js +15 -0
  116. package/dist/server/chktex.js +23 -11
  117. package/dist/server/collaboration.js +2 -1
  118. package/dist/server/compileDiagnostics.js +13 -9
  119. package/dist/server/compiler.js +70 -25
  120. package/dist/server/config.js +5 -1
  121. package/dist/server/db.js +4 -0
  122. package/dist/server/drawioLocks.js +114 -0
  123. package/dist/server/drawioOwnedBrowser.js +122 -0
  124. package/dist/server/drawioPdf.js +182 -0
  125. package/dist/server/environment.js +17 -8
  126. package/dist/server/files.js +86 -20
  127. package/dist/server/git.js +20 -16
  128. package/dist/server/harper.js +29 -10
  129. package/dist/server/history.js +62 -15
  130. package/dist/server/i18n.js +15 -0
  131. package/dist/server/index.js +15 -8
  132. package/dist/server/locales/zh-Hant.js +9 -0
  133. package/dist/server/pdfFonts.js +78 -0
  134. package/dist/server/pm2.js +2 -1
  135. package/dist/server/processTree.js +128 -7
  136. package/dist/server/projectDeletionCleanup.js +62 -0
  137. package/dist/server/projectMutations.js +3 -0
  138. package/dist/server/projectReplace.js +2 -2
  139. package/dist/server/projectSearch.js +2 -1
  140. package/dist/server/projectTemplateCache.js +94 -0
  141. package/dist/server/projectTemplateDownload.js +75 -0
  142. package/dist/server/projectTextSave.js +56 -0
  143. package/dist/server/routes/agents.js +2 -15
  144. package/dist/server/routes/compile.js +67 -9
  145. package/dist/server/routes/drawio.js +192 -0
  146. package/dist/server/routes/projectFiles.js +106 -20
  147. package/dist/server/routes/projects.js +81 -20
  148. package/dist/server/routes/users.js +10 -14
  149. package/dist/server/synctex.js +20 -3
  150. package/dist/server/texcount.js +27 -23
  151. package/dist/server/zip.js +37 -11
  152. package/dist/shared/drawio.js +79 -0
  153. package/dist/shared/fileTypes.js +1 -1
  154. package/dist/shared/pdfFonts.js +14 -0
  155. package/dist/shared/projectImport.js +21 -0
  156. package/package.json +3 -1
  157. package/dist/client/assets/AdminUsers-C-8tXzvj.js +0 -1
  158. package/dist/client/assets/AdminUsers-C-8tXzvj.js.br +0 -0
  159. package/dist/client/assets/AdminUsers-C-8tXzvj.js.gz +0 -0
  160. package/dist/client/assets/AgentManagement-DXgfP7l_.js +0 -1
  161. package/dist/client/assets/AgentManagement-DXgfP7l_.js.br +0 -0
  162. package/dist/client/assets/AgentManagement-DXgfP7l_.js.gz +0 -0
  163. package/dist/client/assets/AgentTerminal-DD4sskCS.js +0 -2
  164. package/dist/client/assets/AgentTerminal-DD4sskCS.js.br +0 -0
  165. package/dist/client/assets/AgentTerminal-DD4sskCS.js.gz +0 -0
  166. package/dist/client/assets/AgentTerminalSurface-DliOcop5.js.gz +0 -0
  167. package/dist/client/assets/AvatarSettingsDialog-iuEbMO4a.js.br +0 -0
  168. package/dist/client/assets/AvatarSettingsDialog-iuEbMO4a.js.gz +0 -0
  169. package/dist/client/assets/CitationBibtexEditor-CDiYDj3M.js +0 -1
  170. package/dist/client/assets/CitationLibraryDialog-CJlL-Ytx.js +0 -3
  171. package/dist/client/assets/CitationLibraryDialog-CJlL-Ytx.js.br +0 -0
  172. package/dist/client/assets/CitationLibraryDialog-CJlL-Ytx.js.gz +0 -0
  173. package/dist/client/assets/Dashboard-DqwGd9wd.js +0 -5
  174. package/dist/client/assets/Dashboard-DqwGd9wd.js.br +0 -0
  175. package/dist/client/assets/Dashboard-DqwGd9wd.js.gz +0 -0
  176. package/dist/client/assets/GitDialog-DUGAigLx.js +0 -4
  177. package/dist/client/assets/GitDialog-DUGAigLx.js.br +0 -0
  178. package/dist/client/assets/GitDialog-DUGAigLx.js.gz +0 -0
  179. package/dist/client/assets/GitHubAccountDialog-B4eD622i.js +0 -1
  180. package/dist/client/assets/GitHubAccountDialog-B4eD622i.js.br +0 -0
  181. package/dist/client/assets/GitHubAccountDialog-B4eD622i.js.gz +0 -0
  182. package/dist/client/assets/HistoryDialog-upkR8E0L.js.br +0 -0
  183. package/dist/client/assets/HistoryDialog-upkR8E0L.js.gz +0 -0
  184. package/dist/client/assets/InfoPopover-CQ3Q10tN.js +0 -1
  185. package/dist/client/assets/LatexEditor-DvDYTc0r.js +0 -25
  186. package/dist/client/assets/LatexEditor-DvDYTc0r.js.br +0 -0
  187. package/dist/client/assets/LatexEditor-DvDYTc0r.js.gz +0 -0
  188. package/dist/client/assets/MarkdownPreview-_AXp5G7f.js.br +0 -0
  189. package/dist/client/assets/MarkdownPreview-_AXp5G7f.js.gz +0 -0
  190. package/dist/client/assets/ProjectIconPickerDialog-BxjEYsau.js.br +0 -0
  191. package/dist/client/assets/ProjectIconPickerDialog-BxjEYsau.js.gz +0 -0
  192. package/dist/client/assets/ProjectSearchDialog-BB8thfK9.js +0 -1
  193. package/dist/client/assets/ProjectSearchDialog-BB8thfK9.js.br +0 -0
  194. package/dist/client/assets/ProjectSearchDialog-BB8thfK9.js.gz +0 -0
  195. package/dist/client/assets/ProjectSettings-Dx-b26uN.js +0 -4
  196. package/dist/client/assets/ProjectSettings-Dx-b26uN.js.br +0 -0
  197. package/dist/client/assets/ProjectSettings-Dx-b26uN.js.gz +0 -0
  198. package/dist/client/assets/ProjectWorkspace-DiurYeU1.js +0 -25
  199. package/dist/client/assets/ProjectWorkspace-DiurYeU1.js.br +0 -0
  200. package/dist/client/assets/ProjectWorkspace-DiurYeU1.js.gz +0 -0
  201. package/dist/client/assets/QuickOpenDialog-HlkWqVR9.js.br +0 -0
  202. package/dist/client/assets/QuickOpenDialog-HlkWqVR9.js.gz +0 -0
  203. package/dist/client/assets/SelectionHistoryDialog-Cb8I-G6m.js.br +0 -0
  204. package/dist/client/assets/SelectionHistoryDialog-Cb8I-G6m.js.gz +0 -0
  205. package/dist/client/assets/SharedProjectPage-BBLOLjnD.js +0 -2
  206. package/dist/client/assets/SharedProjectPage-BBLOLjnD.js.br +0 -0
  207. package/dist/client/assets/SharedProjectPage-BBLOLjnD.js.gz +0 -0
  208. package/dist/client/assets/SystemMetricsDialog-Dr4pYWG6.js +0 -1
  209. package/dist/client/assets/SystemMetricsDialog-Dr4pYWG6.js.br +0 -0
  210. package/dist/client/assets/SystemMetricsDialog-Dr4pYWG6.js.gz +0 -0
  211. package/dist/client/assets/TagManagementDialog-D4fYVboy.js +0 -1
  212. package/dist/client/assets/TagManagementDialog-D4fYVboy.js.br +0 -0
  213. package/dist/client/assets/TagManagementDialog-D4fYVboy.js.gz +0 -0
  214. package/dist/client/assets/ThemeSwitcher-BgzkYTeA.js +0 -1
  215. package/dist/client/assets/TikzGalleryDialog-cPUDQ5Wj.js.br +0 -0
  216. package/dist/client/assets/TikzGalleryDialog-cPUDQ5Wj.js.gz +0 -0
  217. package/dist/client/assets/WordCountDialog-AiuR3rra.js.br +0 -0
  218. package/dist/client/assets/WordCountDialog-AiuR3rra.js.gz +0 -0
  219. package/dist/client/assets/dist-DdUqlCPw.js +0 -1
  220. package/dist/client/assets/dist-DdUqlCPw.js.br +0 -0
  221. package/dist/client/assets/dist-DdUqlCPw.js.gz +0 -0
  222. package/dist/client/assets/i18n-Dpk6KCs6.js +0 -13
  223. package/dist/client/assets/i18n-Dpk6KCs6.js.br +0 -0
  224. package/dist/client/assets/i18n-Dpk6KCs6.js.gz +0 -0
  225. package/dist/client/assets/index-B1vejuOw.js +0 -2
  226. package/dist/client/assets/index-B1vejuOw.js.br +0 -0
  227. package/dist/client/assets/index-B1vejuOw.js.gz +0 -0
  228. package/dist/client/assets/index-Blr4J_Pq.css +0 -1
  229. package/dist/client/assets/index-Blr4J_Pq.css.br +0 -0
  230. package/dist/client/assets/index-Blr4J_Pq.css.gz +0 -0
  231. package/dist/client/assets/relativeTime-CcP1IEvr.js +0 -1
  232. package/dist/client/assets/relativeTime-CcP1IEvr.js.br +0 -0
  233. package/dist/client/assets/relativeTime-CcP1IEvr.js.gz +0 -0
  234. package/dist/client/assets/sourceCursorStore-EycYBVxj.js +0 -1
  235. package/dist/client/assets/sourceCursorStore-EycYBVxj.js.br +0 -0
  236. package/dist/client/assets/sourceCursorStore-EycYBVxj.js.gz +0 -0
  237. package/dist/client/assets/spellCheck-DpWPgtM7.js.br +0 -0
  238. package/dist/client/assets/spellCheck-DpWPgtM7.js.gz +0 -0
  239. package/dist/client/assets/useDeletionTransitions-DvxVkRuo.js +0 -1
  240. package/dist/client/assets/useDeletionTransitions-DvxVkRuo.js.br +0 -0
  241. package/dist/client/assets/useDeletionTransitions-DvxVkRuo.js.gz +0 -0
@@ -2,18 +2,31 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { execFile } from "node:child_process";
4
4
  import { promisify } from "node:util";
5
- export const executeAgentCommand = promisify(execFile);
5
+ import { windowsAgentCommand } from "../terminal.js";
6
+ const exec = promisify(execFile);
7
+ export function executeAgentCommand(executable, args, options) {
8
+ if (process.platform === "win32" && /\.(?:cmd|bat)$/i.test(executable)) {
9
+ const command = windowsAgentCommand(executable, args);
10
+ return exec(command.executable, command.argv, { ...options, shell: false, windowsVerbatimArguments: true, encoding: "utf8" });
11
+ }
12
+ return exec(executable, args, { ...options, shell: false, encoding: "utf8" });
13
+ }
6
14
  export const noAgentFeatures = async () => new Set();
7
15
  export function hostAgentEnvironment() {
8
16
  const env = {};
9
17
  const names = /^(?:PATH|HOME|USER|USERNAME|USERPROFILE|SHELL|COMSPEC|SystemRoot|SYSTEMROOT|WINDIR|APPDATA|LOCALAPPDATA|TEMP|TMP|TMPDIR|LANG|LC_.*|COLORTERM|XDG_.*|https?_proxy|HTTPS?_PROXY|ALL_PROXY|all_proxy|NO_PROXY|no_proxy|SSL_CERT_FILE|SSL_CERT_DIR|NODE_EXTRA_CA_CERTS|SSH_AUTH_SOCK|OPENAI_.*|ANTHROPIC_.*|GOOGLE_.*|GEMINI_.*|OPENCODE_CONFIG(?:_DIR|_CONTENT)?|CODEX_API_KEY|CLAUDE_CODE_OAUTH_TOKEN|CLAUDE_CODE_USE_BEDROCK|CLAUDE_CODE_USE_VERTEX)$/;
10
- for (const [key, value] of Object.entries(process.env))
11
- if (value !== undefined && names.test(key))
12
- env[key] = value;
18
+ for (const [key, value] of Object.entries(process.env)) {
19
+ const allowed = process.platform === "win32" ? key.toUpperCase() : key;
20
+ if (value !== undefined && names.test(allowed))
21
+ env[allowed] = value;
22
+ }
13
23
  env.TERM = "xterm-256color";
14
24
  return env;
15
25
  }
16
26
  export function agentLaunch(context, args, overrides = {}) {
27
+ const platformOverrides = process.platform === "win32"
28
+ ? Object.fromEntries(Object.entries(overrides).map(([key, value]) => [key.toUpperCase(), value]))
29
+ : overrides;
17
30
  // Inherit host cache settings for reuse across tasks and native terminals.
18
31
  // Adapters define native state/session ownership independently of caching.
19
32
  return { executable: context.executable, args, env: { ...hostAgentEnvironment(),
@@ -21,7 +34,7 @@ export function agentLaunch(context, args, overrides = {}) {
21
34
  // discovery from treating that ancestor repository as the paper's repo.
22
35
  GIT_CEILING_DIRECTORIES: path.dirname(context.workingDirectory),
23
36
  TEXLITE_PROJECT_CONTEXT: path.join(context.stateDirectory, "project-context.json"),
24
- TEXLITE_COMPILE_LOG: path.join(context.stateDirectory, "compile.log"), ...overrides } };
37
+ TEXLITE_COMPILE_LOG: path.join(context.stateDirectory, "compile.log"), ...platformOverrides } };
25
38
  }
26
39
  /** Copy an explicit credential/config file; never share native conversation history. */
27
40
  export async function copyAgentSetting(source, target) {
@@ -4,6 +4,7 @@ import { fileURLToPath } from "node:url";
4
4
  import { inspectAgentProcess, agentProcessGroupAlive } from "./processIdentity.js";
5
5
  import { stopAgentPty, windowsAgentCommand } from "./terminal.js";
6
6
  import { httpError } from "../http.js";
7
+ import { attachWindowsAgentJob, stopWindowsAgentJob } from "./windowsJob.js";
7
8
  function readRecord(filename) {
8
9
  let value;
9
10
  try {
@@ -14,7 +15,8 @@ function readRecord(filename) {
14
15
  return null;
15
16
  throw error;
16
17
  }
17
- if (value?.version !== 1 || !/^[a-f\d-]{36}$/.test(value.executionId) || value.platform !== process.platform
18
+ if ((value?.version !== 1 && value?.version !== 2) || !/^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/.test(value.executionId) || value.platform !== process.platform
19
+ || (value.version === 2 && (value.platform !== "win32" || value.pid === null))
18
20
  || !(value.pid === null && value.identity === null || Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.identity === "string" && value.identity)) {
19
21
  throw httpError(409, "AGENT_RECOVERY_FAILED");
20
22
  }
@@ -34,7 +36,19 @@ export async function recoverAgentExecution(filename) {
34
36
  const record = readRecord(filename);
35
37
  if (!record)
36
38
  return;
39
+ if (record.version === 2) {
40
+ // The job outlives a dead launcher until all its members have exited.
41
+ // Never stop a recycled PID or infer completion from launcher exit.
42
+ await stopWindowsAgentJob(record.executionId);
43
+ clearAgentExecution(filename);
44
+ return;
45
+ }
37
46
  if (record.pid !== null) {
47
+ if (record.platform === "win32") {
48
+ // Legacy records have no owned job and cannot prove that every
49
+ // descendant is gone. Do not release the project on that basis.
50
+ throw httpError(409, "AGENT_RECOVERY_FAILED");
51
+ }
38
52
  const process = await inspectAgentProcess(record.pid, record.executionId);
39
53
  if (process && process.identity === record.identity && process.owned) {
40
54
  // Verify twice before signalling; a recycled PID must never be targeted.
@@ -68,14 +82,14 @@ export async function recoverAgentExecution(filename) {
68
82
  /** Start a gated, identifiable group leader without changing the CLI's TTY. */
69
83
  export async function spawnRecoverableAgent(spawn, executable, args, options, filename, beforeStart) {
70
84
  const record = { version: 1, executionId: randomUUID(), platform: process.platform, pid: null, identity: null };
71
- fs.writeFileSync(filename, JSON.stringify(record), { flag: "wx", mode: 0o600 });
72
85
  const compiled = new URL("./launcher.js", import.meta.url);
73
86
  const launcher = fileURLToPath(fs.existsSync(compiled) ? compiled : new URL("./launcher.ts", import.meta.url));
74
87
  let launch = { executable, args, windowsVerbatimArguments: false };
75
88
  if (process.platform === "win32" && /\.(?:cmd|bat)$/i.test(executable)) {
76
89
  const command = windowsAgentCommand(executable, args);
77
- launch = { executable: command.executable, args: ["/d", "/v:off", "/s", "/c", command.args.slice("/d /v:off /s /c ".length)], windowsVerbatimArguments: true };
90
+ launch = { executable: command.executable, args: command.argv, windowsVerbatimArguments: true };
78
91
  }
92
+ fs.writeFileSync(filename, JSON.stringify(record), { flag: "wx", mode: 0o600 });
79
93
  let pty;
80
94
  try {
81
95
  pty = await spawn(process.execPath, [launcher, filename, record.executionId], {
@@ -93,6 +107,11 @@ export async function spawnRecoverableAgent(spawn, executable, args, options, fi
93
107
  throw httpError(409, "AGENT_START_FAILED");
94
108
  record.pid = pty.pid;
95
109
  record.identity = identity.identity;
110
+ if (process.platform === "win32") {
111
+ await attachWindowsAgentJob(pty.pid, record.executionId);
112
+ record.version = 2;
113
+ wrapped.stop = () => stopWindowsAgentJob(record.executionId);
114
+ }
96
115
  // Conversation cleanup ownership must be durable before the CLI is allowed
97
116
  // to create any native state, not after the launch promise returns.
98
117
  beforeStart?.();
@@ -104,7 +123,9 @@ export async function spawnRecoverableAgent(spawn, executable, args, options, fi
104
123
  catch (error) {
105
124
  // No permit was issued, so the CLI cannot have started. Keep any failed
106
125
  // cleanup lease so service recovery can cancel the waiting launcher.
107
- if (pty)
126
+ // On Windows no permit was issued. The launcher will exit when the
127
+ // pending record is removed; no CLI or descendants can have started.
128
+ if (pty && process.platform !== "win32")
108
129
  await stopAgentPty(pty);
109
130
  clearAgentExecution(filename);
110
131
  throw error;
@@ -14,7 +14,7 @@ process.on("SIGTERM", () => undefined);
14
14
  process.on("SIGINT", () => undefined);
15
15
  if (process.platform !== "win32")
16
16
  process.on("SIGHUP", () => undefined);
17
- const deadline = Date.now() + 10_000;
17
+ const deadline = Date.now() + (process.platform === "win32" ? 30_000 : 10_000);
18
18
  while (true) {
19
19
  let record;
20
20
  try {
@@ -25,8 +25,11 @@ while (true) {
25
25
  }
26
26
  if (record.executionId !== executionId)
27
27
  process.exit(1);
28
- if (record.pid === process.pid && record.identity)
28
+ if (record.pid === process.pid && record.identity) {
29
+ if (record.version !== (process.platform === "win32" ? 2 : 1))
30
+ process.exit(1);
29
31
  break;
32
+ }
30
33
  if (Date.now() >= deadline)
31
34
  process.exit(1);
32
35
  await new Promise((resolve) => setTimeout(resolve, 25));
@@ -54,7 +54,7 @@ export async function inspectAgentProcess(pid, executionId, io = systemIO) {
54
54
  /** A vanished leader is not proof that all members of its POSIX group exited. */
55
55
  export async function agentProcessGroupAlive(pid, io = systemIO) {
56
56
  if (io.platform === "win32")
57
- return false;
57
+ throw new Error("Windows agent groups require an owned Job Object");
58
58
  const output = await io.command("ps", ["-axo", "pgid=,stat="]);
59
59
  return output.split("\n").some((line) => {
60
60
  const [group, state] = line.trim().split(/\s+/);
@@ -30,15 +30,18 @@ export function windowsAgentCommand(executable, args) {
30
30
  const quote = (value) => {
31
31
  // Registered CLI flags/IDs never require shell expansion. Refuse values
32
32
  // that cmd.exe would reinterpret even within double quotes.
33
- if (/["%\r\n]/.test(value))
33
+ if (/["%\0\r\n]/.test(value))
34
34
  throw new Error("Unsupported Windows command argument");
35
35
  return `"${value}"`;
36
36
  };
37
37
  const command = [executable, ...args].map(quote).join(" ");
38
- return { executable: process.env.COMSPEC ?? process.env.ComSpec ?? "cmd.exe", args: `/d /v:off /s /c "${command}"` };
38
+ const argv = ["/d", "/v:off", "/s", "/c", `"${command}"`];
39
+ return { executable: process.env.COMSPEC ?? process.env.ComSpec ?? "cmd.exe", args: argv.join(" "), argv };
39
40
  }
40
41
  /** Caller must own the live PTY or verify the persisted launcher's birth identity. */
41
42
  export async function stopAgentPty(pty) {
43
+ if (pty.stop)
44
+ return pty.stop();
42
45
  if (process.platform === "win32") {
43
46
  // Natural exit (or another stop) may have already removed the process.
44
47
  // Do not interpret localized taskkill output/exit codes as proof of this:
@@ -0,0 +1,141 @@
1
+ import { execFile } from "node:child_process";
2
+ import path from "node:path";
3
+ import { promisify } from "node:util";
4
+ const run = promisify(execFile);
5
+ // Windows PowerShell provides .NET interop on the target Windows x64 hosts.
6
+ // Keep the handle in the gated Node launcher, not in TexLite or a permanent
7
+ // helper process. The handle is non-inheritable and dies with that launcher.
8
+ const native = String.raw `
9
+ using System;
10
+ using System.ComponentModel;
11
+ using System.Diagnostics;
12
+ using System.Runtime.InteropServices;
13
+ using System.Threading;
14
+
15
+ public static class TexLiteJob {
16
+ [StructLayout(LayoutKind.Sequential)]
17
+ struct BasicLimits {
18
+ public long ProcessTime, JobTime;
19
+ public uint Flags;
20
+ public UIntPtr MinimumWorkingSet, MaximumWorkingSet;
21
+ public uint ActiveProcessLimit;
22
+ public UIntPtr Affinity;
23
+ public uint Priority, Scheduling;
24
+ }
25
+ [StructLayout(LayoutKind.Sequential)]
26
+ struct ExtendedLimits {
27
+ public BasicLimits Basic;
28
+ public ulong ReadOperations, WriteOperations, OtherOperations;
29
+ public ulong ReadBytes, WriteBytes, OtherBytes;
30
+ public UIntPtr ProcessMemory, JobMemory, PeakProcessMemory, PeakJobMemory;
31
+ }
32
+ [StructLayout(LayoutKind.Sequential)]
33
+ struct Accounting {
34
+ public long TotalUserTime, TotalKernelTime, PeriodUserTime, PeriodKernelTime;
35
+ public uint PageFaults, TotalProcesses, ActiveProcesses, TerminatedProcesses;
36
+ }
37
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
38
+ static extern IntPtr CreateJobObject(IntPtr attributes, string name);
39
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
40
+ static extern IntPtr OpenJobObject(uint access, bool inherit, string name);
41
+ [DllImport("kernel32.dll", SetLastError = true)]
42
+ static extern bool SetInformationJobObject(IntPtr job, int type, ref ExtendedLimits value, uint size);
43
+ [DllImport("kernel32.dll", SetLastError = true)]
44
+ static extern bool QueryInformationJobObject(IntPtr job, int type, out Accounting value, uint size, IntPtr returned);
45
+ [DllImport("kernel32.dll", SetLastError = true)]
46
+ static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
47
+ [DllImport("kernel32.dll", SetLastError = true)]
48
+ static extern bool DuplicateHandle(IntPtr sourceProcess, IntPtr source, IntPtr targetProcess, out IntPtr target, uint access, bool inherit, uint options);
49
+ [DllImport("kernel32.dll", SetLastError = true)]
50
+ static extern bool TerminateJobObject(IntPtr job, uint exitCode);
51
+ [DllImport("kernel32.dll")]
52
+ static extern IntPtr GetCurrentProcess();
53
+ [DllImport("kernel32.dll")]
54
+ static extern bool CloseHandle(IntPtr handle);
55
+
56
+ public static void Attach(string name, IntPtr process) {
57
+ IntPtr job = CreateJobObject(IntPtr.Zero, name);
58
+ int error = Marshal.GetLastWin32Error();
59
+ if (job == IntPtr.Zero) throw new Win32Exception(error);
60
+ try {
61
+ if (error == 183) throw new Win32Exception(error); // ERROR_ALREADY_EXISTS
62
+ ExtendedLimits limits = new ExtendedLimits();
63
+ limits.Basic.Flags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; no breakaway
64
+ if (!SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf(limits))) throw new Win32Exception();
65
+ if (!AssignProcessToJobObject(job, process)) throw new Win32Exception();
66
+ IntPtr ownedHandle;
67
+ if (!DuplicateHandle(GetCurrentProcess(), job, process, out ownedHandle, 0, false, 2)) throw new Win32Exception();
68
+ } finally { CloseHandle(job); }
69
+ }
70
+
71
+ public static void Stop(string name) {
72
+ IntPtr job = OpenJobObject(0x000C, false, name); // JOB_OBJECT_QUERY | JOB_OBJECT_TERMINATE
73
+ if (job == IntPtr.Zero) {
74
+ int error = Marshal.GetLastWin32Error();
75
+ // Once the last handle is closed, the kernel destroys the job
76
+ // only after every member has terminated.
77
+ if (error == 2) return; // ERROR_FILE_NOT_FOUND
78
+ throw new Win32Exception(error);
79
+ }
80
+ try {
81
+ if (Active(job) == 0) return;
82
+ if (!TerminateJobObject(job, 1)) {
83
+ int error = Marshal.GetLastWin32Error();
84
+ if (Active(job) != 0) throw new Win32Exception(error);
85
+ return;
86
+ }
87
+ Stopwatch timer = Stopwatch.StartNew();
88
+ while (true) {
89
+ if (Active(job) == 0) return;
90
+ if (timer.ElapsedMilliseconds >= 3000) throw new TimeoutException("TexLite job still has active processes");
91
+ Thread.Sleep(30);
92
+ }
93
+ } finally { CloseHandle(job); }
94
+ }
95
+
96
+ static uint Active(IntPtr job) {
97
+ Accounting value;
98
+ if (!QueryInformationJobObject(job, 1, out value, (uint)Marshal.SizeOf(typeof(Accounting)), IntPtr.Zero)) throw new Win32Exception();
99
+ return value.ActiveProcesses;
100
+ }
101
+ }
102
+ `;
103
+ function jobName(executionId, kind) {
104
+ if (!/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(executionId))
105
+ throw new Error("Invalid execution ID");
106
+ // Use the same namespace across login sessions when the server restarts.
107
+ return `Global\\TexLite.${kind}.${executionId}`;
108
+ }
109
+ async function powershell(body) {
110
+ const command = `$ErrorActionPreference = 'Stop'\nAdd-Type -TypeDefinition @'\n${native}\n'@\n${body}`;
111
+ const executable = path.win32.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
112
+ try {
113
+ await run(executable, ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(command, "utf16le").toString("base64")], { timeout: 10_000, windowsHide: true, maxBuffer: 32 * 1024 });
114
+ }
115
+ catch (error) {
116
+ const stderr = error?.stderr?.trim();
117
+ throw new Error(stderr ? `Windows job: ${stderr.slice(0, 512)}` : "Could not manage the Windows job", { cause: error });
118
+ }
119
+ }
120
+ /** Attach before issuing the launch permit, so all CLI descendants inherit the job. */
121
+ export async function attachWindowsJob(pid, executionId, kind) {
122
+ if (!Number.isSafeInteger(pid) || pid <= 0)
123
+ throw new Error("Invalid Windows launcher PID");
124
+ const name = jobName(executionId, kind);
125
+ await powershell(`
126
+ $launcher = Get-Process -Id ${pid} -ErrorAction Stop
127
+ try {
128
+ $handle = $launcher.Handle
129
+ $entry = Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}' -ErrorAction Stop
130
+ if (-not $entry.CommandLine -or -not $entry.CommandLine.Contains('${executionId}') -or $launcher.HasExited) {
131
+ throw 'The launcher identity changed before job assignment'
132
+ }
133
+ [TexLiteJob]::Attach('${name}', $handle)
134
+ } finally { $launcher.Dispose() }
135
+ `);
136
+ }
137
+ export function stopWindowsJob(executionId, kind) {
138
+ return powershell(`[TexLiteJob]::Stop('${jobName(executionId, kind)}')`);
139
+ }
140
+ export const attachWindowsAgentJob = (pid, id) => attachWindowsJob(pid, id, "Agent");
141
+ export const stopWindowsAgentJob = (id) => stopWindowsJob(id, "Agent");
@@ -9,10 +9,11 @@ import websocket from "@fastify/websocket";
9
9
  import { pruneExpiredSessions } from "./db.js";
10
10
  import { digestToken, LoginRateLimiter } from "./security.js";
11
11
  import { currentUser } from "./auth.js";
12
- import { pruneTrashDirectory } from "./files.js";
12
+ import { pruneTrashDirectory, removeProjectDirectory } from "./files.js";
13
13
  import { CompileQueue, ProjectCompileCoordinator, listPublishedCompileArtifacts, pruneOrphanedCompileRuns, reconcilePublishedCompileRuns } from "./compiler.js";
14
14
  import { CollaborationService } from "./collaboration.js";
15
15
  import { ProjectMutationCoordinator } from "./projectMutations.js";
16
+ import { ProjectDeletionCleanup } from "./projectDeletionCleanup.js";
16
17
  import { ProjectGitService } from "./git.js";
17
18
  import { LatexCompletionService } from "./latexCompletion.js";
18
19
  import { ProjectHistoryService } from "./history.js";
@@ -32,6 +33,7 @@ import { registerCommentRoutes } from "./routes/comments.js";
32
33
  import { registerProjectMemberRoutes } from "./routes/projectMembers.js";
33
34
  import { registerProjectViewLinkRoutes } from "./routes/projectViewLinks.js";
34
35
  import { registerProjectFileRoutes } from "./routes/projectFiles.js";
36
+ import { registerDrawioRoutes } from "./routes/drawio.js";
35
37
  import { registerProjectSearchRoutes } from "./routes/projectSearch.js";
36
38
  import { registerProjectReferenceRoutes } from "./routes/projectReferences.js";
37
39
  import { registerProjectHistoryRoutes } from "./routes/projectHistory.js";
@@ -86,10 +88,16 @@ export async function buildApp(config, db, options = {}) {
86
88
  app.addHook("onClose", async () => { await updates.dispose(); });
87
89
  const queue = new CompileQueue(config.maxCompileJobs);
88
90
  const compileCoordinator = new ProjectCompileCoordinator(queue);
91
+ // Windows PM2 uses a bounded IPC shutdown. Do not change when a POSIX
92
+ // instance drains in-flight compile requests.
93
+ if (process.platform === "win32")
94
+ app.addHook("preClose", async () => { await compileCoordinator.close(); });
89
95
  const metrics = new MetricRegistry(200);
90
96
  const eventLoopDelay = monitorEventLoopDelay({ resolution: EVENT_LOOP_DELAY_RESOLUTION_MS });
91
97
  eventLoopDelay.enable();
92
- const history = new ProjectHistoryService(config, db);
98
+ const history = new ProjectHistoryService(config, db, (error, directory) => {
99
+ app.log.warn({ err: error, directory }, "Could not clean up a snapshot restore directory");
100
+ });
93
101
  const editHistory = new ProjectEditHistoryService(db, config.editHistoryMaxStorageBytes, config.editHistoryMaxSegments);
94
102
  const historyRetention = new HistoryRetentionScheduler(history, {
95
103
  onError: (error, projectId) => app.log.error({ err: error, projectId }, "Failed to enforce project history retention")
@@ -151,6 +159,14 @@ export async function buildApp(config, db, options = {}) {
151
159
  metrics.record("collaboration.persist", durationMs + performance.now() - started);
152
160
  });
153
161
  const projectMutations = new ProjectMutationCoordinator(collaboration);
162
+ const projectDeletionCleanup = new ProjectDeletionCleanup(db, (id) => projectMutations.runExclusive(id, "admin user deletion cleanup", () => {
163
+ collaboration.resetProject(id);
164
+ latexCompletions.invalidate(id);
165
+ projectOutlines.invalidate(id);
166
+ removeProjectDirectory(config, id);
167
+ }, { flush: false }), (err, projectId) => app.log.warn({ err, projectId }, "Pending project directory cleanup will be retried"));
168
+ app.addHook("onListen", async () => { projectDeletionCleanup.start(); });
169
+ app.addHook("preClose", async () => { projectMutations.drawioLocks.close(); });
154
170
  const agents = new AgentService({ config, db, collaboration, projectMutations, recordHistory,
155
171
  recordEdits: (id, edits) => editRetry.save(id, edits)
156
172
  }, { onError: (error) => app.log.error({ err: error }, "External agent operation failed"), ...options.agents });
@@ -207,11 +223,13 @@ export async function buildApp(config, db, options = {}) {
207
223
  // instance lock is held. Finish cleanup before accepting requests so a
208
224
  // freshly started server never races a stale trash/tmp removal.
209
225
  await pruneTrashDirectory(config);
226
+ await projectDeletionCleanup.retryPending();
210
227
  for (const row of db.prepare("SELECT id FROM projects").all()) {
228
+ history.pruneRestoreBackups(row.id);
211
229
  history.enforceRetention(row.id);
212
230
  editHistory.enforceRetention(row.id);
213
231
  pruneCompileRuns(row.id);
214
- pruneOrphanedCompileRuns(config, row.id);
232
+ pruneOrphanedCompileRuns(config, row.id, (err, directory) => app.log.warn({ err, directory }, "Could not remove a retired compile run"));
215
233
  }
216
234
  app.addHook("onClose", async () => {
217
235
  eventLoopDelay.disable();
@@ -271,6 +289,7 @@ export async function buildApp(config, db, options = {}) {
271
289
  // Fastify runs close hooks in reverse registration order. Drain external
272
290
  // writers while Yjs rooms and history retry/retention services still exist.
273
291
  app.addHook("onClose", async () => { await agents.dispose(); });
292
+ app.addHook("onClose", async () => { await projectDeletionCleanup.close(); });
274
293
  const indexPath = path.join(config.clientDir, "index.html");
275
294
  const renderedIndex = fs.existsSync(indexPath)
276
295
  ? renderClientIndex(fs.readFileSync(indexPath, "utf8"), config.basePath)
@@ -311,12 +330,10 @@ export async function buildApp(config, db, options = {}) {
311
330
  registerAvatarRoutes(routes, { db, collaboration });
312
331
  registerCitationRoutes(routes, { db });
313
332
  registerUserManagementRoutes(routes, {
314
- config,
315
333
  db,
316
334
  collaboration,
317
335
  projectMutations,
318
- latexCompletions,
319
- projectOutlines
336
+ projectDeletionCleanup
320
337
  });
321
338
  registerCommentRoutes(routes, { config, db, collaboration, projectMutations });
322
339
  registerProjectMemberRoutes(routes, { db, collaboration, projectMutations });
@@ -332,6 +349,7 @@ export async function buildApp(config, db, options = {}) {
332
349
  recordHistory
333
350
  });
334
351
  registerProjectSearchRoutes(routes, { config, db, projectMutations, collaboration });
352
+ registerDrawioRoutes(routes, { config, db, collaboration, projectMutations, recordHistory });
335
353
  registerProjectReferenceRoutes(routes, { config, db, projectMutations });
336
354
  registerProjectHistoryRoutes(routes, { config, db, history, editHistory, projectMutations, recordHistory,
337
355
  clearPendingEdits: (id) => { editRetry.clear(id); failedEdits.delete(id); signalHistory(id); },
@@ -14,8 +14,9 @@ export function publicUser(user) {
14
14
  };
15
15
  }
16
16
  const requestUserCache = new WeakMap();
17
- export function currentUser(request, db) {
18
- if (requestUserCache.has(request)) {
17
+ /** Refresh after a long operation when authorization may have changed meanwhile. */
18
+ export function currentUser(request, db, refresh = false) {
19
+ if (!refresh && requestUserCache.has(request)) {
19
20
  return requestUserCache.get(request) ?? null;
20
21
  }
21
22
  const token = request.cookies.texlite_session;
@@ -0,0 +1,15 @@
1
+ /** Cookie-authenticated WebSockets must originate from this deployment. */
2
+ export function browserOriginAllowed(request) {
3
+ const origin = request.headers.origin;
4
+ if (!origin)
5
+ return false;
6
+ try {
7
+ const parsed = new URL(origin);
8
+ const forwarded = request.headers["x-forwarded-proto"];
9
+ const protocol = forwarded === "https" || forwarded === "http" ? forwarded : request.protocol;
10
+ return parsed.host === request.headers.host && parsed.protocol === `${protocol}:` && parsed.origin === origin;
11
+ }
12
+ catch {
13
+ return false;
14
+ }
15
+ }
@@ -1,6 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
- import { detachedProcessGroup, killProcessGroup } from "./processTree.js";
3
+ import { afterProcessStop, detachedProcessGroup, stopProcessTree } from "./processTree.js";
4
4
  const commandProbeTimeoutMs = 5_000;
5
5
  const checkTimeoutMs = 5_000;
6
6
  const maxOutputBytes = 2 * 1024 * 1024;
@@ -151,8 +151,12 @@ export class ChktexService {
151
151
  }
152
152
  this.waitingByLane.clear();
153
153
  this.latestSequenceByLane.clear();
154
- for (const child of this.activeChildren)
155
- killProcessGroup(child, "SIGTERM");
154
+ const children = [...this.activeChildren];
155
+ if (process.platform === "win32")
156
+ await Promise.allSettled(children.map((child) => stopProcessTree(child)));
157
+ else
158
+ for (const child of children)
159
+ void stopProcessTree(child, "SIGTERM");
156
160
  await Promise.allSettled([...this.activeOperations]);
157
161
  await this.probePromise?.catch(() => undefined);
158
162
  this.inFlight.clear();
@@ -331,6 +335,7 @@ export class ChktexService {
331
335
  let outputBytes = 0;
332
336
  let settled = false;
333
337
  let timedOut = false;
338
+ let terminationError;
334
339
  const finish = (callback) => {
335
340
  if (settled)
336
341
  return;
@@ -340,12 +345,14 @@ export class ChktexService {
340
345
  callback();
341
346
  };
342
347
  const terminate = (error) => {
343
- killProcessGroup(child);
344
- finish(() => reject(error));
348
+ if (terminationError || settled)
349
+ return;
350
+ terminationError = error;
351
+ void stopProcessTree(child).then(() => finish(() => reject(error)), (failure) => finish(() => reject(failure)));
345
352
  };
346
353
  const timer = setTimeout(() => {
347
354
  timedOut = true;
348
- killProcessGroup(child);
355
+ void stopProcessTree(child).catch((error) => finish(() => reject(error)));
349
356
  }, timeoutMs);
350
357
  const collect = (target) => (chunk) => {
351
358
  outputBytes += chunk.length;
@@ -365,11 +372,16 @@ export class ChktexService {
365
372
  return reject(new ChktexUnavailableError(`The optional ${this.command} command is not available.`));
366
373
  reject(error);
367
374
  }));
368
- child.once("close", (code) => finish(() => {
369
- if (timedOut)
370
- return reject(new Error(`${this.command} timed out after ${Math.ceil(timeoutMs / 1000)} seconds.`));
371
- resolve({ code, stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8") });
372
- }));
375
+ child.once("close", (code) => {
376
+ clearTimeout(timer);
377
+ afterProcessStop(child, () => finish(() => {
378
+ if (terminationError)
379
+ return reject(terminationError);
380
+ if (timedOut)
381
+ return reject(new Error(`${this.command} timed out after ${Math.ceil(timeoutMs / 1000)} seconds.`));
382
+ resolve({ code, stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8") });
383
+ }), (error) => finish(() => reject(error)));
384
+ });
373
385
  child.stdin?.end(input);
374
386
  });
375
387
  }
@@ -16,6 +16,7 @@ import { finishSuggestionApplications, hasPendingSuggestionApplication, prepareS
16
16
  import { httpError, SourceFlushError } from "./http.js";
17
17
  import { createEditHistorySpan, hashText } from "./editHistory.js";
18
18
  import { isEditableTextFile, isTextContent, MAX_TEXT_EDITOR_BYTES } from "../shared/fileTypes.js";
19
+ import { isDrawioFile } from "../shared/drawio.js";
19
20
  import { COLLABORATION_PROTOCOL_VERSION, CollaborationMessageType, isCollaborationCleanMode, isCollaborationCompileStatus } from "../shared/collaborationProtocol.js";
20
21
  export { COLLABORATION_PROTOCOL_VERSION } from "../shared/collaborationProtocol.js";
21
22
  const { Sync: MESSAGE_SYNC, Awareness: MESSAGE_AWARENESS, QueryAwareness: MESSAGE_QUERY_AWARENESS, Flush: MESSAGE_FLUSH, Protocol: MESSAGE_PROTOCOL, Maintenance: MESSAGE_MAINTENANCE, Permission: MESSAGE_PERMISSION, CompileStates: MESSAGE_COMPILE_STATES, FormatLease: MESSAGE_FORMAT_LEASE } = CollaborationMessageType;
@@ -1802,7 +1803,7 @@ export function maxCollaborativeFileBytes(config) {
1802
1803
  return Math.min(config.maxUploadBytes, MAX_COLLABORATIVE_FILE_BYTES);
1803
1804
  }
1804
1805
  export function isCollaborativeTextFile(filePath) {
1805
- return isEditableTextFile(filePath);
1806
+ return isEditableTextFile(filePath) && !isDrawioFile(filePath);
1806
1807
  }
1807
1808
  function collaborativeEntrySignature(entry) {
1808
1809
  return `${entry.path}\0${entry.size ?? 0}\0${entry.mtimeMs ?? 0}`;
@@ -8,7 +8,7 @@
8
8
  * still retained separately for users who need all details.
9
9
  */
10
10
  const commandPattern = /\b(pdflatex|xelatex|lualatex|bibtex|biber)\b/i;
11
- const locationPattern = /^(?<file>[^:\n]+):(?<line>\d+)(?::(?<column>\d+))?:\s*(?<rest>.*)$/;
11
+ const locationPattern = /^(?<file>(?:[A-Za-z]:[\\/])?[^:\r\n]+):(?<line>\d+)(?::(?<column>\d+))?:\s*(?<rest>.*)$/;
12
12
  const inputLinePattern = /\bon input line (?<line>\d+)\b/i;
13
13
  const latexLinePattern = /^l\.(?<line>\d+)\b/;
14
14
  export function parseCompileDiagnostics(log, outcome = null) {
@@ -38,15 +38,18 @@ export function parseCompileDiagnostics(log, outcome = null) {
38
38
  phase = "latexmk";
39
39
  const located = parseLocatedLine(line);
40
40
  if (located) {
41
- currentFile = located.file ?? currentFile;
42
- const severity = located.severity;
41
+ currentFile = located.file;
42
+ // With -file-line-error, TeX errors such as "Undefined control sequence."
43
+ // have a location but no Error: prefix. Infer severity only on a failed pass.
44
+ const severity = located.severity ?? (resolvedOutcome === "failed" && isLatexPhase(phase) && /\.[a-z0-9]+$/i.test(located.file) && located.message
45
+ ? "error" : undefined);
43
46
  if (severity) {
44
47
  addDiagnostic(diagnostics, {
45
48
  severity,
46
49
  phase,
47
50
  message: located.message,
48
51
  raw: line,
49
- file: located.file ?? currentFile,
52
+ file: located.file,
50
53
  line: located.line,
51
54
  column: located.column,
52
55
  latexPass: isLatexPhase(phase) ? latexPass : undefined
@@ -149,15 +152,16 @@ function parseLocatedLine(line) {
149
152
  if (!match?.groups)
150
153
  return null;
151
154
  const rest = match.groups.rest;
152
- const marker = rest.match(/\b(?:LaTeX(?:\s+[^:]+)?|Package|Class|pdfTeX|XeTeX|LuaTeX)\s+(?<severity>Error|Warning):\s*(?<message>.*)$/i);
153
- if (!marker?.groups)
154
- return { file: match.groups.file, line: Number(match.groups.line), column: match.groups.column ? Number(match.groups.column) : undefined, message: rest };
155
+ const marker = rest.match(/^(?<severity>Error|Warning):\s*(?<message>.*)$/i)?.groups
156
+ ?? rest.match(/\b(?:LaTeX(?:\s+[^:]+)?|Package|Class|pdfTeX|XeTeX|LuaTeX)\s+(?<severity>Error|Warning):\s*(?<message>.*)$/i)?.groups;
157
+ const diagnostic = marker
158
+ ? { severity: marker.severity.toLowerCase(), message: marker.message.trim() }
159
+ : parseGenericWarning(rest) ?? { message: rest };
155
160
  return {
156
161
  file: match.groups.file.replaceAll("\\", "/"),
157
162
  line: Number(match.groups.line),
158
163
  column: match.groups.column ? Number(match.groups.column) : undefined,
159
- severity: marker.groups.severity.toLowerCase(),
160
- message: marker.groups.message.trim()
164
+ ...diagnostic
161
165
  };
162
166
  }
163
167
  function parsePackageLine(line) {