A menu for what a chat may use, and three keys

Six smaller things, all of them about the interface not saying what is true.

The @ button only ever inserted the character, which the @ key already does
without a button. It becomes the scope menu: what this chat may use, switched
off per chat. Chat.scope_json is filtered inside resolve_tools AFTER the
capability, permission and instance gates -- exactly as chat.knowledge_bases
narrows knowledge_search -- so a crafted POST turning something on reaches a
tool the gates already removed, and there is a test that writes the column
directly to prove it. Absent means on, for every key, so "why is this off?" has
one answer. It is keyed on the gate rather than the tool name, so notes is one
switch rather than five. The switches carry no role="menuitem", deliberately:
ui.js closes a picker when a menuitem is clicked, which is right for an action
menu and wrong for a list you want to set several of -- which is why the menu
needs no JavaScript at all. Typing @ is untouched.

With no skills, nothing should mention them. tool.skills was gated on the family
alone, so somebody with an empty library was told "the list below gives each
one's name" above no list, handed skill_get, and watched the model spend a round
finding out. It requires skills now; the writing half moved to
tool.skills_write, which is deliberately not gated, because saving the first one
is what somebody with none most needs. And core.tool_list finally reads
tool_names, which had been resolved and documented with no fragment using it.

The composer's toolbar is one row again. .composer__actions is last in the DOM
with margin-left:auto, so the moment an agent chat added a connection, a
directory and a mode, Send and the microphone dropped to a second line.
chat.css has no media queries by design and the fix is not to add one:
.composer__context is the single child allowed to shrink and scroll sideways.
There is a test asserting the file still contains no @media.

The effort picker shows the level in force. "Effort: default" named no level and
was true of nothing in particular; chat.resolved_effort is the chat's own value
and build_request reads the same field, so what is shown is what is sent. The
model's default is a seed, copied onto the row at creation and on a model
change, and never consulted at request time -- a fallback would resurrect it
underneath a cleared effort and make "off" silently do nothing. "off" is a
sentinel and not an empty value, because start_chat declares Form("") and cannot
tell absent from empty: with value="" the reader picks off and gets high.

Alt+M dictates, Alt+R reads the last reply aloud, Ctrl+Enter sends from
anywhere. All three click the button that already does the job, so audio.js
keeps its one delegated listener. Alt+M and not Alt+D, which is the address bar
in Chrome and Firefox. Ctrl+Enter never means Stop -- Send and Stop are the same
element, and Esc already stops. Driven under a DOM stub before committing, per
the rule in CLAUDE.md, and tests/test_commands_js.py pins that every key has a
row in SHORTCUTS, since /help reads that list.

