Skip to content

The agent that grows with you

fix(lsp): use UTF-16 units for document replacement ranges

liuzikaiid23d6e821876
diff --git a/agent/lsp/client.py b/agent/lsp/client.py
index c6072955777..a286160d74a 100644
--- a/agent/lsp/client.py
+++ b/agent/lsp/client.py
@@ -99,7 +99,8 @@ def _end_position(text: str) -> Dict[str, int]:
# splitlines drops a trailing newline: the end is then the start of the next (empty) line.
if text.endswith(("\n", "\r")):
return {"line": len(lines), "character": 0}
- return {"line": len(lines) - 1, "character": len(lines[-1])}
+ # Positions use UTF-16 code units, matching our advertised positionEncodings.
+ return {"line": len(lines) - 1, "character": len(lines[-1].encode("utf-16-le")) // 2}
@dataclass
diff --git a/tests/agent/lsp/_mock_lsp_server.py b/tests/agent/lsp/_mock_lsp_server.py
index 5dbd41202bf..15d468d2fa7 100644
--- a/tests/agent/lsp/_mock_lsp_server.py
+++ b/tests/agent/lsp/_mock_lsp_server.py
@@ -29,6 +29,8 @@ Behaviour (all behaviours selectable via env var ``MOCK_LSP_SCRIPT``):
no ``version`` field in any publishDiagnostics (the client credits
each push with its current document version at receipt). Push-only:
the pull endpoint rejects.
+- ``"incremental"`` — apply ranged edits as UTF-16 and expose the server's
+ document mirror through hover, for synchronization contract tests.
- ``"clean_eof"`` — closes stdout after ``didOpen`` but keeps the
process and stdin alive.
- ``"malformed_frame"`` — writes an invalid frame after ``didOpen``,
@@ -72,6 +74,7 @@ def write_message(obj):
def main():
script = os.environ.get("MOCK_LSP_SCRIPT", "clean")
+ documents = {}
while True:
msg = read_message()
@@ -87,7 +90,7 @@ def main():
"id": msg["id"],
"result": {
"capabilities": {
- "textDocumentSync": 1, # Full
+ "textDocumentSync": 2 if script == "incremental" else 1,
"diagnosticProvider": {"interFileDependencies": False, "workspaceDiagnostics": False},
},
"serverInfo": {"name": "mock-lsp", "version": "0.1"},
@@ -121,6 +124,22 @@ def main():
uri = td.get("uri", "")
version = td.get("version", 0)
is_change = msg.get("method") == "textDocument/didChange"
+ if script == "incremental":
+ text = documents.get(uri, "") if is_change else td["text"]
+ for change in params.get("contentChanges", []):
+ if "range" not in change:
+ text = change["text"]
+ continue
+ # Apply the range using the protocol's UTF-16 offsets, as a real server does.
+ lines = text.splitlines(keepends=True)
+ def byte_offset(position):
+ prefix = "".join(lines[:position["line"]])
+ return len(prefix.encode("utf-16-le")) + position["character"] * 2
+ start = byte_offset(change["range"]["start"])
+ end = byte_offset(change["range"]["end"])
+ encoded = text.encode("utf-16-le")
+ text = (encoded[:start] + change["text"].encode("utf-16-le") + encoded[end:]).decode("utf-16-le")
+ documents[uri] = text
if not is_change and script in {"clean_eof", "malformed_frame"}:
if script == "malformed_frame":
sys.stdout.buffer.write(b"Content-Length: invalid\r\n\r\n")
@@ -185,6 +204,13 @@ def main():
write_message({"jsonrpc": "2.0", "method": "textDocument/publishDiagnostics", "params": params})
continue
+ if script == "incremental" and msg.get("method") == "textDocument/hover":
+ uri = msg["params"]["textDocument"]["uri"]
+ write_message({"jsonrpc": "2.0", "id": msg["id"], "result": {
+ "contents": {"kind": "plaintext", "value": documents[uri]},
+ }})
+ continue
+
if msg.get("method") == "textDocument/diagnostic":
if script in {"stale", "slow_push", "versionless", "silent"}:
# These scripts model push-only servers so the ghost
diff --git a/tests/agent/lsp/test_incremental_unicode.py b/tests/agent/lsp/test_incremental_unicode.py
new file mode 100644
index 00000000000..6511756999f
--- /dev/null
+++ b/tests/agent/lsp/test_incremental_unicode.py
@@ -0,0 +1,50 @@
+"""The server's document mirror must match disk after each incremental replacement."""
+
+from __future__ import annotations
+
+import asyncio
+import sys
+from pathlib import Path
+
+import pytest
+
+from agent.lsp.client import LSPClient, file_uri
+
+
+ "original",
+ [
+ 'const face = "😀";',
+ '// header\nconst letter = "𐐀";',
+ 'const word = "中文";',
+ 'const face = "😀";\n',
+ "",
+ ],
+)
+async def test_incremental_replacements_preserve_server_document(tmp_path, original):
+ path = tmp_path / "sample.ts"
+ client = LSPClient(
+ server_id="incremental",
+ workspace_root=str(tmp_path),
+ command=[sys.executable, str(Path(__file__).with_name("_mock_lsp_server.py"))],
+ env={"MOCK_LSP_SCRIPT": "incremental"},
+ )
+ await client.start()
+ try:
+ for text in (original, 'const next = "🚀";', "const done = true;"):
+ path.write_text(text, encoding="utf-8")
+ await client.open_file(str(path), language_id="typescript")
+ hover = await asyncio.wait_for(
+ client._send_request(
+ "textDocument/hover",
+ {
+ "textDocument": {"uri": file_uri(str(path))},
+ "position": {"line": 0, "character": 0},
+ },
+ ),
+ timeout=5,
+ )
+ assert hover["contents"]["value"] == path.read_text(encoding="utf-8")
+ finally:
+ await client.shutdown()