Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(chats): name history rows by topic and drop the per-row icons
rubenluetke10-beepac3ce255065a
diff --git a/jarvis/sessions/chat_titles.py b/jarvis/sessions/chat_titles.pynew file mode 100644index 0000000000..4bca6dacac--- /dev/null+++ b/jarvis/sessions/chat_titles.py@@ -0,0 +1,710 @@+"""Titles for the chat history: a topic, never the first thing someone said.++The sidebar used to show each conversation's opening words. Spoken chats open+with "Hey George, was geht ab", "Hallo" or a cut-off "Kannst", so the list read+as a column of greetings and the one row that mattered was indistinguishable+from the twenty that did not. A title has to name what the conversation was+ABOUT, the way a mail subject does.++Two writers, best first:++* **model** — a connected subscription (or nothing) names finished+ conversations in two to six words. Background work: it never touches a+ per-token API key (``background_policy``), it batches several conversations+ per call, and it backs off when the subscription cannot answer.+* **rules** — :func:`tidy_title`, deterministic and free: it drops greetings,+ small talk, filler sounds, transcription annotations and polite lead-ins+ ("Kannst du bitte mal …"), then keeps the first clause that still says+ something. Every install has it, and it is what a row shows until the model+ has written.++A conversation with no topic at all — only greetings, a test, a fragment —+gets an EMPTY title on purpose. The interface then says what it honestly is+("Voice chat · 09:42") instead of promoting "Was" to a headline.++Nothing here runs on a request path: :meth:`ChatTitler.titles_for` answers from+memory and queues the work for one daemon thread.+"""++from __future__ import annotations++import asyncio+import logging+import re+import sqlite3+import threading+import time+from collections.abc import Callable, Iterable, Sequence+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++log = logging.getLogger(__name__)++#: Longest title kept; the sidebar truncates to its real width anyway.+TITLE_MAX_CHARS = 60++#: How many user utterances the rules and the model read per conversation.+USER_TURNS_READ = 6+#: Characters kept per utterance in the model prompt.+UTTERANCE_CHARS = 280+#: Characters of the first assistant reply shown to the model as context.+REPLY_CHARS = 200++#: Conversations named per model call.+MODEL_BATCH = 10+#: Only the newest conversations of a listing are sent to the model; older ones+#: keep their rules title, so a first start does not name a year of history.+MODEL_BACKFILL = 40+#: A typed chat is renamed when it has at least doubled (and grown by this many+#: messages) since its last model title — its topic may have moved on.+MODEL_REGROW_MESSAGES = 4+#: Seconds a typed chat must be quiet before the model names it.+TYPED_SETTLE_S = 45.0+#: Model calls that fail in a row before the titler goes quiet.+MODEL_FAILURES_BEFORE_QUIET = 2+#: How long the titler stays quiet after repeated model failures.+MODEL_QUIET_S = 600.0+#: How long the titler stops asking after finding no subscription at all.+NO_SUBSCRIPTION_QUIET_S = 3 * 3600.0+#: Per-call timeout for the subscription CLI.+MODEL_TIMEOUT_S = 60.0+#: Attempts per conversation before the model gives up on it.+MODEL_ATTEMPTS_PER_ITEM = 2++WRITER_RULES = "rules"+WRITER_MODEL = "model"+WRITER_USER = "user"++KIND_VOICE = "voice"+KIND_TYPED = "agent"+++# ----------------------------------------------------------------------+# Rules: tidy_title+# ----------------------------------------------------------------------++#: "[tongue click]", "(laughs)", and Whisper's unterminated "[tongue click".+_ANNOTATION_RE = re.compile(+ r"\[[^\]\n]{0,40}\]|\([^)\n]{0,40}\)|\[[a-z][a-z \-]{0,30}(?=\s|$)|\*[^*\n]{0,30}\*"+)+#: Hesitation sounds anywhere in an utterance.+_FILLER_RE = re.compile(+ r"(?i)(?<!\w)(?:ähm+|äh+|öhm+|öh+|ehm+|hmm*|mhm*|mh+|mm+|uh+m*|um+|erm+)(?!\w)[,.…]*"+)+_GREETING = (+ r"(?:hey|hi|hallo|hello|moin|servus|na|yo|huhu|hej|hola|buenas|"+ r"guten\s+(?:morgen|tag|abend)|good\s+(?:morning|afternoon|evening))"+)+#: A greeting, optionally followed by a name it addresses ("Hey George,").+_GREETING_RE = re.compile(+ rf"(?i:{_GREETING})(?:[\s,]+[A-ZÄÖÜ][\w-]*(?=\s*[,.!?]))?(?![\w-])"+)+#: Whole phrases that carry no topic when they open an utterance.+_SMALL_TALK_RE = re.compile(+ r"(?i)(?:"+ r"was\s+geht(?:\s+ab)?|wie\s+geht(?:'?s|\s+es)(?:\s+dir)?|alles\s+(?:klar|gut|fit)|"+ r"what'?s\s+(?:up|good)(?:\s+up)?|how\s+are\s+you(?:\s+doing)?|how'?s\s+it\s+going|"+ r"qu[eé]\s+tal|c[oó]mo\s+est[aá]s|"+ r"nicht\s+(?:so\s+)?viel|weiß\s+ich\s+(?:nicht|nich)(?:\s+genau)?|"+ r"ich\s+hab(?:e)?\s+(?:ne|eine)\s+frage|i\s+have\s+a\s+question|"+ r"ich\s+verspre\w*(?:\s+mich)?|sorry|entschuldigung|moment|warte\s+mal|warte|"+ r"sehr\s+gut|na\s+gut|ok(?:ay|ey)?|alles\s+klar|also|gut|ja|jo|jep|nee|nein|"+ r"nichts|nix|danke|egal|du|so|und|test(?:ing)?|eins\s+zwei(?:\s+drei)?|"+ r"hörst\s+du\s+mich|can\s+you\s+hear\s+me"+ r")(?![\w-])"+)+#: Polite lead-ins whose remainder IS the request.+_LEAD_IN_RE = re.compile(+ r"(?i)(?:"+ r"(?:kannst|könntest|kannste|würdest|kann(?:st)?)\s+du"+ r"(?:\s+(?:mir|für\s+mich|bitte|mal|eben|kurz|schnell|einfach|nochmal|auch|ganz))*|"+ r"ich\s+(?:möchte|will|würde\s+gerne?|hätte\s+gerne?)(?:\s+(?:bitte|gerne?|jetzt))*"+ r",?\s+dass\s+du(?:\s+(?:mir|für\s+mich|bitte|mal|kurz|einfach))*|"+ r"(?:can|could|would|will)\s+you(?:\s+(?:please|just|quickly|maybe))*|"+ r"(?:puedes|podrías)(?:\s+por\s+favor)?|"+ r"hilf\s+mir(?:\s+(?:bitte|mal|dabei))*|help\s+me|"+ r"please|bitte(?:\s+mal)?|mal|auch|ganz"+ r")(?![\w-])"+)+_LEAD_PUNCT_RE = re.compile(r"^[\s,.;:!?…\-–—'\"]+")+_SENTENCE_END_RE = re.compile(r"(?<=[.!?…])\s+|(?<=[.!?…])$")+#: Where a long clause can be cut without losing its head.+_CLAUSE_CUT_RE = re.compile(r"(?i),\s+|\s+(?:und|and|aber|but|weil|because|y|pero)\s+")+_WORD_RE = re.compile(r"[^\W\d_][\w'-]*", re.UNICODE)++#: Words that never make a topic on their own.+_STOP_WORDS = frozenset(+ """+ ich du er sie es wir ihr mir mich dir dich uns euch mein meine dein deine+ der die das den dem des ein eine einen einem einer und oder aber auch noch+ mal bitte ja nein nee doch so was wer wie wo wann warum kannst kann könntest+ hallo hey hi na ok okay gut also dann jetzt hier da ist sind bin bist war+ nicht nichts nix viel einfach eben kurz schnell gerne für mit von zu im in an+ i you he she it we they me my your the a an and or but also just so what who+ how where when why can could would please hello yes no not ok here there is+ are am was be this that of to in on for with+ """.split()+)+++def _strip_lead(text: str) -> str:+ """Peel greetings, small talk and polite lead-ins off the front of *text*."""+ previous = None+ while previous != text:+ previous = text+ text = _LEAD_PUNCT_RE.sub("", text)+ for pattern in (_GREETING_RE, _SMALL_TALK_RE, _LEAD_IN_RE):+ match = pattern.match(text)+ if match and match.end() > 0:+ text = text[match.end():]+ break+ return text+++def _content_words(text: str) -> list[str]:+ return [w for w in _WORD_RE.findall(text) if w.lower() not in _STOP_WORDS]+++def _substantive(clause: str) -> bool:+ """Does *clause* name something, rather than only greet or hesitate?"""+ words = _content_words(clause)+ if len(words) >= 2:+ return True+ return len(words) == 1 and len(words[0]) >= 5 and len(_WORD_RE.findall(clause)) >= 2+++def _dedupe_words(text: str) -> str:+ """'einen einen Agent' -> 'einen Agent' (speech repeats a word while thinking)."""+ out: list[str] = []+ for word in text.split():+ if out and word.lower().strip(",.") == out[-1].lower().strip(",."):+ continue+ out.append(word)+ return " ".join(out)+++def _polish(clause: str) -> str:+ """One clause as a title: trimmed at a natural cut, capitalised, no end mark."""+ clause = clause.strip().rstrip(".!?…,;: ").strip()+ words = clause.split()+ if len(words) > 9:+ for match in _CLAUSE_CUT_RE.finditer(clause):+ head = clause[: match.start()]+ if len(head.split()) >= 4:+ clause = head+ break+ clause = clause.strip().rstrip(".!?…,;: ")+ if len(clause) > TITLE_MAX_CHARS:+ # A clause boundary inside the limit reads complete; a word boundary+ # needs the ellipsis to say something was cut.+ heads = [+ clause[: m.start()] for m in _CLAUSE_CUT_RE.finditer(clause)+ if m.start() <= TITLE_MAX_CHARS and len(clause[: m.start()].split()) >= 3+ ]+ if heads:+ clause = heads[-1].rstrip(",;: ")+ else:+ cut = clause[: TITLE_MAX_CHARS - 1]+ if " " in cut:+ cut = cut[: cut.rfind(" ")]+ clause = cut.rstrip(",;: ") + "…"+ return clause[:1].upper() + clause[1:]+++def tidy_title(utterances: Iterable[str]) -> str:+ """A topic title from what the user said, or ``""`` when there is none.++ The utterances are joined first: live voice splits one sentence across+ several segments ("Kannst du bitte mal" | "einen Agent spawnen"), and the+ request only reads as one once they are back together.+ """+ joined = " ".join(" ".join(str(u or "").split()) for u in utterances if u)+ text = _FILLER_RE.sub(" ", _ANNOTATION_RE.sub(" ", joined))+ text = _dedupe_words(" ".join(text.split()))+ for _ in range(12):+ text = _strip_lead(text)+ if not text:+ return ""+ parts = _SENTENCE_END_RE.split(text, maxsplit=1)+ clause = parts[0]+ rest = parts[1] if len(parts) > 1 else ""+ clause = _strip_lead(clause)+ if _substantive(clause):+ return _polish(clause)+ text = rest+ return ""+++# ----------------------------------------------------------------------+# Model: prompt + parse+# ----------------------------------------------------------------------++_SYSTEM = """\+You name conversations for the history list of a personal assistant app, the way \+a mail client shows subjects.++For every numbered conversation, write ONE title:+- 2 to 6 words that name the topic or the task, e.g. "Security audit for the workspace", \+"Set up a trend-analysis agent", "Weather in Berlin".+- In the language the user spoke.+- A noun phrase or a short task. No greeting, no "User asks", no quotes, no emoji, \+no trailing period.+- Spell product and proper names correctly even when the transcript garbled them.+- If the conversation has no topic — only greetings, small talk, a test or a cut-off \+fragment — write a single dash: -++Answer with exactly one line per conversation, in the form+<number>: <title>+and nothing else."""++_ANSWER_RE = re.compile(r"^\s*(\d{1,3})\s*[:.)\]-]\s*(.*?)\s*$")+_TITLE_NOISE_RE = re.compile(r"^[\s\"'„“”«»`*#\-–—]+|[\s\"'„“”«»`*.。!]+$")+++@dataclass(frozen=True, slots=True)+class Conversation:+ """What the titler reads of one conversation."""++ user: tuple[str, ...]+ reply: str = ""+++def build_prompt(conversations: Sequence[Conversation]) -> str:+ blocks: list[str] = []+ for number, convo in enumerate(conversations, start=1):+ lines = [f"Conversation {number}:"]+ for text in convo.user[:USER_TURNS_READ]:+ lines.append(f"User: {' '.join(text.split())[:UTTERANCE_CHARS]}")+ if convo.reply:+ lines.append(f"Assistant: {' '.join(convo.reply.split())[:REPLY_CHARS]}")+ blocks.append("\n".join(lines))+ return "\n\n".join(blocks)+++def clean_model_title(raw: str) -> str:+ """A model's title line, cleaned; ``""`` for its no-topic dash."""+ title = _TITLE_NOISE_RE.sub("", " ".join(str(raw or "").split()))+ if not title or not _WORD_RE.search(title):+ return ""+ if len(title) > TITLE_MAX_CHARS:+ cut = title[: TITLE_MAX_CHARS - 1]+ title = (cut[: cut.rfind(" ")] if " " in cut else cut).rstrip(",;: ") + "…"+ return title+++def parse_answer(text: str, count: int) -> dict[int, str]:+ """``{index: title}`` for the numbered lines the model answered (0-based)."""+ out: dict[int, str] = {}+ for line in str(text or "").splitlines():+ match = _ANSWER_RE.match(line)+ if not match:+ continue+ index = int(match.group(1)) - 1+ if 0 <= index < count and index not in out:+ out[index] = clean_model_title(match.group(2))+ return out+++# ----------------------------------------------------------------------+# Storage+# ----------------------------------------------------------------------+++@dataclass(slots=True)+class TitleEntry:+ title: str+ writer: str+ #: The listing's change token when the entry was written.+ version: str+ #: Message count the title was written at (typed chats re-title on growth).+ messages_at: int+ #: The stored seed (a typed chat's own title) the entry was written against.+ seed: str = ""+ attempts: int = 0+++class TitleBook:+ """Durable titles, keyed by ``(kind, conversation id)``; mirrored in memory."""++ def __init__(self, db_path: str | Path = ":memory:") -> None:+ self._path = str(db_path)+ if self._path != ":memory:":+ Path(self._path).parent.mkdir(parents=True, exist_ok=True)+ self._conn = sqlite3.connect(self._path, check_same_thread=False)+ self._lock = threading.Lock()+ with self._lock:+ self._conn.execute(+ "CREATE TABLE IF NOT EXISTS chat_titles ("+ " kind TEXT NOT NULL, conv_id TEXT NOT NULL, title TEXT NOT NULL,"+ " writer TEXT NOT NULL, version TEXT NOT NULL DEFAULT '',"+ " messages_at INTEGER NOT NULL DEFAULT 0, seed TEXT NOT NULL DEFAULT '',"+ " attempts INTEGER NOT NULL DEFAULT 0, written_ms INTEGER NOT NULL DEFAULT 0,"+ " PRIMARY KEY (kind, conv_id))"+ )+ self._conn.commit()+ self._mirror: dict[tuple[str, str], TitleEntry] = {+ (row[0], row[1]): TitleEntry(+ title=row[2], writer=row[3], version=row[4],+ messages_at=int(row[5]), seed=row[6], attempts=int(row[7]),+ )+ for row in self._conn.execute(+ "SELECT kind, conv_id, title, writer, version, messages_at, seed, attempts "+ "FROM chat_titles"+ )+ }++ # Reads take only this lock, never the SQLite one: a listing on the event+ # loop must not wait behind the worker's commits (an fsync each).+ self._mirror_lock = threading.Lock()++ def get(self, kind: str, conv_id: str) -> TitleEntry | None:+ with self._mirror_lock:+ return self._mirror.get((kind, conv_id))++ def put(self, kind: str, conv_id: str, entry: TitleEntry) -> None:+ with self._mirror_lock:+ self._mirror[(kind, conv_id)] = entry+ with self._lock:+ self._conn.execute(+ "INSERT INTO chat_titles (kind, conv_id, title, writer, version, messages_at,"+ " seed, attempts, written_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"+ " ON CONFLICT(kind, conv_id) DO UPDATE SET title=excluded.title,"+ " writer=excluded.writer, version=excluded.version,"+ " messages_at=excluded.messages_at, seed=excluded.seed,"+ " attempts=excluded.attempts, written_ms=excluded.written_ms",+ (+ kind, conv_id, entry.title, entry.writer, entry.version,+ int(entry.messages_at), entry.seed, int(entry.attempts),+ int(time.time() * 1000),+ ),+ )+ self._conn.commit()++ def close(self) -> None:+ with self._lock:+ self._conn.close()+++# ----------------------------------------------------------------------+# The titler+# ----------------------------------------------------------------------+++@dataclass(frozen=True, slots=True)+class TitleRequest:+ """One listed conversation, as the history route sees it."""++ kind: str+ conv_id: str+ #: Changes whenever the conversation does (ended_ms, message count).+ version: str+ message_count: int+ updated_ms: int+ #: Finished (voice) or quiet long enough (typed) for the model to name it.+ settled: bool+ #: The cheap text the row already has (preview / stored title).+ seed: str+ #: Reads the conversation as ``[(role, text), …]`` — called off the request path.+ loader: Callable[[], Sequence[tuple[str, str]]] = field(compare=False)+ #: For typed chats: the title the store derives from a first message, so a+ #: title the user typed themselves is recognised and kept.+ auto_title: Callable[[str], str] | None = field(default=None, compare=False)+++def _first_guess(req: TitleRequest) -> str:+ """The title a row shows before its conversation has been read.++ A typed chat's seed may be a title the user typed; only the full read can+ tell, so a seed the rules would blank out is shown as it is meanwhile.+ """+ guess = tidy_title([req.seed])+ if not guess and req.auto_title is not None:+ return req.seed+ return guess+++#: Resolves the brain that may write titles, or None. Test seam.+BrainFactory = Callable[[], Any]+++def _subscription_brain() -> Any | None:+ """A connected subscription brain, or None — titles never bill an API key."""+ try:+ from jarvis.brain.resolver import resolve_subscription_brain+ from jarvis.core.config import load_config++ return resolve_subscription_brain(load_config(), cli_timeout_s=MODEL_TIMEOUT_S)+ except Exception: # noqa: BLE001 - no brain means rules titles, said here+ log.info("chat titles: no subscription brain reachable", exc_info=True)+ return None+++class ChatTitler:+ """Answers titles from memory; writes better ones on one background thread."""++ def __init__(+ self,+ book: TitleBook,+ *,+ brain_factory: BrainFactory | None = None,+ background: bool = True,+ ) -> None:+ self._book = book+ self._brain_factory = brain_factory or _subscription_brain+ #: False: answer with the rules over each seed and never queue work —+ #: for an app without a data folder, which could not keep a title anyway.+ self._background = background+ self._lock = threading.Condition()+ self._queue: dict[tuple[str, str], tuple[TitleRequest, bool]] = {}+ self._thread: threading.Thread | None = None+ self._model_failures = 0+ self._quiet_until = 0.0+ self._closed = False++ # -- request path ------------------------------------------------------++ def known(self, kind: str, conv_id: str) -> str:+ """The stored title of one conversation; ``""`` when none is known yet."""+ entry = self._book.get(kind, conv_id)+ return entry.title if entry is not None else ""++ def titles_for(self, requests: Sequence[TitleRequest]) -> dict[tuple[str, str], str]:+ """The best title known for each request, right now. Queues what is stale.++ *requests* are expected newest first; only the first+ :data:`MODEL_BACKFILL` of them are offered to the model.+ """+ out: dict[tuple[str, str], str] = {}+ if not self._background:+ return {(r.kind, r.conv_id): _first_guess(r) for r in requests}+ queued = False+ for position, req in enumerate(requests):+ key = (req.kind, req.conv_id)+ entry = self._book.get(*key)+ same_seed = entry is not None and entry.seed == req.seed+ fresh = same_seed and entry is not None and entry.version == req.version+ # A model or user title outlives new messages until it is renewed;+ # a rules title is only as good as the read it came from.+ kept = same_seed and entry is not None and entry.writer in (WRITER_MODEL, WRITER_USER)+ known = entry is not None and (fresh or kept)+ out[key] = entry.title if known and entry is not None else _first_guess(req)+ model = position < MODEL_BACKFILL and self._wants_model(req, entry)+ if not fresh or model:+ queued |= self._enqueue(req, model=model)+ if queued:+ self._ensure_worker()+ return out++ def _wants_model(self, req: TitleRequest, entry: TitleEntry | None) -> bool:+ if not req.settled or time.monotonic() < self._quiet_until:+ return False+ if entry is None or entry.writer == WRITER_RULES:+ return entry is None or entry.attempts < MODEL_ATTEMPTS_PER_ITEM+ if entry.writer == WRITER_USER or entry.seed != req.seed:+ return False+ grown = req.message_count >= max(+ entry.messages_at * 2, entry.messages_at + MODEL_REGROW_MESSAGES+ )+ return req.kind == KIND_TYPED and grown++ def _enqueue(self, req: TitleRequest, *, model: bool) -> bool:+ key = (req.kind, req.conv_id)+ with self._lock:+ if self._closed:+ return False+ pending = self._queue.get(key)+ same = pending is not None and pending[0].version == req.version+ if same and pending is not None and (pending[1] or not model):+ return False+ self._queue[key] = (req, model or bool(pending and pending[1]))+ self._lock.notify()+ return True++ def _ensure_worker(self) -> None:+ with self._lock:+ if self._thread is not None and self._thread.is_alive():+ return+ self._thread = threading.Thread(+ target=self._run, name="chat-titler", daemon=True+ )+ self._thread.start()++ def close(self) -> None:+ with self._lock:+ self._closed = True+ self._queue.clear()+ self._lock.notify_all()++ # -- worker ------------------------------------------------------------++ def _run(self) -> None:+ while True:+ with self._lock:+ while not self._queue and not self._closed:+ if not self._lock.wait(timeout=30.0):+ # Idle: let the thread end; the next listing restarts it.+ if not self._queue:+ self._thread = None+ return+ if self._closed:+ self._thread = None+ return+ batch = list(self._queue.values())+ self._queue.clear()+ try:+ self.drain(batch)+ except Exception: # noqa: BLE001 - one bad batch must not end the thread+ log.warning("chat titles: a batch failed", exc_info=True)++ def drain(self, batch: Sequence[tuple[TitleRequest, bool]]) -> None:+ """Rules for every request, then the model for the ones that want it."""+ for_model: list[tuple[TitleRequest, Conversation, TitleEntry]] = []+ for req, model in batch:+ try:+ messages = list(req.loader())+ except Exception: # noqa: BLE001 - an unreadable row keeps its seed title+ log.debug("chat titles: cannot read %s/%s", req.kind, req.conv_id, exc_info=True)+ # Remember the seed's title for this version, or the row would+ # be re-read on every listing.+ self._book.put(req.kind, req.conv_id, TitleEntry(+ title=_first_guess(req), writer=WRITER_RULES, version=req.version,+ messages_at=req.message_count, seed=req.seed,+ attempts=MODEL_ATTEMPTS_PER_ITEM,+ ))+ continue+ user = tuple(t for r, t in messages if r == "user" and str(t).strip())+ reply = next((t for r, t in messages if r == "assistant" and str(t).strip()), "")+ previous = self._book.get(req.kind, req.conv_id)+ # Any opening message can have named the chat — an agent's message+ # lands with role "agent" and titles an empty chat as well.+ openers = [t for r, t in messages if r in ("user", "agent") and str(t).strip()][:3]+ if req.auto_title is not None and req.seed and openers and \+ req.seed not in {req.auto_title(t) for t in openers}:+ # The stored title is not the one a first message makes: the+ # user typed it. It wins over every writer here.+ self._book.put(req.kind, req.conv_id, TitleEntry(+ title=req.seed, writer=WRITER_USER, version=req.version,+ messages_at=req.message_count, seed=req.seed,+ ))+ continue+ entry = TitleEntry(+ title=tidy_title(user[:USER_TURNS_READ]),+ writer=WRITER_RULES,+ version=req.version,+ messages_at=req.message_count,+ seed=req.seed,+ attempts=previous.attempts if previous is not None else 0,+ )+ renewing = previous is not None and previous.writer == WRITER_MODEL+ if renewing and previous is not None and previous.seed == req.seed:+ # Keep the model's title on screen while a renewal is pending.+ entry = TitleEntry(+ title=previous.title, writer=WRITER_MODEL, version=req.version,+ messages_at=previous.messages_at, seed=req.seed,+ )+ self._book.put(req.kind, req.conv_id, entry)+ if model and user and time.monotonic() >= self._quiet_until:+ convo = Conversation(user=user[:USER_TURNS_READ], reply=reply)+ for_model.append((req, convo, entry))+ for start in range(0, len(for_model), MODEL_BATCH):+ if time.monotonic() < self._quiet_until:+ break+ self._name_with_model(for_model[start:start + MODEL_BATCH])++ def _name_with_model(+ self, chunk: Sequence[tuple[TitleRequest, Conversation, TitleEntry]]+ ) -> None:+ brain = self._brain_factory()+ if brain is None:+ # No subscription: rules titles stand. Ask again only after a long+ # pause — a key-only install would otherwise re-read its history+ # every few minutes for a model it will never get.+ self._quiet_until = time.monotonic() + NO_SUBSCRIPTION_QUIET_S+ return+ try:+ answer = asyncio.run(_complete(brain, [c for _, c, _ in chunk]))+ except Exception as exc: # noqa: BLE001 - the rules title stands; logged+ self._model_failures += 1+ log.info("chat titles: the model could not write (%s)", type(exc).__name__)+ if self._model_failures >= MODEL_FAILURES_BEFORE_QUIET:+ self._quiet_until = time.monotonic() + MODEL_QUIET_S+ for req, _, entry in chunk:+ entry.attempts += 1+ self._book.put(req.kind, req.conv_id, entry)+ return+ self._model_failures = 0+ titles = parse_answer(answer, len(chunk))+ for index, (req, _, entry) in enumerate(chunk):+ if index not in titles:+ entry.attempts += 1+ self._book.put(req.kind, req.conv_id, entry)+ continue+ self._book.put(req.kind, req.conv_id, TitleEntry(+ title=titles[index], writer=WRITER_MODEL, version=req.version,+ messages_at=req.message_count, seed=req.seed,+ ))+++async def _complete(brain: Any, conversations: Sequence[Conversation]) -> str:+ from jarvis.core.protocols import BrainMessage, BrainRequest++ request = BrainRequest(+ messages=(BrainMessage(role="user", content=build_prompt(conversations)),),+ system=_SYSTEM,+ temperature=0.1,+ max_tokens=60 + 30 * len(conversations),+ stream=True,+ reasoning_effort="none",+ )+ chunks: list[str] = []++ async def collect() -> None:+ async for delta in brain.complete(request):+ if delta.content:+ chunks.append(delta.content)++ await asyncio.wait_for(collect(), timeout=MODEL_TIMEOUT_S + 15.0)+ return "".join(chunks)+++# ----------------------------------------------------------------------+# Process-wide titler+# ----------------------------------------------------------------------++_shared: dict[str, ChatTitler] = {}+_shared_lock = threading.Lock()+++def titler_in(folder: str | Path | None) -> ChatTitler:+ """The titler whose book lives in *folder*.++ ``None`` gives a rules-only titler: no durable book, no background thread+ and no model call — nothing worth paying for that could not be kept.+ """+ key = str(Path(folder).resolve()) if folder else ":memory:"+ with _shared_lock:+ titler = _shared.get(key)+ if titler is None:+ if folder:+ titler = ChatTitler(TitleBook(Path(folder) / "chat_titles.db"))+ else:+ titler = ChatTitler(TitleBook(":memory:"), background=False)+ _shared[key] = titler+ return titler+++def titler_for_state(state: Any) -> ChatTitler:+ """The titler for a web app's state: its book sits in the configured data folder."""+ config = getattr(state, "config", None)+ if config is None:+ return titler_in(None)+ memory = getattr(config, "memory", None)+ return titler_in(getattr(memory, "data_dir", None) or "./data")+++def reset_for_tests() -> None:+ with _shared_lock:+ for titler in _shared.values():+ titler.close()+ _shared.clear()diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.pyindex 7d2d2835b8..749fda2e74 100644--- a/jarvis/ui/web/agent_chat_routes.py+++ b/jarvis/ui/web/agent_chat_routes.py@@ -700,9 +700,65 @@ async def list_sessions(d = s.to_dict()d["running"] = svc.is_running(s.session_id)out.append(d)+ _title_jarvis_chats(request, svc, out)return {"sessions": out}+def _title_jarvis_chats(request: Request, svc: Any, rows: list[dict[str, Any]]) -> None:+ """Give the Jarvis chats a topic title instead of their first words.++ Only the ``jarvis`` surface — the front page's own history — is retitled;+ an agent's chat keeps the title its first message gave it. A title the user+ typed is recognised by the titler and kept.+ """+ from jarvis.agent_chat.store import _title_from+ from jarvis.sessions import chat_titles++ now = int(time.time() * 1000)+ requests: list[chat_titles.TitleRequest] = []+ for row in rows:+ if row.get("surface") != "jarvis":+ continue+ sid = str(row["session_id"])++ def load(sid: str = sid) -> list[tuple[str, str]]:+ texts: list[tuple[str, str]] = []+ for event in svc.store.list_events(sid):+ text = str((event.get("payload") or {}).get("text") or "")+ if event["kind"] == "user_message":+ texts.append(("user", text))+ elif event["kind"] == "agent_message":+ texts.append(("agent", text))+ elif event["kind"] == "assistant_text":+ texts.append(("assistant", text))+ return texts++ updated = int(row.get("updated_ms") or 0)+ requests.append(chat_titles.TitleRequest(+ kind=chat_titles.KIND_TYPED,+ conv_id=sid,+ version=str(int(row.get("message_count") or 0)),+ message_count=int(row.get("message_count") or 0),+ updated_ms=updated,+ settled=not row.get("running")+ and now - updated >= chat_titles.TYPED_SETTLE_S * 1000,+ seed=str(row.get("title") or ""),+ loader=load,+ auto_title=_title_from,+ ))+ if not requests:+ return+ try:+ titles = chat_titles.titler_for_state(request.app.state).titles_for(requests)+ except Exception: # noqa: BLE001 - the stored title is a fine answer; logged+ log.warning("Jarvis chat titles unavailable, keeping the stored ones", exc_info=True)+ return+ for row in rows:+ key = (chat_titles.KIND_TYPED, str(row["session_id"]))+ if key in titles:+ row["title"] = titles[key]++@router.post("/sessions", status_code=201)async def create_session(body: CreateSessionBody, request: Request) -> dict[str, Any]:svc = _service(request)diff --git a/jarvis/ui/web/chats_routes.py b/jarvis/ui/web/chats_routes.pyindex 4c3e7375a1..5fd273807a 100644--- a/jarvis/ui/web/chats_routes.py+++ b/jarvis/ui/web/chats_routes.py@@ -31,6 +31,8 @@ from typing import Anyfrom fastapi import APIRouter, HTTPException, Query, Requestfrom pydantic import BaseModel, Field+from jarvis.sessions import chat_titles+from jarvis.sessions.chat_titles import TitleRequestfrom jarvis.sessions.formatter import _jarvis_outputs_for_turnfrom jarvis.state.chat_store import ChatStorefrom jarvis.state.conversation_constants import (@@ -152,14 +154,15 @@ def _optional_pipeline(request: Request) -> Any | None:# -----------------------------------------------------------------------def _voice_session_to_summary(s: Any) -> ConversationSummary:+def _voice_session_to_summary(s: Any, title: str = "") -> ConversationSummary:+ """A voice session as a history row. An empty ``title`` means "no topic"."""preview = getattr(s, "preview", "") or ""started = int(getattr(s, "started_ms", 0) or 0)ended = getattr(s, "ended_ms", None)return ConversationSummary(kind=CONVERSATION_KIND_VOICE,id=str(s.id),- title=preview or "Voice session",+ title=title,preview=preview,created_ms=started,updated_ms=int(ended) if ended else started,@@ -331,15 +334,56 @@ def _seed_pairs(messages: list[ChatTurn]) -> list[tuple[str, str]]:return pairs[-_SEED_MAX_MESSAGES:]+def _voice_title_request(+ s: Any, chat_store: ChatStore, session_store: Any+) -> TitleRequest:+ """What the titler needs to name one voice session (read lazily, off-request)."""+ sid = str(s.id)+ ended = getattr(s, "ended_ms", None)++ def load() -> list[tuple[str, str]]:+ messages = _normalized_messages(CONVERSATION_KIND_VOICE, sid, chat_store, session_store)+ return [(m.role, m.text) for m in messages or []]++ return TitleRequest(+ kind=chat_titles.KIND_VOICE,+ conv_id=sid,+ version=str(ended or ""),+ message_count=int(getattr(s, "turn_count", 0) or 0),+ updated_ms=int(ended or getattr(s, "started_ms", 0) or 0),+ settled=ended is not None,+ seed=str(getattr(s, "preview", "") or ""),+ loader=load,+ )+++def _voice_titles(+ request: Request, sessions: list[Any], chat_store: ChatStore, session_store: Any+) -> dict[tuple[str, str], str]:+ """Topic titles for voice sessions; the rules over the preview if the titler fails."""+ requests = [_voice_title_request(s, chat_store, session_store) for s in sessions]+ try:+ return chat_titles.titler_for_state(request.app.state).titles_for(requests)+ except Exception: # noqa: BLE001 - a title is never worth an empty history+ log.warning("chat titles unavailable, using the plain rules", exc_info=True)+ return {(r.kind, r.conv_id): chat_titles.tidy_title([r.seed]) for r in requests}++def _conversation_title(- kind: str, cid: str, chat_store: ChatStore, session_store: Any | None+ request: Request,+ kind: str,+ cid: str,+ chat_store: ChatStore,+ session_store: Any | None,) -> str:if kind == CONVERSATION_KIND_TEXT:thread = chat_store.get_thread(cid)return (thread or {}).get("title", "") if thread else ""if kind == CONVERSATION_KIND_VOICE and session_store is not None:- session = session_store.get_session(cid)- return "Voice session" if session is not None else ""+ if session_store.get_session(cid) is None:+ return ""+ titler = chat_titles.titler_for_state(request.app.state)+ return titler.known(chat_titles.KIND_VOICE, cid)return ""@@ -366,8 +410,11 @@ def list_conversations(]if session_store is not None:try:- for s in session_store.list_sessions(limit=limit, include_empty=False):- items.append(_voice_session_to_summary(s))+ sessions = session_store.list_sessions(limit=limit, include_empty=False)+ titles = _voice_titles(request, sessions, chat_store, session_store)+ for s in sessions:+ title = titles.get((chat_titles.KIND_VOICE, str(s.id)), "")+ items.append(_voice_session_to_summary(s, title))except Exception as exc: # noqa: BLE001 — voice list must never 500 the pagelog.warning("voice session list failed, showing text-only: %s", exc)@@ -447,7 +494,7 @@ async def get_conversation(return ConversationDetail(kind=kind,id=cid,- title=_conversation_title(kind, cid, chat_store, session_store),+ title=_conversation_title(request, kind, cid, chat_store, session_store),messages=messages,)@@ -475,7 +522,7 @@ async def resume_conversation(return ResumeResponse(kind=kind,id=cid,- title=_conversation_title(kind, cid, chat_store, session_store),+ title=_conversation_title(request, kind, cid, chat_store, session_store),messages=messages,seeded_turns=seeded,)diff --git a/jarvis/ui/web/frontend/src/components/QuickSwitchList.tsx b/jarvis/ui/web/frontend/src/components/QuickSwitchList.tsxindex af98c879aa..da36e0c605 100644--- a/jarvis/ui/web/frontend/src/components/QuickSwitchList.tsx+++ b/jarvis/ui/web/frontend/src/components/QuickSwitchList.tsx@@ -26,7 +26,7 @@ import { useHomeStore } from "@/store/home";import { useSettingsJump } from "@/store/settingsJump";import { useIdeProjectsStore } from "@/store/ideProjects";import { useIdeSidePanelStore } from "@/store/ideSidePanel";-import { formatChatWhen, useChatRows, type ChatRow } from "@/components/home/chatRows";+import { chatRowLabel, formatChatWhen, useChatRows, type ChatRow } from "@/components/home/chatRows";import {fetchIdeProjects,fetchWorkspacePanes,@@ -312,7 +312,7 @@ export function QuickSwitchList({value={`chat:${row.kind}:${row.id}`}testId={`quick-switch-chat-${row.id}`}icon={row.kind === "voice" ? VoiceIcon : ChatIcon}- label={row.title || t("quick_switch.untitled_chat")}+ label={chatRowLabel(row, t).text}detail={formatChatWhen(row.updatedMs)}size={size}onSelect={() => goToChat(row)}diff --git a/jarvis/ui/web/frontend/src/components/home/AllChatsDialog.tsx b/jarvis/ui/web/frontend/src/components/home/AllChatsDialog.tsxindex 0387064736..1350bd23c6 100644--- a/jarvis/ui/web/frontend/src/components/home/AllChatsDialog.tsx+++ b/jarvis/ui/web/frontend/src/components/home/AllChatsDialog.tsx@@ -1,10 +1,11 @@import { useEffect, useMemo, useRef, useState } from "react";import * as Dialog from "@radix-ui/react-dialog";-import { MessageSquare, Mic, Search, Trash2, X } from "lucide-react";+import { Search, Trash2, X } from "lucide-react";import { useT } from "@/i18n";import { cn } from "@/lib/utils";import {+ chatRowLabel,filterChatRows,formatChatWhen,groupChatRows,@@ -221,8 +222,8 @@ function ArchiveRow({}) {const t = useT();const isVoice = row.kind === "voice";- const Icon = isVoice ? Mic : MessageSquare;- const title = row.title || t("chats_view.new_chat");+ const label = chatRowLabel(row, t);+ const title = label.text;const preview = row.preview && row.preview !== title ? row.preview : "";return (<li className="group relative">@@ -238,17 +239,23 @@ function ArchiveRow({active ? "bg-background/80" : "hover:bg-background/50",)}>- <Icon- aria-hidden- className={cn("mt-0.5 h-3.5 w-3.5 shrink-0", active ? "text-primary" : "text-muted-foreground")}- /><span className="min-w-0 flex-1">- <span className="block truncate text-xs font-medium text-foreground">{title}</span>+ <span+ className={cn(+ "block truncate text-xs font-medium",+ label.untitled ? "text-muted-foreground" : "text-foreground",+ )}+ >+ {title}+ </span>{preview && (<span className="mt-0.5 block truncate text-xs text-muted-foreground">{preview}</span>)}</span>- <span className="mt-0.5 shrink-0 pr-6 font-mono text-micro tabular-nums text-muted-foreground">+ {/* The kind is said in words, once, beside the time — not as a glyph+ on every row. A topicless voice chat already names it. */}+ <span className="mt-0.5 shrink-0 pr-6 text-micro tabular-nums text-muted-foreground">+ {isVoice && !label.untitled && `${t("all_chats.filter_voice")} · `}{formatChatWhen(row.updatedMs)}</span></button>diff --git a/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx b/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsxindex 5b300de0af..8322470a19 100644--- a/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx+++ b/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx@@ -106,6 +106,31 @@ describe("RecentChats", () => {]);});+ it("lists chats as plain titles and names a topicless voice chat by its kind", async () => {+ useEventStore.setState({+ conversations: [...CONVERSATIONS, { ...row("voice", "v2", ""), preview: "Hallo" }],+ });+ render(<RecentChats />);+ // No per-row glyphs: the title is the row.+ for (const item of screen.getAllByTestId("recent-chat-row")) {+ expect(item.querySelector("svg")).toBeNull();+ }+ const voice = screen.getByRole("button", { name: "Voice: Spoken thread" });+ expect(voice.getAttribute("data-kind")).toBe("voice");+ // A voice chat with no topic never shows its first words as a headline.+ expect(screen.queryByText("Hallo")).toBeNull();+ const untitled = screen.getAllByTestId("recent-chat-row").find(+ (item) => item.textContent?.startsWith("Voice chat"),+ );+ expect(untitled?.querySelector(".text-muted-foreground")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Pin chat: Spoken thread" }));+ expect(screen.getByTestId("pinned-chats").contains(+ screen.getByRole("button", { name: "Voice: Spoken thread" }),+ )).toBe(true);+ expect(screen.getAllByTitle("Spoken thread")).toHaveLength(1);+ await flush();+ });+it("opens an agent chat on the chat surface even from the voice stage", async () => {render(<RecentChats />);// The classic brain's text threads are no longer listed — the chatdiff --git a/jarvis/ui/web/frontend/src/components/home/RecentChats.tsx b/jarvis/ui/web/frontend/src/components/home/RecentChats.tsxindex 16b2b22ec8..f57208ba3b 100644--- a/jarvis/ui/web/frontend/src/components/home/RecentChats.tsx+++ b/jarvis/ui/web/frontend/src/components/home/RecentChats.tsx@@ -1,11 +1,11 @@import { useEffect, useState } from "react";-import { Archive, MessageSquare, Pin, PinOff, Trash2 } from "lucide-react";+import { Archive, Pin, PinOff, Trash2 } from "lucide-react";import { useAgentChatStore } from "@/store/agentChat";import { useT } from "@/i18n";import { cn } from "@/lib/utils";import { AllChatsDialog } from "@/components/home/AllChatsDialog";-import { useChatRows, type ChatRow } from "@/components/home/chatRows";+import { chatRowLabel, useChatRows, type ChatRow } from "@/components/home/chatRows";import { CONVERSATIONS_REFRESH_MS } from "@/hooks/useConversations";@@ -121,32 +121,36 @@ function ChatRowItem({onPin: () => void;}) {const t = useT();- const title = row.title || t("chats_view.new_chat");+ const label = chatRowLabel(row, t);+ const title = label.text;return (<li className="group relative"><buttontype="button"onClick={onOpen}title={title}- aria-label={title}+ aria-label={row.kind === "voice" && !label.untitled ? `${t("all_chats.filter_voice")}: ${title}` : title}data-testid="recent-chat-row"data-kind={row.kind}className={cn(- "flex h-8 w-full items-center gap-3 rounded-lg px-3 text-left transition-colors group-hover:pr-16 group-focus-within:pr-16",+ "flex h-8 w-full items-center rounded-lg px-3 text-left transition-colors group-hover:pr-16 group-focus-within:pr-16","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",// The open one wears the same accent edge as the active nav row, so// "where am I" is said in one voice all the way down the column.active ? "jarvis-nav-active bg-secondary text-foreground-strong" : "text-foreground hover:bg-secondary",)}>- {/* A small open ring, the Claude app's chat bullet; a pinned chat- keeps its bubble so the two lists stay told apart. */}- {pinned ? (- <MessageSquare aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />- ) : (- <span aria-hidden className="ml-1 h-[7px] w-[7px] shrink-0 rounded-full border border-muted-foreground" />- )}- <span className="min-w-0 flex-1 truncate text-base leading-5">{compactChatTitle(title)}</span>+ {/* Text only, the way the Claude and ChatGPT columns list chats: one+ glyph repeated on every row is noise, not information. A chat with+ no topic says what it was ("Voice chat · 09:42"), in a quieter tone. */}+ <span+ className={cn(+ "min-w-0 flex-1 truncate text-base leading-5",+ label.untitled && !active && "text-muted-foreground",+ )}+ >+ {compactChatTitle(title)}+ </span></button><button type="button" onClick={onPin} title={t(pinned ? "sidebar.unpin_chat" : "sidebar.pin_chat")}diff --git a/jarvis/ui/web/frontend/src/components/home/chatRows.ts b/jarvis/ui/web/frontend/src/components/home/chatRows.tsindex c03a5596a9..c296b703e5 100644--- a/jarvis/ui/web/frontend/src/components/home/chatRows.ts+++ b/jarvis/ui/web/frontend/src/components/home/chatRows.ts@@ -67,7 +67,10 @@ export function useChatRows({ poll = false }: { poll?: boolean } = {}): ChatRows.map((c) => ({kind: "voice",id: c.id,- title: c.title || c.preview,+ // The backend names each chat by its topic; "" means it has none, and+ // the row then says what kind of chat it was (chatRowLabel) instead+ // of promoting its first words ("Hallo", "Kannst") to a headline.+ title: c.title,preview: c.preview,updatedMs: c.updated_ms,messageCount: c.message_count,@@ -77,7 +80,7 @@ export function useChatRows({ poll = false }: { poll?: boolean } = {}): ChatRowsconst agent: ChatRow[] = sessions.map((s) => ({kind: "agent",id: s.session_id,- title: s.title || s.preview,+ title: s.title,preview: s.preview,updatedMs: s.updated_ms,messageCount: s.message_count,@@ -131,6 +134,21 @@ export function useChatRows({ poll = false }: { poll?: boolean } = {}): ChatRowsreturn { rows, isActive, open, remove };}+/**+ * What a row is called: its topic, or — when it has none — what it was.+ * ``untitled`` lets a list set those rows in a quieter tone.+ */+export function chatRowLabel(row: ChatRow, t: (key: string) => string): { text: string; untitled: boolean } {+ const title = row.title.trim();+ if (title) return { text: title, untitled: false };+ if (row.kind === "voice") {+ const when = formatChatWhen(row.updatedMs);+ const kind = t("sidebar.untitled_voice_chat");+ return { text: when ? `${kind} · ${when}` : kind, untitled: true };+ }+ return { text: t("chats_view.new_chat"), untitled: true };+}+/** Short time for a row: clock today, day + month before that. */export function formatChatWhen(ms: number): string {if (!ms) return "";diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex f32678662f..7d35769d36 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -556,6 +556,7 @@"surface_hint": "Startseite zwischen Sprache und getipptem Chat umschalten","new_chat": "Neuer Chat","new_voice_chat": "Neuer Voice-Chat",+ "untitled_voice_chat": "Sprachchat","recent_chats": "Letzte Chats","show_all": "Alle anzeigen","show_less": "Weniger anzeigen",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex cce20821a0..bfe1ababbf 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -556,6 +556,7 @@"surface_hint": "Switch the front page between voice and typed chat","new_chat": "New chat","new_voice_chat": "New voice chat",+ "untitled_voice_chat": "Voice chat","recent_chats": "Recent chats","show_all": "Show all","show_less": "Show less",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex c034c9657a..3ffca4e705 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -556,6 +556,7 @@"surface_hint": "Cambiar la página de inicio entre voz y chat escrito","new_chat": "Nuevo chat","new_voice_chat": "Nuevo chat de voz",+ "untitled_voice_chat": "Chat de voz","recent_chats": "Chats recientes","show_all": "Mostrar todo","show_less": "Mostrar menos",diff --git a/scripts/ci/german-allowlist.txt b/scripts/ci/german-allowlist.txtindex 7a4f3b6546..0ae4aa27ea 100644--- a/scripts/ci/german-allowlist.txt+++ b/scripts/ci/german-allowlist.txt@@ -472,3 +472,9 @@ jarvis/society/focus.py# --- Local voice engine bench (2026-10-01): the German speech-input corpus the# P0 bench renders, transcribes and sends to the local LLM (ADR-0037) ---jarvis/voice_engine/bench/corpus/de.json++# --- Chat history titles (2026-10-02): the closed de/en/es greeting, small-talk+# and polite lead-in vocabulary the rules strip from spoken openings, and the+# real transcripts that pin it ---+jarvis/sessions/chat_titles.py+tests/unit/sessions/test_chat_titles.pydiff --git a/tests/unit/sessions/test_chat_titles.py b/tests/unit/sessions/test_chat_titles.pynew file mode 100644index 0000000000..cf780bb17d--- /dev/null+++ b/tests/unit/sessions/test_chat_titles.py@@ -0,0 +1,246 @@+"""Chat history titles: a topic, never the greeting the conversation opened with."""++from __future__ import annotations++from collections.abc import AsyncIterator+from dataclasses import dataclass, field++import pytest++from jarvis.core.protocols import BrainDelta, BrainRequest+from jarvis.sessions import chat_titles+from jarvis.sessions.chat_titles import (+ ChatTitler,+ TitleBook,+ TitleRequest,+ clean_model_title,+ parse_answer,+ tidy_title,+)++# --------------------------------------------------------------------- rules+++ "utterances",+ [+ ["Was geht ab"],+ ["Hallo"],+ ["Was"],+ ["Kannst"],+ ["Kannst du"],+ ["Was geht ab", "ähm, nichts", "ähm", ", ähm, ähm"],+ ["Was geht ab", "Nicht so viel", ". Hallo"],+ ["Hi. What's good up", "Mm."],+ [""],+ [],+ ],+)+def test_greetings_and_fragments_have_no_topic(utterances: list[str]) -> None:+ assert tidy_title(utterances) == ""+++ ("utterances", "title"),+ [+ (["Hallo was geht ab Kannst du bitte meine gmail Analysieren"],+ "Meine gmail Analysieren"),+ (["Ich verspre... Was ist Personal Jarvis? Was ist es überhaupt"],+ "Was ist Personal Jarvis"),+ (["Weißt du noch worum es ging"], "Weißt du noch worum es ging"),+ (["Browser acceptance"], "Browser acceptance"),+ (["Hey George, hallo", "Can you please summarize my inbox"], "Summarize my inbox"),+ (["Hi, was geht ab? Kannst du bitte schnell sagen, was alles zu tun ist?"],+ "Sagen, was alles zu tun ist"),+ ],+)+def test_the_request_survives_its_lead_in(utterances: list[str], title: str) -> None:+ assert tidy_title(utterances) == title+++def test_split_voice_segments_are_read_as_one_sentence() -> None:+ title = tidy_title([+ "Hey George, was geht ab",+ "Kannst du bitte mal",+ "einen ähm einen Claude Code Agent spawnen. Er soll einen Deep Dive machen",+ ])+ assert title == "Einen Claude Code Agent spawnen"+++def test_transcription_annotations_are_dropped() -> None:+ assert tidy_title(["Was geht ab [tongue click", "Kannst du bitte das Wetter prüfen"]) == (+ "Das Wetter prüfen"+ )+ assert tidy_title(["[laughs] Plan the next release"]) == "Plan the next release"+++def test_long_titles_end_at_a_clause_or_say_they_were_cut() -> None:+ clause = tidy_title([+ "Kannst du für mich bitte einen neuen Jarvis-Agent erstellen namens Trendfinder, "+ "und ich möchte, dass er jeden Tag die besten Projekte analysiert"+ ])+ assert clause == "Einen neuen Jarvis-Agent erstellen namens Trendfinder"+ cut = tidy_title(["Research " + " ".join(f"topic{n}" for n in range(30))])+ assert cut.endswith("…") and len(cut) <= chat_titles.TITLE_MAX_CHARS+++# --------------------------------------------------------------------- model+++def test_model_answers_are_parsed_by_number_and_cleaned() -> None:+ answer = '1: "Security-Audit für den Workspace".\n2: -\nnoise\n3) **Wetter in Berlin**\n9: x'+ assert parse_answer(answer, 3) == {+ 0: "Security-Audit für den Workspace",+ 1: "",+ 2: "Wetter in Berlin",+ }+ assert clean_model_title("—") == ""+++@dataclass+class _ScriptedBrain:+ """Answers every request with one scripted text; records the prompts."""++ answer: str+ prompts: list[BrainRequest] = field(default_factory=list)++ async def complete(self, request: BrainRequest) -> AsyncIterator[BrainDelta]:+ self.prompts.append(request)+ yield BrainDelta(content=self.answer)+++class _FailingBrain:+ async def complete(self, request: BrainRequest) -> AsyncIterator[BrainDelta]:+ raise RuntimeError("subscription rate limited")+ yield BrainDelta() # pragma: no cover - makes this an async generator+++def _voice(conv_id: str, user: list[str], *, settled: bool = True, seed: str = "") -> TitleRequest:+ return TitleRequest(+ kind=chat_titles.KIND_VOICE,+ conv_id=conv_id,+ version="2000" if settled else "",+ message_count=len(user),+ updated_ms=2_000,+ settled=settled,+ seed=seed or (user[0] if user else ""),+ loader=lambda: [("user", text) for text in user] + [("assistant", "Klar.")],+ )+++def _drain_queue(titler: ChatTitler) -> None:+ """Run the queued work on this thread, the way the worker would."""+ batch = list(titler._queue.values())+ titler._queue.clear()+ titler.drain(batch)+++def _titler(brain: object | None) -> ChatTitler:+ titler = ChatTitler(TitleBook(), brain_factory=lambda: brain)+ # Keep the work on the test thread.+ titler._ensure_worker = lambda: None # type: ignore[method-assign]+ return titler+++def test_listing_answers_at_once_and_the_model_names_settled_chats() -> None:+ brain = _ScriptedBrain("1: Claude-Code-Agent für Deep Dive\n2: -")+ titler = _titler(brain)+ requests = [+ _voice("a", ["Hey George, was geht ab", "Kannst du einen Agent spawnen"]),+ _voice("b", ["Hallo"]),+ ]+ first = titler.titles_for(requests)+ assert first == {("voice", "a"): "", ("voice", "b"): ""}++ _drain_queue(titler)+ assert titler.titles_for(requests) == {+ ("voice", "a"): "Claude-Code-Agent für Deep Dive",+ ("voice", "b"): "",+ }+ assert len(brain.prompts) == 1 # both conversations in one call+ prompt = brain.prompts[0].messages[0].content+ assert "Conversation 2:" in prompt and "Kannst du einen Agent spawnen" in prompt+++def test_unsettled_chats_get_rules_only() -> None:+ brain = _ScriptedBrain("1: Should not be asked")+ titler = _titler(brain)+ request = _voice("live", ["Kannst du bitte das Wetter prüfen"], settled=False)+ titler.titles_for([request])+ _drain_queue(titler)+ assert titler.titles_for([request]) == {("voice", "live"): "Das Wetter prüfen"}+ assert brain.prompts == []+++def test_without_a_subscription_the_rules_title_stands() -> None:+ titler = _titler(None)+ request = _voice("a", ["Hallo", "Kannst du bitte das Wetter prüfen"])+ titler.titles_for([request])+ _drain_queue(titler)+ assert titler.titles_for([request]) == {("voice", "a"): "Das Wetter prüfen"}+++def test_a_failing_model_keeps_the_rules_title_and_goes_quiet() -> None:+ titler = _titler(_FailingBrain())+ requests = [_voice(str(n), [f"Kannst du bitte Thema {n} recherchieren"]) for n in range(2)]+ for _ in range(chat_titles.MODEL_FAILURES_BEFORE_QUIET):+ titler.titles_for(requests)+ _drain_queue(titler)+ assert titler.titles_for(requests)[("voice", "0")] == "Thema 0 recherchieren"+ assert titler._queue == {} # quiet: nothing re-queued for the model+++def test_a_title_the_user_typed_is_kept() -> None:+ brain = _ScriptedBrain("1: Model title")+ titler = _titler(brain)+ request = TitleRequest(+ kind=chat_titles.KIND_TYPED,+ conv_id="t1",+ version="4",+ message_count=4,+ updated_ms=1,+ settled=True,+ seed="My release notes",+ loader=lambda: [("user", "Hallo was geht ab"), ("assistant", "Hi!")],+ auto_title=lambda text: " ".join(text.split()),+ )+ titler.titles_for([request])+ _drain_queue(titler)+ assert titler.titles_for([request]) == {("agent", "t1"): "My release notes"}+ assert brain.prompts == []+++def test_a_short_typed_title_is_shown_as_is_before_the_read() -> None:+ titler = _titler(None)+ request = TitleRequest(+ kind=chat_titles.KIND_TYPED, conv_id="t2", version="1", message_count=1,+ updated_ms=1, settled=False, seed="Budget",+ loader=lambda: [("user", "Plan next month")], auto_title=lambda text: text,+ )+ # The rules alone would blank a one-word title; the user may have typed it.+ assert titler.titles_for([request]) == {("agent", "t2"): "Budget"}+++def test_titles_survive_a_restart(tmp_path) -> None:+ book_path = tmp_path / "chat_titles.db"+ titler = ChatTitler(TitleBook(book_path), brain_factory=lambda: _ScriptedBrain("1: Wetter"))+ titler._ensure_worker = lambda: None # type: ignore[method-assign]+ request = _voice("a", ["Kannst du das Wetter prüfen"])+ titler.titles_for([request])+ _drain_queue(titler)++ reopened = ChatTitler(TitleBook(book_path), brain_factory=lambda: None)+ reopened._ensure_worker = lambda: None # type: ignore[method-assign]+ assert reopened.titles_for([request]) == {("voice", "a"): "Wetter"}+ assert reopened._queue == {}+++def test_an_app_without_a_data_folder_never_queues_work() -> None:+ chat_titles.reset_for_tests()+ try:+ titler = chat_titles.titler_in(None)+ request = _voice("a", ["Hallo", "Kannst du das Wetter prüfen"], seed="Hallo")+ assert titler.titles_for([request]) == {("voice", "a"): ""}+ assert titler._queue == {} and titler._thread is None+ finally:+ chat_titles.reset_for_tests()