Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(workbench): backfill session titles from backends (#397)
Call White2a0b64f028b4
diff --git a/core/services/sessions.py b/core/services/sessions.pyindex 7b9d4903e..2a0755953 100644--- a/core/services/sessions.py+++ b/core/services/sessions.py@@ -39,6 +39,7 @@ from config import pathsfrom storage.workbench_sessions_service import (SessionBackendLockedError,archive_session,+ backfill_session_title,create_session,get_session,list_sessions,@@ -51,6 +52,7 @@ from storage.workbench_sessions_service import (__all__ = ["SessionBackendLockedError","archive_session",+ "backfill_session_title","create_session","get_session","list_sessions",diff --git a/core/session_titles.py b/core/session_titles.pynew file mode 100644index 000000000..8714056b5--- /dev/null+++ b/core/session_titles.py@@ -0,0 +1,82 @@+"""Backfill Vibe session titles from backend-native session metadata."""++from __future__ import annotations++import logging+from typing import Any++from core.inbox_events import bus+from core.services import sessions as workbench_sessions_service+from modules.agents.native_sessions.service import AgentNativeSessionService+from storage import messages_service+from storage.db import create_sqlite_engine++logger = logging.getLogger(__name__)+++def backfill_agent_session_title(+ *,+ agent_session_id: str,+ backend: str,+ native_session_id: str,+ working_path: str,+ fallback_first_user_message: str = "",+) -> dict[str, Any] | None:+ """Backfill one empty ``agent_sessions.title`` from backend metadata.++ Best-effort and write-once: returns the updated session payload when a title+ was written, otherwise ``None``. User-owned or already non-empty titles are+ preserved by the storage-layer writer.+ """++ if not (agent_session_id and backend and native_session_id and working_path):+ return None++ inbox_row: dict[str, Any] | None = None+ engine = create_sqlite_engine()+ try:+ with engine.begin() as conn:+ try:+ first_user_message = messages_service.first_user_text(conn, agent_session_id)+ except Exception:+ logger.debug("session-title: failed to read first user text", exc_info=True)+ first_user_message = ""+ candidate = AgentNativeSessionService().get_title(+ working_path=working_path,+ agent=backend,+ native_session_id=native_session_id,+ first_user_message=first_user_message or fallback_first_user_message,+ )+ if candidate is None:+ return None+ updated = workbench_sessions_service.backfill_session_title(+ conn,+ agent_session_id,+ title=candidate.title,+ backend=backend,+ source=candidate.source,+ confidence=candidate.confidence,+ native_session_id=native_session_id,+ )+ if updated is not None:+ try:+ inbox_row = messages_service.get_inbox_session(conn, agent_session_id, platform="avibe")+ except Exception:+ logger.debug("session-title: failed to build inbox row", exc_info=True)+ finally:+ engine.dispose()++ if updated is None:+ return None+ bus.publish(+ "session.activity",+ {+ "session_id": updated["id"],+ "scope_id": updated.get("scope_id"),+ "event": "updated",+ "title": updated.get("title"),+ },+ )+ if inbox_row is not None:+ bus.publish("inbox.session.updated", inbox_row)+ return updateddiff --git a/docs/plans/backend-session-title-backfill.md b/docs/plans/backend-session-title-backfill.mdnew file mode 100644index 000000000..d88ace525--- /dev/null+++ b/docs/plans/backend-session-title-backfill.md@@ -0,0 +1,311 @@+# Backend-native session title backfill++## Background++`agent_sessions.title` is currently a Vibe-owned display field. Workbench-created+sessions may have a title, but IM-created sessions usually leave it empty. Native+backend sessions also have their own naming behavior:++- **OpenCode** currently receives `title="vibe-remote:{base_session_id}"` when a+ new native session is created. This blocks OpenCode's own title generation,+ because OpenCode only auto-generates a semantic title while its title still+ matches the default `New session - <ISO timestamp>` format.+- **Codex** does not receive a title from Vibe Remote. Its local thread store has+ `title`, `first_user_message`, and `preview` fields.+- **Claude Code** does not receive a title from Vibe Remote through the current+ SDK path. The CLI has session naming / rename concepts, but the SDK options+ used here do not expose a first-class title/name field, and the stable local+ session index exposes `firstPrompt`, not a reliable generated `title`. Product+ direction: use the first user message's first 10 visible characters as the+ Claude fallback title.++The current OpenCode behavior is backwards for product quality: Vibe Remote+injects a technical title, then loses access to the backend's better title.++## Goal++Use backend-native titles as the source of truth for empty Vibe session titles:++1. Do not pass a Vibe-generated title/name to any backend when creating a native+ session.+2. Pull the backend's native title after a turn has enough context to name the+ conversation.+3. Backfill `agent_sessions.title` only while it is still empty and not+ user-owned.+4. Never overwrite a title the user has edited.++## Non-goals++- Do not add a Vibe-side LLM title generator in this change.+- Do not try to force Claude Code to accept a title via undocumented CLI flags+ or by mutating Claude's private storage.+- Do not rewrite historical session titles in a migration. This is a forward+ behavior change; optional historical backfill can be a separate maintenance+ command later.++## Backend Findings++### OpenCode++Confirmed behavior:++- `POST /session` with no title creates a default title like+ `New session - 2026-06-02T07:35:03.127Z`.+- OpenCode stores this in its sqlite `session.title` field and returns it in+ the create-session response.+- OpenCode source has an `ensureTitle` path that only runs when+ `Session.isDefaultTitle(session.title)` is true. After the first real user+ message, it asks the built-in `title` agent to generate a semantic title and+ calls `Session.setTitle`.++Implication:++- Vibe Remote must stop passing `vibe-remote:{base_session_id}`.+- The initial default title must be ignored for backfill.+- The semantic title should be read after the first turn completes, or on a+ short delayed retry if it is not available immediately.++### Codex++Current behavior:++- Vibe Remote starts Codex threads with `thread/start` params containing cwd,+ sandbox, approval policy, and developer instructions, but no title.+- Codex local state has `threads.title`, `threads.first_user_message`, and+ `threads.preview`.+- The existing `CodexNativeSessionProvider` already reads `title` from the+ native sqlite store for `/resume`.++Implication:++- Codex is already aligned with "do not pass title".+- Add a small title pull path that reads the current native thread by id and+ returns `threads.title` when it is non-empty and not a placeholder.++### Claude Code++Current behavior:++- The CLI supports `--name` and rename/display-name concepts.+- The current `ClaudeAgentOptions` used by Vibe Remote does not expose a+ first-class `name` or `title` field.+- Stable local discovery data currently exposes `sessions-index.json` fields+ such as `firstPrompt`, `sessionId`, timestamps, path, and message count.+ It does not expose a reliable generated `title`.+- `history.jsonl` has `display`, but that is a history-entry display string,+ not a stable session title contract.++Implication:++- Claude should not claim a backend-generated title.+- Claude should expose a low-confidence derived title from the first user+ message: the first 10 visible characters after trimming whitespace.+- Source should be `derived_first_prompt`, not `backend`.+- Normalize before slicing: trim, collapse whitespace/newlines to a single+ space, then take the first 10 visible characters. If the first user message+ has no text content, return no title.++## Data Ownership++Use `agent_sessions.metadata_json` to track title ownership. Avoid adding columns+unless this becomes a heavily queried feature.++Suggested metadata shape:++```json+{+ "title_source": "backend",+ "title_backend": "opencode",+ "title_native_session_id": "ses_...",+ "title_synced_at": "2026-06-02T07:40:00Z"+}+```++When the user edits a session title through the UI/API:++```json+{+ "title_source": "user",+ "title_user_modified_at": "2026-06-02T07:40:00Z"+}+```++Rules:++- `title_source=user` means backend title sync must never overwrite it.+- Empty `title` with missing/other source is eligible for backend backfill.+- Backend backfill sets `title_source=backend`.+- Once a non-empty title is written into Vibe, backend sync should not overwrite+ it. This keeps the rule simple: backfill empty titles only.+- Placeholder backend titles must not be written.++## Proposed Abstraction++Add a small backend title provider contract instead of duplicating storage logic+inside each agent implementation.++```python+@dataclass(slots=True)+class BackendSessionTitle:+ title: str+ source: Literal["backend", "derived_first_prompt"]+ confidence: Literal["high", "low"]+++class BackendSessionTitleProvider(Protocol):+ def get_title(+ self,+ *,+ native_session_id: str,+ working_path: str,+ first_user_message: str = "",+ ) -> BackendSessionTitle | None:+ ...+```++Provider behavior:++- `OpenCodeSessionTitleProvider`: read `session.title` by native id, ignore+ default `New session - ...` and `Child session - ...`.+- `CodexSessionTitleProvider`: read `threads.title` by native thread id, ignore+ empty/default-looking values. Use `first_user_message` only if we explicitly+ choose derived fallback.+- `ClaudeSessionTitleProvider`: derive a fallback from the first user message's+ first 10 visible characters with `source="derived_first_prompt"` and+ `confidence="low"`.++Implemented shape:++- `modules/agents/native_sessions/*` already contains backend-specific read+ logic for `/resume`, so each provider now exposes a focused `get_title()`.+- `core.session_titles.backfill_agent_session_title()` owns the shared+ orchestration: read first user text, ask the provider, call the storage writer,+ and publish `session.activity` after a successful write.+- `BaseAgent` only schedules best-effort title sync after successful terminal+ turns.++## Backfill Flow++Trigger title sync after the native session id is known and a turn reaches a+terminal state.++Recommended flow:++1. Agent creates or resumes native session.+2. Vibe Remote binds `native_session_id` to the reserved `agent_sessions` row.+3. User turn completes.+4. Agent calls a shared helper:++```python+maybe_backfill_agent_session_title(+ agent_session_id=...,+ backend=...,+ native_session_id=...,+ working_path=...,+)+```++5. Helper checks the Vibe session row:+ - no row: skip+ - non-empty title with `title_source=user`: skip+ - any non-empty title: skip+ - empty title: backfill if provider returns an eligible title+6. Persist title + metadata.+7. Publish a session update event so Workbench sidebar/header refreshes.++OpenCode timing:++- The semantic title may be generated shortly after the first prompt path runs.+- First call after turn completion should try once.+- If the provider returns no title because it is still the default placeholder,+ schedule one short retry after 3 seconds, without blocking the agent response.+- Do not create a long-running poll loop just for title sync.++## UI / API Behavior++Session update API:++- When `PATCH /api/sessions/<id>` changes `title`, mark metadata+ `title_source=user`.+- Clearing a title should be treated as user intent. Suggested behavior:+ - if user sets empty title explicitly, set `title_source=user` and keep title+ empty, so backend sync does not immediately refill it.+ - if we want "reset to backend title" later, add an explicit reset action.++Workbench display:++- Prefer `agent_sessions.title` when present.+- If empty, keep current fallback behavior.+- Do not display backend placeholder titles such as `New session - ...`.++Creation-path confirmation:++- Plain Avibe Workbench chat creation currently calls `api.createSession` with+ only `project_id`; it does not send the localized UI fallback+ `Untitled session` / `未命名会话`.+- Sidebar "new session" also sends only `project_id`.+- Chat header and sidebar render `Untitled session` / `未命名会话` only as a UI+ fallback when `session.title` is null/empty.+- The backend `create_session` path stores `title=None` when the incoming title+ is missing, empty, or whitespace-only.+- `CreateViaChatDialog` is a different, explicit task/watch setup flow and+ intentionally sends a business title such as Task / Watch; it is not the+ plain new-chat fallback.++## Tests++Unit coverage:++- OpenCode create-session no longer sends `title`.+- OpenCode provider ignores default `New session - ...`.+- OpenCode provider returns semantic `session.title`.+- Codex provider returns `threads.title`.+- Claude provider derives the first 10 visible characters from the first user+ message and marks the source as `derived_first_prompt`.+- Backfill writes title only when Vibe title is empty.+- Backfill does not overwrite `title_source=user`.+- Backfill does not overwrite an existing backend-owned title.+- User `PATCH title` marks metadata as user-owned.+- Plain Workbench create-session requests without a title persist+ `agent_sessions.title = NULL`; localized fallback strings never enter the DB.++Integration-ish tests:++- Workbench session first turn with OpenCode binds native id and eventually+ fills `agent_sessions.title` from OpenCode.+- Workbench session first turn with Codex fills from Codex native title when+ available.+- Claude session fills from the first user message's first 10 visible+ characters.++Regression scenarios:++- Existing IM thread with no Workbench title still replies normally.+- Existing Workbench session renamed by user is not overwritten by a later+ backend-generated title.+- OpenCode `/resume` list still shows OpenCode native titles through the native+ session provider.++## Implementation Status++Implemented in `feature/backend-session-title-backfill`:++1. Added backend title candidate API and provider implementations.+2. Stopped passing `title` to OpenCode `create_session`.+3. Added shared session-title backfill helper in `core.session_titles`.+4. Called the helper after successful terminal turns for OpenCode, Codex, and+ Claude.+5. Added Claude provider with the first-10-visible-characters fallback.+6. Updated session title PATCH path to mark user ownership, including explicit+ user clears.+7. Published session update events after successful backend backfill.+8. Added focused tests.++## Open Questions++- Should Codex fallback to `first_user_message` when `threads.title` is empty,+ or should only backend-native `title` count?+- Is `metadata_json` enough for title ownership, or should `title_source` become+ a column once filtering/sorting by title origin matters?+- Should OpenCode title sync use one short delayed retry, or wait for a later+ natural session refresh when the semantic title is not ready immediately?diff --git a/modules/agents/base.py b/modules/agents/base.pyindex 2a12eeb32..4a1a730e4 100644--- a/modules/agents/base.py+++ b/modules/agents/base.py@@ -2,6 +2,7 @@from __future__ import annotations+import asyncioimport loggingimport timefrom abc import ABC, abstractmethod@@ -225,6 +226,74 @@ class BaseAgent(ABC):self._pin_agent_session_id(context, new_id)return new_id+ def _maybe_backfill_session_title(+ self,+ request: AgentRequest | None,+ native_session_id: Any,+ *,+ retry_delay_seconds: float | None = None,+ ) -> None:+ """Best-effort backfill of an empty Vibe session title from the backend."""++ if request is None or not native_session_id:+ return+ agent_session_id = self._reserved_agent_session_id(request.context) or self._session_id_from_context(+ request.context+ )+ if not agent_session_id:+ return+ working_path = getattr(request, "working_path", "") or ""+ if not working_path:+ return++ async def _run(delay: float | None = None) -> None:+ if delay:+ await asyncio.sleep(delay)+ updated = self._backfill_session_title_once(+ agent_session_id=agent_session_id,+ native_session_id=str(native_session_id),+ working_path=working_path,+ fallback_first_user_message=getattr(request, "message", "") or "",+ )+ if updated is None and delay is None and retry_delay_seconds:+ asyncio.create_task(_run(retry_delay_seconds))++ asyncio.create_task(_run())++ @staticmethod+ def _session_id_from_context(context: Any) -> Optional[str]:+ payload = getattr(context, "platform_specific", None) or {}+ sid = payload.get("agent_session_id")+ return str(sid).strip() if sid else None++ def _backfill_session_title_once(+ self,+ *,+ agent_session_id: str,+ native_session_id: str,+ working_path: str,+ fallback_first_user_message: str = "",+ ) -> Optional[dict[str, Any]]:+ try:+ from core.session_titles import backfill_agent_session_title++ return backfill_agent_session_title(+ agent_session_id=agent_session_id,+ backend=self.name,+ native_session_id=native_session_id,+ working_path=working_path,+ fallback_first_user_message=fallback_first_user_message,+ )+ except Exception:+ logger.debug(+ "session-title: backfill failed for agent=%s session=%s native=%s",+ self.name,+ agent_session_id,+ native_session_id,+ exc_info=True,+ )+ return None+def bind_agent_session_id(self,request: AgentRequest,diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 77f09fd26..e5e5a38a8 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -35,6 +35,7 @@ class ClaudeAgent(BaseAgent):self.claude_client = controller.claude_clientself._last_assistant_text: dict[str, str] = {}self._pending_assistant_message: dict[str, str] = {}+ self._native_session_ids: dict[str, str] = {}# Store reaction info per session as a queue (FIFO) for cleanup after result# Each entry is (reaction_message_id, emoji)self._pending_reactions: dict[str, list[tuple[str, str]]] = {}@@ -292,6 +293,7 @@ class ClaudeAgent(BaseAgent):cleanup_from_receiver = receiver_task is not None and receiver_task is current_receiver_taskself._last_assistant_text.pop(composite_key, None)self._pending_assistant_message.pop(composite_key, None)+ self._native_session_ids.pop(composite_key, None)if not preserve_pending_request_state:self._pending_reactions.pop(composite_key, None)self._pending_requests.pop(composite_key, None)@@ -377,6 +379,7 @@ class ClaudeAgent(BaseAgent):touch_session_activity(composite_key)claude_session_id = self._maybe_capture_session_id(message, base_session_id, session_key, context)if claude_session_id:+ self._native_session_ids[composite_key] = claude_session_idlogger.info(f"Captured Claude session id {claude_session_id} for {base_session_id}")if self.claude_client._is_skip_message(message):@@ -555,6 +558,15 @@ class ClaudeAgent(BaseAgent):parse_mode="markdown",request=pending_request,)+ native_session_id = self._native_session_ids.get(composite_key) or self._reserved_native_session_id(+ context,+ self.name,+ ) or self._reserved_native_session_id(+ getattr(pending_request, "context", None),+ self.name,+ )+ if pending_request is not None and native_session_id:+ self._maybe_backfill_session_title(pending_request, native_session_id)self._discard_pending_reaction(composite_key)diff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.pyindex b29ad6766..97cc21adb 100644--- a/modules/agents/codex/event_handler.py+++ b/modules/agents/codex/event_handler.py@@ -222,6 +222,11 @@ class CodexEventHandler:parse_mode="markdown",request=tracked_request,)+ thread_id = self._extract_thread_id(params) or self._agent._session_mgr.get_thread_id(+ tracked_request.base_session_id+ )+ if thread_id:+ self._agent._maybe_backfill_session_title(tracked_request, thread_id)async def _on_item_completed(self, params: dict[str, Any], request: AgentRequest) -> None:item = params.get("item", {})diff --git a/modules/agents/native_sessions/base.py b/modules/agents/native_sessions/base.pyindex a29da6edb..8a1cd0fd1 100644--- a/modules/agents/native_sessions/base.py+++ b/modules/agents/native_sessions/base.py@@ -6,7 +6,7 @@ from datetime import datetimefrom pathlib import Pathfrom typing import Protocol-from .types import NativeResumeSession+from .types import BackendSessionTitle, NativeResumeSessionlogger = logging.getLogger(__name__)EDGE_SYMBOLS = " \t\r\n`*_~'\"“”‘’.,!?!?。,、::;;-—…()()[]【】<>《》「」『』{}|/\\"@@ -21,6 +21,15 @@ class NativeSessionProvider(Protocol):def hydrate_preview(self, item: NativeResumeSession) -> NativeResumeSession:"""Fill in the assistant preview text for one item."""+ def get_title(+ self,+ *,+ native_session_id: str,+ working_path: str,+ first_user_message: str = "",+ ) -> BackendSessionTitle | None:+ """Return a backfillable title for a native session, if available."""+def normalize_preview_text(text: str) -> str:if not text:@@ -32,6 +41,13 @@ def normalize_preview_text(text: str) -> str:return " ".join(lines).strip()+def normalize_title_text(text: str, *, limit: int | None = None) -> str:+ cleaned = normalize_preview_text(text)+ if not cleaned:+ return ""+ return cleaned[:limit] if limit is not None else cleaned++def normalize_multiline_preview_text(text: str) -> str:if not text:return ""diff --git a/modules/agents/native_sessions/claude.py b/modules/agents/native_sessions/claude.pyindex ff3ca7950..0f2f08749 100644--- a/modules/agents/native_sessions/claude.py+++ b/modules/agents/native_sessions/claude.py@@ -11,10 +11,11 @@ from .base import (NativeSessionProvider,build_tail_preview,dt_from_ts,+ normalize_title_text,normalize_preview_text,read_json_lines,)-from .types import NativeResumeSession+from .types import BackendSessionTitle, NativeResumeSessionlogger = logging.getLogger(__name__)@@ -339,3 +340,21 @@ class ClaudeNativeSessionProvider(NativeSessionProvider):item.last_agent_message = normalize_preview_text(preview)item.last_agent_tail = build_tail_preview(item.last_agent_message or preview or item.native_session_id)return item++ def get_title(+ self,+ *,+ native_session_id: str,+ working_path: str,+ first_user_message: str = "",+ ) -> BackendSessionTitle | None:+ title = normalize_title_text(first_user_message, limit=10)+ if not title:+ for item in self.list_metadata(working_path):+ if item.native_session_id != native_session_id:+ continue+ title = normalize_title_text(str(item.locator.get("first_prompt") or ""), limit=10)+ break+ if not title:+ return None+ return BackendSessionTitle(title=title, source="derived_first_prompt", confidence="low")diff --git a/modules/agents/native_sessions/codex.py b/modules/agents/native_sessions/codex.pyindex 0758877b5..e9bcd6167 100644--- a/modules/agents/native_sessions/codex.py+++ b/modules/agents/native_sessions/codex.py@@ -1,20 +1,23 @@from __future__ import annotationsimport logging+import osimport sqlite3from pathlib import Path-from .base import NativeSessionProvider, build_tail_preview, dt_from_ts, read_json_lines-from .types import NativeResumeSession+from .base import NativeSessionProvider, build_tail_preview, dt_from_ts, normalize_title_text, read_json_lines+from .types import BackendSessionTitle, NativeResumeSessionlogger = logging.getLogger(__name__)class CodexNativeSessionProvider(NativeSessionProvider):agent_name = "codex"+ _PLACEHOLDER_TITLES = {"new session", "untitled session", "未命名会话"}def __init__(self, db_path: str | None = None):- self.db_path = Path(db_path or Path.home() / ".codex" / "state_5.sqlite")+ codex_home = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex").expanduser()+ self.db_path = Path(db_path) if db_path is not None else codex_home / "state_5.sqlite"def _connect(self) -> sqlite3.Connection:return sqlite3.connect(f"file:{self.db_path}?mode=ro", uri=True)@@ -85,3 +88,35 @@ class CodexNativeSessionProvider(NativeSessionProvider):item.last_agent_message = previewitem.last_agent_tail = build_tail_preview(preview or item.native_session_id)return item++ @classmethod+ def is_placeholder_title(cls, title: str) -> bool:+ return title.strip().lower() in cls._PLACEHOLDER_TITLES++ def get_title(+ self,+ *,+ native_session_id: str,+ working_path: str,+ first_user_message: str = "",+ ) -> BackendSessionTitle | None:+ if not self.db_path.exists():+ return None+ try:+ with self._connect() as conn:+ row = conn.execute(+ """+ SELECT title+ FROM threads+ WHERE id = ? AND cwd = ? AND archived = 0+ LIMIT 1+ """,+ (native_session_id, working_path),+ ).fetchone()+ except Exception as exc:+ logger.warning("Failed to read Codex thread title %s: %s", native_session_id, exc)+ return None+ title = normalize_title_text(str(row[0] or "")) if row else ""+ if not title or self.is_placeholder_title(title):+ return None+ return BackendSessionTitle(title=title, source="backend", confidence="high")diff --git a/modules/agents/native_sessions/opencode.py b/modules/agents/native_sessions/opencode.pyindex 73142958a..17265156a 100644--- a/modules/agents/native_sessions/opencode.py+++ b/modules/agents/native_sessions/opencode.py@@ -1,20 +1,28 @@from __future__ import annotationsimport logging+import osimport sqlite3from pathlib import Path-from .base import NativeSessionProvider, build_tail_preview, dt_from_ts, parse_json_blob-from .types import NativeResumeSession+from .base import NativeSessionProvider, build_tail_preview, dt_from_ts, normalize_title_text, parse_json_blob+from .types import BackendSessionTitle, NativeResumeSessionlogger = logging.getLogger(__name__)class OpenCodeNativeSessionProvider(NativeSessionProvider):agent_name = "opencode"+ _IGNORED_TITLE_PREFIXES = ("New session - ", "Child session - ", "vibe-remote:")def __init__(self, db_path: str | None = None):- self.db_path = Path(db_path or Path.home() / ".local" / "share" / "opencode" / "opencode.db")+ self.db_path = Path(db_path).expanduser() if db_path else self.default_db_path()++ @staticmethod+ def default_db_path() -> Path:+ data_home = os.environ.get("XDG_DATA_HOME")+ base = Path(data_home).expanduser() if data_home else Path.home() / ".local" / "share"+ return base / "opencode" / "opencode.db"def _connect(self) -> sqlite3.Connection:return sqlite3.connect(f"file:{self.db_path}?mode=ro", uri=True)@@ -86,3 +94,35 @@ class OpenCodeNativeSessionProvider(NativeSessionProvider):fallback = str(item.locator.get("title") or item.native_session_id)item.last_agent_tail = build_tail_preview(preview or fallback)return item++ @classmethod+ def is_ignored_title(cls, title: str) -> bool:+ return any(title.startswith(prefix) for prefix in cls._IGNORED_TITLE_PREFIXES)++ def get_title(+ self,+ *,+ native_session_id: str,+ working_path: str,+ first_user_message: str = "",+ ) -> BackendSessionTitle | None:+ if not self.db_path.exists():+ return None+ try:+ with self._connect() as conn:+ row = conn.execute(+ """+ SELECT title+ FROM session+ WHERE id = ? AND directory = ?+ LIMIT 1+ """,+ (native_session_id, working_path),+ ).fetchone()+ except Exception as exc:+ logger.warning("Failed to read OpenCode session title %s: %s", native_session_id, exc)+ return None+ title = normalize_title_text(str(row[0] or "")) if row else ""+ if not title or self.is_ignored_title(title):+ return None+ return BackendSessionTitle(title=title, source="backend", confidence="high")diff --git a/modules/agents/native_sessions/service.py b/modules/agents/native_sessions/service.pyindex 223c5beca..dea70d388 100644--- a/modules/agents/native_sessions/service.py+++ b/modules/agents/native_sessions/service.py@@ -7,7 +7,7 @@ from collections import Counterfrom .base import NativeSessionProviderfrom .display import format_display_summary, format_display_timefrom .providers import DEFAULT_PROVIDER_SPECS, NativeSessionProviderSpec-from .types import NativeResumeSession+from .types import BackendSessionTitle, NativeResumeSessionlogger = logging.getLogger(__name__)@@ -128,3 +128,28 @@ class AgentNativeSessionService:logger.warning("Failed to hydrate %s session %s: %s", agent, native_session_id, exc)return itemreturn None++ def get_title(+ self,+ *,+ working_path: str,+ agent: str,+ native_session_id: str,+ first_user_message: str = "",+ ) -> BackendSessionTitle | None:+ provider_by_name = {provider.agent_name: provider for provider in self.providers}+ provider = provider_by_name.get(agent)+ if not provider:+ return None+ getter = getattr(provider, "get_title", None)+ if not callable(getter):+ return None+ try:+ return getter(+ native_session_id=native_session_id,+ working_path=working_path,+ first_user_message=first_user_message,+ )+ except Exception as exc:+ logger.warning("Failed to read %s title for session %s: %s", agent, native_session_id, exc)+ return Nonediff --git a/modules/agents/native_sessions/types.py b/modules/agents/native_sessions/types.pyindex ed5a233fb..36a29bd0d 100644--- a/modules/agents/native_sessions/types.py+++ b/modules/agents/native_sessions/types.py@@ -21,3 +21,10 @@ class NativeResumeSession:last_agent_message: str = ""last_agent_tail: str = ""locator: dict[str, Any] = field(default_factory=dict)+++@dataclass(frozen=True, slots=True)+class BackendSessionTitle:+ title: str+ source: Literal["backend", "derived_first_prompt"]+ confidence: Literal["high", "low"]diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex c42a0b256..ad568411c 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -349,6 +349,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):request=request,)+ self._maybe_backfill_session_title(request, session_id, retry_delay_seconds=3.0)self.sessions.remove_active_poll(session_id)except asyncio.CancelledError:diff --git a/modules/agents/opencode/session.py b/modules/agents/opencode/session.pyindex 7e8f8d0c2..0855bf548 100644--- a/modules/agents/opencode/session.py+++ b/modules/agents/opencode/session.py@@ -238,7 +238,6 @@ class OpenCodeSessionManager:try:session_data = await server.create_session(directory=request.working_path,- title=f"vibe-remote:{request.base_session_id}",)session_id = session_data.get("id")if session_id:diff --git a/storage/messages_service.py b/storage/messages_service.pyindex 86385a3e8..d6a658569 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -202,6 +202,28 @@ def list_session_messages(return {"messages": rows, "next_after_id": next_after}+def first_user_text(conn: Connection, session_id: str) -> str:+ """Return the first visible user text for a session, if any."""++ row = conn.execute(+ select(messages.c.content_text, messages.c.content_json)+ .where(messages.c.session_id == session_id)+ .where(messages.c.type == "user")+ .order_by(messages.c.created_at.asc(), messages.c.id.asc())+ .limit(1)+ ).first()+ if row is None:+ return ""+ text = str(row[0] or "").strip()+ if text:+ return text+ try:+ content = json.loads(row[1] or "{}")+ except json.JSONDecodeError:+ return ""+ return str(content.get("text") or "").strip() if isinstance(content, dict) else ""++# --- Send-while-busy queue + per-session draft -----------------------------# Both reuse the ``messages`` table via dedicated ``type`` values so no extra# table is needed (the queue is ephemeral operational state, not conversation):diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.pyindex 1e9dd4a15..a4b274293 100644--- a/storage/workbench_sessions_service.py+++ b/storage/workbench_sessions_service.py@@ -19,7 +19,7 @@ import secretsfrom datetime import datetime, timezonefrom typing import Any, Optional-from sqlalchemy import select, update+from sqlalchemy import func, select, updatefrom sqlalchemy.engine import Connectionfrom storage.models import agent_sessions, scope_settings, scopes@@ -46,10 +46,7 @@ def _new_session_id(conn: Connection) -> str:def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:- try:- metadata = json.loads(row.get("metadata_json") or "{}")- except json.JSONDecodeError:- metadata = {}+ metadata = _load_metadata(row.get("metadata_json"))return {"id": row["id"],"scope_id": row.get("scope_id"),@@ -78,6 +75,18 @@ def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:}+def _load_metadata(value: Any) -> dict[str, Any]:+ try:+ loaded = json.loads(value or "{}")+ except json.JSONDecodeError:+ return {}+ return loaded if isinstance(loaded, dict) else {}+++def _dumps_metadata(metadata: dict[str, Any]) -> str:+ return json.dumps(metadata)++def list_sessions(conn: Connection,*,@@ -231,7 +240,7 @@ def update_session(conn: Connection,session_id: str,*,- title: Optional[str] = None,+ title: Any = _UNSET,agent_id: Optional[str] = None,agent_name: Optional[str] = None,agent_backend: Optional[str] = None,@@ -244,6 +253,7 @@ def update_session(agent_sessions.c.id,agent_sessions.c.agent_backend,agent_sessions.c.native_session_id,+ agent_sessions.c.metadata_json,).where(agent_sessions.c.id == session_id)).first()if existing is None:@@ -271,9 +281,13 @@ def update_session()values: dict[str, Any] = {"updated_at": _utc_now_iso()}- if title is not None:- cleaned = title.strip()+ if title is not _UNSET:+ cleaned = str(title or "").strip()values["title"] = cleaned or None+ metadata = _load_metadata(existing.metadata_json)+ metadata["title_source"] = "user"+ metadata["title_user_modified_at"] = values["updated_at"]+ values["metadata_json"] = _dumps_metadata(metadata)if agent_id is not None:values["agent_id"] = agent_id or Noneif agent_name is not None:@@ -295,6 +309,72 @@ def update_session(return get_session(conn, session_id)+def backfill_session_title(+ conn: Connection,+ session_id: str,+ *,+ title: str,+ backend: str,+ source: str = "backend",+ confidence: Optional[str] = None,+ native_session_id: Optional[str] = None,+) -> dict[str, Any] | None:+ """Fill an empty Vibe session title from a backend/derived source.++ Returns the updated session payload when a title was written; returns+ ``None`` when the row is missing, already has any title, is explicitly+ user-owned, or the incoming title is empty. This is intentionally+ write-once for title content: backend sync backfills blank sessions only.+ """++ cleaned = str(title or "").strip()+ if not cleaned:+ return None++ row = conn.execute(+ select(+ agent_sessions.c.id,+ agent_sessions.c.title,+ agent_sessions.c.metadata_json,+ agent_sessions.c.native_session_id,+ ).where(agent_sessions.c.id == session_id)+ ).mappings().first()+ if row is None:+ return None++ metadata = _load_metadata(row.get("metadata_json"))+ if metadata.get("title_source") == "user":+ return None+ if str(row.get("title") or "").strip():+ return None++ now = _utc_now_iso()+ metadata.update(+ {+ "title_source": source,+ "title_backend": backend,+ "title_synced_at": now,+ }+ )+ if native_session_id:+ metadata["title_native_session_id"] = native_session_id+ elif row.get("native_session_id"):+ metadata["title_native_session_id"] = row.get("native_session_id")+ if confidence:+ metadata["title_confidence"] = confidence++ result = conn.execute(+ update(agent_sessions)+ .where(agent_sessions.c.id == session_id)+ .where((agent_sessions.c.title.is_(None)) | (agent_sessions.c.title == ""))+ .where(func.coalesce(func.json_extract(agent_sessions.c.metadata_json, "$.title_source"), "") != "user")+ .values(title=cleaned, metadata_json=_dumps_metadata(metadata), updated_at=now)+ )+ if result.rowcount == 0:+ return None+ return get_session(conn, session_id)++def archive_session(conn: Connection, session_id: str) -> dict[str, Any]:existing = conn.execute(select(agent_sessions.c.id).where(agent_sessions.c.id == session_id)diff --git a/tests/test_codex_event_handler.py b/tests/test_codex_event_handler.pyindex da5acb2a5..9e035d44e 100644--- a/tests/test_codex_event_handler.py+++ b/tests/test_codex_event_handler.py@@ -85,7 +85,7 @@ class _StubTurnRegistry:class _StubAgent:def __init__(self):self._turn_registry = _StubTurnRegistry()- self._session_mgr = SimpleNamespace(set_thread_id=Mock())+ self._session_mgr = SimpleNamespace(set_thread_id=Mock(), get_thread_id=Mock(return_value=None))self.controller = SimpleNamespace(config=SimpleNamespace(reply_enhancements=True),emit_agent_message=AsyncMock(),@@ -93,6 +93,7 @@ class _StubAgent:)self.emit_result_message = AsyncMock()self._remove_ack_reaction = AsyncMock()+ self._maybe_backfill_session_title = Mock()def bind_agent_session_id(self, request, native_session_id):payload = dict(request.context.platform_specific or {})@@ -394,6 +395,7 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):assert "Generated image:" in result_textassert f".as_uri()})" in result_textassert str(old_image.resolve()) not in result_text+ agent._maybe_backfill_session_title.assert_called_once_with(request, "thread-1")async def test_empty_success_result_falls_back_when_generated_image_path_is_reused(self):agent = _StubAgent()diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.pyindex c92235cbe..99267d418 100644--- a/tests/test_core_services_sessions.py+++ b/tests/test_core_services_sessions.py@@ -47,6 +47,7 @@ def test_public_surface_is_stable():expected = {# Modern workbench CRUD (takes ``conn``):"archive_session",+ "backfill_session_title","create_session","get_session","list_sessions",@@ -72,6 +73,7 @@ def test_each_workbench_function_delegates_to_storage():"""for name in ("archive_session",+ "backfill_session_title","create_session","get_session","list_sessions",@@ -107,6 +109,17 @@ def test_create_and_get_round_trip(isolated_state):assert fetched["agent_name"] == "contract-bot"+def test_create_session_without_title_persists_null(isolated_state):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ missing = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="")+ blank = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="", title=" ")++ assert missing["title"] is None+ assert blank["title"] is None++def test_update_then_list_reflects_changes(isolated_state):engine = create_sqlite_engine()with engine.begin() as conn:@@ -177,6 +190,84 @@ def test_update_session_present_null_clears_model_and_effort(isolated_state):assert kept["title"] == "renamed"+def test_update_session_marks_user_title_ownership(isolated_state):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ sid = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")["id"]+ updated = sessions_service.update_session(conn, sid, title=" renamed ")++ assert updated["title"] == "renamed"+ assert updated["metadata"]["title_source"] == "user"+ assert updated["metadata"]["title_user_modified_at"]+++def test_update_session_empty_title_is_user_owned_clear(isolated_state):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ sid = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude", title="Old")["id"]+ updated = sessions_service.update_session(conn, sid, title="")++ assert updated["title"] is None+ assert updated["metadata"]["title_source"] == "user"+++def test_backfill_session_title_only_fills_empty_non_user_title(isolated_state):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ sid = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="opencode")["id"]+ filled = sessions_service.backfill_session_title(+ conn,+ sid,+ title="Plan backend title",+ backend="opencode",+ source="backend",+ confidence="high",+ native_session_id="oc-1",+ )+ skipped = sessions_service.backfill_session_title(+ conn,+ sid,+ title="Should not replace",+ backend="opencode",+ source="backend",+ )++ assert filled is not None+ assert filled["title"] == "Plan backend title"+ assert filled["metadata"]["title_source"] == "backend"+ assert filled["metadata"]["title_backend"] == "opencode"+ assert filled["metadata"]["title_native_session_id"] == "oc-1"+ assert filled["metadata"]["title_confidence"] == "high"+ assert skipped is None++ with engine.connect() as conn:+ assert sessions_service.get_session(conn, sid)["title"] == "Plan backend title"+++def test_backfill_session_title_does_not_override_user_owned_clear(isolated_state):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ sid = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")["id"]+ sessions_service.update_session(conn, sid, title="")+ skipped = sessions_service.backfill_session_title(+ conn,+ sid,+ title="Derived",+ backend="claude",+ source="derived_first_prompt",+ )++ assert skipped is None+ with engine.connect() as conn:+ session = sessions_service.get_session(conn, sid)+ assert session["title"] is None+ assert session["metadata"]["title_source"] == "user"++# --- Live agent-runtime status (sidebar dot) --------------------------diff --git a/tests/test_native_session_providers.py b/tests/test_native_session_providers.pyindex 668040898..4d28fbd34 100644--- a/tests/test_native_session_providers.py+++ b/tests/test_native_session_providers.py@@ -1,4 +1,5 @@import os+import sqlite3import subprocessimport sysfrom pathlib import Path@@ -10,6 +11,7 @@ from modules.agents.native_sessions import claude as claude_modulefrom modules.agents.native_sessions.claude import ClaudeNativeSessionProvider, encode_project_pathfrom modules.agents.native_sessions import codex as codex_modulefrom modules.agents.native_sessions.codex import CodexNativeSessionProvider+from modules.agents.native_sessions.opencode import OpenCodeNativeSessionProviderfrom modules.agents.native_sessions import service as service_modulefrom modules.agents.native_sessions.service import AgentNativeSessionServicefrom modules.agents.native_sessions.types import NativeResumeSession@@ -220,6 +222,134 @@ def test_codex_provider_skips_empty_rollout_path(monkeypatch) -> None:assert hydrated.last_agent_tail == "Fallback title"+def test_opencode_title_provider_ignores_default_title(tmp_path: Path) -> None:+ db_path = tmp_path / "opencode.db"+ with sqlite3.connect(db_path) as conn:+ conn.execute("create table session (id text primary key, directory text, title text)")+ conn.execute(+ "insert into session (id, directory, title) values (?, ?, ?)",+ ("ses_default", "/repo", "New session - 2026-06-02T07:35:03.127Z"),+ )+ conn.execute(+ "insert into session (id, directory, title) values (?, ?, ?)",+ ("ses_legacy", "/repo", "vibe-remote:base-session-1"),+ )+ conn.execute(+ "insert into session (id, directory, title) values (?, ?, ?)",+ ("ses_title", "/repo", "Implement session titles"),+ )++ provider = OpenCodeNativeSessionProvider(db_path=str(db_path))++ assert provider.get_title(native_session_id="ses_default", working_path="/repo") is None+ assert provider.get_title(native_session_id="ses_legacy", working_path="/repo") is None+ title = provider.get_title(native_session_id="ses_title", working_path="/repo")+ assert title is not None+ assert title.title == "Implement session titles"+ assert title.source == "backend"+ assert title.confidence == "high"+++def test_opencode_title_provider_uses_xdg_data_home(tmp_path: Path, monkeypatch) -> None:+ data_home = tmp_path / "xdg-data"+ db_path = data_home / "opencode" / "opencode.db"+ db_path.parent.mkdir(parents=True)+ with sqlite3.connect(db_path) as conn:+ conn.execute("create table session (id text primary key, directory text, title text)")+ conn.execute(+ "insert into session (id, directory, title) values (?, ?, ?)",+ ("ses_title", "/repo", "Use XDG data home"),+ )++ monkeypatch.setenv("XDG_DATA_HOME", str(data_home))+ provider = OpenCodeNativeSessionProvider()++ assert provider.db_path == db_path+ title = provider.get_title(native_session_id="ses_title", working_path="/repo")+ assert title is not None+ assert title.title == "Use XDG data home"+++def test_codex_title_provider_reads_thread_title(tmp_path: Path) -> None:+ db_path = tmp_path / "state_5.sqlite"+ with sqlite3.connect(db_path) as conn:+ conn.execute(+ """+ create table threads (+ id text primary key,+ cwd text,+ archived integer,+ title text+ )+ """+ )+ conn.execute(+ "insert into threads (id, cwd, archived, title) values (?, ?, ?, ?)",+ ("thread_empty", "/repo", 0, ""),+ )+ conn.execute(+ "insert into threads (id, cwd, archived, title) values (?, ?, ?, ?)",+ ("thread_title", "/repo", 0, "Backend title"),+ )+ conn.execute(+ "insert into threads (id, cwd, archived, title) values (?, ?, ?, ?)",+ ("thread_archived", "/repo", 1, "Archived title"),+ )++ provider = CodexNativeSessionProvider(db_path=str(db_path))++ assert provider.get_title(native_session_id="thread_empty", working_path="/repo") is None+ assert provider.get_title(native_session_id="thread_archived", working_path="/repo") is None+ title = provider.get_title(native_session_id="thread_title", working_path="/repo")+ assert title is not None+ assert title.title == "Backend title"+ assert title.source == "backend"+++def test_codex_title_provider_honors_codex_home(monkeypatch, tmp_path: Path) -> None:+ codex_home = tmp_path / "codex-home"+ codex_home.mkdir()+ db_path = codex_home / "state_5.sqlite"+ with sqlite3.connect(db_path) as conn:+ conn.execute(+ """+ create table threads (+ id text primary key,+ cwd text,+ archived integer,+ title text+ )+ """+ )+ conn.execute(+ "insert into threads (id, cwd, archived, title) values (?, ?, ?, ?)",+ ("thread_title", "/repo", 0, "CODEX_HOME title"),+ )++ monkeypatch.setenv("CODEX_HOME", str(codex_home))+ provider = CodexNativeSessionProvider()++ title = provider.get_title(native_session_id="thread_title", working_path="/repo")++ assert title is not None+ assert title.title == "CODEX_HOME title"+++def test_claude_title_provider_derives_first_10_visible_chars(tmp_path: Path) -> None:+ provider = ClaudeNativeSessionProvider(root=str(tmp_path / "projects"), history_path=str(tmp_path / "history.jsonl"))++ title = provider.get_title(+ native_session_id="claude-1",+ working_path="/repo",+ first_user_message=" 帮我\n实现 session title 回填 ",+ )++ assert title is not None+ assert title.title == "帮我 实现 sess"+ assert title.source == "derived_first_prompt"+ assert title.confidence == "low"++def test_native_session_service_preserves_agent_visibility_when_limited() -> None:def _item(agent: str, prefix: str, session_id: str, sort_ts: float) -> NativeResumeSession:return NativeResumeSession(diff --git a/tests/test_opencode_session_manager.py b/tests/test_opencode_session_manager.pyindex 4d6cee803..6ab3c0583 100644--- a/tests/test_opencode_session_manager.py+++ b/tests/test_opencode_session_manager.py@@ -52,6 +52,22 @@ def test_opencode_reused_session_attaches_agent_session_id() -> None:)+def test_opencode_create_session_does_not_pass_vibe_title() -> None:+ sessions = SimpleNamespace(+ get_agent_session_id=Mock(return_value=None),+ ensure_agent_session_id=Mock(return_value="sesk8m4q2p7x"),+ bind_agent_session=Mock(return_value="sesk8m4q2p7x"),+ )+ manager = OpenCodeSessionManager(SimpleNamespace(sessions=sessions), "opencode")+ server = SimpleNamespace(create_session=AsyncMock(return_value={"id": "oc-session-1"}))+ request = _request()++ session_id = asyncio.run(manager.get_or_create_session_id(request, server))++ assert session_id == "oc-session-1"+ server.create_session.assert_awaited_once_with(directory="/repo")++def test_opencode_reserved_agent_session_id_is_not_replaced() -> None:sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="oc-session-1"),diff --git a/tests/test_session_titles.py b/tests/test_session_titles.pynew file mode 100644index 000000000..ce4503196--- /dev/null+++ b/tests/test_session_titles.py@@ -0,0 +1,77 @@+from __future__ import annotations++import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core import inbox_events+from core.session_titles import backfill_agent_session_title+from core.services import sessions as sessions_service+from storage import messages_service+from storage.db import create_sqlite_engine+from storage.importer import ensure_sqlite_state+from storage.settings_service import upsert_scope+++def test_backfill_agent_session_title_uses_first_user_message_for_claude(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()+ published: list[tuple[str, dict]] = []+ monkeypatch.setattr(inbox_events.bus, "publish", lambda event_type, data: published.append((event_type, data)))++ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn,+ platform="avibe",+ scope_type="project",+ native_id="proj_titles",+ now="2026-06-02T08:00:00Z",+ )+ session = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=session["id"],+ platform="avibe",+ author="user",+ source="user",+ message_type="user",+ text=" 帮我\n实现 session title 回填 ",+ )+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=session["id"],+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="title backfill done",+ )++ updated = backfill_agent_session_title(+ agent_session_id=session["id"],+ backend="claude",+ native_session_id="claude-native-1",+ working_path="/repo",+ fallback_first_user_message="fallback should not win",+ )++ assert updated is not None+ assert updated["title"] == "帮我 实现 sess"+ assert updated["metadata"]["title_source"] == "derived_first_prompt"+ assert [event_type for event_type, _data in published] == ["session.activity", "inbox.session.updated"]+ assert published[0] == (+ "session.activity",+ {+ "session_id": session["id"],+ "scope_id": scope_id,+ "event": "updated",+ "title": "帮我 实现 sess",+ },+ )+ assert published[1][1]["session_id"] == session["id"]+ assert published[1][1]["title"] == "帮我 实现 sess"+ assert published[1][1]["preview_text"] == "title backfill done"diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 881c1ddab..acd93fd5f 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -376,7 +376,12 @@ export const ChatPage: React.FC = () => {// keep this chat's header in sync without a reload. Match the CURRENT// route via sessionIdRef like the handlers above.if (data.session_id !== sessionIdRef.current || data.event !== 'updated') return;- setSession((prev) => (prev ? { ...prev, title: data.title ?? null } : prev));+ if (!Object.prototype.hasOwnProperty.call(data, 'title')) return;+ const nextTitle = data.title ?? null;+ setSession((prev) => {+ if (!prev || prev.id !== data.session_id || prev.title === nextTitle) return prev;+ return { ...prev, title: nextTitle };+ });},onConnected: () => {// Every (re)connect recovers any state missed while the socket was down: