From a1856ea73756bb641f82eb50fd1892ea9b4e4833 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Thu, 16 Jul 2026 01:09:35 -0400 Subject: [PATCH] refac --- .../src/lib/components/chat/ChatPanel.svelte | 6 ++- .../lib/components/chat/UserMessage.svelte | 4 +- cptr/models/__init__.py | 12 +++++- cptr/models/chats.py | 37 +++++++++++++++++-- cptr/routers/search.py | 4 +- cptr/utils/async_subagents.py | 7 ++-- cptr/utils/chat_task.py | 36 +++++++++++++----- cptr/utils/timers.py | 9 +++-- cptr/utils/tools.py | 2 +- 9 files changed, 90 insertions(+), 27 deletions(-) diff --git a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte index 780d129..457d1fd 100644 --- a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte +++ b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte @@ -206,7 +206,11 @@ } function isPendingHiddenMessage(m: ChatMessageRow): boolean { - return !!(m.meta?.queued || m.meta?.async_subagent_pending); + return !!( + m.meta?.queued || + m.meta?.async_subagent_pending || + (m.meta?.internal === true && m.meta?.type === 'subagent' && m.meta?.status === 'pending') + ); } function nearestVisibleAncestorId( diff --git a/cptr/frontend/src/lib/components/chat/UserMessage.svelte b/cptr/frontend/src/lib/components/chat/UserMessage.svelte index ce58ac7..82757f2 100644 --- a/cptr/frontend/src/lib/components/chat/UserMessage.svelte +++ b/cptr/frontend/src/lib/components/chat/UserMessage.svelte @@ -56,7 +56,9 @@ let textareaEl: HTMLTextAreaElement; let asyncExpanded = $state(false); let timerExpanded = $state(false); - const isAsyncSubagentResult = $derived(meta?.async_subagent_result === true); + const isAsyncSubagentResult = $derived( + (meta?.internal === true && meta?.type === 'subagent') || meta?.async_subagent_result === true + ); const isTimer = $derived(meta?.internal === true && meta?.type === 'timer'); const delegationId = $derived(meta?.delegation_id || ''); const delegationIds = $derived(Array.isArray(meta?.delegation_ids) ? meta.delegation_ids : []); diff --git a/cptr/models/__init__.py b/cptr/models/__init__.py index b6a0a85..747438b 100644 --- a/cptr/models/__init__.py +++ b/cptr/models/__init__.py @@ -5,7 +5,14 @@ from cptr.models.users import User, Auth, UserStates from cptr.models.workspaces import Workspace from cptr.models.config import Config from cptr.models.files import File -from cptr.models.chats import Chat, ChatMessage, is_internal_chat +from cptr.models.chats import ( + Chat, + ChatMessage, + internal_status, + is_internal_chat, + is_pending_subagent_result_message, + is_subagent_result_message, +) from cptr.models.automations import Automation, AutomationRun __all__ = [ @@ -18,7 +25,10 @@ __all__ = [ "File", "Chat", "ChatMessage", + "internal_status", "is_internal_chat", + "is_pending_subagent_result_message", + "is_subagent_result_message", "Automation", "AutomationRun", ] diff --git a/cptr/models/chats.py b/cptr/models/chats.py index 2b9b3f2..59c2d04 100644 --- a/cptr/models/chats.py +++ b/cptr/models/chats.py @@ -30,7 +30,36 @@ def _uuid() -> str: def is_internal_chat(meta: dict | None) -> bool: """Whether a chat is harness-owned and should stay out of normal chat surfaces.""" meta = meta or {} - return bool(meta.get("internal") or meta.get("subagent")) + return bool(meta.get("internal") is True or meta.get("subagent") is True) + + +def internal_status(meta: dict | None) -> str | None: + """Canonical internal lifecycle status, with legacy timer fallback.""" + meta = meta or {} + return meta.get("status") or meta.get("timer_status") + + +def is_subagent_result_message(meta: dict | None) -> bool: + """Whether a parent-chat message carries a subagent result.""" + meta = meta or {} + return bool( + (meta.get("internal") is True and meta.get("type") == "subagent") + or meta.get("async_subagent_result") + or meta.get("async_subagent_pending") + ) + + +def is_pending_subagent_result_message(meta: dict | None) -> bool: + """Whether a subagent result is queued behind active parent work.""" + meta = meta or {} + return bool( + ( + meta.get("internal") is True + and meta.get("type") == "subagent" + and meta.get("status") == "pending" + ) + or meta.get("async_subagent_pending") + ) class Chat(Base): @@ -75,7 +104,7 @@ class Chat(Base): for chat in result.scalars().all() if (chat.meta or {}).get("internal") is True and (chat.meta or {}).get("type") == "timer" - and (chat.meta or {}).get("timer_status") == "pending" + and internal_status(chat.meta) == "pending" and int((chat.meta or {}).get("timer_at") or 0) <= now_ns ] timers.sort(key=lambda chat: int((chat.meta or {}).get("timer_at") or 0)) @@ -92,7 +121,7 @@ class Chat(Base): if (chat.meta or {}).get("internal") is True and (chat.meta or {}).get("type") == "timer" and (chat.meta or {}).get("parent_chat_id") == parent_chat_id - and (chat.meta or {}).get("timer_status") == "pending" + and internal_status(chat.meta) == "pending" ] @staticmethod @@ -105,7 +134,7 @@ class Chat(Base): for chat in result.scalars().all() if (chat.meta or {}).get("internal") is True and (chat.meta or {}).get("type") == "timer" - and (status is None or (chat.meta or {}).get("timer_status") == status) + and (status is None or internal_status(chat.meta) == status) ] @staticmethod diff --git a/cptr/routers/search.py b/cptr/routers/search.py index 8b32aa6..a590c50 100644 --- a/cptr/routers/search.py +++ b/cptr/routers/search.py @@ -8,7 +8,7 @@ from typing import List, Optional from fastapi import APIRouter, HTTPException, Query, Request -from cptr.models import Chat +from cptr.models import Chat, is_internal_chat from cptr.routers.workspace import walk_and_rank_files router = APIRouter(prefix="/api/search", tags=["search"]) @@ -123,7 +123,7 @@ async def recent_chats( rows = [ c for c in rows - if not (c.meta or {}).get("subagent") + if not is_internal_chat(c.meta) and (workspace is None or (c.meta or {}).get("workspace") == workspace) ][:limit] diff --git a/cptr/utils/async_subagents.py b/cptr/utils/async_subagents.py index 8af8ed3..3511fe1 100644 --- a/cptr/utils/async_subagents.py +++ b/cptr/utils/async_subagents.py @@ -202,12 +202,13 @@ async def _inject_completion(record: dict[str, Any]) -> None: parent_id = done_assistants[-1].id if done_assistants else record.get("parent_message_id") meta = { - "async_subagent_result": True, + "internal": True, + "type": "timer" if record.get("timer_chat_id") else "subagent", "delegation_id": record.get("delegation_id"), "subagent_chat_id": record.get("subagent_chat_id"), } if active: - meta["async_subagent_pending"] = True + meta["status"] = "pending" if record.get("timer_chat_id") and not active: direct_timer_completion = True @@ -264,7 +265,7 @@ async def _inject_completion(record: dict[str, Any]) -> None: { "chat_id": parent_chat_id, "message_id": user_msg.id, - "async_subagent_pending": True, + "pending_inputs_processed": True, }, ) return diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 78d777a..dea9aa5 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -31,7 +31,14 @@ from cptr.utils.skills import ( load_skill, ) from cptr.utils.summarize import summarize_messages -from cptr.models import Chat, ChatMessage, Config, is_internal_chat +from cptr.models import ( + Chat, + ChatMessage, + Config, + is_internal_chat, + is_pending_subagent_result_message, + is_subagent_result_message, +) from cptr.socket.main import emit_to_user from cptr.utils.ai import ( ChatCompletionForm, @@ -463,11 +470,11 @@ def _memory_recall_inputs( # ── Pending input processing ──────────────────────────────── -def _merge_async_subagent_result_meta(messages: list[ChatMessage]) -> dict | None: +def _merge_subagent_result_meta(messages: list[ChatMessage]) -> dict | None: if not messages: return None - if all((m.meta or {}).get("async_subagent_result") for m in messages): + if all(is_subagent_result_message(m.meta) for m in messages): delegation_ids = [ m.meta.get("delegation_id") for m in messages if m.meta and m.meta.get("delegation_id") ] @@ -476,7 +483,7 @@ def _merge_async_subagent_result_meta(messages: list[ChatMessage]) -> dict | Non for m in messages if m.meta and m.meta.get("subagent_chat_id") ] - meta = {"async_subagent_result": True} + meta = {"internal": True, "type": "subagent"} if len(delegation_ids) == 1: meta["delegation_id"] = delegation_ids[0] elif delegation_ids: @@ -491,18 +498,18 @@ def _merge_async_subagent_result_meta(messages: list[ChatMessage]) -> dict | Non def _is_pending_internal_subagent_result(message: ChatMessage) -> bool: - return bool((message.meta or {}).get("async_subagent_pending")) + return is_pending_subagent_result_message(message.meta) def _is_pending_chat_input(message: ChatMessage) -> bool: meta = message.meta or {} - return bool(meta.get("queued") or meta.get("async_subagent_pending")) + return bool(meta.get("queued") or is_pending_subagent_result_message(meta)) def _merge_pending_input_meta(messages: list[ChatMessage]) -> dict | None: - async_meta = _merge_async_subagent_result_meta(messages) - if async_meta: - return async_meta + subagent_meta = _merge_subagent_result_meta(messages) + if subagent_meta: + return subagent_meta files: list[dict] = [] for message in messages: @@ -2034,7 +2041,16 @@ async def run_chat_task( review_model_name = model review_chat_params = { **chat_params, - "subagent": bool(chat_obj and (chat_obj.meta or {}).get("subagent")), + "subagent": bool( + chat_obj + and ( + (chat_obj.meta or {}).get("subagent") + or ( + (chat_obj.meta or {}).get("internal") is True + and (chat_obj.meta or {}).get("type") == "subagent" + ) + ) + ), } review_builtin_tools = builtin_tools diff --git a/cptr/utils/timers.py b/cptr/utils/timers.py index 165b702..30d7a8b 100644 --- a/cptr/utils/timers.py +++ b/cptr/utils/timers.py @@ -74,7 +74,7 @@ async def cancel_timers_for_event(event) -> None: continue meta.update( { - "timer_status": "cancelled", + "status": "cancelled", "timer_cancelled_at": time.time_ns(), "timer_cancelled_by": event.event, } @@ -90,7 +90,7 @@ async def _set_timer_status(chat_id: str, status: str, **fields) -> None: if not chat: return meta = dict(chat.meta or {}) - meta["timer_status"] = status + meta["status"] = status meta.update(fields) await Chat.update_meta(chat_id, meta, now_ms()) @@ -108,7 +108,8 @@ async def _launch_timer(timer, app) -> None: if not timer: return meta = dict(timer.meta or {}) - if meta.get("timer_status") != "pending" or int(meta.get("timer_at") or 0) > time.time_ns(): + status = meta.get("status") or meta.get("timer_status") + if status != "pending" or int(meta.get("timer_at") or 0) > time.time_ns(): return parent = await Chat.get_by_id(meta.get("parent_chat_id", "")) @@ -165,7 +166,7 @@ async def _launch_timer(timer, app) -> None: meta.update( { - "timer_status": "completed", + "status": "completed", "timer_completed_at": time.time_ns(), } ) diff --git a/cptr/utils/tools.py b/cptr/utils/tools.py index f9a2650..0fc7deb 100644 --- a/cptr/utils/tools.py +++ b/cptr/utils/tools.py @@ -2523,7 +2523,7 @@ async def timer( extra_meta={ "timer_at": due_at, "cancel_on": selected_events, - "timer_status": "pending", + "status": "pending", "timer_parent_message_id": __context__.get("message_id"), "timer_model_id": full_model_id, },