Skip to content

Agent Zero AI framework

fix(webui): stop stale snapshots after chat switches

Alessandrod1945523afe5
diff --git a/tests/test_webui_chat_deletion.py b/tests/test_webui_chat_deletion.py
index 51ece733d..9492036ca 100644
--- a/tests/test_webui_chat_deletion.py
+++ b/tests/test_webui_chat_deletion.py
@@ -213,3 +213,38 @@ assert(model.selected === "b", "rollback must not override the fallback or a lat
check=True,
text=True,
)
+
+
+def test_snapshot_cannot_reconcile_another_chat_after_an_async_context_switch():
+ if not shutil.which("node"):
+ pytest.skip("Node.js is required for the snapshot race regression.")
+ source = (PROJECT_ROOT / "webui/index.js").read_text(encoding="utf-8")
+ source = source[source.index("export async function applySnapshot("):source.index("export async function poll(")]
+ source = source.replace("export async", "async", 1)
+ import json
+
+ script = f"""
+import assert from 'node:assert/strict';
+import vm from 'node:vm';
+for (const phase of ['extension', 'messages']) {{
+ const sandbox = {{
+ context: 'old', lastLogGuid: '', lastLogVersion: 0,
+ chatsStore: {{ applyContexts() {{ assert.fail('stale sidebar reconciliation'); }} }},
+ tasksStore: {{}},
+ msgs: {{ resetMessageRenderState() {{}} }},
+ modelGateStore: {{ mergeSyntheticMessages: logs => logs }},
+ afterMessagesUpdate() {{ assert.fail('stale message completion'); }},
+ }};
+ sandbox.callJsExtensions = async () => {{ if (phase === 'extension') sandbox.context = 'new'; }};
+ sandbox.setMessages = async () => {{
+ assert.notEqual(phase, 'extension', 'stale snapshot reached message rendering');
+ sandbox.context = 'new';
+ }};
+ vm.createContext(sandbox);
+ vm.runInContext({json.dumps(source)}, sandbox);
+ const result = await sandbox.applySnapshot({{context:'old', contexts:[], tasks:[], logs:[], log_version:1, log_guid:'guid'}});
+ assert.equal(result.updated, false);
+ assert.equal(sandbox.context, 'new');
+}}
+"""
+ subprocess.run(["node", "--input-type=module", "-e", script], check=True, capture_output=True, text=True)
diff --git a/webui/AGENTS.md b/webui/AGENTS.md
index 520f8b8b7..c4261d26b 100644
--- a/webui/AGENTS.md
+++ b/webui/AGENTS.md
@@ -27,6 +27,7 @@
- `js/icons.js` owns the native `<x-icon>` element. First-party WebUI and bundled-plugin markup must use `<x-icon name="lowercase_snake_case"></x-icon>` for static Material Symbols and `:name="expression"` for Alpine-driven names; do not put ligature text inside the element or author new `.material-symbols-outlined` spans. The element uses the single local WOFF2 font rather than per-icon SVG requests, validates names, defaults unlabeled icons to `aria-hidden="true"`, and retains the legacy Material class internally so established selectors continue to apply. The shared vendor CSS constrains both `<x-icon>` and legacy ligature spans to a clipped 1:1 em square and keeps them transparent until the icon face is confirmed after the installed application document finishes parsing. `.material-symbols-outlined` and `.material-icons-outlined` spans remain supported for third-party plugin compatibility but are not the first-party authoring API.
- Component HTML loaded by the shared loader may include `<title>`, module scripts, body content, and scoped styles; modal content uses the same loader path.
- Do not bypass WebSocket origin/auth/CSRF assumptions from frontend code.
+- `index.js` rechecks the selected context after asynchronous snapshot hooks and message rendering; an older snapshot must not replace selection or sidebar state after a chat switch or creation.
- Avoid editing vendored files unless intentionally updating the vendor asset.
- Startup scripts in `index.html` must be local and non-parser-blocking: use ES modules, `defer`, or `async` for every script with `src`.
- Baseline main and login pages must load scripts, styles, fonts, and images from same-origin vendored or first-party assets so they remain usable without internet access.
diff --git a/webui/index.js b/webui/index.js
index 681a561e5..8f23ad6e9 100644
--- a/webui/index.js
+++ b/webui/index.js
@@ -391,8 +391,9 @@ export async function applySnapshot(snapshot, options = {}) {
willUpdateMessages: lastLogVersion != snapshot.log_version,
skip: false,
};
+ const applyingContext = context;
await callJsExtensions("apply_snapshot_before", snapCtx);
- if (snapCtx.skip) return { updated: false };
+ if (snapCtx.skip || context !== applyingContext) return { updated: false };
// If the chat has been reset, reset cursors and request a resync from the caller.
// Note: on first snapshot after a context switch, lastLogGuid is intentionally empty,
@@ -418,6 +419,7 @@ export async function applySnapshot(snapshot, options = {}) {
msgs.resetMessageRenderState();
}
await setMessages(modelGateStore.mergeSyntheticMessages(snapshot.logs, context));
+ if (context !== applyingContext) return { updated: false };
afterMessagesUpdate(snapshot.logs);
}