sync_diagnostics.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. """Synchronous diagnostics requests, for servers that answer "what is wrong with this file now" directly.
  2. typescript-language-server publishes diagnostics asynchronously and stays silent when a file's
  3. diagnostics are unchanged, so waiting for a push costs the push latency (hundreds of ms after an edit)
  4. or the whole wait budget (a clean edit never publishes). It also forwards raw tsserver requests through
  5. ``workspace/executeCommand typescript.tsserverRequest``: ``syntacticDiagnosticsSync`` +
  6. ``semanticDiagnosticsSync`` answer for the text last synced, in about 10ms on a warm project. The edit
  7. check (``agent.lsp.edit_check``) asks this module first and falls back to the push/pull wait when the
  8. server has no synchronous request or the request fails.
  9. Returned diagnostics use the shape typescript-language-server pushes (0-based range, numeric severity,
  10. ``source`` "typescript"), so a sync verdict and a pushed baseline compare equal by
  11. ``agent.lsp.client._diagnostic_key``.
  12. """
  13. from __future__ import annotations
  14. import logging
  15. from typing import Any, Optional
  16. from agent.lsp.protocol import LSPProtocolError, LSPRequestError
  17. logger = logging.getLogger("agent.lsp.sync_diagnostics")
  18. # tsserver category -> LSP DiagnosticSeverity, as typescript-language-server maps it.
  19. _TS_SEVERITY = {"error": 1, "warning": 2, "message": 3, "suggestion": 4}
  20. _TS_SERVERS = frozenset({"typescript"})
  21. _TS_COMMANDS = ("syntacticDiagnosticsSync", "semanticDiagnosticsSync")
  22. _UNSUPPORTED = "_hermes_sync_diagnostics_unsupported"
  23. def supported(client: Any) -> bool:
  24. return client.server_id in _TS_SERVERS and not getattr(client, _UNSUPPORTED, False)
  25. async def request(client: Any, abs_path: str, *, timeout: float) -> Optional[list[dict[str, Any]]]:
  26. """Diagnostics for the text last synced to ``client`` for ``abs_path``, or None when the server has
  27. no synchronous request (it failed): wait for a push then. Raises ``TimeoutError`` when the server
  28. did not answer within ``timeout`` (a cold project still loading): there is no verdict in budget,
  29. and a push wait after it would only hold the next check of the file longer."""
  30. if not supported(client) or timeout <= 0:
  31. return None
  32. out: list[dict[str, Any]] = []
  33. for command in _TS_COMMANDS:
  34. try:
  35. reply = await client._send_request_with_retry("workspace/executeCommand", {
  36. "command": "typescript.tsserverRequest",
  37. "arguments": [command, {"file": abs_path, "includeLinePosition": True}, {"executionTarget": 0}],
  38. }, timeout=timeout)
  39. except TimeoutError:
  40. raise TimeoutError(f"{command} did not answer in {timeout:.1f}s") from None
  41. except LSPRequestError as e: # the server rejects the command: use the push wait from now on
  42. logger.debug("[%s] %s rejected: %s", client.server_id, command, e)
  43. setattr(client, _UNSUPPORTED, True)
  44. return None
  45. except LSPProtocolError as e: # connection trouble: the push wait reports it
  46. logger.debug("[%s] %s failed: %s", client.server_id, command, e)
  47. return None
  48. body = reply.get("body") if isinstance(reply, dict) and reply.get("success", True) else None
  49. if not isinstance(body, list):
  50. setattr(client, _UNSUPPORTED, True)
  51. return None
  52. out.extend(d for d in (_from_tsserver(item) for item in body) if d is not None)
  53. return out
  54. def _from_tsserver(item: Any) -> Optional[dict[str, Any]]:
  55. if not isinstance(item, dict):
  56. return None
  57. start, end = item.get("startLocation"), item.get("endLocation")
  58. if not isinstance(start, dict) or not isinstance(end, dict):
  59. return None
  60. diag: dict[str, Any] = {
  61. "range": {"start": {"line": start.get("line", 1) - 1, "character": start.get("offset", 1) - 1},
  62. "end": {"line": end.get("line", 1) - 1, "character": end.get("offset", 1) - 1}},
  63. "message": str(item.get("message") or ""),
  64. "severity": _TS_SEVERITY.get(str(item.get("category") or "error"), 1),
  65. "source": item.get("source") or "typescript",
  66. }
  67. if item.get("code") is not None:
  68. diag["code"] = item["code"]
  69. return diag
  70. __all__ = ["request", "supported"]