And the memory tooling, which had seven defects. The worst: memory_forget was a
case-insensitive substring first-match delete with nothing warning about it, so
forgetting "coffee" against "Drinks coffee black" and "Allergic to coffee"
silently removed whichever was older -- a wrong deletion nobody would ever find
out about, from a tool whose description invited exactly the short fragment that
misfires. It matches exactly first, then by substring, and refuses an ambiguous
one while naming what it matched. add() refuses an exact duplicate. The
at-the-limit refusal no longer tells the model to delete one to make room: past
the block's budget it is not shown all of them and would be guessing, which
feeds straight back into the first defect. And context.memories no longer claims
the memories "still apply", which nothing checks and which taught a model to
trust a stale one over what the person had just said.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jaroslav Beneš
2026-08-03 11:22:03 +02:00
parent 0e3133a1e7
commit 816f2ae957
21 changed files with 1547 additions and 102 deletions
+19
View File
@@ -332,6 +332,25 @@ def build_request(
EFFORTS = ("low", "medium", "high")
def resolved_effort(chat) -> str:
"""The effort this chat will actually send, or "" for none.
Its own value, and nothing else. The model's default is a **seed** applied
when the chat is created (`api/chats.py:_new_chat`) and on a model change,
and is deliberately not consulted here for two reasons. A chat's request
should be a function of the chat row alone -- the same rule that has PDF
text extracted once at upload and knowledge attachments copied. And a
fallback would break "off": `update_chat` stores `None` for a cleared
effort, a fallback would resurrect the model's default underneath it, and
the off option would silently do nothing.
The picker shows exactly this, which is the whole point of it existing:
"Effort: default" named no level and was true of nothing in particular.
"""
value = (getattr(chat, "params_json", None) or {}).get("reasoning_effort")
return value if value in EFFORTS else ""
def apply_effort(body: dict[str, Any], effort: str | None) -> None:
"""Put a chosen reasoning effort into a request body, in both forms."""
if not effort or effort not in EFFORTS:
+5 -1
View File
@@ -133,7 +133,11 @@ def context_variables(
"memory_limit": str(memories_service.MAX_MEMORY_CHARS),
"tool_names": _tool_names(offered),
"memories": memories_service.block(db, user) if "memory" in families else "",
"skills": skills_service.index_block(db, user) if "skills" in families else "",
"skills": (
skills_service.index_block(db, user, exclude=tools_service.scoped_skills_off(chat))
if "skills" in families
else ""
),
"knowledge_bases": "",
"document_names": "",
"agent_target": "",
+26 -4
View File
@@ -57,23 +57,45 @@ def get(db: DBSession, memory_id: str, user: User | None) -> Memory | None:
def add(db: DBSession, *, owner: User, content: str, author: str = AUTHOR_MODEL) -> Memory:
"""Record a fact. Raises ValueError when there is no room or nothing to say."""
"""Record a fact. Raises ValueError when there is no room or nothing to say.
An exact repeat returns the record that already exists rather than making a
second one. The prompt asks the model to check before adding -- it is shown
every memory, so it can -- but the same preference saved four times in
slightly different words is the commonest failure here, and it is worse than
wasted tokens: it makes `memory_forget` ambiguous for every one of them.
Wording handles the near-duplicates; this handles the exact ones, which is
the half a prompt cannot be relied on for.
"""
content = " ".join((content or "").split())
if not content:
raise ValueError("A memory cannot be empty.")
content = content[:MAX_MEMORY_CHARS]
existing = db.scalars(
select(Memory).where(Memory.owner_id == owner.id, Memory.content == content)
).first()
if existing is not None:
return existing
count = db.scalar(
select(func.count()).select_from(Memory).where(Memory.owner_id == owner.id)
)
if (count or 0) >= MAX_RECORDS:
# Deliberately does NOT say "remove one first". Past MAX_TOTAL_CHARS the
# injected block is truncated, so the model is not shown every memory
# and would be choosing blind -- and deleting the wrong one is not
# something anybody finds out about.
raise ValueError(
f"There are already {MAX_RECORDS} memories. Remove one first, or put "
f"this in a note instead."
f"There are already {MAX_RECORDS} memories, which is the limit, so "
f"nothing was saved. Do not remove one to make room — you are not "
f"shown all of them and would be guessing. Say that the limit has "
f"been reached, and put this in a note instead."
)
memory = Memory(
owner_id=owner.id,
content=content[:MAX_MEMORY_CHARS],
content=content,
author=author if author in (AUTHOR_USER, AUTHOR_MODEL) else AUTHOR_MODEL,
)
db.add(memory)
+28 -11
View File
@@ -23,6 +23,7 @@ from __future__ import annotations
import logging
import re
from collections.abc import Iterable
from sqlalchemy import select
from sqlalchemy.orm import Session as DBSession
@@ -72,18 +73,34 @@ def by_name(db: DBSession, name: str, user: User | None) -> Skill | None:
return db.scalar(visible(db, user).where(Skill.name == slugify(name)))
def enabled_for(db: DBSession, user: User | None) -> list[Skill]:
"""Skills that should appear in the index, oldest first for a stable order."""
def enabled_for(
db: DBSession, user: User | None, *, exclude: Iterable[str] = ()
) -> list[Skill]:
"""Skills that should appear in the index, oldest first for a stable order.
`exclude` is what one chat has switched off by name -- a narrowing of what
the library already allows, never a widening of it.
"""
if user is None:
return []
return list(
db.scalars(
visible(db, user)
.where(Skill.enabled.is_(True))
.order_by(Skill.name)
.limit(MAX_INDEX_SKILLS)
)
hidden = {slugify(name) for name in exclude}
rows = db.scalars(
visible(db, user)
.where(Skill.enabled.is_(True))
.order_by(Skill.name)
.limit(MAX_INDEX_SKILLS + len(hidden))
)
return [skill for skill in rows if skill.name not in hidden][:MAX_INDEX_SKILLS]
def count_enabled(db: DBSession, user: User | None, *, exclude: Iterable[str] = ()) -> int:
"""How many skills are available here at all.
Zero is what withdraws `skill_get` and `skill_edit`: reading and improving
are meaningless with nothing to read, and a model told to "read one with
skill_get" above a list that is not there spends a round finding out.
"""
return len(enabled_for(db, user, exclude=exclude))
def search(db: DBSession, user: User | None, needle: str, *, limit: int = 10) -> list[Skill]:
@@ -199,9 +216,9 @@ def delete(db: DBSession, skill: Skill) -> None:
db.commit()
def index_block(db: DBSession, user: User | None) -> str:
def index_block(db: DBSession, user: User | None, *, exclude: Iterable[str] = ()) -> str:
"""The one-line-per-skill listing that goes into the prompt."""
skills = enabled_for(db, user)
skills = enabled_for(db, user, exclude=exclude)
if not skills:
return ""
return "\n".join(f"- {skill.name}: {skill.description}" for skill in skills)
+43 -12
View File
@@ -801,7 +801,8 @@ BUILTIN: tuple[Fragment, ...] = (
"would be tedious to work out again: a procedure, a decision and its reasons, "
"a summary of a long document. Correct one with notes_edit when it turns out "
"to be wrong, and remove it with notes_delete when it is no longer true — a "
"stale note is worse than no note."
"stale note is worse than no note. Anything short and durable about the "
"person themselves is a memory rather than a note."
),
),
Fragment(
@@ -813,32 +814,58 @@ BUILTIN: tuple[Fragment, ...] = (
variables=("memory_limit",),
hint="Appears when memory_add and memory_forget are offered. What is "
"remembered costs tokens on every request forever, which is why the "
"wording is about restraint.",
"wording is about restraint — and why it says to read what is already "
"there first: the same fact stored twice in different words costs the "
"window twice and makes either one ambiguous to remove afterwards.",
default=(
"- You can remember durable facts about this person — a preference, a "
"constraint, a name, how they like to be addressed. Use memory_add for those: "
"one fact each, under {{memory_limit}} characters. Do not remember the details "
"of a single task, anything that will be untrue next month, or anything "
"secret — keys, passwords, or health details they have not asked you to keep. "
"one fact each, under {{memory_limit}} characters. Everything remembered is "
"already in this message, so read it before adding: saying the same thing "
"again in different words costs the window twice and makes either one hard "
"to remove afterwards. Do not remember the details of a single task, anything "
"that will be untrue next month, or anything secret — keys, passwords, or "
"health details they have not asked you to keep. Anything longer than a "
"sentence, or about the work rather than about them, does not belong here. "
"When something you remembered turns out to be wrong, remove it with "
"memory_forget rather than adding a correction beside it."
"memory_forget, quoting it in full, rather than adding a correction beside it."
),
),
Fragment(
key="tool.skills",
label="Skills",
label="Skills: reading one",
group=GROUP_TOOLS,
order=240,
families=("skills",),
hint="Appears when the skill tools are offered.",
requires=("skills",),
hint="Only once there is at least one skill. This used to be one "
"fragment gated on the family alone, so a person with no skills got "
"'the list below gives each one's name' above no list, and skill_get "
"in the tools array — which is exactly why models hunt for skills that "
"do not exist. The writing half is its own fragment below, because "
"that half is most useful precisely when there are none.",
default=(
"- Skills are procedures you have saved. The list below gives only each one's "
"name and when to use it; read the full instructions with skill_get before "
"following one. If you work out a repeatable way to do something, save it with "
"skill_create. If following one shows it to be wrong or incomplete, improve it "
"following one. If following one shows it to be wrong or incomplete, improve it "
"with skill_edit and say why — the previous version is kept and can be restored."
),
),
Fragment(
key="tool.skills_write",
label="Skills: saving one",
group=GROUP_TOOLS,
order=241,
families=("skills",),
hint="The other half, and deliberately NOT gated on there being any: "
"somebody with no skills is exactly who most needs to be told they can "
"save the first one.",
default=(
"- If you work out a repeatable way to do something you expect to be asked for "
"again, save it with skill_create. The description has to say when to use it, "
"since that is all you will see next time."
),
),
# --- Context -------------------------------------------------------------
Fragment(
key="context.knowledge_scope",
@@ -864,11 +891,15 @@ BUILTIN: tuple[Fragment, ...] = (
variables=("memories",),
requires=("memories",),
hint="The remembered facts themselves, injected whole on every turn. "
"Skipped entirely when there are none.",
"Skipped entirely when there are none. It used to say these 'still "
"apply', which nothing checks — and which taught a model to trust a "
"stale memory over what the person had just said.",
default=(
"### What you know about this person\n"
"\n"
"The following was remembered in earlier conversations and still applies.\n"
"These were remembered in earlier conversations. If something here is "
"contradicted by what they say now, believe them and remove it with "
"memory_forget.\n"
"\n"
"{{memories}}"
),
+104 -10
View File
@@ -160,6 +160,11 @@ class ToolContext:
# the decrypted credential. None everywhere else, which is what every agent
# runner checks first. `generation` clears it when the reply ends.
agent: Any = None
# Skills this chat has switched off, by name. Enforced in `_run_skill_get`
# and not only in the listing: without that the narrowing is advisory, since
# a model can name a skill it was never shown and the runner would fetch it
# anyway. Same rule as "what may be run is what was offered".
skills_off: frozenset[str] = field(default_factory=frozenset)
@dataclass
@@ -530,18 +535,46 @@ async def _run_memory_add(context: ToolContext, args: dict[str, Any]) -> ToolOut
async def _run_memory_forget(context: ToolContext, args: dict[str, Any]) -> ToolOutcome:
"""Remove one memory, or refuse and say why.
Exact match first, then substring, and an ambiguous substring removes
nothing. This used to be a case-insensitive substring FIRST-match delete
with nothing warning about it, so `memory_forget("coffee")` against "Drinks
coffee black" and "Allergic to coffee" silently deleted whichever was older
-- a wrong deletion nobody would ever find out about, from a tool whose
description invited exactly the short fragment that misfires.
Exact-first is not a nicety: without it, quoting a memory in full still
fails whenever that text happens to be a substring of another one.
"""
wanted = str(args.get("content") or "").strip().lower()
with session_scope() as db:
user = db.get(User, context.owner_id)
records = memories_service.all_for(db, user)
match = next((m for m in records if wanted and wanted in m.content.lower()), None)
if match is None:
if not wanted:
return ToolOutcome(
"Say which memory to remove, quoting its text.",
{"name": "memory_forget", "status": "error", "error": "Nothing given."},
)
exact = [m for m in records if m.content.strip().lower() == wanted]
matches = exact or [m for m in records if wanted in m.content.lower()]
if not matches:
return ToolOutcome(
"No memory matches that. The full list is in the prompt already.",
{"name": "memory_forget", "status": "error", "error": "No match."},
)
content = match.content
memories_service.delete(db, match)
if len(matches) > 1:
listed = "\n".join(f"- {m.content}" for m in matches[:10])
return ToolOutcome(
f"That matches {len(matches)} memories, so nothing was removed. "
f"Quote the whole text of the one you mean:\n{listed}",
{"name": "memory_forget", "status": "error", "error": "Ambiguous."},
)
content = matches[0].content
memories_service.delete(db, matches[0])
return ToolOutcome(
f"Forgotten: {content}",
{"name": "memory_forget", "query": content, "status": "ok", "results": []},
@@ -554,6 +587,13 @@ async def _run_skill_get(context: ToolContext, args: dict[str, Any]) -> ToolOutc
with session_scope() as db:
user = db.get(User, context.owner_id)
skill = skills_service.by_name(db, name, user)
# Enforced here and not only in the listing. Without this the per-chat
# narrowing is advisory: a model can name a skill it was never shown --
# from an earlier turn, from a note -- and the runner would fetch it.
if skill is not None and skill.name in {
skills_service.slugify(off) for off in context.skills_off
}:
skill = None
if skill is None:
return ToolOutcome(
f"There is no skill called {name!r}.",
@@ -778,9 +818,13 @@ REGISTRY: dict[str, ToolDef] = {
family=FAMILY_MEMORY,
description=(
"Remember one short, durable fact about the user — a preference, a "
"constraint, how they like to be addressed. You are shown every "
"memory on every turn, so keep them few and short, and never store "
"passwords, keys or anything else secret."
"constraint, a name, how they like to be addressed. Every memory is "
"put in front of you on every turn, up to a budget, so keep them few "
"and keep them short; text over the limit is shortened rather than "
"refused, and you are told. Check what is already remembered before "
"adding: a fact you have stored already in slightly different words "
"costs the same again and makes both of them harder to remove. Never "
"store a password, a key or anything else secret."
),
parameters=_object(
{"content": {**_STRING, "description": "One fact, in one sentence."}},
@@ -793,10 +837,16 @@ REGISTRY: dict[str, ToolDef] = {
name="memory_forget",
family=FAMILY_MEMORY,
description=(
"Remove a memory that has become wrong. Give enough of its text to "
"identify it."
"Remove a memory that is no longer true. Quote it in full — the "
"whole sentence as it appears in your prompt. A fragment that "
"matches more than one removes nothing and tells you which ones it "
"matched, because deleting the wrong memory is not something anyone "
"would find out about."
),
parameters=_object(
{"content": {**_STRING, "description": "The memory's whole text."}},
["content"],
),
parameters=_object({"content": _STRING}, ["content"]),
run=_run_memory_forget,
risk=RISK_WRITE,
),
@@ -1035,6 +1085,17 @@ def resolve_tools(db: DBSession, chat: Chat, user: User | None) -> ToolSet:
# Resolved against what this reader may see, not against everything that
# exists: a tool restricted to a group is not offered outside it.
book = _book([*_row_defs(db, user), *_agent_defs(db, chat, user)])
# What this chat has switched off, applied AFTER the gates and never
# instead of them. A chat can only ever *narrow* what the model's
# capabilities, the reader's permissions and the instance configuration
# already allow -- exactly as `chat.knowledge_bases` narrows
# `knowledge_search` and can never widen it. A crafted request that turned
# something on here would still be reaching for a tool the gates had
# already removed.
off = scoped_off(chat)
empty_library = not skills_service.count_enabled(db, user, exclude=scoped_skills_off(chat))
return ToolSet(
tuple(
tool
@@ -1042,10 +1103,42 @@ def resolve_tools(db: DBSession, chat: Chat, user: User | None) -> ToolSet:
if _family_allowed(
tool.family, config=config, capabilities=capabilities, allowed=allowed
)
and gate_of(tool.family) not in off
# Nothing to read and nothing to improve. Offering `skill_get` with
# no skills is what makes a model spend a round looking one up and
# being told it does not exist -- and `context.skills` already
# vanishes, so the prompt says "read one with skill_get" above a
# list that is not there. `skill_create` stays: writing the first
# one is exactly what somebody with none needs.
and not (empty_library and tool.name in _NEEDS_A_SKILL)
)
)
# Skills tools that are meaningless with an empty library.
_NEEDS_A_SKILL = frozenset({"skill_get", "skill_edit"})
def scoped_off(chat: Chat | None) -> frozenset[str]:
"""Gates this chat has switched off. **Absent means on**, always.
One representation of "on" -- the key not being there -- so that "why is
this off?" has one answer rather than two.
"""
if chat is None:
return frozenset()
wanted = (getattr(chat, "scope_json", None) or {}).get("families") or {}
return frozenset(str(name) for name, on in wanted.items() if on is False)
def scoped_skills_off(chat: Chat | None) -> frozenset[str]:
"""Individual skills this chat has switched off, by name."""
if chat is None:
return frozenset()
wanted = (getattr(chat, "scope_json", None) or {}).get("skills") or {}
return frozenset(str(name) for name, on in wanted.items() if on is False)
def enabled_tools(db: DBSession, chat: Chat, user: User | None) -> list[dict[str, Any]]:
"""The tool schemas to offer for this chat.
@@ -1070,6 +1163,7 @@ def context_for(
owner_id=user.id if user else "",
search_config=settings_store.search(db),
base_ids=[base.id for base in chat.knowledge_bases] if chat is not None else [],
skills_off=scoped_skills_off(chat),
tools=tools.by_name if tools is not None else None,
interaction_timeout=float(settings_store.agents(db)["approval_timeout"]),
)