From af11e0f2d3b6a554a2bca1f1f1931debd8444cbf Mon Sep 17 00:00:00 2001 From: Jer Miller Date: Fri, 6 Mar 2026 10:43:52 -0700 Subject: [PATCH] Fix chat metadata race during agent startup Background chat event handling could look up a new chat before its metadata file had been written, causing a 404 once the agent started emitting events. Save new chat metadata to disk immediately after agent creation using a fallback title, then update it with the generated title if it differs. Also move chat redirect journal setup ahead of cortex_request so the metadata save runs immediately after agent spawn succeeds. --- apps/chat/call.py | 14 +++++++------- apps/chat/routes.py | 8 ++++++-- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/apps/chat/call.py b/apps/chat/call.py index 093e23e76..bd0a0cf7c 100644 --- a/apps/chat/call.py +++ b/apps/chat/call.py @@ -66,6 +66,13 @@ def redirect( title = generate_chat_title(message) + import convey.state + from apps.utils import get_app_storage_path + from convey.utils import save_json + from think.utils import get_journal, now_ms + + convey.state.journal_root = str(get_journal()) + from think.cortex_client import cortex_request config: dict = {} @@ -81,13 +88,6 @@ def redirect( typer.echo("Error: failed to create chat thread", err=True) raise typer.Exit(1) - import convey.state - from apps.utils import get_app_storage_path - from convey.utils import save_json - from think.utils import get_journal, now_ms - - convey.state.journal_root = str(get_journal()) - chat_id = agent_id ts = now_ms() chat_record = { diff --git a/apps/chat/routes.py b/apps/chat/routes.py index 63189768a..040ae8c13 100644 --- a/apps/chat/routes.py +++ b/apps/chat/routes.py @@ -216,17 +216,21 @@ def send_message() -> Any: else: # New chat: create metadata record chat_id = agent_id - title = generate_chat_title(message) + fallback_title = message.split("\n")[0][:30] chat_record = { "ts": ts, "facet": facet, "provider": provider, "muse": "default", - "title": title, + "title": fallback_title, "agent_ids": [agent_id], } chats_dir = get_app_storage_path("chat", "chats") save_json(chats_dir / f"{chat_id}.json", chat_record) + title = generate_chat_title(message) + if title != fallback_title: + chat_record["title"] = title + _save_chat(chat_id, chat_record) return jsonify(chat_id=chat_id, agent_id=agent_id) except Exception as e: -- 2.51.2