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:
+82
-7
@@ -55,6 +55,11 @@ KEEPALIVE_AFTER = 15.0
|
|||||||
# better than four hundred rows nobody meant to write.
|
# better than four hundred rows nobody meant to write.
|
||||||
MAX_QUEUED = 10
|
MAX_QUEUED = 10
|
||||||
|
|
||||||
|
# How many things one chat may have switched off. There are a dozen families and
|
||||||
|
# sixty skills at most, so this is not a limit anybody reaches by hand -- it is
|
||||||
|
# there so a crafted POST cannot grow the column without bound.
|
||||||
|
MAX_SCOPE_KEYS = 200
|
||||||
|
|
||||||
|
|
||||||
def _owned_chat(db: DBSession, chat_id: str, user_id: str) -> Chat:
|
def _owned_chat(db: DBSession, chat_id: str, user_id: str) -> Chat:
|
||||||
chat = db.get(Chat, chat_id)
|
chat = db.get(Chat, chat_id)
|
||||||
@@ -135,10 +140,19 @@ def _new_chat(
|
|||||||
if profile is not None and agent_mode.strip() in agent_policy.MODES:
|
if profile is not None and agent_mode.strip() in agent_policy.MODES:
|
||||||
chat.agent_mode = agent_mode.strip()
|
chat.agent_mode = agent_mode.strip()
|
||||||
# After the model's defaults, so choosing one on the new-chat screen wins
|
# After the model's defaults, so choosing one on the new-chat screen wins
|
||||||
# over the administrator's. Empty means "whatever the model said", not
|
# over the administrator's.
|
||||||
# "none" -- clearing it is what the blank option on an existing chat does.
|
#
|
||||||
|
# `"off"` is a sentinel, and it has to be: `reasoning_effort` arrives as
|
||||||
|
# `Form("")`, so an absent field and an empty one are indistinguishable --
|
||||||
|
# the FastAPI trap this codebase has already been bitten by once. With
|
||||||
|
# `value=""` on the off option, the reader would pick "off", the value would
|
||||||
|
# fall out of EFFORTS, the model's default seeded above would stay, and they
|
||||||
|
# would silently get "high". The picker shows what will be sent, so the two
|
||||||
|
# have to agree.
|
||||||
wanted_effort = reasoning_effort.strip().lower()
|
wanted_effort = reasoning_effort.strip().lower()
|
||||||
if wanted_effort in chat_service.EFFORTS:
|
if wanted_effort == "off":
|
||||||
|
chat.params_json = {k: v for k, v in chat.params_json.items() if k != "reasoning_effort"}
|
||||||
|
elif wanted_effort in chat_service.EFFORTS:
|
||||||
chat.params_json = {**chat.params_json, "reasoning_effort": wanted_effort}
|
chat.params_json = {**chat.params_json, "reasoning_effort": wanted_effort}
|
||||||
db.add(chat)
|
db.add(chat)
|
||||||
db.commit()
|
db.commit()
|
||||||
@@ -518,6 +532,54 @@ async def attach_base(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{chat_id}/scope")
|
||||||
|
async def set_scope(
|
||||||
|
db: Db,
|
||||||
|
user: RequiredUser,
|
||||||
|
chat_id: str,
|
||||||
|
kind: str = Form(""),
|
||||||
|
name: str = Form(""),
|
||||||
|
on: bool = Form(False),
|
||||||
|
) -> Response:
|
||||||
|
"""Turn one thing this chat may use on or off. **Narrowing only.**
|
||||||
|
|
||||||
|
Nothing here widens anything. `resolve_tools` applies this *after* the
|
||||||
|
model's capabilities, the reader's permissions and the instance
|
||||||
|
configuration, so a crafted POST turning something on reaches a tool those
|
||||||
|
gates have already removed -- there is a test for exactly that.
|
||||||
|
|
||||||
|
On is stored by **removing** the key rather than by writing True, so absent
|
||||||
|
stays the single representation of "on" and the column cannot grow a row per
|
||||||
|
family per chat. Bounded, so a crafted request cannot grow it either.
|
||||||
|
|
||||||
|
JSON reassignment rather than mutation: a plain dict assignment into a JSON
|
||||||
|
column is not detected.
|
||||||
|
"""
|
||||||
|
chat = _owned_chat(db, chat_id, user.id)
|
||||||
|
bucket = {"family": "families", "skill": "skills"}.get(kind.strip())
|
||||||
|
wanted = name.strip()[:64]
|
||||||
|
if bucket is None or not wanted:
|
||||||
|
raise HTTPException(status.HTTP_400_BAD_REQUEST, "Say what to turn on or off.")
|
||||||
|
|
||||||
|
scope = dict(chat.scope_json or {})
|
||||||
|
entries = dict(scope.get(bucket) or {})
|
||||||
|
if on:
|
||||||
|
entries.pop(wanted, None)
|
||||||
|
else:
|
||||||
|
if len(entries) >= MAX_SCOPE_KEYS:
|
||||||
|
raise HTTPException(status.HTTP_409_CONFLICT, "Too many things switched off.")
|
||||||
|
entries[wanted] = False
|
||||||
|
|
||||||
|
if entries:
|
||||||
|
scope[bucket] = entries
|
||||||
|
else:
|
||||||
|
scope.pop(bucket, None)
|
||||||
|
chat.scope_json = scope
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/{chat_id}/keep")
|
@router.post("/{chat_id}/keep")
|
||||||
async def keep_chat(db: Db, user: RequiredUser, chat_id: str) -> Response:
|
async def keep_chat(db: Db, user: RequiredUser, chat_id: str) -> Response:
|
||||||
"""Stop a temporary chat being temporary.
|
"""Stop a temporary chat being temporary.
|
||||||
@@ -1373,20 +1435,33 @@ async def update_chat(request: Request, db: Db, user: RequiredUser, chat_id: str
|
|||||||
**_clean_params(**{k: str(v) for k, v in submitted_params.items()}),
|
**_clean_params(**{k: str(v) for k, v in submitted_params.items()}),
|
||||||
}
|
}
|
||||||
|
|
||||||
# Not a number, so it cannot go through _PARAM_RANGES. Empty means clear it,
|
# Not a number, so it cannot go through _PARAM_RANGES. `"off"` and empty
|
||||||
# the same as every other parameter here; anything that is not one of the
|
# both clear it -- the sentinel because that is what the picker sends now,
|
||||||
# three is ignored rather than refused, so a typo does not cost a message.
|
# empty because anything still posting the old value must keep working.
|
||||||
|
# Anything that is neither is ignored rather than refused, so a typo does
|
||||||
|
# not cost a message.
|
||||||
if "reasoning_effort" in form:
|
if "reasoning_effort" in form:
|
||||||
if not allowed.get("chat.params"):
|
if not allowed.get("chat.params"):
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status.HTTP_403_FORBIDDEN, "You may not change sampling parameters."
|
status.HTTP_403_FORBIDDEN, "You may not change sampling parameters."
|
||||||
)
|
)
|
||||||
wanted = str(form["reasoning_effort"]).strip().lower()
|
wanted = str(form["reasoning_effort"]).strip().lower()
|
||||||
if not wanted:
|
if not wanted or wanted == "off":
|
||||||
chat.params_json = {**(chat.params_json or {}), "reasoning_effort": None}
|
chat.params_json = {**(chat.params_json or {}), "reasoning_effort": None}
|
||||||
elif wanted in chat_service.EFFORTS:
|
elif wanted in chat_service.EFFORTS:
|
||||||
chat.params_json = {**(chat.params_json or {}), "reasoning_effort": wanted}
|
chat.params_json = {**(chat.params_json or {}), "reasoning_effort": wanted}
|
||||||
|
|
||||||
|
# Switching model re-seeds an effort that was never chosen, so "what the
|
||||||
|
# picker shows is what is sent" stays true afterwards. Only when the key is
|
||||||
|
# ABSENT: `None` means somebody cleared it deliberately, and resurrecting
|
||||||
|
# that would make "off" silently do nothing on the next model change.
|
||||||
|
if model_id and "reasoning_effort" not in (chat.params_json or {}):
|
||||||
|
seeded = ((match.params_json if match is not None else None) or {}).get(
|
||||||
|
"reasoning_effort"
|
||||||
|
)
|
||||||
|
if seeded in chat_service.EFFORTS:
|
||||||
|
chat.params_json = {**(chat.params_json or {}), "reasoning_effort": seeded}
|
||||||
|
|
||||||
db.commit()
|
db.commit()
|
||||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
|
||||||
|
|||||||
@@ -62,11 +62,87 @@ def _chat_context(db: DBSession, user: User, chat: Chat | None) -> dict:
|
|||||||
# command, the control and the request builder cannot disagree about
|
# command, the control and the request builder cannot disagree about
|
||||||
# what is a valid effort.
|
# what is a valid effort.
|
||||||
"efforts": chat_service.EFFORTS,
|
"efforts": chat_service.EFFORTS,
|
||||||
|
# What the picker shows, and what `build_request` will send. One
|
||||||
|
# resolver so the two cannot disagree.
|
||||||
|
"resolved_effort": chat_service.resolved_effort(chat) if chat else "",
|
||||||
|
**_scope_context(db, user, chat),
|
||||||
**_agent_context(db, user, chat),
|
**_agent_context(db, user, chat),
|
||||||
**audio_service.template_flags(db, user),
|
**audio_service.template_flags(db, user),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _scope_context(db: DBSession, user: User, chat: Chat | None) -> dict:
|
||||||
|
"""What this chat may use, for the menu that narrows it.
|
||||||
|
|
||||||
|
Only for an existing chat: there is no row to write to before one exists,
|
||||||
|
and a menu whose choices went nowhere would be worse than no menu. The
|
||||||
|
families listed are the ones actually offered *right now*, so the menu never
|
||||||
|
shows a switch for something the model, the reader's permissions or the
|
||||||
|
instance has already ruled out -- turning that on would do nothing, since
|
||||||
|
`resolve_tools` applies this after the gates.
|
||||||
|
"""
|
||||||
|
from lembas.services import tool_labels
|
||||||
|
from lembas.services import tools as tools_service
|
||||||
|
from lembas.services.library import skills as skills_service
|
||||||
|
|
||||||
|
if chat is None:
|
||||||
|
return {"scope_families": [], "scope_skills": []}
|
||||||
|
|
||||||
|
off = tools_service.scoped_off(chat)
|
||||||
|
skills_off = tools_service.scoped_skills_off(chat)
|
||||||
|
|
||||||
|
# Gates rather than tool names: `notes` is one switch, not five, which is
|
||||||
|
# the same reasoning the per-model capability checkboxes carry.
|
||||||
|
seen: dict[str, str] = {}
|
||||||
|
for tool in tools_service.resolve_tools(db, chat, user).defs:
|
||||||
|
seen.setdefault(tools_service.gate_of(tool.family), tool.name)
|
||||||
|
# Anything already switched off is absent from the offered set, so it has to
|
||||||
|
# be put back or there would be no way to turn it on again.
|
||||||
|
for gate in off:
|
||||||
|
seen.setdefault(gate, "")
|
||||||
|
|
||||||
|
families = [
|
||||||
|
{
|
||||||
|
"gate": gate,
|
||||||
|
"label": _GATE_LABELS.get(gate) or tool_labels.label_for(example) or gate,
|
||||||
|
"on": gate not in off,
|
||||||
|
}
|
||||||
|
for gate, example in sorted(seen.items())
|
||||||
|
]
|
||||||
|
|
||||||
|
skills = []
|
||||||
|
if permissions.has(db, user, "library.use"):
|
||||||
|
skills = [
|
||||||
|
{
|
||||||
|
"name": skill.name,
|
||||||
|
"description": skill.description,
|
||||||
|
"on": skill.name not in skills_off,
|
||||||
|
}
|
||||||
|
for skill in skills_service.enabled_for(db, user)
|
||||||
|
]
|
||||||
|
for name in sorted(skills_off):
|
||||||
|
if name not in {s["name"] for s in skills}:
|
||||||
|
skills.append({"name": name, "description": "", "on": False})
|
||||||
|
|
||||||
|
return {"scope_families": families, "scope_skills": skills}
|
||||||
|
|
||||||
|
|
||||||
|
# What a gate is called in the menu. A gate covers several tools, so no single
|
||||||
|
# tool's label is the right name for it.
|
||||||
|
_GATE_LABELS = {
|
||||||
|
"web_search": "Web search",
|
||||||
|
"fetch": "Fetching pages",
|
||||||
|
"knowledge": "Your knowledge library",
|
||||||
|
"notes": "Notes",
|
||||||
|
"memory": "Memory",
|
||||||
|
"skills": "Skills",
|
||||||
|
"ask": "Asking you questions",
|
||||||
|
"agent": "Running commands",
|
||||||
|
"custom": "Custom tools",
|
||||||
|
"mcp": "MCP servers",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def _agent_context(db: DBSession, user: User, chat: Chat | None) -> dict:
|
def _agent_context(db: DBSession, user: User, chat: Chat | None) -> dict:
|
||||||
"""What the composer and the chat header need to know about agent chats.
|
"""What the composer and the chat header need to know about agent chats.
|
||||||
|
|
||||||
|
|||||||
@@ -151,6 +151,12 @@ class Chat(UUIDPrimaryKey, Timestamps, Base):
|
|||||||
# message with a plan" -- `context_variables` is synchronous and on the
|
# message with a plan" -- `context_variables` is synchronous and on the
|
||||||
# request path. A plan a model cannot see is a plan it cannot keep current.
|
# request path. A plan a model cannot see is a plan it cannot keep current.
|
||||||
plan_message_id: Mapped[str | None] = mapped_column(String(32))
|
plan_message_id: Mapped[str | None] = mapped_column(String(32))
|
||||||
|
# What this chat has switched off, narrowing what it is already allowed.
|
||||||
|
# {"families": {"web_search": false}, "skills": {"weekly-report": false}}.
|
||||||
|
# **Absent means on**, for every key -- the same convention
|
||||||
|
# `McpServer.tool_overrides_json` uses, and for the same reason: two
|
||||||
|
# representations of "on" makes "why is this off?" unanswerable.
|
||||||
|
scope_json: Mapped[dict[str, Any]] = mapped_column(JSONDict, default=dict)
|
||||||
|
|
||||||
# --- Compaction ----------------------------------------------------------
|
# --- Compaction ----------------------------------------------------------
|
||||||
# A summary of the turns up to `compacted_through_id`, sent in their place.
|
# A summary of the turns up to `compacted_through_id`, sent in their place.
|
||||||
|
|||||||
@@ -332,6 +332,25 @@ def build_request(
|
|||||||
EFFORTS = ("low", "medium", "high")
|
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:
|
def apply_effort(body: dict[str, Any], effort: str | None) -> None:
|
||||||
"""Put a chosen reasoning effort into a request body, in both forms."""
|
"""Put a chosen reasoning effort into a request body, in both forms."""
|
||||||
if not effort or effort not in EFFORTS:
|
if not effort or effort not in EFFORTS:
|
||||||
|
|||||||
@@ -133,7 +133,11 @@ def context_variables(
|
|||||||
"memory_limit": str(memories_service.MAX_MEMORY_CHARS),
|
"memory_limit": str(memories_service.MAX_MEMORY_CHARS),
|
||||||
"tool_names": _tool_names(offered),
|
"tool_names": _tool_names(offered),
|
||||||
"memories": memories_service.block(db, user) if "memory" in families else "",
|
"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": "",
|
"knowledge_bases": "",
|
||||||
"document_names": "",
|
"document_names": "",
|
||||||
"agent_target": "",
|
"agent_target": "",
|
||||||
|
|||||||
@@ -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:
|
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())
|
content = " ".join((content or "").split())
|
||||||
if not content:
|
if not content:
|
||||||
raise ValueError("A memory cannot be empty.")
|
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(
|
count = db.scalar(
|
||||||
select(func.count()).select_from(Memory).where(Memory.owner_id == owner.id)
|
select(func.count()).select_from(Memory).where(Memory.owner_id == owner.id)
|
||||||
)
|
)
|
||||||
if (count or 0) >= MAX_RECORDS:
|
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(
|
raise ValueError(
|
||||||
f"There are already {MAX_RECORDS} memories. Remove one first, or put "
|
f"There are already {MAX_RECORDS} memories, which is the limit, so "
|
||||||
f"this in a note instead."
|
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(
|
memory = Memory(
|
||||||
owner_id=owner.id,
|
owner_id=owner.id,
|
||||||
content=content[:MAX_MEMORY_CHARS],
|
content=content,
|
||||||
author=author if author in (AUTHOR_USER, AUTHOR_MODEL) else AUTHOR_MODEL,
|
author=author if author in (AUTHOR_USER, AUTHOR_MODEL) else AUTHOR_MODEL,
|
||||||
)
|
)
|
||||||
db.add(memory)
|
db.add(memory)
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
|
from collections.abc import Iterable
|
||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
from sqlalchemy.orm import Session as DBSession
|
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)))
|
return db.scalar(visible(db, user).where(Skill.name == slugify(name)))
|
||||||
|
|
||||||
|
|
||||||
def enabled_for(db: DBSession, user: User | None) -> list[Skill]:
|
def enabled_for(
|
||||||
"""Skills that should appear in the index, oldest first for a stable order."""
|
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:
|
if user is None:
|
||||||
return []
|
return []
|
||||||
return list(
|
hidden = {slugify(name) for name in exclude}
|
||||||
db.scalars(
|
rows = db.scalars(
|
||||||
visible(db, user)
|
visible(db, user)
|
||||||
.where(Skill.enabled.is_(True))
|
.where(Skill.enabled.is_(True))
|
||||||
.order_by(Skill.name)
|
.order_by(Skill.name)
|
||||||
.limit(MAX_INDEX_SKILLS)
|
.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]:
|
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()
|
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."""
|
"""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:
|
if not skills:
|
||||||
return ""
|
return ""
|
||||||
return "\n".join(f"- {skill.name}: {skill.description}" for skill in skills)
|
return "\n".join(f"- {skill.name}: {skill.description}" for skill in skills)
|
||||||
|
|||||||
@@ -801,7 +801,8 @@ BUILTIN: tuple[Fragment, ...] = (
|
|||||||
"would be tedious to work out again: a procedure, a decision and its reasons, "
|
"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 "
|
"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 "
|
"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(
|
Fragment(
|
||||||
@@ -813,32 +814,58 @@ BUILTIN: tuple[Fragment, ...] = (
|
|||||||
variables=("memory_limit",),
|
variables=("memory_limit",),
|
||||||
hint="Appears when memory_add and memory_forget are offered. What is "
|
hint="Appears when memory_add and memory_forget are offered. What is "
|
||||||
"remembered costs tokens on every request forever, which is why the "
|
"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=(
|
default=(
|
||||||
"- You can remember durable facts about this person — a preference, a "
|
"- 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: "
|
"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 "
|
"one fact each, under {{memory_limit}} characters. Everything remembered is "
|
||||||
"of a single task, anything that will be untrue next month, or anything "
|
"already in this message, so read it before adding: saying the same thing "
|
||||||
"secret — keys, passwords, or health details they have not asked you to keep. "
|
"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 "
|
"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(
|
Fragment(
|
||||||
key="tool.skills",
|
key="tool.skills",
|
||||||
label="Skills",
|
label="Skills: reading one",
|
||||||
group=GROUP_TOOLS,
|
group=GROUP_TOOLS,
|
||||||
order=240,
|
order=240,
|
||||||
families=("skills",),
|
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=(
|
default=(
|
||||||
"- Skills are procedures you have saved. The list below gives only each one's "
|
"- 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 "
|
"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 "
|
"following one. If following one shows it to be wrong or incomplete, improve it "
|
||||||
"skill_create. 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."
|
"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 -------------------------------------------------------------
|
# --- Context -------------------------------------------------------------
|
||||||
Fragment(
|
Fragment(
|
||||||
key="context.knowledge_scope",
|
key="context.knowledge_scope",
|
||||||
@@ -864,11 +891,15 @@ BUILTIN: tuple[Fragment, ...] = (
|
|||||||
variables=("memories",),
|
variables=("memories",),
|
||||||
requires=("memories",),
|
requires=("memories",),
|
||||||
hint="The remembered facts themselves, injected whole on every turn. "
|
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=(
|
default=(
|
||||||
"### What you know about this person\n"
|
"### What you know about this person\n"
|
||||||
"\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"
|
"\n"
|
||||||
"{{memories}}"
|
"{{memories}}"
|
||||||
),
|
),
|
||||||
|
|||||||
+104
-10
@@ -160,6 +160,11 @@ class ToolContext:
|
|||||||
# the decrypted credential. None everywhere else, which is what every agent
|
# the decrypted credential. None everywhere else, which is what every agent
|
||||||
# runner checks first. `generation` clears it when the reply ends.
|
# runner checks first. `generation` clears it when the reply ends.
|
||||||
agent: Any = None
|
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
|
@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:
|
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()
|
wanted = str(args.get("content") or "").strip().lower()
|
||||||
with session_scope() as db:
|
with session_scope() as db:
|
||||||
user = db.get(User, context.owner_id)
|
user = db.get(User, context.owner_id)
|
||||||
records = memories_service.all_for(db, user)
|
records = memories_service.all_for(db, user)
|
||||||
match = next((m for m in records if wanted and wanted in m.content.lower()), None)
|
if not wanted:
|
||||||
if match is None:
|
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(
|
return ToolOutcome(
|
||||||
"No memory matches that. The full list is in the prompt already.",
|
"No memory matches that. The full list is in the prompt already.",
|
||||||
{"name": "memory_forget", "status": "error", "error": "No match."},
|
{"name": "memory_forget", "status": "error", "error": "No match."},
|
||||||
)
|
)
|
||||||
content = match.content
|
if len(matches) > 1:
|
||||||
memories_service.delete(db, match)
|
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(
|
return ToolOutcome(
|
||||||
f"Forgotten: {content}",
|
f"Forgotten: {content}",
|
||||||
{"name": "memory_forget", "query": content, "status": "ok", "results": []},
|
{"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:
|
with session_scope() as db:
|
||||||
user = db.get(User, context.owner_id)
|
user = db.get(User, context.owner_id)
|
||||||
skill = skills_service.by_name(db, name, user)
|
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:
|
if skill is None:
|
||||||
return ToolOutcome(
|
return ToolOutcome(
|
||||||
f"There is no skill called {name!r}.",
|
f"There is no skill called {name!r}.",
|
||||||
@@ -778,9 +818,13 @@ REGISTRY: dict[str, ToolDef] = {
|
|||||||
family=FAMILY_MEMORY,
|
family=FAMILY_MEMORY,
|
||||||
description=(
|
description=(
|
||||||
"Remember one short, durable fact about the user — a preference, a "
|
"Remember one short, durable fact about the user — a preference, a "
|
||||||
"constraint, how they like to be addressed. You are shown every "
|
"constraint, a name, how they like to be addressed. Every memory is "
|
||||||
"memory on every turn, so keep them few and short, and never store "
|
"put in front of you on every turn, up to a budget, so keep them few "
|
||||||
"passwords, keys or anything else secret."
|
"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(
|
parameters=_object(
|
||||||
{"content": {**_STRING, "description": "One fact, in one sentence."}},
|
{"content": {**_STRING, "description": "One fact, in one sentence."}},
|
||||||
@@ -793,10 +837,16 @@ REGISTRY: dict[str, ToolDef] = {
|
|||||||
name="memory_forget",
|
name="memory_forget",
|
||||||
family=FAMILY_MEMORY,
|
family=FAMILY_MEMORY,
|
||||||
description=(
|
description=(
|
||||||
"Remove a memory that has become wrong. Give enough of its text to "
|
"Remove a memory that is no longer true. Quote it in full — the "
|
||||||
"identify it."
|
"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,
|
run=_run_memory_forget,
|
||||||
risk=RISK_WRITE,
|
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
|
# Resolved against what this reader may see, not against everything that
|
||||||
# exists: a tool restricted to a group is not offered outside it.
|
# exists: a tool restricted to a group is not offered outside it.
|
||||||
book = _book([*_row_defs(db, user), *_agent_defs(db, chat, user)])
|
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(
|
return ToolSet(
|
||||||
tuple(
|
tuple(
|
||||||
tool
|
tool
|
||||||
@@ -1042,10 +1103,42 @@ def resolve_tools(db: DBSession, chat: Chat, user: User | None) -> ToolSet:
|
|||||||
if _family_allowed(
|
if _family_allowed(
|
||||||
tool.family, config=config, capabilities=capabilities, allowed=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]]:
|
def enabled_tools(db: DBSession, chat: Chat, user: User | None) -> list[dict[str, Any]]:
|
||||||
"""The tool schemas to offer for this chat.
|
"""The tool schemas to offer for this chat.
|
||||||
|
|
||||||
@@ -1070,6 +1163,7 @@ def context_for(
|
|||||||
owner_id=user.id if user else "",
|
owner_id=user.id if user else "",
|
||||||
search_config=settings_store.search(db),
|
search_config=settings_store.search(db),
|
||||||
base_ids=[base.id for base in chat.knowledge_bases] if chat is not None else [],
|
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,
|
tools=tools.by_name if tools is not None else None,
|
||||||
interaction_timeout=float(settings_store.agents(db)["approval_timeout"]),
|
interaction_timeout=float(settings_store.agents(db)["approval_timeout"]),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1053,6 +1053,27 @@ body.is-resizing .terminal__screen { pointer-events: none; }
|
|||||||
right: auto;
|
right: auto;
|
||||||
}
|
}
|
||||||
.picker__menu--compact { width: min(18rem, calc(100vw - var(--sp-8))); padding: var(--sp-1); }
|
.picker__menu--compact { width: min(18rem, calc(100vw - var(--sp-8))); padding: var(--sp-1); }
|
||||||
|
|
||||||
|
/* "What this chat can use": a list of switches rather than a list of actions.
|
||||||
|
Wider than the compact menu because a skill's description has to fit, and
|
||||||
|
scrollable because a library of sixty skills would otherwise run off the top
|
||||||
|
of the window -- this menu opens upward. */
|
||||||
|
.picker__menu--scope {
|
||||||
|
width: min(22rem, calc(100vw - var(--sp-8)));
|
||||||
|
max-height: min(26rem, 60vh);
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: var(--sp-1);
|
||||||
|
}
|
||||||
|
.picker__lede {
|
||||||
|
margin: 0;
|
||||||
|
padding: var(--sp-2) var(--sp-3);
|
||||||
|
font-size: var(--text-xs);
|
||||||
|
color: var(--ink-faint);
|
||||||
|
}
|
||||||
|
/* A label, not a button, so several can be set without the menu closing --
|
||||||
|
ui.js closes on `[role="menuitem"]`, and these deliberately have none. */
|
||||||
|
.picker__option--toggle { align-items: center; }
|
||||||
|
.picker__option--toggle input { flex: none; margin: 0; }
|
||||||
.picker__option-note {
|
.picker__option-note {
|
||||||
font-size: var(--text-xs);
|
font-size: var(--text-xs);
|
||||||
color: var(--ink-faint);
|
color: var(--ink-faint);
|
||||||
|
|||||||
@@ -846,25 +846,54 @@
|
|||||||
font-size: 0.95em;
|
font-size: 0.95em;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Everything that acts on the message, on one line under it. It wraps rather
|
/* Everything that acts on the message, on one line under it. ONE line, always.
|
||||||
than scrolls: on a narrow window the context controls drop to their own row
|
|
||||||
and attach/send stay where the thumb expects them. */
|
It used to wrap, and .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 to this row, Send and the microphone were what dropped
|
||||||
|
to a second line. There are no media queries in this file, deliberately, and
|
||||||
|
the fix is not to add one: it is to say which child gives. */
|
||||||
.composer__toolbar {
|
.composer__toolbar {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
flex-wrap: wrap;
|
flex-wrap: nowrap;
|
||||||
gap: var(--sp-2);
|
|
||||||
}
|
|
||||||
.composer__tools { display: flex; align-items: center; gap: var(--sp-1); flex: none; }
|
|
||||||
.composer__actions { display: flex; align-items: center; gap: var(--sp-1); margin-left: auto; }
|
|
||||||
.composer__context {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: var(--sp-2);
|
gap: var(--sp-2);
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
.composer__agent { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; }
|
.composer__tools { display: flex; align-items: center; gap: var(--sp-1); flex: none; }
|
||||||
|
|
||||||
|
/* Never shrinks, never wraps, always at the end of the line. This is where the
|
||||||
|
hand is going. */
|
||||||
|
.composer__actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--sp-1);
|
||||||
|
flex: none;
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
[data-effort] { flex: none; }
|
||||||
|
|
||||||
|
/* The one thing allowed to give. It shrinks past its content and scrolls
|
||||||
|
sideways rather than wrapping. The scrollbar is hidden: the controls are
|
||||||
|
already visibly cut off, and a scrollbar under a --control-h row would change
|
||||||
|
the row's height, which is the one thing --control-h exists to prevent. */
|
||||||
|
.composer__context {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
gap: var(--sp-2);
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-width: 0;
|
||||||
|
overflow-x: auto;
|
||||||
|
scrollbar-width: none;
|
||||||
|
}
|
||||||
|
.composer__context::-webkit-scrollbar { display: none; }
|
||||||
|
.composer__agent { display: flex; align-items: center; gap: var(--sp-2); flex-wrap: nowrap; }
|
||||||
|
|
||||||
|
/* Floors, not fixed widths: a select narrower than this shows no text at all,
|
||||||
|
which is worse than the scrolling it was avoiding. */
|
||||||
|
.composer__context .select { flex: 0 1 auto; min-width: 6rem; }
|
||||||
|
/* `.segmented` already declares flex: none further down, where it is defined. */
|
||||||
|
|
||||||
/* Round, and the same size as each other: attach and send read as one pair
|
/* Round, and the same size as each other: attach and send read as one pair
|
||||||
bracketing the row. */
|
bracketing the row. */
|
||||||
@@ -872,7 +901,12 @@
|
|||||||
|
|
||||||
/* The directory, on a new chat. Monospace because it is a path, and it grows
|
/* The directory, on a new chat. Monospace because it is a path, and it grows
|
||||||
to fit rather than being pinned to a width that truncates every real one. */
|
to fit rather than being pinned to a width that truncates every real one. */
|
||||||
.composer__dir { max-width: 16rem; font-family: var(--font-mono); font-weight: 400; }
|
.composer__dir {
|
||||||
|
flex: 0 1 16rem;
|
||||||
|
min-width: 5rem;
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
.composer__dir-path { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
.composer__dir-path { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
|
||||||
.composer__hint {
|
.composer__hint {
|
||||||
|
|||||||
@@ -37,6 +37,9 @@
|
|||||||
/* --- Shortcuts ---------------------------------------------------------- */
|
/* --- Shortcuts ---------------------------------------------------------- */
|
||||||
var SHORTCUTS = [
|
var SHORTCUTS = [
|
||||||
{ keys: "Ctrl/⌘ + K", what: "Open the command menu" },
|
{ keys: "Ctrl/⌘ + K", what: "Open the command menu" },
|
||||||
|
{ keys: "Ctrl/⌘ + Enter", what: "Send, from anywhere on the page" },
|
||||||
|
{ keys: "Alt + M", what: "Dictate" },
|
||||||
|
{ keys: "Alt + R", what: "Read the last reply aloud" },
|
||||||
{ keys: "Alt + 1 … 4", what: "Manual, Edit, Auto, Plan" },
|
{ keys: "Alt + 1 … 4", what: "Manual, Edit, Auto, Plan" },
|
||||||
{ keys: "Alt + T", what: "Terminal" },
|
{ keys: "Alt + T", what: "Terminal" },
|
||||||
{ keys: "Alt + I", what: "Inspector" },
|
{ keys: "Alt + I", what: "Inspector" },
|
||||||
@@ -74,7 +77,7 @@
|
|||||||
{
|
{
|
||||||
name: "effort",
|
name: "effort",
|
||||||
summary: "How hard a reasoning model should think",
|
summary: "How hard a reasoning model should think",
|
||||||
argument: "low | medium | high",
|
argument: "low | medium | high | off",
|
||||||
/* Offered wherever there is a model, not only where the control is.
|
/* Offered wherever there is a model, not only where the control is.
|
||||||
`available()` filters `find()` and `run()` as well as the menu, so a
|
`available()` filters `find()` and `run()` as well as the menu, so a
|
||||||
command hidden here is not merely unlisted -- typing it in full stops
|
command hidden here is not merely unlisted -- typing it in full stops
|
||||||
@@ -216,21 +219,25 @@
|
|||||||
var wanted = (rest || "").trim().toLowerCase();
|
var wanted = (rest || "").trim().toLowerCase();
|
||||||
if (!wanted) {
|
if (!wanted) {
|
||||||
return note(
|
return note(
|
||||||
select.value
|
EFFORTS.indexOf(select.value) === -1
|
||||||
? "Effort is " + select.value + ". /effort low, medium, high, or default."
|
? "No effort is being sent. Try low, medium or high."
|
||||||
: "Effort is whatever the model does by default. Try low, medium or high."
|
: "Effort is " + select.value + ". /effort low, medium, high, or off."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (wanted === "default" || wanted === "none") wanted = "";
|
/* "off" is the option's real value, not an empty string: the new-chat form
|
||||||
else if (EFFORTS.indexOf(wanted) === -1) {
|
cannot tell an absent field from an empty one, so the picker sends a
|
||||||
return note("“" + wanted + "” is not an effort. Try low, medium or high.", "error");
|
sentinel and this has to match it. "default" and "none" still work,
|
||||||
|
because somebody's fingers will type them. */
|
||||||
|
if (wanted === "default" || wanted === "none") wanted = "off";
|
||||||
|
else if (wanted !== "off" && EFFORTS.indexOf(wanted) === -1) {
|
||||||
|
return note("“" + wanted + "” is not an effort. Try low, medium, high or off.", "error");
|
||||||
}
|
}
|
||||||
select.value = wanted;
|
select.value = wanted;
|
||||||
select.dispatchEvent(new Event("change", { bubbles: true }));
|
select.dispatchEvent(new Event("change", { bubbles: true }));
|
||||||
note(
|
note(
|
||||||
wanted
|
wanted === "off"
|
||||||
? "Effort set to " + wanted + "."
|
? "Effort cleared; nothing is sent."
|
||||||
: "Effort cleared; the model decides."
|
: "Effort set to " + wanted + "."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -467,8 +474,51 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Send, from anywhere on the page.
|
||||||
|
|
||||||
|
Enter already sends, but only with the caret inside the box (app.js), and
|
||||||
|
deliberately not at all on a touch device. This covers both: after
|
||||||
|
clicking a message to copy it, after using the model picker, after
|
||||||
|
answering an approval card, or with a hardware keyboard on a tablet.
|
||||||
|
|
||||||
|
Never Stop. Send and Stop are the same element, so Ctrl+Enter meaning
|
||||||
|
"abandon the reply" would be a trap -- and Esc already stops. */
|
||||||
|
if ((event.ctrlKey || event.metaKey) &&
|
||||||
|
(event.code === "Enter" || event.code === "NumpadEnter")) {
|
||||||
|
var action = el("[data-composer-action]");
|
||||||
|
var box = el("[data-composer-input]");
|
||||||
|
if (action && action.dataset.composerAction === "send" && box && box.value.trim()) {
|
||||||
|
event.preventDefault();
|
||||||
|
action.click();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!event.altKey || event.ctrlKey || event.metaKey) return;
|
if (!event.altKey || event.ctrlKey || event.metaKey) return;
|
||||||
|
|
||||||
|
/* Dictation and read-aloud both work by clicking the button that already
|
||||||
|
does the job, so audio.js keeps its one delegated click listener and
|
||||||
|
there is no second copy of the recording state machine. Alt+M rather than
|
||||||
|
Alt+D: Alt+D is the address bar in Chrome and Firefox. */
|
||||||
|
if (event.code === "KeyM") {
|
||||||
|
var mic = el("[data-mic]");
|
||||||
|
if (mic) {
|
||||||
|
event.preventDefault();
|
||||||
|
mic.click();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (event.code === "KeyR") {
|
||||||
|
var speakers = document.querySelectorAll("#thread .msg--assistant [data-speak]");
|
||||||
|
if (speakers.length) {
|
||||||
|
event.preventDefault();
|
||||||
|
/* A second press stops it: audio.js already toggles a message that is
|
||||||
|
speaking, so this costs nothing and is the obvious second press. */
|
||||||
|
speakers[speakers.length - 1].click();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (event.code === "KeyT" && el("#terminal")) {
|
if (event.code === "KeyT" && el("#terminal")) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
return toggle("#terminal", "side");
|
return toggle("#terminal", "side");
|
||||||
|
|||||||
@@ -107,7 +107,7 @@
|
|||||||
<div class="field">
|
<div class="field">
|
||||||
<label class="field__label" for="default-effort">Default reasoning effort</label>
|
<label class="field__label" for="default-effort">Default reasoning effort</label>
|
||||||
<select class="select" id="default-effort" name="default_effort">
|
<select class="select" id="default-effort" name="default_effort">
|
||||||
<option value="">Whatever the model does</option>
|
<option value="">None — send nothing</option>
|
||||||
{% for value in efforts %}
|
{% for value in efforts %}
|
||||||
<option value="{{ value }}"
|
<option value="{{ value }}"
|
||||||
{{ 'selected' if model.params_json.get('reasoning_effort') == value }}>
|
{{ 'selected' if model.params_json.get('reasoning_effort') == value }}>
|
||||||
@@ -116,7 +116,12 @@
|
|||||||
{% endfor %}
|
{% endfor %}
|
||||||
</select>
|
</select>
|
||||||
<p class="field__hint">
|
<p class="field__hint">
|
||||||
Where new chats on this model start. Anyone can change it per chat with
|
A <em>seed</em>, not a per-request setting: it is copied onto a chat when
|
||||||
|
the chat is created and when somebody switches to this model, and from
|
||||||
|
then on the chat's own value is what is sent. Changing it here therefore
|
||||||
|
does nothing to chats that already exist. The composer's picker shows
|
||||||
|
whichever level is actually in force, so what somebody sees there is
|
||||||
|
what goes out. Anyone can change it per chat with
|
||||||
<span class="mono">/effort</span>, and the control only appears on a
|
<span class="mono">/effort</span>, and the control only appears on a
|
||||||
model marked <strong>Reasoning</strong> above.
|
model marked <strong>Reasoning</strong> above.
|
||||||
<br>
|
<br>
|
||||||
|
|||||||
@@ -140,13 +140,100 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{# The same menu the `@` key opens, for anyone who would rather press
|
{% endif %}
|
||||||
than type. It inserts the character and gets out of the way. #}
|
|
||||||
<button class="btn btn--icon composer__btn" type="button" data-mention-open
|
{#
|
||||||
aria-label="Mention a file or a document"
|
What this chat may use.
|
||||||
title="Mention a file or a document">
|
|
||||||
{{ icon("at") }}
|
This slot used to be an `@` button that inserted the character and
|
||||||
|
got out of the way -- which the `@` key already does, from the
|
||||||
|
keyboard, without a button. Typing `@` is untouched; composer.js
|
||||||
|
recognises the token on its own and knows nothing about this menu.
|
||||||
|
|
||||||
|
The rows are `<label>`s wrapping a checkbox and deliberately carry
|
||||||
|
no `role="menuitem"`: ui.js closes a picker when a menuitem is
|
||||||
|
clicked, which is right for an action menu and wrong for a list of
|
||||||
|
switches you want to set several of. That is the whole reason this
|
||||||
|
needs no JavaScript at all.
|
||||||
|
|
||||||
|
The verb is on the CHECKBOX, not on the label and not on a form: the
|
||||||
|
element carrying `name` has to be the element carrying the request,
|
||||||
|
which is what tests/conftest.py:control_named exists to pin.
|
||||||
|
|
||||||
|
Only on an existing chat -- there is no row to write to before one
|
||||||
|
exists, and a switch that went nowhere is worse than no switch.
|
||||||
|
#}
|
||||||
|
{% set has_scope = chat and (scope_families or scope_skills) %}
|
||||||
|
{% if has_scope or can.get("files.upload") %}
|
||||||
|
<div class="picker picker--up" data-picker>
|
||||||
|
<button class="btn btn--icon composer__btn" type="button" data-picker-toggle
|
||||||
|
aria-haspopup="menu" aria-expanded="false"
|
||||||
|
aria-label="{{ 'What this chat can use' if has_scope else 'Mention a file' }}"
|
||||||
|
title="{{ 'What this chat can use' if has_scope else 'Mention a file' }}">
|
||||||
|
{{ icon("sliders" if has_scope else "at") }}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
<div class="picker__menu picker__menu--scope" data-picker-menu role="menu"
|
||||||
|
hidden aria-label="What this chat can use">
|
||||||
|
{% if has_scope %}
|
||||||
|
<p class="picker__lede">
|
||||||
|
Switched off here only. Everything is on unless you say otherwise.
|
||||||
|
</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if scope_families %}
|
||||||
|
<p class="picker__group">Tools</p>
|
||||||
|
{% for family in scope_families %}
|
||||||
|
<label class="picker__option picker__option--toggle">
|
||||||
|
<input type="checkbox" name="on" value="true"
|
||||||
|
{{ 'checked' if family.on }}
|
||||||
|
hx-post="/api/chats/{{ chat.id }}/scope" hx-swap="none"
|
||||||
|
hx-vals='{"kind": "family", "name": "{{ family.gate }}"}'>
|
||||||
|
<span class="picker__option-body">
|
||||||
|
<span class="picker__option-name">{{ family.label }}</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if scope_skills %}
|
||||||
|
<p class="picker__group">Skills</p>
|
||||||
|
{% for skill in scope_skills %}
|
||||||
|
<label class="picker__option picker__option--toggle">
|
||||||
|
<input type="checkbox" name="on" value="true"
|
||||||
|
{{ 'checked' if skill.on }}
|
||||||
|
hx-post="/api/chats/{{ chat.id }}/scope" hx-swap="none"
|
||||||
|
hx-vals='{"kind": "skill", "name": "{{ skill.name }}"}'>
|
||||||
|
<span class="picker__option-body">
|
||||||
|
<span class="picker__option-name">{{ skill.name }}</span>
|
||||||
|
{% if skill.description %}
|
||||||
|
<span class="picker__option-note">{{ skill.description }}</span>
|
||||||
|
{% endif %}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{# The affordance the `@` button used to be, kept as one row so
|
||||||
|
nothing is lost by replacing the button -- and it is what this
|
||||||
|
menu holds on a chat that does not exist yet, where there is no
|
||||||
|
scope to narrow.
|
||||||
|
|
||||||
|
This one DOES carry role="menuitem", unlike the switches above:
|
||||||
|
it is an action, so ui.js closing the picker after it is
|
||||||
|
exactly right. #}
|
||||||
|
{% if can.get("files.upload") %}
|
||||||
|
<button class="picker__option" type="button" role="menuitem"
|
||||||
|
data-mention-open>
|
||||||
|
{{ icon("at", "icon--sm") }}
|
||||||
|
<span class="picker__option-body">
|
||||||
|
<span class="picker__option-name">Mention a file or a document</span>
|
||||||
|
<span class="picker__option-note">Or just type @</span>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -256,9 +343,23 @@
|
|||||||
form="chat-params-form"
|
form="chat-params-form"
|
||||||
hx-patch="/api/chats/{{ chat.id }}" hx-swap="none"
|
hx-patch="/api/chats/{{ chat.id }}" hx-swap="none"
|
||||||
{% endif %}>
|
{% endif %}>
|
||||||
{% set chosen = chat.params_json.get('reasoning_effort') if chat
|
{#
|
||||||
|
It shows the level actually in force, never the word "default".
|
||||||
|
|
||||||
|
On an existing chat that is `resolved_effort`, which is the chat's
|
||||||
|
own value and nothing else -- `build_request` reads the same field,
|
||||||
|
so what is shown is what is sent, by construction. Before there is a
|
||||||
|
chat it is the model's configured level, which `_new_chat` seeds
|
||||||
|
onto the row, so the same holds.
|
||||||
|
|
||||||
|
"off" is a sentinel and NOT an empty value. `start_chat` declares
|
||||||
|
`reasoning_effort: str = Form("")`, so absent and empty are
|
||||||
|
indistinguishable there -- with `value=""` the reader would pick off
|
||||||
|
and silently get the model's default.
|
||||||
|
#}
|
||||||
|
{% set chosen = resolved_effort if chat
|
||||||
else (current_model.params_json or {}).get('reasoning_effort') %}
|
else (current_model.params_json or {}).get('reasoning_effort') %}
|
||||||
<option value="">Effort: default</option>
|
<option value="off" {{ 'selected' if chosen not in efforts }}>Effort: off</option>
|
||||||
{% for value in efforts %}
|
{% for value in efforts %}
|
||||||
<option value="{{ value }}" {{ 'selected' if chosen == value }}>
|
<option value="{{ value }}" {{ 'selected' if chosen == value }}>
|
||||||
Effort: {{ value }}
|
Effort: {{ value }}
|
||||||
|
|||||||
@@ -686,7 +686,7 @@ async def test_an_ordinary_chat_is_told_none_of_it(db, user_id, machine):
|
|||||||
|
|
||||||
|
|
||||||
async def test_an_agent_chat_is_told_its_real_round_budget(db, user_id, machine):
|
async def test_an_agent_chat_is_told_its_real_round_budget(db, user_id, machine):
|
||||||
"""MAX_ROUNDS is three. An agent chat gets forty, and telling it three would
|
"""MAX_ROUNDS is one. An agent chat gets hundreds, and telling it one would
|
||||||
be a false fact about its own budget on every turn."""
|
be a false fact about its own budget on every turn."""
|
||||||
from lembas.services import harness
|
from lembas.services import harness
|
||||||
|
|
||||||
|
|||||||
@@ -699,3 +699,79 @@ def test_the_sidebar_shows_an_unread_dot(client: TestClient, db, registered, mak
|
|||||||
page = client.get("/chat").text
|
page = client.get("/chat").text
|
||||||
assert f'id="unread-{chat_id}" class="unread-dot"' in page
|
assert f'id="unread-{chat_id}" class="unread-dot"' in page
|
||||||
assert 'hx-get="/api/chats/unread"' in page
|
assert 'hx-get="/api/chats/unread"' in page
|
||||||
|
|
||||||
|
|
||||||
|
# --- The composer's one row --------------------------------------------------
|
||||||
|
def test_the_send_button_is_the_last_thing_in_the_toolbar(client: TestClient, db, registered):
|
||||||
|
"""What the layout depends on. `.composer__actions` is pushed right by
|
||||||
|
`margin-left: auto` and refuses to shrink, and both only work while it is
|
||||||
|
the last child -- when the row wrapped instead, it was the last child that
|
||||||
|
dropped to a second line, so an agent chat pushed Send and the microphone
|
||||||
|
off the row entirely."""
|
||||||
|
_add_connection(db)
|
||||||
|
html = client.get("/chat").text
|
||||||
|
toolbar = html.split('class="composer__toolbar"', 1)[1]
|
||||||
|
|
||||||
|
assert 'class="composer__actions"' in toolbar
|
||||||
|
assert toolbar.index("composer__actions") > toolbar.index("composer__tools")
|
||||||
|
assert "data-composer-action" in toolbar
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_agent_controls_shrink_rather_than_pushing_send_off_the_row(
|
||||||
|
client: TestClient, db, registered
|
||||||
|
):
|
||||||
|
"""They live in `.composer__context`, which is the only flex child allowed
|
||||||
|
to shrink and scroll. Anything moved out of it stops shrinking and starts
|
||||||
|
pushing Send onto a second line again -- which is what this whole row was
|
||||||
|
rearranged to stop."""
|
||||||
|
from lembas.db.models import SshProfile
|
||||||
|
from lembas.services import settings_store
|
||||||
|
|
||||||
|
_add_connection(db)
|
||||||
|
settings_store.update(db, {"enabled": True}, key=settings_store.AGENTS)
|
||||||
|
db.add(
|
||||||
|
SshProfile(
|
||||||
|
owner_id=_user_id(db),
|
||||||
|
name="Test box",
|
||||||
|
host="127.0.0.1",
|
||||||
|
port=22,
|
||||||
|
username="t",
|
||||||
|
host_key="k",
|
||||||
|
host_fingerprint="f",
|
||||||
|
default_dir="/work",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
html = client.get("/chat").text
|
||||||
|
if "composer__context" not in html:
|
||||||
|
pytest.skip("agent chats are unavailable here")
|
||||||
|
|
||||||
|
# The three that appear when Agent is chosen sit between the start of
|
||||||
|
# `.composer__context` and the start of `.composer__actions` -- which is
|
||||||
|
# what puts them inside the one child that is allowed to give, and keeps
|
||||||
|
# the actions last.
|
||||||
|
opens = html.index('class="composer__context"')
|
||||||
|
actions = html.index('class="composer__actions"')
|
||||||
|
for control in ("ssh_profile_id", "data-dir-browse", 'name="agent_mode"'):
|
||||||
|
assert opens < html.index(control) < actions, control
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_chat_stylesheet_has_no_media_queries(client: TestClient):
|
||||||
|
"""A stated design constraint, pinned so nobody 'fixes' a layout with a
|
||||||
|
breakpoint later. The composer fits at every width by saying which child
|
||||||
|
gives, not by rearranging itself at a threshold."""
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import lembas
|
||||||
|
|
||||||
|
css = Path(lembas.__file__).parent / "web/static/css/chat.css"
|
||||||
|
assert "@media" not in css.read_text()
|
||||||
|
|
||||||
|
|
||||||
|
def _user_id(db):
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from lembas.db.models import User
|
||||||
|
|
||||||
|
return db.scalar(select(User.id))
|
||||||
|
|||||||
@@ -0,0 +1,284 @@
|
|||||||
|
"""What one chat may use, and the rule that it can only ever be less.
|
||||||
|
|
||||||
|
The security-shaped test here is `test_a_chat_cannot_widen_what_it_was_not_given`.
|
||||||
|
The scope is applied inside `resolve_tools` *after* the model's capabilities,
|
||||||
|
the reader's permissions and the instance configuration, so a crafted POST
|
||||||
|
turning something on reaches a tool those gates have already removed. Asserting
|
||||||
|
that against the UI path alone would prove nothing, so it is asserted against a
|
||||||
|
directly-written column.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from lembas.db.models import Chat, Connection, Model, User
|
||||||
|
from lembas.services import settings_store
|
||||||
|
from lembas.services import tools as tools_service
|
||||||
|
from lembas.services.library import skills as skills_service
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def chat(db, user_id):
|
||||||
|
connection = Connection(name="c", base_url="http://127.0.0.1:1", api_key_encrypted="")
|
||||||
|
db.add(connection)
|
||||||
|
db.commit()
|
||||||
|
db.add(Model(connection_id=connection.id, model_id="m", capabilities_json={"tools": True}))
|
||||||
|
db.commit()
|
||||||
|
row = Chat(user_id=user_id, model_id="m", connection_id=connection.id)
|
||||||
|
db.add(row)
|
||||||
|
db.commit()
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def _names(db, chat, user) -> set[str]:
|
||||||
|
return set(tools_service.resolve_tools(db, chat, user).by_name)
|
||||||
|
|
||||||
|
|
||||||
|
# --- The route ------------------------------------------------------------------
|
||||||
|
def test_switching_a_family_off_writes_it_to_the_row(client: TestClient, db, chat, registered):
|
||||||
|
response = client.post(
|
||||||
|
f"/api/chats/{chat.id}/scope", data={"kind": "family", "name": "web_search"}
|
||||||
|
)
|
||||||
|
assert response.status_code == 204
|
||||||
|
|
||||||
|
db.expire_all()
|
||||||
|
assert db.get(Chat, chat.id).scope_json["families"]["web_search"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_switching_it_back_on_removes_the_key(client: TestClient, db, chat, registered):
|
||||||
|
"""On is stored by *removing* the key, so absent stays the single
|
||||||
|
representation of on and the column cannot grow a row per family per chat."""
|
||||||
|
client.post(f"/api/chats/{chat.id}/scope", data={"kind": "family", "name": "notes"})
|
||||||
|
client.post(
|
||||||
|
f"/api/chats/{chat.id}/scope",
|
||||||
|
data={"kind": "family", "name": "notes", "on": "true"},
|
||||||
|
)
|
||||||
|
|
||||||
|
db.expire_all()
|
||||||
|
assert "families" not in db.get(Chat, chat.id).scope_json
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_route_refuses_a_kind_it_does_not_know(client: TestClient, chat, registered):
|
||||||
|
response = client.post(
|
||||||
|
f"/api/chats/{chat.id}/scope", data={"kind": "everything", "name": "x"}
|
||||||
|
)
|
||||||
|
assert response.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_route_refuses_the_wrong_verb(client: TestClient, chat, registered):
|
||||||
|
"""The half of `tests/test_agent_mode.py`'s lesson that actually caught the
|
||||||
|
bug: a control wired to a method a route does not serve fails silently."""
|
||||||
|
assert client.get(f"/api/chats/{chat.id}/scope").status_code == 405
|
||||||
|
|
||||||
|
|
||||||
|
def test_somebody_elses_chat_is_not_reachable(client: TestClient, db, chat, registered):
|
||||||
|
from lembas.security.passwords import hash_password
|
||||||
|
|
||||||
|
other = User(name="Sam", email="s@shire.test", password_hash=hash_password("secret123"))
|
||||||
|
db.add(other)
|
||||||
|
db.commit()
|
||||||
|
chat.user_id = other.id
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
response = client.post(
|
||||||
|
f"/api/chats/{chat.id}/scope", data={"kind": "family", "name": "notes"}
|
||||||
|
)
|
||||||
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
# --- What it does to the offer ------------------------------------------------------
|
||||||
|
def test_a_family_switched_off_is_not_offered(db, chat, user_id):
|
||||||
|
settings_store.update(db, {"enabled": True}, key=settings_store.SEARCH)
|
||||||
|
user = db.get(User, user_id)
|
||||||
|
assert "web_search" in _names(db, chat, user)
|
||||||
|
|
||||||
|
chat.scope_json = {"families": {"web_search": False}}
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
assert "web_search" not in _names(db, chat, user)
|
||||||
|
|
||||||
|
|
||||||
|
def test_switching_a_gate_off_takes_every_tool_in_it(db, chat, user_id):
|
||||||
|
"""A gate is one switch, not five. `notes` covers search, get, create, edit
|
||||||
|
and delete -- which is the same reasoning the per-model capability
|
||||||
|
checkboxes carry."""
|
||||||
|
user = db.get(User, user_id)
|
||||||
|
chat.scope_json = {"families": {"notes": False}}
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
offered = _names(db, chat, user)
|
||||||
|
assert not [name for name in offered if name.startswith("notes_")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_chat_cannot_widen_what_it_was_not_given(db, chat, user_id):
|
||||||
|
"""The one that matters. Scope is applied AFTER the gates and never instead
|
||||||
|
of them, so writing `True` into the column reaches a tool the model's
|
||||||
|
capabilities had already removed."""
|
||||||
|
user = db.get(User, user_id)
|
||||||
|
model = db.scalar(tools_service.select(Model))
|
||||||
|
model.capabilities_json = {"tools": True, "tool_notes": False}
|
||||||
|
chat.scope_json = {"families": {"notes": True}}
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
assert "notes_search" not in _names(db, chat, user)
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_unknown_family_in_the_column_changes_nothing(db, chat, user_id):
|
||||||
|
user = db.get(User, user_id)
|
||||||
|
before = _names(db, chat, user)
|
||||||
|
chat.scope_json = {"families": {"not-a-family": False}}
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
assert _names(db, chat, user) == before
|
||||||
|
|
||||||
|
|
||||||
|
# --- Skills -------------------------------------------------------------------------
|
||||||
|
@pytest.fixture
|
||||||
|
def skill(db, user_id):
|
||||||
|
return skills_service.create(
|
||||||
|
db,
|
||||||
|
owner=db.get(User, user_id),
|
||||||
|
name="weekly-report",
|
||||||
|
description="When asked for the weekly report.",
|
||||||
|
body="Do the thing.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_skill_switched_off_leaves_the_index(db, chat, user_id, skill):
|
||||||
|
user = db.get(User, user_id)
|
||||||
|
assert "weekly-report" in skills_service.index_block(db, user)
|
||||||
|
assert "weekly-report" not in skills_service.index_block(
|
||||||
|
db, user, exclude=["weekly-report"]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_skill_switched_off_cannot_be_fetched_anyway(db, chat, user_id, skill):
|
||||||
|
"""Without this the narrowing is advisory: a model can name a skill it was
|
||||||
|
never shown -- from an earlier turn, from a note -- and the runner would
|
||||||
|
happily fetch it. Same rule as "what may be run is what was offered"."""
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
user = db.get(User, user_id)
|
||||||
|
chat.scope_json = {"skills": {"weekly-report": False}}
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
context = tools_service.context_for(db, user, chat)
|
||||||
|
outcome = asyncio.run(
|
||||||
|
tools_service.run_tool(context, "skill_get", '{"name": "weekly-report"}')
|
||||||
|
)
|
||||||
|
assert outcome.event["status"] == "error"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_last_skill_switched_off_withdraws_skill_get(db, chat, user_id, skill):
|
||||||
|
user = db.get(User, user_id)
|
||||||
|
assert "skill_get" in _names(db, chat, user)
|
||||||
|
|
||||||
|
chat.scope_json = {"skills": {"weekly-report": False}}
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
offered = _names(db, chat, user)
|
||||||
|
assert "skill_get" not in offered
|
||||||
|
assert "skill_create" in offered, "writing the first one is still possible"
|
||||||
|
|
||||||
|
|
||||||
|
# --- The zero-skills asymmetry --------------------------------------------------------
|
||||||
|
def test_with_no_skills_nothing_tells_the_model_to_read_one(db, chat, user_id):
|
||||||
|
"""The complaint this fixes. `tool.skills` was gated on the family alone, so
|
||||||
|
a person with no skills got "read the full instructions with skill_get"
|
||||||
|
above a list that was not there -- and got skill_get in the tools array, so
|
||||||
|
the model spent a round finding out."""
|
||||||
|
from lembas.services import harness
|
||||||
|
|
||||||
|
user = db.get(User, user_id)
|
||||||
|
offered = tools_service.resolve_tools(db, chat, user).schemas
|
||||||
|
text = harness.compose(db, user, offered, chat)
|
||||||
|
|
||||||
|
assert "skill_get" not in _names(db, chat, user)
|
||||||
|
assert "skill_get" not in text
|
||||||
|
assert "Skills available" not in text
|
||||||
|
# The half that is most useful with none: you can save the first one.
|
||||||
|
assert "save it with skill_create" in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_with_a_skill_the_reading_guidance_comes_back(db, chat, user_id, skill):
|
||||||
|
from lembas.services import harness
|
||||||
|
|
||||||
|
user = db.get(User, user_id)
|
||||||
|
offered = tools_service.resolve_tools(db, chat, user).schemas
|
||||||
|
text = harness.compose(db, user, offered, chat)
|
||||||
|
|
||||||
|
assert "skill_get" in text
|
||||||
|
assert "weekly-report" in text
|
||||||
|
assert "save it with skill_create" in text
|
||||||
|
|
||||||
|
|
||||||
|
# --- The tool list --------------------------------------------------------------------
|
||||||
|
def test_the_model_is_told_what_it_actually_has(db, chat, user_id):
|
||||||
|
"""`tool_names` was resolved and documented with no fragment reading it. A
|
||||||
|
model that has to discover its own list by calling something and being told
|
||||||
|
it does not exist spends a round finding out -- and with one round, that is
|
||||||
|
the whole reply."""
|
||||||
|
from lembas.services import harness
|
||||||
|
|
||||||
|
user = db.get(User, user_id)
|
||||||
|
offered = tools_service.resolve_tools(db, chat, user).schemas
|
||||||
|
text = harness.compose(db, user, offered, chat)
|
||||||
|
|
||||||
|
assert "The tools you have on this request are:" in text
|
||||||
|
for name in tools_service.resolve_tools(db, chat, user).by_name:
|
||||||
|
assert name in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_family_switched_off_disappears_from_the_list_too(db, chat, user_id):
|
||||||
|
from lembas.services import harness
|
||||||
|
|
||||||
|
settings_store.update(db, {"enabled": True}, key=settings_store.SEARCH)
|
||||||
|
user = db.get(User, user_id)
|
||||||
|
chat.scope_json = {"families": {"web_search": False}}
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
offered = tools_service.resolve_tools(db, chat, user).schemas
|
||||||
|
text = harness.compose(db, user, offered, chat)
|
||||||
|
|
||||||
|
assert "web_search" not in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_tools_means_no_list(db, chat, user_id):
|
||||||
|
from lembas.services import harness
|
||||||
|
|
||||||
|
text = harness.compose(db, db.get(User, user_id), [])
|
||||||
|
assert "The tools you have on this request" not in text
|
||||||
|
|
||||||
|
|
||||||
|
# --- The control that writes ------------------------------------------------------------
|
||||||
|
def test_the_verb_is_on_every_checkbox(client: TestClient, db, chat, registered):
|
||||||
|
"""The element carrying `name` has to be the element carrying the request.
|
||||||
|
Two selects lost an entire release to getting this wrong -- their verb was
|
||||||
|
on a form the event never reached, and the tests passed throughout because
|
||||||
|
they asserted the markup rather than the property.
|
||||||
|
|
||||||
|
`conftest.control_named` is the helper for this and wants exactly one match;
|
||||||
|
there is one checkbox per family here, so the same check is made over all of
|
||||||
|
them, which is the stronger claim anyway.
|
||||||
|
"""
|
||||||
|
from html.parser import HTMLParser
|
||||||
|
|
||||||
|
settings_store.update(db, {"enabled": True}, key=settings_store.SEARCH)
|
||||||
|
html = client.get(f"/chat/{chat.id}").text
|
||||||
|
|
||||||
|
found: list[dict[str, str]] = []
|
||||||
|
|
||||||
|
class Finder(HTMLParser):
|
||||||
|
def handle_starttag(self, tag, attrs):
|
||||||
|
got = {key: (value or "") for key, value in attrs}
|
||||||
|
if got.get("name") == "on":
|
||||||
|
found.append(got)
|
||||||
|
|
||||||
|
Finder().feed(html)
|
||||||
|
|
||||||
|
assert found, "the scope menu rendered no switches"
|
||||||
|
for box in found:
|
||||||
|
assert box.get("hx-post") == f"/api/chats/{chat.id}/scope"
|
||||||
|
assert "kind" in box.get("hx-vals", ""), "and says which thing it is"
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"""The keyboard, checked without a runtime.
|
||||||
|
|
||||||
|
There is no JavaScript test runner here and hard rule 1 keeps Node out of the
|
||||||
|
project, so the behaviour is driven by hand under a DOM stub before committing.
|
||||||
|
What can be pinned in the suite is the invariant the file states about itself:
|
||||||
|
`/help` reads `SHORTCUTS`, so a shortcut that is not in that list is a shortcut
|
||||||
|
nobody can discover. That is the direction this actually rots -- a key gets
|
||||||
|
added to the handler and the sheet is forgotten.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import lembas
|
||||||
|
|
||||||
|
SOURCE = (
|
||||||
|
Path(lembas.__file__).parent / "web/static/js/commands.js"
|
||||||
|
).read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
# The declared list, up to where the command table starts.
|
||||||
|
SHORTCUTS = SOURCE[SOURCE.index("var SHORTCUTS") : SOURCE.index("/* --- The table")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_letter_key_the_handlers_match_is_described():
|
||||||
|
letters = {match[-1] for match in re.findall(r'event\.code === "Key([A-Z])"', SOURCE)}
|
||||||
|
assert letters, "no letter shortcuts found at all, which means the regex is wrong"
|
||||||
|
|
||||||
|
missing = [letter for letter in sorted(letters) if f"+ {letter}" not in SHORTCUTS]
|
||||||
|
assert not missing, f"not in /help: {missing}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_three_new_ones_are_there():
|
||||||
|
"""Named rather than only counted, because the point of them is being
|
||||||
|
findable: Enter already sends *inside the box*, and dictation and read-aloud
|
||||||
|
were click-only."""
|
||||||
|
assert "Ctrl/⌘ + Enter" in SHORTCUTS
|
||||||
|
assert "Alt + M" in SHORTCUTS
|
||||||
|
assert "Alt + R" in SHORTCUTS
|
||||||
|
|
||||||
|
|
||||||
|
def test_dictation_is_not_bound_to_alt_d():
|
||||||
|
"""Alt+D is the address bar in Chrome and Firefox on Windows and Linux. A
|
||||||
|
shortcut the browser wins is a shortcut that looks broken."""
|
||||||
|
assert 'event.code === "KeyD"' not in SOURCE
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_shortcuts_are_matched_on_the_physical_key():
|
||||||
|
"""The file's own stated rule: `event.code`, so a Dvorak or Slovak layout
|
||||||
|
gets the same shortcuts rather than whichever letters sit there."""
|
||||||
|
assert "event.key ===" not in SOURCE
|
||||||
|
|
||||||
|
|
||||||
|
def test_send_from_anywhere_never_means_stop():
|
||||||
|
"""Send and Stop are the same element. Ctrl+Enter reaching it while it is
|
||||||
|
Stop would abandon a reply on a key people press to send -- and Esc already
|
||||||
|
stops."""
|
||||||
|
window = SOURCE[SOURCE.index('event.code === "Enter"') :][:600]
|
||||||
|
assert 'composerAction === "send"' in window
|
||||||
@@ -230,3 +230,139 @@ def test_a_nonsense_effort_at_the_start_falls_back(client: TestClient, db, regis
|
|||||||
)
|
)
|
||||||
|
|
||||||
assert db.scalars(select(Chat)).one().params_json["reasoning_effort"] == "high"
|
assert db.scalars(select(Chat)).one().params_json["reasoning_effort"] == "high"
|
||||||
|
|
||||||
|
|
||||||
|
# --- What the picker says is what is sent ---------------------------------------
|
||||||
|
def test_the_resolver_is_what_the_request_carries(client: TestClient, db, registered):
|
||||||
|
"""One resolver, so the control and the request cannot disagree. That
|
||||||
|
disagreement is the whole reason the picker said "default": it named no
|
||||||
|
level, and was true of nothing in particular."""
|
||||||
|
chat = _chat(db, "high")
|
||||||
|
|
||||||
|
assert chat_service.resolved_effort(chat) == "high"
|
||||||
|
assert chat_service.build_request(db, chat)["reasoning_effort"] == "high"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_cleared_effort_is_not_resurrected_by_the_models_default(
|
||||||
|
client: TestClient, db, registered
|
||||||
|
):
|
||||||
|
"""What the no-fallback decision buys. If `build_request` fell back to the
|
||||||
|
model, `update_chat` storing None for a cleared effort would be undone
|
||||||
|
underneath it and the off option would silently do nothing."""
|
||||||
|
model = _model(db)
|
||||||
|
model.params_json = {"reasoning_effort": "high"}
|
||||||
|
user = db.scalars(select(User)).first()
|
||||||
|
chat = Chat(
|
||||||
|
user_id=user.id,
|
||||||
|
model_id=model.model_id,
|
||||||
|
connection_id=model.connection_id,
|
||||||
|
params_json={"reasoning_effort": None},
|
||||||
|
)
|
||||||
|
db.add(chat)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
assert chat_service.resolved_effort(chat) == ""
|
||||||
|
body = chat_service.build_request(db, chat)
|
||||||
|
assert "reasoning_effort" not in body
|
||||||
|
assert "chat_template_kwargs" not in body
|
||||||
|
|
||||||
|
|
||||||
|
def test_choosing_off_before_the_chat_exists_sends_nothing(
|
||||||
|
client: TestClient, db, registered
|
||||||
|
):
|
||||||
|
"""The one that would otherwise ship broken. `start_chat` declares
|
||||||
|
`Form("")`, so an absent field and an empty one are the same thing there --
|
||||||
|
with `value=""` on the off option the reader picks off, the value falls out
|
||||||
|
of EFFORTS, and the model's default seeded onto the row stays. They get
|
||||||
|
"high"."""
|
||||||
|
model = _model(db)
|
||||||
|
model.params_json = {"reasoning_effort": "high"}
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
client.post(
|
||||||
|
"/api/chats/start",
|
||||||
|
data={"content": "hello", "model_id": "m", "reasoning_effort": "off"},
|
||||||
|
)
|
||||||
|
chat = db.scalars(select(Chat)).first()
|
||||||
|
|
||||||
|
assert not (chat.params_json or {}).get("reasoning_effort")
|
||||||
|
assert "reasoning_effort" not in chat_service.build_request(db, chat)
|
||||||
|
|
||||||
|
|
||||||
|
def test_patching_off_clears_it(client: TestClient, db, registered):
|
||||||
|
chat = _chat(db, "high")
|
||||||
|
client.patch(f"/api/chats/{chat.id}", data={"reasoning_effort": "off"})
|
||||||
|
|
||||||
|
db.expire_all()
|
||||||
|
assert chat_service.resolved_effort(db.get(Chat, chat.id)) == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_switching_model_seeds_an_effort_that_was_never_chosen(
|
||||||
|
client: TestClient, db, registered
|
||||||
|
):
|
||||||
|
"""So "what the picker shows is what is sent" stays true after a switch."""
|
||||||
|
chat = _chat(db)
|
||||||
|
second = Model(
|
||||||
|
connection_id=chat.connection_id,
|
||||||
|
model_id="m2",
|
||||||
|
capabilities_json={"reasoning": True},
|
||||||
|
params_json={"reasoning_effort": "medium"},
|
||||||
|
)
|
||||||
|
db.add(second)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
client.patch(f"/api/chats/{chat.id}", data={"model_id": "m2"})
|
||||||
|
|
||||||
|
db.expire_all()
|
||||||
|
assert chat_service.resolved_effort(db.get(Chat, chat.id)) == "medium"
|
||||||
|
|
||||||
|
|
||||||
|
def test_switching_model_does_not_overwrite_a_chosen_effort(
|
||||||
|
client: TestClient, db, registered
|
||||||
|
):
|
||||||
|
chat = _chat(db, "low")
|
||||||
|
second = Model(
|
||||||
|
connection_id=chat.connection_id,
|
||||||
|
model_id="m2",
|
||||||
|
capabilities_json={"reasoning": True},
|
||||||
|
params_json={"reasoning_effort": "high"},
|
||||||
|
)
|
||||||
|
db.add(second)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
client.patch(f"/api/chats/{chat.id}", data={"model_id": "m2"})
|
||||||
|
|
||||||
|
db.expire_all()
|
||||||
|
assert chat_service.resolved_effort(db.get(Chat, chat.id)) == "low"
|
||||||
|
|
||||||
|
|
||||||
|
def test_switching_model_does_not_resurrect_a_cleared_effort(
|
||||||
|
client: TestClient, db, registered
|
||||||
|
):
|
||||||
|
"""`None` means somebody cleared it deliberately. Only an ABSENT key is
|
||||||
|
seeded, or "off" would silently undo itself on the next model change."""
|
||||||
|
chat = _chat(db, "high")
|
||||||
|
client.patch(f"/api/chats/{chat.id}", data={"reasoning_effort": "off"})
|
||||||
|
second = Model(
|
||||||
|
connection_id=chat.connection_id,
|
||||||
|
model_id="m2",
|
||||||
|
capabilities_json={"reasoning": True},
|
||||||
|
params_json={"reasoning_effort": "high"},
|
||||||
|
)
|
||||||
|
db.add(second)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
client.patch(f"/api/chats/{chat.id}", data={"model_id": "m2"})
|
||||||
|
|
||||||
|
db.expire_all()
|
||||||
|
assert chat_service.resolved_effort(db.get(Chat, chat.id)) == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_picker_never_says_default(client: TestClient, db, registered):
|
||||||
|
"""The one markup assertion. It named no level and was true of nothing."""
|
||||||
|
chat = _chat(db, "medium")
|
||||||
|
html = client.get(f"/chat/{chat.id}").text
|
||||||
|
|
||||||
|
assert "Effort: default" not in html
|
||||||
|
assert "Effort: off" in html
|
||||||
|
assert '<option value="medium" selected>' in html.replace("\n", "").replace(" ", "")
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
"""Memory: the two ways it used to lose somebody's facts quietly.
|
||||||
|
|
||||||
|
`memory_forget` was a case-insensitive substring FIRST-match delete with nothing
|
||||||
|
warning about it, so a short fragment removed whichever memory happened to be
|
||||||
|
older -- and a wrong deletion here is not something anybody finds out about.
|
||||||
|
`memory_add` had no defence against the same fact being stored four times in
|
||||||
|
slightly different words, which costs the window forever *and* makes every
|
||||||
|
forget after it ambiguous.
|
||||||
|
|
||||||
|
Both are asserted on the rows, not on the wording.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
|
||||||
|
from lembas.db.models import Memory, User
|
||||||
|
from lembas.security.passwords import hash_password
|
||||||
|
from lembas.services import tools as tools_service
|
||||||
|
from lembas.services.library import memories as memories_service
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def owner(db):
|
||||||
|
user = User(name="Frodo", email="f@shire.test", password_hash=hash_password("x"))
|
||||||
|
db.add(user)
|
||||||
|
db.commit()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _count(db, owner) -> int:
|
||||||
|
return db.scalar(
|
||||||
|
select(func.count()).select_from(Memory).where(Memory.owner_id == owner.id)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _forget(owner, text: str):
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
context = tools_service.ToolContext(owner_id=owner.id)
|
||||||
|
return asyncio.run(tools_service.run_tool(context, "memory_forget", f'{{"content": "{text}"}}'))
|
||||||
|
|
||||||
|
|
||||||
|
# --- Forgetting ----------------------------------------------------------------
|
||||||
|
def test_an_ambiguous_forget_removes_nothing(db, owner):
|
||||||
|
"""Two memories about coffee; "coffee" names neither of them."""
|
||||||
|
memories_service.add(db, owner=owner, content="Drinks coffee black.")
|
||||||
|
memories_service.add(db, owner=owner, content="Allergic to coffee.")
|
||||||
|
|
||||||
|
outcome = _forget(owner, "coffee")
|
||||||
|
|
||||||
|
assert _count(db, owner) == 2
|
||||||
|
assert outcome.event["status"] == "error"
|
||||||
|
assert "Drinks coffee black." in outcome.content
|
||||||
|
assert "Allergic to coffee." in outcome.content
|
||||||
|
|
||||||
|
|
||||||
|
def test_quoting_a_memory_in_full_removes_that_one(db, owner):
|
||||||
|
"""Exact-first is what makes this work. "Drinks coffee." is a substring of
|
||||||
|
"Drinks coffee. Never tea." too, so a substring-only match would call the
|
||||||
|
unambiguous case ambiguous and refuse to do anything at all."""
|
||||||
|
short = memories_service.add(db, owner=owner, content="Drinks coffee.")
|
||||||
|
long = memories_service.add(db, owner=owner, content="Drinks coffee. Never tea.")
|
||||||
|
short_id, long_id = short.id, long.id
|
||||||
|
|
||||||
|
_forget(owner, "Drinks coffee.")
|
||||||
|
|
||||||
|
db.expire_all()
|
||||||
|
assert db.get(Memory, short_id) is None
|
||||||
|
assert db.get(Memory, long_id) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_forgetting_something_that_is_not_there_says_so(db, owner):
|
||||||
|
memories_service.add(db, owner=owner, content="Drinks coffee black.")
|
||||||
|
outcome = _forget(owner, "tea")
|
||||||
|
assert _count(db, owner) == 1
|
||||||
|
assert outcome.event["status"] == "error"
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_unambiguous_fragment_still_works(db, owner):
|
||||||
|
"""Quoting in full is what the description asks for, but a fragment that
|
||||||
|
genuinely names one memory should not be made to fail."""
|
||||||
|
memories_service.add(db, owner=owner, content="Drinks coffee black.")
|
||||||
|
memories_service.add(db, owner=owner, content="Lives in Bree.")
|
||||||
|
|
||||||
|
_forget(owner, "Bree")
|
||||||
|
|
||||||
|
db.expire_all()
|
||||||
|
assert _count(db, owner) == 1
|
||||||
|
|
||||||
|
|
||||||
|
# --- Adding --------------------------------------------------------------------
|
||||||
|
def test_an_exact_duplicate_creates_nothing(db, owner):
|
||||||
|
first = memories_service.add(db, owner=owner, content="Prefers metric units.")
|
||||||
|
again = memories_service.add(db, owner=owner, content=" Prefers metric units. ")
|
||||||
|
|
||||||
|
assert _count(db, owner) == 1
|
||||||
|
assert again.id == first.id
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_limit_refuses_and_does_not_tell_the_model_to_guess(db, owner, monkeypatch):
|
||||||
|
"""Past MAX_TOTAL_CHARS the injected block is truncated, so the model is not
|
||||||
|
shown every memory. Telling it to remove one to make room asks it to choose
|
||||||
|
blind -- and the forget path above is exactly where blind guessing bites."""
|
||||||
|
monkeypatch.setattr(memories_service, "MAX_RECORDS", 3)
|
||||||
|
for index in range(3):
|
||||||
|
memories_service.add(db, owner=owner, content=f"Fact {index}")
|
||||||
|
|
||||||
|
with pytest.raises(ValueError) as caught:
|
||||||
|
memories_service.add(db, owner=owner, content="One too many")
|
||||||
|
|
||||||
|
assert _count(db, owner) == 3
|
||||||
|
message = str(caught.value)
|
||||||
|
assert "note instead" in message
|
||||||
|
assert "Remove one first" not in message
|
||||||
Reference in New Issue
Block a user