Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

test: accept fresh-socket prewarm on chain reanchor; settle portal clicks

Rach12d5402cc7d1
diff --git a/apps/native/electron/composer-interaction-visual.cjs b/apps/native/electron/composer-interaction-visual.cjs
index 52d52058..f7c5fd0d 100644
--- a/apps/native/electron/composer-interaction-visual.cjs
+++ b/apps/native/electron/composer-interaction-visual.cjs
@@ -18,11 +18,24 @@ async function runComposerInteractions({ win, origin, output }) {
await js(`(()=>{const e=document.querySelector(${JSON.stringify(selector)});e.focus();Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(e,${JSON.stringify(text)});e.dispatchEvent(new Event('input',{bubbles:true}));})()`);
await pause();
};
+ const frames = () => js('new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve(true))))');
const pointer = async selector => {
- const point = await js(`(()=>{const e=document.querySelector(${JSON.stringify(selector)});e.scrollIntoView({block:'nearest'});const r=e.getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`);
- wc.sendInputEvent({ type: 'mouseDown', button: 'left', clickCount: 1, ...point });
- wc.sendInputEvent({ type: 'mouseUp', button: 'left', clickCount: 1, ...point });
- await pause();
+ await js(`document.querySelector(${JSON.stringify(selector)}).scrollIntoView({block:'nearest',behavior:'instant'})`);
+ for (let attempt = 0; attempt < 30; attempt++) {
+ await frames();
+ const point = await js(`(()=>{const r=document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`);
+ // Hover can scroll the active option or reposition its portal. Settle it
+ // before pressing, then verify that the coordinates still hit this row.
+ wc.sendInputEvent({ type: 'mouseMove', ...point });
+ await frames();
+ const ready = await js(`(()=>{const e=document.querySelector(${JSON.stringify(selector)}),r=e.getBoundingClientRect();return Math.round(r.x+r.width/2)===${point.x}&&Math.round(r.y+r.height/2)===${point.y}&&e.contains(document.elementFromPoint(${point.x},${point.y}));})()`);
+ if (!ready) continue;
+ wc.sendInputEvent({ type: 'mouseDown', button: 'left', clickCount: 1, ...point });
+ wc.sendInputEvent({ type: 'mouseUp', button: 'left', clickCount: 1, ...point });
+ await pause();
+ return;
+ }
+ throw Error(`Pointer target did not settle: ${selector}`);
};
const draft = id => js(`document.querySelector('[data-chat="${id}"] textarea').value`);
const focused = () => js(`Number(document.querySelector('[data-chat][data-focused="true"]').dataset.chat)`);
@@ -53,6 +66,9 @@ async function runComposerInteractions({ win, origin, output }) {
await pointer('[data-composer-menu] [role="option"][title^="$gui-theme"]');
assert.equal(await js('document.querySelector("textarea").value'), '$gui-theme ', 'A portaled skill selection must reach the composer');
+ // Do not let a stationary pointer hover newly mounted options during IME checks.
+ wc.sendInputEvent({ type: 'mouseMove', x: 1, y: 1 });
+ await frames();
await input('/');
await wait(`document.querySelectorAll('[data-composer-menu] [role="option"]').length>10`);
const firstOption = await js(`document.querySelector('textarea').getAttribute('aria-activedescendant')`);
@@ -86,11 +102,17 @@ async function runComposerInteractions({ win, origin, output }) {
await key('2', { metaKey: true });
assert.equal(await draft(second), 'Second unsent draft', 'An older upload must not reset another chat');
assert.equal(await js(`!!document.querySelector('[aria-label="Remove composer-image.png"]')`), false, 'Attachments never move between chats');
- await key('1', { metaKey: true });
-
+ // Delay the first shortcut's focus frame until a newer navigation has won.
+ await js(`(()=>{const raf=window.requestAnimationFrame,frames=[];window.requestAnimationFrame=callback=>{frames.push(callback);return 0;};
+ try{document.activeElement.dispatchEvent(new KeyboardEvent('keydown',{key:'1',metaKey:true,bubbles:true,cancelable:true}));}
+ finally{window.requestAnimationFrame=raf;}window.flushOldFocus=()=>frames.forEach(callback=>callback(performance.now()));})()`);
+ await wait(`document.querySelector('[data-chat][data-focused="true"]')?.dataset.chat==='${first}'`);
await key('d', { metaKey: true });
await wait(`document.querySelectorAll('[data-chat]').length===2`);
const split = await focused();
+ assert.notEqual(split, first, 'A new split becomes active');
+ await js('window.flushOldFocus()');
+ assert.equal(await focused(), split, 'An older shortcut focus frame must not steal the new split');
await input('Keep this split draft');
await pointer(`[data-chat="${first}"] textarea`);
// Use a native key event so an accidental textarea newline is observable.
diff --git a/scripts/codex_ws_error_test.py b/scripts/codex_ws_error_test.py
index d35c82cc..219555fe 100644
--- a/scripts/codex_ws_error_test.py
+++ b/scripts/codex_ws_error_test.py
@@ -188,11 +188,15 @@ def run_chain_reanchor_scenario(
first.connection_id != rejected.connection_id
or rejected.connection_id == rebuilt.connection_id
or rejected.body.get("previous_response_id") != "resp_chain_1"
- or "previous_response_id" in rebuilt.body
+ # A fresh socket may chain only from its observed prewarm,
+ # never from the rejected inference response or another socket.
+ or not mock.has_fresh_parent(rebuilt)
):
raise AssertionError(
"chain-error: rejected delta was not rebuilt as full input on a fresh WS: "
- f"{requests!r}"
+ f"connections={(first.connection_id, rejected.connection_id, rebuilt.connection_id)!r}, "
+ f"rejected_parent={rejected.body.get('previous_response_id')!r}, "
+ f"rebuilt_parent={rebuilt.body.get('previous_response_id')!r}"
)
rebuilt_types = [
item.get("type")
diff --git a/scripts/codex_ws_mock.py b/scripts/codex_ws_mock.py
index 4fbca80a..9bbf6863 100644
--- a/scripts/codex_ws_mock.py
+++ b/scripts/codex_ws_mock.py
@@ -227,11 +227,20 @@ class CodexMock:
default=None, repr=False
)
requests: list[RecordedRequest] = field(default_factory=list, repr=False)
+ prewarm_ids: dict[int, str] = field(default_factory=dict, repr=False)
_sock: socket.socket | None = field(default=None, repr=False)
_threads: list[threading.Thread] = field(default_factory=list, repr=False)
_lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
_stopping: bool = field(default=False, repr=False)
+ def has_fresh_parent(self, request: RecordedRequest) -> bool:
+ """Only no parent or this socket's observed prewarm is a fresh anchor."""
+ parent = request.body.get("previous_response_id")
+ if parent is None:
+ return True
+ with self._lock:
+ return request.transport == "ws" and parent == self.prewarm_ids.get(request.connection_id)
+
def start(self) -> int:
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
@@ -391,6 +400,8 @@ class CodexMock:
# (the transport smoke assertions count real model turns).
if event.get("generate") is False:
prewarm_id = f"resp_prewarm_{self.ws_turns + 1}"
+ with self._lock:
+ self.prewarm_ids[connection_id] = prewarm_id
_send_frame(conn, OP_TEXT, json.dumps(
{"type": "response.completed",
"response": {"id": prewarm_id, "usage": dict(USAGE)}},
diff --git a/scripts/codex_ws_test.py b/scripts/codex_ws_test.py
index 8941846c..68baf7da 100644
--- a/scripts/codex_ws_test.py
+++ b/scripts/codex_ws_test.py
@@ -437,7 +437,7 @@ def assert_midturn_requests(mock: CodexMock) -> None:
if first.connection_id == final.connection_id:
raise AssertionError("midturn: final request reused the pre-compaction WS")
for request in requests:
- if "previous_response_id" in request.body:
+ if not mock.has_fresh_parent(request):
raise AssertionError(
f"midturn: request {request.ordinal} carried stale previous_response_id: "
f"{request.body['previous_response_id']!r}"
@@ -580,7 +580,7 @@ def assert_transactional_requests(mock: CodexMock) -> None:
"transactional: final request reused the pre-compaction WS"
)
for request in requests:
- if "previous_response_id" in request.body:
+ if not mock.has_fresh_parent(request):
raise AssertionError(
f"transactional: request {request.ordinal} carried stale "
f"previous_response_id: {request.body['previous_response_id']!r}"