Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: let @skill mentions work without Code and add bulk skill toggles (#13163)

Etherld50286cfd4d5
diff --git a/studio/SKILL_MENTIONS.md b/studio/SKILL_MENTIONS.md
index 2b88742bc6a..9a17dcbead9 100644
--- a/studio/SKILL_MENTIONS.md
+++ b/studio/SKILL_MENTIONS.md
@@ -1,8 +1,10 @@
# Explicit Agent Skill mentions
-With Code on and an enabled skill in the effective model's Studio tool catalog,
-Studio reads the complete `SKILL.md` for an explicit `@skill-name` **before the
-first generation**. It does not depend on a model calling `read_skill`. This loads
+With an enabled skill in the effective model's Unsloth Studio tool catalog, Unsloth Studio reads
+the complete `SKILL.md` for an explicit `@skill-name` **before the first
+generation**. With Code off, the composer offers `read_skill` alone, and only for
+a thread whose user messages mention an enabled skill, so a plain chat stays out
+of the tool loop. It does not depend on a model calling `read_skill`. This loads
instructions, not referenced resources, scripts, or skill creation. Existing
account discovery, capability, tool selection and permission policy still apply.
Ask mode waits for the ordinary scoped read approval; Auto permits this read-only
diff --git a/studio/backend/core/inference/skill_mentions.py b/studio/backend/core/inference/skill_mentions.py
index 2f31c245b06..8a99e05fb96 100644
--- a/studio/backend/core/inference/skill_mentions.py
+++ b/studio/backend/core/inference/skill_mentions.py
@@ -156,6 +156,14 @@ def load_mentioned_skills(
names = mentioned_skill_names(_text(messages[-1]))
if not names:
return
+ tool_names = {tool.get("function", {}).get("name") for tool in tools}
+ gate = "Follow these instructions only within the current tool and permission gates."
+ if not {"python", "terminal"} & tool_names:
+ gate += (
+ " No local python or terminal tool is available, so its bundled scripts cannot run;"
+ " never claim to have run one, and tell the user a script needs Unsloth Studio's"
+ " local Code tool."
+ )
# @john is a person, not a skill: no card or approval. Known-but-unusable skills report unavailable.
try:
known = list_skills()
@@ -218,7 +226,7 @@ def load_mentioned_skills(
)
block = (
f"\n\n[Studio loaded Agent Skill @{name} · SKILL.md]\n"
- "Follow these instructions only within the current tool and permission gates.\n"
+ f"{gate}\n"
f"{content}\n[End Agent Skill @{name}]"
)
_append_system(messages, block)
diff --git a/studio/backend/core/inference/skills.py b/studio/backend/core/inference/skills.py
index 02605ccc5c3..c1136aeb744 100644
--- a/studio/backend/core/inference/skills.py
+++ b/studio/backend/core/inference/skills.py
@@ -625,6 +625,25 @@ def set_skill_enabled(
return {**record, "enabled": enabled}
+def set_all_skills_enabled(enabled: Optional[bool], *, home: Optional[Path] = None) -> list[dict]:
+ """set listed skills, with None clearing overrides to restore fresh-install defaults."""
+ if enabled is not None and not isinstance(enabled, bool):
+ raise SkillError("Skill enabled state must be a boolean or null.")
+ with _LOCK:
+ overrides = {} if enabled is None else _load_overrides()
+ if enabled is not None:
+ # preserve overrides for skills absent from disk, matching single-skill toggles
+ for record, _, _ in _discover(home):
+ if not record["valid"] or record["shadowed"]:
+ continue
+ if enabled == _default_enabled(record["source"]):
+ overrides.pop(record["name"], None)
+ else:
+ overrides[record["name"]] = enabled
+ _save_overrides(overrides)
+ return [record for record, _, _ in _discover(home)]
+
+
def _validate_draft(description: str, instructions: str) -> str:
if not isinstance(description, str) or not description.strip() or len(description) > 1024:
raise SkillError("Skill description must be 1-1024 characters.")
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 8385e704fd1..57ee1b9c141 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -6031,7 +6031,12 @@ def _enabled_agent_skills() -> list[dict]:
return current
-def _skill_tool_tip(*, can_create: bool, compact: bool = False) -> str:
+def _skill_tool_tip(
+ *,
+ can_create: bool,
+ can_run_scripts: bool = True,
+ compact: bool = False,
+) -> str:
from core.inference.skills import (
LARGE_SKILL_CATALOG_BYTES,
MAX_SKILL_CATALOG_BYTES,
@@ -6045,6 +6050,14 @@ def _skill_tool_tip(*, can_create: bool, compact: bool = False) -> str:
create_tip = (
" To create a skill, read skill-creator and then call create_skill." if can_create else ""
)
+ # code-off mentions and hosted Code can read skills but cannot run bundled local scripts
+ scripts_tip = (
+ ""
+ if can_run_scripts
+ else " No local python or terminal tool is available, so a skill's bundled scripts cannot "
+ "run: follow its written instructions, never claim to have run a script, and when a step "
+ "needs one, tell the user it needs Unsloth Studio's local Code tool."
+ )
return (
"Enabled Agent Skills are listed below. Use their descriptions to select one when "
"helpful, then call read_skill before following its instructions unless the complete "
@@ -6052,6 +6065,7 @@ def _skill_tool_tip(*, can_create: bool, compact: bool = False) -> str:
"generation when permitted; do not read an already loaded manifest again or claim a "
"failed/denied load succeeded."
+ create_tip
+ + scripts_tip
+ " Skill allowed-tools metadata never overrides Unsloth tool permissions.\n"
+ catalog
)
@@ -6090,7 +6104,11 @@ def _build_tool_action_nudge(
model_size_b = _extract_model_size_b(model_name)
# Small models get the shorter web tip and the smaller skill catalog.
compact = model_size_b is not None and model_size_b < 9
- skill_tip = _skill_tool_tip(can_create = "create_skill" in tool_names, compact = compact)
+ skill_tip = _skill_tool_tip(
+ can_create = "create_skill" in tool_names,
+ can_run_scripts = bool({"python", "terminal"} & tool_names),
+ compact = compact,
+ )
if full_access_only:
tips = []
if full_access and has_code:
diff --git a/studio/backend/routes/skills.py b/studio/backend/routes/skills.py
index 46589b473c3..50d3f846593 100644
--- a/studio/backend/routes/skills.py
+++ b/studio/backend/routes/skills.py
@@ -15,6 +15,7 @@ from core.inference.skills import (
delete_skill,
list_skills,
read_skill_manifest,
+ set_all_skills_enabled,
set_skill_enabled,
update_skill,
)
@@ -52,6 +53,13 @@ class SkillEnabledRequest(BaseModel):
enabled: StrictBool
+class AllSkillsEnabledRequest(BaseModel):
+ model_config = ConfigDict(extra = "forbid")
+
+ # null restores the defaults a fresh install has.
+ enabled: Optional[StrictBool]
+
+
class SkillDraft(BaseModel):
model_config = ConfigDict(extra = "forbid")
@@ -87,6 +95,18 @@ def get_skills(current_subject: str = Depends(get_current_subject)) -> list[dict
return records
[email protected]("", response_model = list[SkillRecord])
+def update_all_skills_enabled(
+ payload: AllSkillsEnabledRequest, current_subject: str = Depends(get_current_subject)
+) -> list[dict[str, Any]]:
+ try:
+ records = set_all_skills_enabled(payload.enabled)
+ except SkillError as exc:
+ raise _http_error(exc) from exc
+ _invalidate_catalog()
+ return records
+
+
@router.post("", response_model = SkillRecord, status_code = 201)
def create_skill_route(
payload: SkillCreateRequest, current_subject: str = Depends(get_current_subject)
diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.py
index cbe9c739b22..b267a06e3fa 100644
--- a/studio/backend/tests/test_anthropic_messages.py
+++ b/studio/backend/tests/test_anthropic_messages.py
@@ -621,6 +621,29 @@ class TestToolActionNudge:
assert "- guided: Guide this task." in nudge
assert "create_skill" not in nudge
+ # without python or terminal, a skill's bundled scripts cannot run here.
+ assert "bundled scripts cannot run" in nudge
+ assert "Unsloth Studio's local Code tool" in nudge
+
+ @pytest.mark.parametrize("code_tool", ["python", "terminal"])
+ def test_skill_nudge_with_a_code_tool_does_not_warn_about_scripts(self, monkeypatch, code_tool):
+ import routes.inference as inference_routes
+
+ monkeypatch.setattr(
+ inference_routes,
+ "_enabled_agent_skills",
+ lambda: [{"name": "guided", "description": "Guide this task."}],
+ )
+ nudge = _build_tool_action_nudge(
+ tools = [
+ {"type": "function", "function": {"name": "read_skill"}},
+ {"type": "function", "function": {"name": code_tool}},
+ ],
+ model_name = "test",
+ )
+
+ assert "- guided: Guide this task." in nudge
+ assert "bundled scripts cannot run" not in nudge
# =====================================================================
diff --git a/studio/backend/tests/test_explicit_skill_loading.py b/studio/backend/tests/test_explicit_skill_loading.py
index 285508092cc..86dde9f58f9 100644
--- a/studio/backend/tests/test_explicit_skill_loading.py
+++ b/studio/backend/tests/test_explicit_skill_loading.py
@@ -117,3 +117,31 @@ def test_actual_local_request_gates_do_not_load(mention_client, gate):
m.get("content", "") for m in backend.requests[0]["messages"]
)
assert '"status": "loaded"' not in response.text
+
+
[email protected]("code_on", [False, True])
+def test_code_off_mention_loads_and_says_scripts_need_code(mention_client, code_on):
+ client, backend, manifest = mention_client
+ response = client.post(
+ "/chat/completions",
+ json = {
+ "messages": [{"role": "user", "content": "@skill-creator what did i just paste?"}],
+ "stream": True,
+ "enable_tools": True,
+ # a Code-off mention sends read_skill alone.
+ "enabled_tools": ["read_skill", "python", "terminal"] if code_on else ["read_skill"],
+ "permission_mode": "auto",
+ },
+ headers = {"X-Unsloth-Events": "1"},
+ )
+ assert response.status_code == 200, response.text
+ context = "\n".join(m.get("content", "") for m in backend.requests[0]["messages"])
+ assert manifest.read_text() in context
+ assert '"status": "loaded"' in response.text
+ names = {t["function"]["name"] for t in backend.requests[0]["tools"]}
+ assert ("python" in names) is code_on
+ assert "create_skill" not in names
+ note = "bundled scripts cannot run"
+ assert (note in context) is not code_on
+ if not code_on:
+ assert "Unsloth Studio's local Code tool" in context
diff --git a/studio/backend/tests/test_skills.py b/studio/backend/tests/test_skills.py
index e3ff92edb97..af6cd60ceeb 100644
--- a/studio/backend/tests/test_skills.py
+++ b/studio/backend/tests/test_skills.py
@@ -1194,3 +1194,77 @@ def test_explicit_manifest_loading_uses_current_account_discovery(managed_accoun
assert not any(e["status"] == "loaded" for e in bob_events)
assert "ALICE_ONLY_INSTRUCTIONS" not in str(bob_messages)
assert "OWNER_ONLY_INSTRUCTIONS" not in str(bob_messages)
+
+
+def test_bulk_enable_disable_and_reset_follow_the_defaults(isolated_skills, monkeypatch):
+ home, studio = isolated_skills
+ _write_skill(home, "agents", "mine")
+ _write_skill(home, "claude", "theirs")
+ roots = (
+ ("agents", home / ".agents" / "skills"),
+ ("claude", home / ".claude" / "skills"),
+ ("bundled", Path(skills.__file__).with_name("bundled_skills")),
+ )
+ monkeypatch.setattr(skills, "_skill_roots", lambda home = None: roots)
+ overrides = studio / "skill-overrides.json"
+ bundled = {r["name"] for r in skills.list_skills() if r["source"] == "bundled"}
+ assert bundled
+ # absent-skill choices survive bulk updates, matching individual toggles.
+ skills._save_overrides({"gone-for-now": False})
+
+ records = skills.set_all_skills_enabled(False)
+ assert all(not record["enabled"] for record in records)
+ assert json.loads(overrides.read_text()) == {
+ "gone-for-now": False,
+ "mine": False,
+ "theirs": False,
+ }
+
+ records = skills.set_all_skills_enabled(True)
+ assert all(record["enabled"] for record in records)
+ assert json.loads(overrides.read_text()) == {
+ "gone-for-now": False,
+ **{name: True for name in bundled},
+ }
+
+ # reset restores fresh-install defaults: home skills on, bundled skills off, no overrides.
+ records = skills.set_all_skills_enabled(None)
+ assert {record["name"]: record["enabled"] for record in records} == {
+ "mine": True,
+ "theirs": True,
+ **{name: False for name in bundled},
+ }
+ assert json.loads(overrides.read_text()) == {}
+ with pytest.raises(skills.SkillError):
+ skills.set_all_skills_enabled("false")
+
+
+def test_bulk_enabled_route(isolated_skills, monkeypatch):
+ home, _ = isolated_skills
+ _write_skill(home, "agents", "api-skill")
+ roots = (
+ ("agents", home / ".agents" / "skills"),
+ ("claude", home / ".claude" / "skills"),
+ )
+ monkeypatch.setattr(skills, "_skill_roots", lambda home = None: roots)
+ from routes import inference as inference_routes
+
+ app = FastAPI()
+ app.include_router(router, prefix = "/api/skills")
+ assert TestClient(app).put("/api/skills", json = {"enabled": False}).status_code in (401, 403)
+ app.dependency_overrides[get_current_subject] = lambda: "test-user"
+ client = TestClient(app)
+
+ monkeypatch.setattr(
+ inference_routes, "_AGENT_SKILLS_CACHE", {None: (float("inf"), [{"name": "stale"}])}
+ )
+ response = client.put("/api/skills", json = {"enabled": False})
+ assert response.status_code == 200
+ assert [(r["name"], r["enabled"]) for r in response.json()] == [("api-skill", False)]
+ assert inference_routes._AGENT_SKILLS_CACHE == {}
+ response = client.put("/api/skills", json = {"enabled": None})
+ assert [(r["name"], r["enabled"]) for r in response.json()] == [("api-skill", True)]
+ # missing or string values are rejected instead of being interpreted as reset.
+ assert client.put("/api/skills", json = {}).status_code == 422
+ assert client.put("/api/skills", json = {"enabled": "false"}).status_code == 422
+ assert client.put("/api/skills/api-skill/enabled", json = {"enabled": False}).status_code == 200
diff --git a/studio/frontend/src/components/assistant-ui/skill-mention-token.ts b/studio/frontend/src/components/assistant-ui/skill-mention-token.ts
index 5f770c5404f..687ea24bf69 100644
--- a/studio/frontend/src/components/assistant-ui/skill-mention-token.ts
+++ b/studio/frontend/src/components/assistant-ui/skill-mention-token.ts
@@ -23,3 +23,32 @@ export function replaceMentionToken(
caret: token.start + directive.length + 1,
};
}
+
+type MentionSkill = {
+ name: string;
+ description: string;
+ valid: boolean;
+ shadowed: boolean;
+ enabled: boolean;
+};
+
+export function mentionableSkills<T extends MentionSkill>(skills: readonly T[]): T[] {
+ return skills.filter((skill) => skill.valid && !skill.shadowed && skill.enabled);
+}
+
+// preserve catalog order within the name-prefix, name-substring, and description-match tiers.
+export function rankMentionSkills<T extends MentionSkill>(
+ skills: readonly T[],
+ query: string,
+ limit: number,
+): T[] {
+ const needle = query.toLowerCase();
+ const tiers: T[][] = [[], [], []];
+ for (const skill of skills) {
+ const name = skill.name.toLowerCase();
+ if (name.startsWith(needle)) tiers[0].push(skill);
+ else if (name.includes(needle)) tiers[1].push(skill);
+ else if (skill.description.toLowerCase().includes(needle)) tiers[2].push(skill);
+ }
+ return tiers.flat().slice(0, limit);
+}
diff --git a/studio/frontend/src/components/assistant-ui/skill-mentions.tsx b/studio/frontend/src/components/assistant-ui/skill-mentions.tsx
index 8499d37df84..4afcdcb8e42 100644
--- a/studio/frontend/src/components/assistant-ui/skill-mentions.tsx
+++ b/studio/frontend/src/components/assistant-ui/skill-mentions.tsx
@@ -36,16 +36,12 @@ import {
import {
type MentionToken,
mentionTokenAt,
+ mentionableSkills,
+ rankMentionSkills,
replaceMentionToken,
} from "./skill-mention-token";
-function enabled(records: readonly SkillRecord[]): readonly SkillRecord[] {
- return records.filter(
- (skill) => skill.valid && !skill.shadowed && skill.enabled,
- );
-}
-
-// The catalog allows 1,000 skills per root; a keystroke must not render them all.
+// cap results because each root can contain 1,000 skills.
const MAX_MENTION_RESULTS = 50;
const skillMentionFormatter: Unstable_DirectiveFormatter = {
@@ -131,7 +127,38 @@ function MentionOpenSignal({
return null;
}
-// The library's insert stops at the caret, leaving "@calculator tor"; replace the whole token.
+// accept Tab only in the composer because the library handles Enter and focus may move elsewhere.
+function MentionTabAccept({
+ scopeRef,
+}: {
+ scopeRef: RefObject<HTMLElement | null>;
+}): null {
+ const { open, items, handleKeyDown } = unstable_useTriggerPopoverScopeContext();
+ const active = open && items.length > 0;
+ useEffect(() => {
+ if (!active) return;
+ const accept = (event: globalThis.KeyboardEvent) => {
+ if (event.key !== "Tab" || event.shiftKey || event.isComposing) return;
+ if (
+ !(event.target instanceof HTMLTextAreaElement) ||
+ !scopeRef.current?.contains(event.target)
+ )
+ return;
+ const enter = {
+ key: "Enter",
+ shiftKey: false,
+ preventDefault: () => event.preventDefault(),
+ };
+ if (handleKeyDown(enter)) event.stopPropagation();
+ };
+ // intercept before the browser moves focus or the composer handles Tab.
+ window.addEventListener("keydown", accept, true);
+ return () => window.removeEventListener("keydown", accept, true);
+ }, [active, handleKeyDown, scopeRef]);
+ return null;
+}
+
+// replace the full token because the library insert stops at the caret and leaves trailing text.
function MentionTokenReplacer(): null {
const aui = useAui();
const { registerSelectItemOverride, setCursorPosition } =
@@ -164,17 +191,22 @@ function MentionTokenReplacer(): null {
export function SkillMentionPopover({
enabled: mentionsEnabled,
+ composerRef,
onConsumesEnterChange,
onOpenChange,
}: {
enabled: boolean;
+ composerRef: RefObject<HTMLElement | null>;
onConsumesEnterChange?: (consumesEnter: boolean) => void;
onOpenChange?: (open: boolean) => void;
}): ReactElement | null {
const t = useT();
const { skills } = useSkillsCatalog();
const [listElement, setListElement] = useState<HTMLDivElement | null>(null);
- const available = mentionsEnabled ? enabled(skills) : [];
+ const available = useMemo(
+ () => (mentionsEnabled ? mentionableSkills(skills) : []),
+ [mentionsEnabled, skills],
+ );
const items = useMemo(
() =>
available.map((skill) => ({
@@ -190,15 +222,17 @@ export function SkillMentionPopover({
includeModelContextTools: false,
formatter: skillMentionFormatter,
});
- // Cap the search itself: the popover navigates and inserts from these results, not the rendered rows.
- const adapter = useMemo(
- () => ({
+ // cap ranked adapter results because the popover navigates them, not only rendered rows.
+ const adapter = useMemo(() => {
+ const byName = new Map(items.map((item) => [item.id, item]));
+ return {
...mention.adapter,
search: (query: string) =>
- (mention.adapter.search?.(query) ?? []).slice(0, MAX_MENTION_RESULTS),
- }),
- [mention.adapter],
- );
+ rankMentionSkills(available, query, MAX_MENTION_RESULTS).flatMap(
+ (skill) => byName.get(skill.name) ?? [],
+ ),
+ };
+ }, [available, items, mention.adapter]);
useHighlightedItemScroll(listElement);
if (items.length === 0) return null;
@@ -214,6 +248,7 @@ export function SkillMentionPopover({
/>
<MentionOpenSignal onChange={onOpenChange} />
<MentionTokenReplacer />
+ <MentionTabAccept scopeRef={composerRef} />
<ComposerPrimitive.Unstable_TriggerPopoverItems>
{(results) => (
<>
@@ -279,22 +314,17 @@ export function useTextareaSkillMentions({
const [range, setRange] = useState<MentionRange>(null);
const listboxId = useId();
const [highlighted, setHighlighted] = useState(0);
- const results = useMemo(() => {
- if (!range) return [];
- const query = range.query.toLowerCase();
- if (!mentionsEnabled) return [];
- const matches: SkillRecord[] = [];
- for (const skill of enabled(skills)) {
- if (
- skill.name.toLowerCase().includes(query) ||
- skill.description.toLowerCase().includes(query)
- ) {
- matches.push(skill);
- if (matches.length === MAX_MENTION_RESULTS) break;
- }
- }
- return matches;
- }, [mentionsEnabled, range, skills]);
+ const results = useMemo(
+ () =>
+ range && mentionsEnabled
+ ? rankMentionSkills(
+ mentionableSkills(skills),
+ range.query,
+ MAX_MENTION_RESULTS,
+ )
+ : [],
+ [mentionsEnabled, range, skills],
+ );
const open = range !== null && results.length > 0;
const activeOptionId = open
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index dbe029f3f68..d7aadd7f8f6 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -2688,8 +2688,6 @@ const Composer: FC<{
const supportsTools = useChatRuntimeStore((s) => s.supportsTools);
const codeToolsEnabled = useChatRuntimeStore((s) => s.codeToolsEnabled);
- // Effective Code (Full Access implies it), the same gate the request uses to offer read_skill.
- const codeToolsEffective = useChatRuntimeStore(codeToolsOn);
const imageToolsEnabled = useChatRuntimeStore((s) => s.imageToolsEnabled);
const supportsBuiltinImageGeneration = useChatRuntimeStore(
(s) => s.supportsBuiltinImageGeneration,
@@ -5600,15 +5598,15 @@ const Composer: FC<{
<PromptQueueContext.Provider value={queueContextValue}>
<ComposerPrimitive.Unstable_TriggerPopoverRoot>
<SkillMentionPopover
- enabled={supportsTools && codeToolsEffective}
+ // mentions remain available without Code because each one offers read_skill.
+ enabled={supportsTools}
+ composerRef={editorRef}
onConsumesEnterChange={setMentionConsumesEnter}
onOpenChange={setMentionOpen}
/>
<ComposerPrimitive.Root
ref={attachComposer}
- // Out of find-in-page's reach: the draft itself lives in a textarea the index cannot read, so
- // all this leaves to find are the pill labels, and a search for "code" or "images" would land
- // on the toolbar instead of on the conversation.
+ // skip find-in-page because it cannot index the textarea and would match toolbar pills.
{...{ [FIND_SKIP_ATTRIBUTE]: "" }}
className="aui-composer-root relative flex w-full flex-col"
data-writing-expanded={
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 213b611452e..afc8097d31f 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -52,24 +52,24 @@ import { resolveSpeculativeType } from "@/lib/speculative-modes";
import { getSkillsSnapshot, settleSkillsForText } from "./skills-api";
-function lastUserText(
+function messageText(content: unknown): string {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return "";
+ return content
+ .map((part) =>
+ part && typeof part === "object" && typeof (part as { text?: unknown }).text === "string"
+ ? (part as { text: string }).text
+ : "",
+ )
+ .join(" ");
+}
+
+function userTexts(
messages: readonly { role?: string; content?: unknown }[],
-): string {
- for (let index = messages.length - 1; index >= 0; index -= 1) {
- const message = messages[index];
- if (message?.role !== "user") continue;
- const content = message.content;
- if (typeof content === "string") return content;
- if (!Array.isArray(content)) return "";
- return content
- .map((part) =>
- part && typeof part === "object" && typeof (part as { text?: unknown }).text === "string"
- ? (part as { text: string }).text
- : "",
- )
- .join(" ");
- }
- return "";
+): string[] {
+ return messages
+ .filter((message) => message?.role === "user")
+ .map((message) => messageText(message.content));
}
import { projectHasSources } from "@/features/rag/api/rag-api";
import {
@@ -251,7 +251,7 @@ import {
providerSupportsFastMode,
} from "../provider-capabilities";
import { selectCodeToolNames } from "./code-tool-placement";
-import { skillToolsOffered } from "./skill-tools";
+import { skillToolNames } from "./skill-tools";
import { ragScopeContextLength } from "./rag-context-length";
import {
type PendingImageEditReference,
@@ -2240,6 +2240,7 @@ export function buildLocalTokenCountReasoning(): Record<string, unknown> {
/** The tool flags a completion would send, so the count includes the schemas and the action nudge. */
export async function buildLocalTokenCountExtras(
threadId: string | undefined,
+ messages: readonly { role?: string; content?: unknown }[] = [],
): Promise<Record<string, unknown>> {
const state = useChatRuntimeStore.getState();
const {
@@ -2282,10 +2283,12 @@ export async function buildLocalTokenCountExtras(
: false;
const ragOn = ragEnabled || projectRagEnabled;
- await settleSkillsForText("");
- const hasEnabledSkills = skillToolsOffered(
+ // re-fetch for every counted user turn so skills created since page load match request pricing.
+ await settleSkillsForText(userTexts(messages).join("\n"));
+ const skillTools = skillToolNames(
getSkillsSnapshot().skills,
codeToolsEnabled,
+ userTexts(messages),
);
if (
!toolsEnabled &&
@@ -2293,7 +2296,7 @@ export async function buildLocalTokenCountExtras(
!mcpEnabledForChat &&
!ragOn &&
!deepResearchEnabled &&
- !hasEnabledSkills
+ skillTools.length === 0
) {
// Explicit false, not omission: the server defaults tools on. The permission level rides
// along because `--enable-tools` still outranks that false in _effective_enable_tools.
@@ -2322,8 +2325,8 @@ export async function buildLocalTokenCountExtras(
...(ragOn ? ["search_knowledge_base"] : []),
...(toolsEnabled ? ["web_search"] : []),
...(codeToolsEnabled ? ["python", "terminal", "edit_file", "view_image"] : []),
- // Same gate as the request: with no enabled skill neither tool is sent, so neither is priced.
- ...(hasEnabledSkills ? ["read_skill", "create_skill"] : []),
+ // match the request gate so token pricing includes only sent skill tools.
+ ...skillTools,
],
mcp_enabled: mcpEnabledForChat,
// Top level, not inside rag_scope: an archived thread puts search_conversation and its
@@ -6597,11 +6600,13 @@ export function createOpenAIStreamAdapter(
forceRefreshPublicKey = false,
): Promise<OpenAIChatCompletionsRequest> => {
if (supportsStudioToolsForThisTurn) {
- await settleSkillsForText(lastUserText(outboundMessages));
+ // include every user turn because follow-ups still need skills mentioned earlier.
+ await settleSkillsForText(userTexts(outboundMessages).join("\n"));
}
- const hasEnabledSkills = skillToolsOffered(
+ const skillTools = skillToolNames(
getSkillsSnapshot().skills,
codeToolsEnabled,
+ userTexts(outboundMessages),
);
if (externalSelection && externalProvider) {
// Per-thread container reuse; empty falls back to container_auto. Anthropic uses its own key.
@@ -6761,7 +6766,7 @@ export function createOpenAIStreamAdapter(
mcpEnabledForChat ||
ragEnabled ||
projectRagEnabled ||
- hasEnabledSkills ||
+ skillTools.length > 0 ||
// Armed research needs Studio's loop: deep_research is appended past every tool filter, but
// only for a request that asked for the loop at all.
deepResearchArmed)
@@ -6772,9 +6777,7 @@ export function createOpenAIStreamAdapter(
? ["search_knowledge_base"]
: []),
...(toolsEnabled ? ["web_search"] : []),
- ...(hasEnabledSkills
- ? ["read_skill", "create_skill"]
- : []),
+ ...skillTools,
...studioLocalCodeTools,
// Hosted tools with no local stand-in; their pills stay lit regardless, so listing only local
// names dropped Images/Fetch whenever another tool selected this branch. Search is excluded
@@ -6991,7 +6994,7 @@ export function createOpenAIStreamAdapter(
mcpEnabledForChat ||
ragEnabled ||
projectRagEnabled ||
- hasEnabledSkills ||
+ skillTools.length > 0 ||
deepResearchArmed)
? {
enable_tools: true,
@@ -7001,9 +7004,7 @@ export function createOpenAIStreamAdapter(
? ["search_knowledge_base"]
: []),
...(toolsEnabled ? ["web_search"] : []),
- ...(hasEnabledSkills
- ? ["read_skill", "create_skill"]
- : []),
+ ...skillTools,
...(codeToolsEnabled
? ["python", "terminal", "edit_file", "view_image"]
: []),
diff --git a/studio/frontend/src/features/chat/api/skill-tools.ts b/studio/frontend/src/features/chat/api/skill-tools.ts
index 673c8dd7c97..718515af744 100644
--- a/studio/frontend/src/features/chat/api/skill-tools.ts
+++ b/studio/frontend/src/features/chat/api/skill-tools.ts
@@ -1,20 +1,36 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-// Home-dir skills are on by default with no pill of their own, so they follow Code (#11671).
+// mirror backend preload token boundaries, including at most one trailing sentence mark.
+export const SKILL_MENTION_PATTERN =
+ /(^|\s)@([a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?)(?=$|\s|[.,;:!?)](?:$|\s))/g;
export interface SkillToolEntry {
+ name: string;
valid: boolean;
shadowed: boolean;
enabled: boolean;
}
-export function skillToolsOffered(
+// with Code off, only an @mention offers read_skill; create_skill stays gated by Code (#11671).
+export function skillToolNames(
skills: readonly SkillToolEntry[],
codeToolsOn: boolean,
-): boolean {
- return (
- codeToolsOn &&
- skills.some((skill) => skill.valid && !skill.shadowed && skill.enabled)
+ userTexts: readonly string[],
+): string[] {
+ const usable = new Set(
+ skills
+ .filter((skill) => skill.valid && !skill.shadowed && skill.enabled)
+ .map((skill) => skill.name),
);
+ if (usable.size === 0) return [];
+ if (codeToolsOn) return ["read_skill", "create_skill"];
+ // earlier turns count because follow-ups must re-read SKILL.md contents that are not replayed.
+ // do not mask code or quotes because frontend Markdown guesses can hide backend-literal mentions.
+ const mentioned = userTexts.some((text) =>
+ Array.from(text.matchAll(SKILL_MENTION_PATTERN)).some((match) =>
+ usable.has(match[2] ?? ""),
+ ),
+ );
+ return mentioned ? ["read_skill"] : [];
}
diff --git a/studio/frontend/src/features/chat/api/skills-api.ts b/studio/frontend/src/features/chat/api/skills-api.ts
index 7716428e03c..9dc02dcfdac 100644
--- a/studio/frontend/src/features/chat/api/skills-api.ts
+++ b/studio/frontend/src/features/chat/api/skills-api.ts
@@ -5,6 +5,9 @@ import { authFetch } from "@/features/auth";
import { AUTH_SESSION_CLEARED_EVENT } from "@/features/auth/session";
import { useEffect, useSyncExternalStore } from "react";
import { refreshContextUsage } from "../utils/refresh-context-usage";
+import { SKILL_MENTION_PATTERN } from "./skill-tools";
+
+export { SKILL_MENTION_PATTERN } from "./skill-tools";
export type SkillRecord = {
name: string;
@@ -46,6 +49,8 @@ const EMPTY_SNAPSHOT: SkillsSnapshot = {
};
let snapshot = EMPTY_SNAPSHOT;
let requestGeneration = 0;
+// increment only on sign-out so a prior account's response cannot be published.
+let sessionEpoch = 0;
let lastFetchedAt = 0;
let pending: Promise<readonly SkillRecord[]> | null = null;
const listeners = new Set<() => void>();
@@ -150,6 +155,27 @@ export async function setSkillEnabled(
return updated;
}
+/** set every skill state; null restores fresh-install defaults. */
+export async function setAllSkillsEnabled(
+ enabled: boolean | null,
+): Promise<readonly SkillRecord[]> {
+ const epoch = sessionEpoch;
+ const response = await authFetch("/api/skills", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ enabled }),
+ });
+ const skills = await parseResponse<SkillRecord[]>(response);
+ if (epoch !== sessionEpoch) return skills;
+ // invalidate older reads before publishing the server's post-change list.
+ requestGeneration += 1;
+ lastFetchedAt = Date.now();
+ publish({ skills, loading: false, initialized: true, error: null });
+ channel?.postMessage("changed");
+ void refreshContextUsage({ invalidate: true });
+ return skills;
+}
+
export const SKILL_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
export function isValidSkillName(name: string): boolean {
@@ -200,10 +226,6 @@ export async function deleteSkill(name: string): Promise<void> {
await skillsMutated();
}
-// Spec skill names only, ending at a word boundary: `@example.com`, `@3pm`, `@Probe` are not mentions.
-export const SKILL_MENTION_PATTERN =
- /(^|\s)@([a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?)(?=$|\s|[.,;:!?)\]'"]+(?:$|\s))/g;
-
// authFetch has no deadline, so a hung /api/skills must not stall the send.
const SETTLE_TIMEOUT_MS = 3000;
@@ -254,6 +276,7 @@ export function useSkillsCatalog(): SkillsSnapshot {
// The snapshot is module state, so a sign-out must drop it or the next account inherits it.
if (typeof window !== "undefined") {
window.addEventListener(AUTH_SESSION_CLEARED_EVENT, () => {
+ sessionEpoch += 1;
requestGeneration += 1;
pending = null;
lastFetchedAt = 0;
diff --git a/studio/frontend/src/features/chat/components/chat-skills-dialog.tsx b/studio/frontend/src/features/chat/components/chat-skills-dialog.tsx
index 1ae4a189a3d..9006d074392 100644
--- a/studio/frontend/src/features/chat/components/chat-skills-dialog.tsx
+++ b/studio/frontend/src/features/chat/components/chat-skills-dialog.tsx
@@ -20,6 +20,13 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
@@ -32,6 +39,7 @@ import {
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import {
+ MoreHorizontalIcon,
PlusSignIcon,
Refresh01Icon,
Scroll01Icon,
@@ -54,6 +62,7 @@ import {
getSkillManifest,
isValidSkillName,
listSkills,
+ setAllSkillsEnabled,
setSkillEnabled,
type SkillDraft,
type SkillManifest,
@@ -68,6 +77,8 @@ type View = { kind: "library" } | { kind: "new" } | { kind: "skill"; key: string
const EMPTY_DRAFT: SkillDraft = { name: "", description: "", instructions: "" };
const LIBRARY: View = { kind: "library" };
const SECTIONS: ReadonlyArray<SkillRecord["source"]> = ["agents", "claude", "bundled"];
+// `*` is the bulk-change sentinel because skill names cannot contain it.
+const ALL_SKILLS = "*";
// A shadowed row shares its name with the one that wins, so skills are keyed by source too.
const keyOf = (skill: SkillRecord) => `${skill.source}:${skill.name}`;
@@ -108,6 +119,7 @@ export function ChatSkillsDialog({
const [changing, setChanging] = useState<string | null>(null);
const [confirmingDelete, setConfirmingDelete] = useState<SkillRecord | null>(null);
const [confirmingDiscard, setConfirmingDiscard] = useState<(() => void) | null>(null);
+ const [confirmingReset, setConfirmingReset] = useState(false);
// Reseeded on render so the first frame after opening is already reset.
const [seenOpen, setSeenOpen] = useState(open);
if (open !== seenOpen) {
@@ -120,6 +132,7 @@ export function ChatSkillsDialog({
setManifests(new Map());
setConfirmingDelete(null);
setConfirmingDiscard(null);
+ setConfirmingReset(false);
}
}
useEffect(() => {
@@ -256,6 +269,18 @@ export function ChatSkillsDialog({
if (selected) readManifest(selected);
};
+ const usable = skills.filter((skill) => skill.valid && !skill.shadowed);
+ const toggleAll = async (enabled: boolean | null) => {
+ setChanging(ALL_SKILLS);
+ try {
+ await setAllSkillsEnabled(enabled);
+ } catch (cause) {
+ toast.error(t("skills.updateError"), { description: describe(cause) });
+ } finally {
+ setChanging(null);
+ }
+ };
+
const toggle = async (name: string, enabled: boolean) => {
setChanging(name);
try {
@@ -393,6 +418,42 @@ export function ChatSkillsDialog({
>
{loading ? <Spinner /> : <HugeiconsIcon icon={Refresh01Icon} strokeWidth={2} />}
</Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild={true}>
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ disabled={loading || usable.length === 0 || changing !== null}
+ aria-label={t("skills.bulkActions")}
+ title={t("skills.bulkActions")}
+ >
+ {changing === ALL_SKILLS ? (
+ <Spinner />
+ ) : (
+ <HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={2} />
+ )}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ disabled={usable.every((skill) => skill.enabled)}
+ onSelect={() => void toggleAll(true)}
+ >
+ {t("skills.enableAll")}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={!usable.some((skill) => skill.enabled)}
+ onSelect={() => void toggleAll(false)}
+ >
+ {t("skills.disableAll")}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={() => setConfirmingReset(true)}>
+ {t("skills.resetAll")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
<Button type="button" size="sm" onClick={openNew}>
<HugeiconsIcon icon={PlusSignIcon} strokeWidth={2} />
{t("skills.newSkill")}
@@ -423,7 +484,7 @@ export function ChatSkillsDialog({
<SkillRow
key={keyOf(skill)}
skill={skill}
- changing={changing === skill.name}
+ changing={changing !== null}
onOpen={() => openSkill(skill)}
onToggle={(enabled) => void toggle(skill.name, enabled)}
/>
@@ -570,7 +631,11 @@ export function ChatSkillsDialog({
<label className="flex items-center gap-2 text-sm text-muted-foreground">
<Switch
checked={selected.valid && !selected.shadowed && selected.enabled}
- disabled={!selected.valid || selected.shadowed || changing === selected.name}
+ disabled={
+ !selected.valid ||
+ selected.shadowed ||
+ changing !== null
+ }
aria-label={t(selected.enabled ? "skills.disable" : "skills.enable", {
name: selected.name,
})}
@@ -651,6 +716,27 @@ export function ChatSkillsDialog({
</AlertDialogContent>
</AlertDialog>
+ <AlertDialog open={open && confirmingReset} onOpenChange={setConfirmingReset}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t("skills.resetTitle")}</AlertDialogTitle>
+ <AlertDialogDescription>{t("skills.resetDescription")}</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() => {
+ setConfirmingReset(false);
+ void toggleAll(null);
+ }}
+ >
+ {t("skills.reset")}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+
<AlertDialog
open={open && confirmingDiscard !== null}
onOpenChange={(next) => {
diff --git a/studio/frontend/src/features/chat/utils/refresh-context-usage.ts b/studio/frontend/src/features/chat/utils/refresh-context-usage.ts
index 5e6edf48e9a..128c17fd75f 100644
--- a/studio/frontend/src/features/chat/utils/refresh-context-usage.ts
+++ b/studio/frontend/src/features/chat/utils/refresh-context-usage.ts
@@ -248,7 +248,10 @@ export async function refreshContextUsage(
payloadThreadId,
);
if (stale()) return;
- const countExtras = await buildLocalTokenCountExtras(payloadThreadId);
+ const countExtras = await buildLocalTokenCountExtras(
+ payloadThreadId,
+ countHistory.messages,
+ );
if (stale()) return;
// Always ask the server: the template itself has tokens, and `unsloth run --enable-tools`
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 2c7a0ca269e..6cecbf5da2a 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -3809,6 +3809,13 @@ export const ar = {
discard: "تجاهل",
mentions: "المهارات",
manage: "إدارة المهارات",
+ bulkActions: "إجراءات المهارات",
+ enableAll: "تفعيل الكل",
+ disableAll: "تعطيل الكل",
+ resetAll: "إعادة التعيين إلى الافتراضي",
+ resetTitle: "إعادة تعيين كل المهارات؟",
+ resetDescription: "تعود كل مهارة إلى حالتها في التثبيت الجديد: مهاراتك ومهارات Claude مفعّلة، والمهارات المضمّنة معطّلة. ستُمسح اختياراتك للتفعيل والتعطيل.",
+ reset: "إعادة التعيين",
},
library: {
tabs: {
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 4801fb73da5..9e93fa67c7e 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -3881,6 +3881,13 @@ export const de = {
discard: "Verwerfen",
mentions: "Fähigkeiten",
manage: "Fähigkeiten verwalten",
+ bulkActions: "Fähigkeiten-Aktionen",
+ enableAll: "Alle aktivieren",
+ disableAll: "Alle deaktivieren",
+ resetAll: "Auf Standard zurücksetzen",
+ resetTitle: "Alle Fähigkeiten zurücksetzen?",
+ resetDescription: "Jede Fähigkeit kehrt zum Zustand einer Neuinstallation zurück: deine Fähigkeiten und Claude-Fähigkeiten an, mitgelieferte Fähigkeiten aus. Deine An/Aus-Auswahl wird gelöscht.",
+ reset: "Zurücksetzen",
},
library: {
tabs: {
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 1cf6abbe447..827080a2a8d 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -3835,6 +3835,13 @@ export const en = {
discard: "Discard",
mentions: "Skills",
manage: "Manage skills",
+ bulkActions: "Skill actions",
+ enableAll: "Enable all",
+ disableAll: "Disable all",
+ resetAll: "Reset to defaults",
+ resetTitle: "Reset all skills?",
+ resetDescription: "Every skill goes back to how a fresh install has it: your skills and Claude skills on, bundled skills off. Your on and off choices are cleared.",
+ reset: "Reset",
},
// The Library page, its file viewer, and the menus and toasts that act on its files.
library: {
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 81fc2f0bc04..8ce2d13a3be 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -3880,6 +3880,13 @@ export const es = {
discard: "Descartar",
mentions: "Habilidades",
manage: "Gestionar habilidades",
+ bulkActions: "Acciones de habilidades",
+ enableAll: "Activar todas",
+ disableAll: "Desactivar todas",
+ resetAll: "Restablecer valores predeterminados",
+ resetTitle: "¿Restablecer todas las habilidades?",
+ resetDescription: "Cada habilidad vuelve a como está en una instalación nueva: tus habilidades y las de Claude activadas, las incluidas desactivadas. Se borran tus elecciones de activar y desactivar.",
+ reset: "Restablecer",
},
library: {
tabs: {
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index e4faa74604f..74b9ed796cb 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -3892,6 +3892,13 @@ export const fr = {
discard: "Abandonner",
mentions: "Compétences",
manage: "Gérer les compétences",
+ bulkActions: "Actions sur les compétences",
+ enableAll: "Tout activer",
+ disableAll: "Tout désactiver",
+ resetAll: "Rétablir les valeurs par défaut",
+ resetTitle: "Réinitialiser toutes les compétences ?",
+ resetDescription: "Chaque compétence revient à son état d’installation : vos compétences et celles de Claude activées, les compétences intégrées désactivées. Vos choix d’activation sont effacés.",
+ reset: "Réinitialiser",
},
library: {
tabs: {
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index 7a064cbd752..59a28c6da14 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -3915,6 +3915,13 @@ export const he = {
discard: "ביטול שינויים",
mentions: "מיומנויות",
manage: "ניהול מיומנויות",
+ bulkActions: "פעולות מיומנויות",
+ enableAll: "הפעל הכול",
+ disableAll: "השבת הכול",
+ resetAll: "איפוס לברירת המחדל",
+ resetTitle: "לאפס את כל המיומנויות?",
+ resetDescription: "כל מיומנות חוזרת למצב של התקנה חדשה: המיומנויות שלך ומיומנויות Claude מופעלות, מיומנויות מובנות מושבתות. בחירות ההפעלה וההשבתה שלך יימחקו.",
+ reset: "איפוס",
},
library: {
tabs: {
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index ffa63b420e2..b2df24f5121 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -3817,6 +3817,13 @@ export const hi = {
discard: "छोड़ें",
mentions: "कौशल",
manage: "कौशल प्रबंधित करें",
+ bulkActions: "कौशल क्रियाएँ",
+ enableAll: "सभी चालू करें",
+ disableAll: "सभी बंद करें",
+ resetAll: "डिफ़ॉल्ट पर रीसेट करें",
+ resetTitle: "सभी कौशल रीसेट करें?",
+ resetDescription: "हर कौशल नए इंस्टॉल वाली स्थिति में लौट आता है: आपके कौशल और Claude कौशल चालू, बंडल किए गए कौशल बंद। आपकी चालू/बंद पसंद हटा दी जाती है।",
+ reset: "रीसेट करें",
},
library: {
tabs: {
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 4dd87beee2e..a57c8afbc2f 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -3882,6 +3882,13 @@ export const it = {
discard: "Scarta",
mentions: "Competenze",
manage: "Gestisci competenze",
+ bulkActions: "Azioni sulle competenze",
+ enableAll: "Attiva tutte",
+ disableAll: "Disattiva tutte",
+ resetAll: "Ripristina predefiniti",
+ resetTitle: "Ripristinare tutte le competenze?",
+ resetDescription: "Ogni competenza torna come in una nuova installazione: le tue competenze e quelle di Claude attive, quelle incluse disattivate. Le tue scelte di attivazione vengono cancellate.",
+ reset: "Ripristina",
},
library: {
tabs: {
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index e522f9eaba9..1590c968ea7 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -3757,6 +3757,13 @@ export const ja = {
discard: "破棄",
mentions: "スキル",
manage: "スキルを管理",
+ bulkActions: "スキルの操作",
+ enableAll: "すべて有効にする",
+ disableAll: "すべて無効にする",
+ resetAll: "デフォルトに戻す",
+ resetTitle: "すべてのスキルをリセットしますか?",
+ resetDescription: "すべてのスキルが新規インストール時の状態に戻ります。自分のスキルと Claude のスキルはオン、同梱スキルはオフになり、オン/オフの選択は消去されます。",
+ reset: "リセット",
},
library: {
tabs: {
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 582e87fa084..0ca3a9b18b9 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -3800,6 +3800,13 @@ export const ko = {
discard: "버리기",
mentions: "스킬",
manage: "스킬 관리",
+ bulkActions: "스킬 작업",
+ enableAll: "모두 사용",
+ disableAll: "모두 사용 안 함",
+ resetAll: "기본값으로 재설정",
+ resetTitle: "모든 스킬을 재설정할까요?",
+ resetDescription: "모든 스킬이 새로 설치한 상태로 돌아갑니다. 내 스킬과 Claude 스킬은 켜지고 번들 스킬은 꺼지며, 켜기/끄기 선택은 지워집니다.",
+ reset: "재설정",
},
library: {
tabs: {
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index e2601626995..1cf87257c72 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -3840,6 +3840,13 @@ export const ptBR = {
discard: "Descartar",
mentions: "Habilidades",
manage: "Gerenciar habilidades",
+ bulkActions: "Ações de habilidades",
+ enableAll: "Ativar todas",
+ disableAll: "Desativar todas",
+ resetAll: "Restaurar padrões",
+ resetTitle: "Redefinir todas as habilidades?",
+ resetDescription: "Cada habilidade volta ao estado de uma instalação nova: suas habilidades e as do Claude ativadas, as incluídas desativadas. Suas escolhas de ativar e desativar são apagadas.",
+ reset: "Redefinir",
},
library: {
tabs: {
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 3359e7ffc62..a19e18ac914 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -3836,6 +3836,13 @@ export const ru = {
discard: "Отменить",
mentions: "Навыки",
manage: "Управлять навыками",
+ bulkActions: "Действия с навыками",
+ enableAll: "Включить все",
+ disableAll: "Отключить все",
+ resetAll: "Сбросить по умолчанию",
+ resetTitle: "Сбросить все навыки?",
+ resetDescription: "Каждый навык вернётся в состояние новой установки: ваши навыки и навыки Claude включены, встроенные отключены. Ваш выбор включения и отключения будет удалён.",
+ reset: "Сбросить",
},
library: {
tabs: {
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index d8f09d8c148..05701dde8fa 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -4049,6 +4049,13 @@ export const sv = {
discard: "Ignorera",
mentions: "Färdigheter",
manage: "Hantera färdigheter",
+ bulkActions: "Färdighetsåtgärder",
+ enableAll: "Aktivera alla",
+ disableAll: "Inaktivera alla",
+ resetAll: "Återställ standard",
+ resetTitle: "Återställa alla färdigheter?",
+ resetDescription: "Varje färdighet återgår till hur en ny installation har den: dina färdigheter och Claude-färdigheter på, medföljande färdigheter av. Dina val av på och av rensas.",
+ reset: "Återställ",
},
library: {
tabs: {
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index ed151b39a36..fcb0945a301 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -3714,6 +3714,13 @@ export const zhCN = {
discard: "放弃",
mentions: "技能",
manage: "管理技能",
+ bulkActions: "技能操作",
+ enableAll: "全部启用",
+ disableAll: "全部停用",
+ resetAll: "恢复默认",
+ resetTitle: "重置所有技能?",
+ resetDescription: "每个技能都会恢复为全新安装时的状态:你的技能和 Claude 技能开启,内置技能关闭。你的开关选择将被清除。",
+ reset: "重置",
},
library: {
tabs: {
diff --git a/studio/frontend/tests/skill-load-event.test.ts b/studio/frontend/tests/skill-load-event.test.ts
index 78718c86b5b..3380e97879a 100644
--- a/studio/frontend/tests/skill-load-event.test.ts
+++ b/studio/frontend/tests/skill-load-event.test.ts
@@ -55,8 +55,8 @@ test("legacy and durable streams normalize preload, and history omits UI evidenc
);
const thread = readSrc("components/assistant-ui/thread.tsx");
assert.match(thread, /studio_load_skill: ReadSkillToolUIConfirmable/);
- assert.match(thread, /enabled=\{supportsTools && codeToolsEffective\}/);
- assert.match(thread, /const codeToolsEffective = useChatRuntimeStore\(codeToolsOn\);/);
+ // read_skill remains available without Code, so the popover depends only on tool support.
+ assert.match(thread, /<SkillMentionPopover[\s\S]*?enabled=\{supportsTools\}/);
const ui = readSrc("components/assistant-ui/tool-ui-read-skill.tsx");
assert.match(ui, /Skill not loaded/);
assert.match(ui, /Loaded \$\{name\}/);
diff --git a/studio/frontend/tests/skill-mention-accessibility.test.ts b/studio/frontend/tests/skill-mention-accessibility.test.ts
index 2bb3a8878b4..e80b2b0575c 100644
--- a/studio/frontend/tests/skill-mention-accessibility.test.ts
+++ b/studio/frontend/tests/skill-mention-accessibility.test.ts
@@ -30,7 +30,25 @@ test("the compare composer exposes its skill suggestions as a linked combobox",
test("the popover caps the adapter search, so navigation never leaves the rendered rows", () => {
assert.ok(
- mentionsSource.includes("(mention.adapter.search?.(query) ?? []).slice(0, MAX_MENTION_RESULTS)"),
+ mentionsSource.includes("rankMentionSkills(available, query, MAX_MENTION_RESULTS)"),
);
assert.ok(!mentionsSource.includes("results.slice(0, MAX_MENTION_RESULTS)"));
});
+
+test("Tab accepts the highlighted row in the main composer, as Enter does", () => {
+ assert.match(
+ mentionsSource,
+ /if \(event\.key !== "Tab" \|\| event\.shiftKey \|\| event\.isComposing\) return;/,
+ );
+ // reuse the library's Enter path so the token replacer still owns insertion.
+ assert.match(mentionsSource, /key: "Enter",\s*shiftKey: false,/);
+ assert.match(mentionsSource, /const active = open && items\.length > 0;/);
+ // focus may leave while the popover is open; Tab elsewhere must stay with that field.
+ assert.match(mentionsSource, /!scopeRef\.current\?\.contains\(event\.target\)/);
+ assert.match(mentionsSource, /<MentionTabAccept scopeRef=\{composerRef\} \/>/);
+ const thread = readFileSync(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(thread, /<SkillMentionPopover[\s\S]*?composerRef=\{editorRef\}/);
+});
diff --git a/studio/frontend/tests/skill-mention-pattern.test.ts b/studio/frontend/tests/skill-mention-pattern.test.ts
index eae8e29332e..53df1df6e84 100644
--- a/studio/frontend/tests/skill-mention-pattern.test.ts
+++ b/studio/frontend/tests/skill-mention-pattern.test.ts
@@ -5,19 +5,7 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
-// The module imports the auth layer, so the pattern is lifted from source; the assertion keeps the copy honest.
-const SKILLS_API_SOURCE = readFileSync(
- new URL("../src/features/chat/api/skills-api.ts", import.meta.url),
- "utf8",
-);
-const declaration = /export const SKILL_MENTION_PATTERN =\s*(\/.*\/g);/.exec(
- SKILLS_API_SOURCE,
-);
-assert.ok(declaration, "SKILL_MENTION_PATTERN declaration not found");
-const SKILL_MENTION_PATTERN = new RegExp(
- declaration[1].slice(1, declaration[1].lastIndexOf("/")),
- "g",
-);
+import { SKILL_MENTION_PATTERN } from "../src/features/chat/api/skill-tools.ts";
const names = (text: string): string[] =>
[...text.matchAll(SKILL_MENTION_PATTERN)].map((match) => match[2] ?? "");
@@ -43,6 +31,15 @@ test("emails, underscores, uppercase and dangling hyphens are not mentions", ()
assert.deepEqual(names("@-probe"), []);
});
+test("one trailing sentence mark, the same rule as the backend preload", () => {
+ for (const text of ["@alpha.", "@alpha,", "@alpha;", "@alpha:", "@alpha!", "@alpha?", "@alpha)"]) {
+ assert.deepEqual(names(`${text} next`), ["alpha"], text);
+ }
+ for (const text of ["@alpha!!", "@alpha]", "@alpha).", "@alpha'", '@alpha"', "@alpha?!"]) {
+ assert.deepEqual(names(text), [], text);
+ }
+});
+
test("a name is at most 64 characters", () => {
const sixtyFour = "a".repeat(64);
assert.deepEqual(names(`@${sixtyFour}`), [sixtyFour]);
diff --git a/studio/frontend/tests/skill-mention-token.test.ts b/studio/frontend/tests/skill-mention-token.test.ts
index 1ead89eef63..7b8add75060 100644
--- a/studio/frontend/tests/skill-mention-token.test.ts
+++ b/studio/frontend/tests/skill-mention-token.test.ts
@@ -6,6 +6,8 @@ import assert from "node:assert/strict";
import test from "node:test";
import {
mentionTokenAt,
+ mentionableSkills,
+ rankMentionSkills,
replaceMentionToken,
} from "../src/components/assistant-ui/skill-mention-token.ts";
import { readSrc } from "./helpers/kit.ts";
@@ -63,3 +65,58 @@ test("both composers replace the whole token", () => {
assert.match(popover, /aui\.composer\(\)\.setText\(next\.text\);\n\s*setCursorPosition\(next\.caret\);/);
assert.match(popover, /<MentionTokenReplacer \/>/);
});
+
+const skill = (name: string, description = "", extra = {}) => ({
+ name,
+ description,
+ valid: true,
+ shadowed: false,
+ enabled: true,
+ ...extra,
+});
+
+test("only enabled, valid, winning skills are offered", () => {
+ const offered = mentionableSkills([
+ skill("on"),
+ skill("off", "", { enabled: false }),
+ skill("broken", "", { valid: false }),
+ skill("shadowed", "", { shadowed: true }),
+ ]);
+ assert.deepEqual(
+ offered.map((entry) => entry.name),
+ ["on"],
+ );
+});
+
+test("suggestions rank name prefixes, then names, then descriptions", () => {
+ const skills = [
+ skill("release-notes", "Write a changelog"),
+ skill("notes", "Plain notes"),
+ skill("pdf", "Read notes from a PDF"),
+ skill("unrelated", "Nothing here"),
+ ];
+ const names = (query: string, limit = 50) =>
+ rankMentionSkills(skills, query, limit).map((entry) => entry.name);
+ assert.deepEqual(names("notes"), ["notes", "release-notes", "pdf"]);
+ assert.deepEqual(names("NOTES"), ["notes", "release-notes", "pdf"]);
+ assert.deepEqual(names("re"), ["release-notes", "unrelated", "pdf"]);
+ // a bare @ preserves catalog order and applies the cap.
+ assert.deepEqual(names(""), skills.map((entry) => entry.name));
+ assert.deepEqual(names("", 2), ["release-notes", "notes"]);
+ assert.deepEqual(names("zzz"), []);
+});
+
+test("picking a suggestion inserts the exact token the send path resolves", () => {
+ const token = mentionTokenAt("summarize with @rel", 19);
+ assert.ok(token);
+ const [picked] = rankMentionSkills([skill("release-notes")], token.query, 50);
+ const next = replaceMentionToken("summarize with @rel", token, `@${picked.name}`);
+ assert.equal(next.text, "summarize with @release-notes ");
+ assert.equal(next.caret, next.text.length);
+});
+
+test("both composers share the ranked filter", () => {
+ const popover = readSrc("components/assistant-ui/skill-mentions.tsx");
+ assert.equal(popover.match(/rankMentionSkills\(/g)?.length, 2);
+ assert.equal(popover.match(/mentionableSkills\(skills\)/g)?.length, 2);
+});
diff --git a/studio/frontend/tests/skill-tools.test.ts b/studio/frontend/tests/skill-tools.test.ts
index 8e6eeff9b47..e74e3f05cb4 100644
--- a/studio/frontend/tests/skill-tools.test.ts
+++ b/studio/frontend/tests/skill-tools.test.ts
@@ -4,18 +4,46 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { skillToolsOffered } from "../src/features/chat/api/skill-tools.ts";
+import { skillToolNames } from "../src/features/chat/api/skill-tools.ts";
-const enabled = { valid: true, shadowed: false, enabled: true };
+const enabled = { name: "guided", valid: true, shadowed: false, enabled: true };
-test("an enabled skill is offered only while Code is on (#11671)", () => {
- assert.equal(skillToolsOffered([enabled], true), true);
- assert.equal(skillToolsOffered([enabled], false), false);
+test("Code on offers both skill tools for any usable skill", () => {
+ assert.deepEqual(skillToolNames([enabled], true, []), ["read_skill", "create_skill"]);
+});
+
+test("Code off keeps a plain chat out of the tool loop (#11671)", () => {
+ assert.deepEqual(skillToolNames([enabled], false, []), []);
+ assert.deepEqual(skillToolNames([enabled], false, ["what is guided?"]), []);
+ // not a mention: no whitespace before @, or the name is not spec-shaped.
+ assert.deepEqual(skillToolNames([enabled], false, ["mail me@guided"]), []);
+ assert.deepEqual(skillToolNames([enabled], false, ["@Guided"]), []);
+ // the backend would not preload these, so they must not open the loop either.
+ assert.deepEqual(skillToolNames([enabled], false, ["use @guided!!"]), []);
+ assert.deepEqual(skillToolNames([enabled], false, ["use @guided]"]), []);
+ assert.deepEqual(skillToolNames([enabled], false, ["use @guided."]), ["read_skill"]);
+});
+
+test("Code off still reads a skill the user @mentions, but never creates one", () => {
+ assert.deepEqual(skillToolNames([enabled], false, ["use @guided please"]), ["read_skill"]);
+ // an earlier mention keeps it readable because preloaded SKILL.md is not replayed.
+ assert.deepEqual(skillToolNames([enabled], false, ["@guided", "and now?"]), ["read_skill"]);
+});
+
+test("a mention of an unusable or unknown skill offers nothing with Code off", () => {
+ for (const skill of [
+ { ...enabled, enabled: false },
+ { ...enabled, shadowed: true },
+ { ...enabled, valid: false },
+ ]) {
+ assert.deepEqual(skillToolNames([skill], false, ["@guided"]), []);
+ }
+ assert.deepEqual(skillToolNames([enabled], false, ["@someone-else"]), []);
});
test("Code alone offers nothing without a usable skill", () => {
- assert.equal(skillToolsOffered([], true), false);
- assert.equal(skillToolsOffered([{ ...enabled, enabled: false }], true), false);
- assert.equal(skillToolsOffered([{ ...enabled, shadowed: true }], true), false);
- assert.equal(skillToolsOffered([{ ...enabled, valid: false }], true), false);
+ assert.deepEqual(skillToolNames([], true, ["@guided"]), []);
+ assert.deepEqual(skillToolNames([{ ...enabled, enabled: false }], true, []), []);
+ assert.deepEqual(skillToolNames([{ ...enabled, shadowed: true }], true, []), []);
+ assert.deepEqual(skillToolNames([{ ...enabled, valid: false }], true, []), []);
});
diff --git a/studio/frontend/tests/skills-dialog-bulk.test.ts b/studio/frontend/tests/skills-dialog-bulk.test.ts
new file mode 100644
index 00000000000..7c711d876cc
--- /dev/null
+++ b/studio/frontend/tests/skills-dialog-bulk.test.ts
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { readSrc } from "./helpers/kit.ts";
+
+const API = readSrc("features/chat/api/skills-api.ts");
+const DIALOG = readSrc("features/chat/components/chat-skills-dialog.tsx");
+
+test("bulk changes go through one PUT on the collection and publish its list", () => {
+ const body = API.slice(
+ API.indexOf("export async function setAllSkillsEnabled"),
+ API.indexOf("export const SKILL_NAME_PATTERN"),
+ );
+ assert.match(body, /enabled: boolean \| null/);
+ // sign-out drops the response; otherwise it supersedes any earlier read.
+ assert.match(body, /const epoch = sessionEpoch;/);
+ assert.match(body, /if \(epoch !== sessionEpoch\) return skills;\s*\/\/[^\n]*\n\s*requestGeneration \+= 1;/);
+ assert.doesNotMatch(body, /\+\+requestGeneration/);
+ assert.match(API, /AUTH_SESSION_CLEARED_EVENT, \(\) => \{\s*sessionEpoch \+= 1;/);
+ assert.match(body, /authFetch\("\/api\/skills", \{\s*method: "PUT"/);
+ assert.match(body, /JSON\.stringify\(\{ enabled \}\)/);
+ assert.match(body, /publish\(\{ skills, loading: false, initialized: true, error: null \}\)/);
+ // match single-toggle fan-out so other tabs and the context bar follow.
+ assert.match(body, /channel\?\.postMessage\("changed"\)/);
+ assert.match(body, /refreshContextUsage\(\{ invalidate: true \}\)/);
+});
+
+test("enable all, disable all and reset sit in one menu beside Refresh", () => {
+ assert.match(DIALOG, /onSelect=\{\(\) => void toggleAll\(true\)\}/);
+ assert.match(DIALOG, /onSelect=\{\(\) => void toggleAll\(false\)\}/);
+ // disable actions with nothing to change instead of allowing silent no-ops.
+ assert.match(DIALOG, /disabled=\{usable\.every\(\(skill\) => skill\.enabled\)\}/);
+ assert.match(DIALOG, /disabled=\{!usable\.some\(\(skill\) => skill\.enabled\)\}/);
+ assert.match(DIALOG, /aria-label=\{t\("skills\.bulkActions"\)\}/);
+});
+
+test("reset discards custom choices, so it asks first", () => {
+ assert.match(DIALOG, /onSelect=\{\(\) => setConfirmingReset\(true\)\}/);
+ assert.match(
+ DIALOG,
+ /setConfirmingReset\(false\);\s*void toggleAll\(null\);/,
+ );
+ assert.doesNotMatch(DIALOG, /onSelect=\{\(\) => void toggleAll\(null\)\}/);
+ // match destructive confirmations because reset discards user choices.
+ assert.match(
+ DIALOG,
+ /variant="destructive"\s*onClick=\{\(\) => \{\s*setConfirmingReset\(false\);/,
+ );
+ // serialize row and bulk changes so response order cannot diverge from server write order.
+ assert.match(DIALOG, /<SkillRow[\s\S]*?changing=\{changing !== null\}/);
+ // gate the detail switch too so it cannot race a library change.
+ assert.match(DIALOG, /<Switch[\s\S]*?disabled=\{[\s\S]*?changing !== null[\s\S]*?\}/);
+});
diff --git a/studio/frontend/tests/skills-token-count-discovery.test.ts b/studio/frontend/tests/skills-token-count-discovery.test.ts
index 49eb93b4884..ee191669fc3 100644
--- a/studio/frontend/tests/skills-token-count-discovery.test.ts
+++ b/studio/frontend/tests/skills-token-count-discovery.test.ts
@@ -23,10 +23,10 @@ test("token counting waits for the initial skills discovery", () => {
/if \(pending\) await Promise\.race\(\[pending\.catch\(\(\) => undefined\), deadline\]\);/,
);
assert.match(SKILLS_API_SOURCE, /let stale = !snapshot\.initialized;/);
- assert.match(CHAT_ADAPTER_SOURCE, /await settleSkillsForText\(""\);/);
+ assert.match(CHAT_ADAPTER_SOURCE, /await settleSkillsForText\(userTexts\(messages\)\.join\("\\n"\)\);/);
assert.match(
CHAT_ADAPTER_SOURCE,
- /const hasEnabledSkills = skillToolsOffered\(\s*getSkillsSnapshot\(\)\.skills,\s*codeToolsEnabled,\s*\);/,
+ /const skillTools = skillToolNames\(\s*getSkillsSnapshot\(\)\.skills,\s*codeToolsEnabled,\s*userTexts\(messages\),\s*\);/,
);
});
@@ -43,10 +43,8 @@ test("token counting lists the skill tools only when the completion would", () =
CHAT_ADAPTER_SOURCE.indexOf("export async function buildLocalTokenCountExtras"),
CHAT_ADAPTER_SOURCE.indexOf("mcp_enabled: mcpEnabledForChat"),
);
- assert.match(
- countExtras,
- /\.\.\.\(hasEnabledSkills \? \["read_skill", "create_skill"\] : \[\]\),/,
- );
+ assert.match(countExtras, /skillTools\.length === 0\n\s*\) \{/);
+ assert.match(countExtras, /^\s*\.\.\.skillTools,$/m);
assert.doesNotMatch(countExtras, /^\s*"read_skill",$/m);
assert.doesNotMatch(countExtras, /^\s*"create_skill",$/m);
});
@@ -61,15 +59,15 @@ test("request building waits for skills and preserves the launcher tool catalog"
);
assert.match(
payloadBuilder,
- /if \(supportsStudioToolsForThisTurn\) \{\s*await settleSkillsForText\(lastUserText\(outboundMessages\)\);/,
+ /if \(supportsStudioToolsForThisTurn\) \{\s*\/\/[^\n]*\n\s*await settleSkillsForText\(userTexts\(outboundMessages\)\.join\("\\n"\)\);/,
);
assert.match(
payloadBuilder,
- /const hasEnabledSkills = skillToolsOffered\(\s*getSkillsSnapshot\(\)\.skills,\s*codeToolsEnabled,\s*\);/,
+ /const skillTools = skillToolNames\(\s*getSkillsSnapshot\(\)\.skills,\s*codeToolsEnabled,\s*userTexts\(outboundMessages\),\s*\);/,
);
assert.match(
payloadBuilder,
- /supportsTools &&\s*\([\s\S]*hasEnabledSkills[\s\S]*\)\s*\? \{\s*enable_tools: true/,
+ /supportsTools &&\s*\([\s\S]*skillTools\.length > 0[\s\S]*\)\s*\? \{\s*enable_tools: true/,
);
const localToolCatalog = payloadBuilder.slice(
payloadBuilder.indexOf("// Sent for every local chat"),
@@ -82,3 +80,14 @@ test("a sign-out drops the module-level skills snapshot", () => {
assert.ok(SKILLS_API_SOURCE.includes("window.addEventListener(AUTH_SESSION_CLEARED_EVENT"));
assert.ok(SKILLS_API_SOURCE.includes("publish(EMPTY_SNAPSHOT)"));
});
+
+test("the count passes the counted history so a Code-off @mention is priced like the send", () => {
+ const refresh = readFileSync(
+ new URL("../src/features/chat/utils/refresh-context-usage.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ refresh,
+ /buildLocalTokenCountExtras\(\s*payloadThreadId,\s*countHistory\.messages,\s*\)/,
+ );
+});