Add note context visibility in chat and standardize UI design tokens

Improve chat context: build_context() now returns metadata about auto-found
notes, emitted as an SSE event so the frontend can display context pills
showing which notes influenced the response. Users can promote notes for
deeper context (+) or exclude irrelevant ones (x). A note picker lets users
manually attach notes. Multi-word search uses per-term AND matching, and
auto-search iterates keywords individually for broader OR-style coverage.

Standardize styling: introduce CSS design tokens (--radius-sm/md/lg/pill,
--color-success/warning/overlay, --focus-ring) and migrate all components
to use them. Fix header alignment to full-width, add active nav link state,
replace hardcoded colors with CSS variables, and normalize button padding.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-11 06:49:12 -05:00
parent 39bcd7a8fa
commit fb18d2c41d
26 changed files with 1070 additions and 237 deletions
+8 -1
View File
@@ -85,6 +85,7 @@ async def send_message_route(conv_id: int):
if not content:
return jsonify({"error": "content is required"}), 400
context_note_id = data.get("context_note_id")
exclude_note_ids = data.get("exclude_note_ids") or []
# Save user message
await add_message(conv_id, "user", content, context_note_id=context_note_id)
@@ -96,11 +97,17 @@ async def send_message_route(conv_id: int):
history.append({"role": msg.role, "content": msg.content})
# Build context with note search, URL fetching, etc.
messages = await build_context(history, context_note_id, content)
messages, context_meta = await build_context(
history, context_note_id, content, exclude_note_ids=exclude_note_ids
)
model = conv.model or await get_setting("default_model", Config.OLLAMA_MODEL)
async def generate():
# Emit context metadata before streaming LLM response
context_event = json.dumps({"context": context_meta})
yield f"data: {context_event}\n\n"
full_response = []
try:
async for chunk in stream_chat(messages, model):
+26
View File
@@ -1,10 +1,29 @@
import httpx
from quart import Blueprint, jsonify, request
from fabledassistant.config import Config
from fabledassistant.services.settings import get_all_settings, set_setting
settings_bp = Blueprint("settings", __name__, url_prefix="/api/settings")
async def _get_installed_models() -> set[str]:
"""Return set of installed Ollama model names, with and without :latest."""
try:
async with httpx.AsyncClient(timeout=5.0) as client:
resp = await client.get(f"{Config.OLLAMA_URL}/api/tags")
resp.raise_for_status()
data = resp.json()
names: set[str] = set()
for m in data.get("models", []):
name = m["name"]
names.add(name)
names.add(name.replace(":latest", ""))
return names
except Exception:
return set()
@settings_bp.route("", methods=["GET"])
async def get_settings_route():
settings = await get_all_settings()
@@ -16,6 +35,13 @@ async def update_settings_route():
data = await request.get_json()
if not isinstance(data, dict):
return jsonify({"error": "Expected a JSON object"}), 400
if "default_model" in data:
model = str(data["default_model"])
installed = await _get_installed_models()
if installed and model not in installed:
return jsonify({"error": f"Model '{model}' is not installed"}), 400
for key, value in data.items():
await set_setting(key, str(value))
settings = await get_all_settings()
+7 -4
View File
@@ -14,10 +14,13 @@ async def create_conversation(title: str = "", model: str = "") -> Conversation:
conv = Conversation(title=title, model=model)
session.add(conv)
await session.commit()
await session.refresh(conv)
# Initialize empty messages list for to_dict()
conv.messages = []
return conv
# Re-fetch with messages eagerly loaded to avoid lazy-load in async context
result = await session.execute(
select(Conversation)
.options(selectinload(Conversation.messages))
.where(Conversation.id == conv.id)
)
return result.scalars().first()
async def get_conversation(conversation_id: int) -> Conversation | None:
+44 -19
View File
@@ -138,8 +138,14 @@ async def build_context(
history: list[dict],
current_note_id: int | None,
user_message: str,
) -> list[dict]:
"""Build messages array for Ollama with system prompt and context."""
exclude_note_ids: list[int] | None = None,
) -> tuple[list[dict], dict]:
"""Build messages array for Ollama with system prompt and context.
Returns (messages, context_meta) where context_meta contains info about
which notes were included as context.
"""
exclude_set = set(exclude_note_ids or [])
assistant_name = await get_setting("assistant_name", "Fable")
system_parts = [
f"You are a helpful assistant named {assistant_name}, integrated into a note-taking and task-tracking app called Fabled Assistant. "
@@ -147,10 +153,18 @@ async def build_context(
"When note context is provided, use it to give relevant answers."
]
context_meta: dict = {
"context_note_id": None,
"context_note_title": None,
"auto_notes": [],
}
# Include current note context if provided
if current_note_id:
note = await get_note(current_note_id)
if note:
context_meta["context_note_id"] = note.id
context_meta["context_note_title"] = note.title
system_parts.append(
f"\n\n--- Current Note ---\n"
f"Title: {note.title}\n"
@@ -158,28 +172,39 @@ async def build_context(
f"--- End Note ---"
)
# Search notes by keywords from user message
# Search notes by keywords from user message — search per keyword
# individually and deduplicate to get OR-style matching (any keyword hit
# is relevant context). Collect up to 3 unique notes.
keywords = _extract_keywords(user_message)
if keywords:
search_q = " ".join(keywords[:3])
try:
notes, _ = await list_notes(q=search_q, limit=3)
if notes:
snippets = []
seen_ids: set[int] = set()
snippets: list[str] = []
for kw in keywords[:5]:
if len(snippets) >= 3:
break
try:
notes, _ = await list_notes(q=kw, limit=3)
for n in notes:
# Skip the current note (already included)
if n.id in seen_ids:
continue
if current_note_id and n.id == current_note_id:
continue
body_preview = n.body[:300] if n.body else ""
if n.id in exclude_set:
continue
seen_ids.add(n.id)
body_preview = n.body[:2000] if n.body else ""
snippets.append(f"- {n.title}: {body_preview}")
if snippets:
system_parts.append(
"\n\n--- Related Notes ---\n"
+ "\n".join(snippets)
+ "\n--- End Related Notes ---"
)
except Exception:
pass
context_meta["auto_notes"].append({"id": n.id, "title": n.title})
if len(snippets) >= 3:
break
except Exception:
continue
if snippets:
system_parts.append(
"\n\n--- Related Notes ---\n"
+ "\n".join(snippets)
+ "\n--- End Related Notes ---"
)
# Fetch URL content from user message
urls = _find_urls(user_message)
@@ -193,4 +218,4 @@ async def build_context(
messages = [{"role": "system", "content": "".join(system_parts)}]
messages.extend(history)
messages.append({"role": "user", "content": user_message})
return messages
return messages, context_meta
+7 -5
View File
@@ -60,11 +60,13 @@ async def list_notes(
count_query = count_query.where(Note.status.is_(None))
if q:
escaped_q = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
pattern = f"%{escaped_q}%"
filter_ = or_(Note.title.ilike(pattern), Note.body.ilike(pattern))
query = query.where(filter_)
count_query = count_query.where(filter_)
terms = q.split()
for term in terms:
escaped_term = term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
pattern = f"%{escaped_term}%"
term_filter = or_(Note.title.ilike(pattern), Note.body.ilike(pattern))
query = query.where(term_filter)
count_query = count_query.where(term_filter)
if tags:
for i, tag in enumerate(tags):