Repository navigation
Auto-generate ai-chat titles via an idle-gated background task (closes #1698) - #2699
Conversation
…#1698) A new chat is created titled "Untitled". Once it has three messages, the model summarises it into a short title — but only while it is otherwise idle, in a context of its own, and never over a title the user set. The title is `node.content`: the ai-chat schema declares no `title` field and both display surfaces already read `content`, so this is a plain `NodeUpdate::with_content` and the frontend's existing `node:updated` refresh picks it up with no change. Scope is the AI-Chat UI. Titling is triggered from the tail of `run_ai_chat_turn`, the daemon-driven native turn path that UI drives. PTY-captured sessions never mint ai-chat nodes and never run that path, so an external agent's conversation is excluded structurally rather than by a provider name check — those keep their own `capture:summary`. Three things the issue's premises got wrong, confirmed by investigation: - `CompositeModelManager` does not exist. There is one `ModelManager`, `GgufModelManager`, and it never touches inference. - A one-shot isolated inference mechanism already existed, in the ReAct loop's own history summarization. `generate_title` follows that shape rather than inventing plumbing: its own `InferenceRequest`, `tools: None`, no session, nothing written back to `properties.messages`. - `has_active_turns()` is per-database while the engine is process-global, so a per-database gate would let one database's title job run into another's live turn. `ChatIdleGate` therefore lives on `SharedLocalAgent`. The gate sits above `generate()` rather than relying on the engine's own `inference_lock`: that lock is an unfair tokio `Mutex`, so a background job reaching it first would block the user's reply for a full generation. Mutual exclusion is not priority. Turns register via an RAII guard, so an early return, cancellation or panic cannot wedge the gate busy. The titler additionally waits for a quiet period, so it runs when the user has stopped rather than merely paused between two messages. The untitled guard is re-checked against freshly-read state immediately before the write, because generation takes seconds and the user may rename the chat while it runs. Losing that race drops the generated title, never the user's. Known consequence of a sentinel string rather than a separate flag: a user who types exactly "Untitled" is indistinguishable from an untitled chat and will have that title replaced once. This is the representation the issue specifies. Tests: 18 new Rust (daemon 216 -> 234) covering the untitled guard, the threshold, prompt sanitisation of model decoration and runaway replies, gate concurrency and panic-safety, deferral while a turn is in flight, and that generation never mutates the conversation. 8 new frontend tests pin the "Untitled" sentinel across the language boundary, where a drift would disable titling silently. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Pragmatic Code Review — PR #2699Review Type: Initial Review SummaryA genuinely well-executed change, and one of the better-documented ones I have reviewed. The commit message corrects three stale premises in the issue with evidence rather than assertion, explains why the gate sits above I verified the areas flagged for scrutiny and found them sound. The One finding is worth fixing before merge — a load-bearing comment states a mechanism that is factually wrong. The rest is polish. Requirements Check (issue #1698)
Code Review Findings🟡-1 A load-bearing comment states a mechanism that is factually wrong📁 // Content only: leaving `properties` untouched means this cannot
// disturb the ai-chat namespace, and so cannot race the turn path's
// own message/status writes into a lost update.
let update = NodeUpdate::new().with_content(title.to_string());
The conclusion is still correct — there is no lost update — but for an entirely different reason than the one stated. The snapshot is read inside the same transaction as the version-gated This is worth fixing rather than leaving, because the comment is exactly the kind a future maintainer would lean on to justify skipping the retry loop, or to add a second content-only writer that bypasses OCC on the belief that content and properties are independently writable. They are not. Reword to name the real invariant. Engineering principle: comments explain why, and a why that is wrong is worse than no comment — it launders a false invariant into the next change. 🟢-2 The shutdown guard covers only the wait, not generation or the write📁 tokio::select! {
_ = shutdown.cancelled() => return,
_ = shared.idle_gate().wait_for_idle_stable(TITLE_QUIET_PERIOD) => {}
}Once this In practice this is benign: Wrapping the remainder in a Engineering principle: cancellation scope should match resource lifetime. A token guarding only the cheapest phase of a task offers less protection than its presence implies. 🟢-3 One background task is spawned per turn, with no single-flight guard📁
The re-read and OCC guard make this correct (only one write lands; the losers observe a titled chat and return). The cost is redundant inference: N parked tasks can each run a full generation before any one writes. On a small local model sharing one engine, that is precisely the contention the gate exists to prevent — merely displaced from "background vs. live" to "background vs. background". Notably the module doc already describes the fix as though it were present: "background jobs are serialised by the single worker that runs them." There is no such worker — each job is a bare Engineering principle: idempotent-under-retry is not the same as work-deduplicated. Correctness under concurrency does not imply efficiency under concurrency. 🟢-4
|
malibio
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review: COMMENT (approaching approve, no blockers — posted as a comment since GitHub blocks self-approval). Full findings in the review comment above: one 🟡 (a load-bearing comment in ai_chat_title.rs states a mechanism that is factually wrong — the conclusion holds, but via OCC rather than column scoping) and six 🟢 polish items. Concurrency, scope guard, and standards all verified sound.
…dicate All four addressed findings are the same class of defect — a comment or an export asserting a mechanism that does not exist. None change behaviour. 🟡 `ai_chat_title.rs`: the comment on the title write claimed that setting only `content` on the `NodeUpdate` keeps it from racing the turn path's message writes. That is wrong: `update_node` is a full-row read-modify-write and rewrites the `properties` column regardless (`node_service/crud.rs:896` sets `properties: Some(updated.properties.clone())` even when only content changed). The conclusion held, but via OCC — the row written back is a snapshot taken inside the version-checked transaction — not via column scoping. Left as written, it invited a future maintainer to delete the retry loop on a false premise, so the comment now says which mechanism actually carries the safety and warns against that specific simplification. 🟢 `chat_idle_gate.rs`: the module doc claimed background jobs are "serialised by the single worker that runs them". There is no such worker. Now states what is actually true — the gate is a liveness check, not a reservation, two jobs waking together both proceed, and correctness comes from the engine lock plus node-level OCC — and says that work which must not run concurrently with itself needs its own single-flight guard. 🟢 `sanitize_title`: doc advertised stripping a "title -" label form the code never handled. Narrowed to the colon form it does handle, with the reason (splitting on a dash would eat half a hyphenated title). 🟢 `isUntitledChat`: exported with no production caller — only its own tests. Deleted rather than kept, per the standing "delete unused code" rule. It also mirrored the daemon's `is_untitled` guard, and a second implementation of a guard that does not gate the write is a drift risk, not a convenience; `ai-chat-title.ts` now records that eligibility is the daemon's decision alone so the mirror is not reintroduced. Skipped, with reasons: - Wrapping `generate_title` and the write in the shutdown `select!` (🟢): the write is already OCC-safe against a closed database and the exposure is one generation, so the added nesting buys little. - A doc note that `TITLE_QUIET_PERIOD` also delays remote openai-compat providers (🟢): true, but it is a 5s delay on a background task. - Sidebar re-sorting when a title write bumps `modifiedAt` (🟢): unobservable today, since the chat was just used and is already at the top. Worth revisiting only if titling ever runs retroactively. Also verified, not changed: the reviewer's UTF-8 concern about `sanitize_title` does not hold — `trim_matches(|c: char|)`, `rsplit_once(char::is_whitespace)` and `chars().take(n)` are all char-oriented. Tests: 234 daemon, 26 frontend in the two touched files (was 30; the 4 removed covered the deleted predicate). quality:fix clean. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Review addressed — 4 of 7 findings, commit
|
Closes #1698.
A new chat is created titled
"Untitled". Once it has three messages, the model summarises it into a short title — but only while it is otherwise idle, in a context of its own, and never over a title the user set.Where the title lives
node.content. The ai-chat schema declares notitlefield (AiChatNode::into_nodesetstitle: None) and both display surfaces — the viewer header and the sidebar list — already readcontent. So the write is a plainNodeUpdate::with_content, and the frontend's existingnode:updatedrefresh picks it up with no frontend change required; that hook was already in the tree, commented "background titling updated a chat's content".Scope: the AI-Chat UI only
Titling is triggered from the tail of
run_ai_chat_turn— the daemon-driven native turn path the AI-Chat UI drives. PTY-captured sessions never mint ai-chat nodes (capture_service) and never run that path, so an external agent's conversation is excluded structurally rather than by a provider name check. Those keep their existingcapture:summary.Corrections to the issue's premises
Three things the issue stated turned out not to hold, all confirmed against the code:
CompositeModelManagerdoes not exist — zero hits repo-wide. There is oneModelManager,GgufModelManager, and it never touches inference (load()only flips a status enum).resolve_query.generate_titlefollows that established shape rather than inventing plumbing: its ownInferenceRequest,tools: None, no session, nothing written back toproperties.messages.has_active_turns()is per-database while the engine is process-global. A per-database gate would happily let one database's title job run into another's live turn, soChatIdleGatelives onSharedLocalAgent.Why a new gate rather than the engine's lock
ChatEnginealready serialises generations with aninference_lock, but it is an unfairtokio::Mutex: a background job that reaches it first holds it for a full generation and the user's reply queues behind work nobody asked for. Mutual exclusion is not priority, so the gate sits abovegenerate().EmbeddingScheduler, including the two subtle details (register before contending; arm theNotifiedfuture before re-reading) that prevent lost wakeups.Never clobbering a user's title
The untitled guard is re-checked against freshly-read state immediately before the write, not just before generating — generation takes seconds and the user may rename the chat while it runs. Losing that race drops the generated title, never the user's.
Known consequence, recorded on the issue: using a sentinel string rather than a separate flag means a user who types exactly
"Untitled"is indistinguishable from an untitled chat and will have that title replaced once. This is the representation the issue specifies (the alternative — treating empty content as the sentinel — was the existing convention and was considered).Adding a persisted "was auto-titled" flag was deliberately avoided: any key under the
ai-chatnamespace must be mirrored on both the Rust struct andconvert.rsor it is silently dropped on the next daemon write.Tests
Title:, quotes, trailing punctuation, multi-line) and runaway replies, gate concurrency and panic-safety, deferral while a turn is in flight (via the existingBlockingEngine), and that generation never mutates the conversation."Untitled"sentinel across the language boundary, where a drift would disable titling silently, and keep it distinct from the display-only"Untitled chat"placeholder.Full frontend suite: 247/247 files, 5092/5092 tests. The pre-push gate (
test:all+ cargo build + e2e) passed.Note
The 1 failing test in the baseline was a pre-existing cross-file timing flake unrelated to this work, filed separately as #2684.
🤖 Generated with Claude Code