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.

Add setting to collapse tool activity by default (#9803)

Lee Jackson4c144b17628e
diff --git a/studio/frontend/smoke-tool-activity-main.tsx b/studio/frontend/smoke-tool-activity-main.tsx
new file mode 100644
index 00000000000..81d9ea2e3ba
--- /dev/null
+++ b/studio/frontend/smoke-tool-activity-main.tsx
@@ -0,0 +1,296 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Harness page for tests/studio/playwright_tool_activity.py.
+//
+// The node suite reaches the open-state reducers and the store, but not a
+// rendered Radix Collapsible, so aria-expanded, whether closed content is in
+// the DOM, and scroll movement are only answerable here.
+//
+// Four disclosure paths reach the same primitive by different routes, and a fix
+// landing in one can miss the others:
+// controlled useToolActivityOpen -- web search, knowledge base, code exec
+// uncontrolled <ToolFallbackRoot defaultOpen> -- terminal, generic/MCP
+// approval the same card with awaitingApproval, which must stay open
+// group <ToolGroupRoot>, whose open state is its own
+//
+// The explicit `overflow-y: auto` ancestor exists because that is what
+// useCollapseScrollLock walks up to find.
+
+import "@/index.css";
+
+// Load-bearing import order. `tool-group.tsx` reaches the `@/features/chat`
+// barrel, which re-exports chat-runtime-store, which sits in a cycle with it;
+// entering that graph from the barrel or from `assistant-ui/thread` dies with
+// "Cannot access 'CHAT_GPU_MEMORY_MODE_KEY' before initialization". Entering
+// from the store module orders it correctly. Observed, not theorised, and a
+// property of the app's module graph rather than of anything under test.
+/* eslint-disable no-restricted-imports -- a harness entry point, not app code. */
+import "@/features/chat/stores/chat-runtime-store";
+
+import {
+ ToolFallbackContent,
+ ToolFallbackRoot,
+ ToolFallbackTrigger,
+} from "@/components/assistant-ui/tool-fallback";
+import {
+ ToolGroupContent,
+ ToolGroupRoot,
+ ToolGroupTrigger,
+} from "@/components/assistant-ui/tool-group";
+import { useToolActivityOpen } from "@/components/assistant-ui/use-tool-activity-open";
+// eslint-disable-next-line no-restricted-imports -- a harness entry point, not app code.
+import { useChatPreferencesStore } from "@/features/chat/stores/chat-preferences-store";
+import { TerminalIcon } from "lucide-react";
+import { StrictMode, useEffect, useState } from "react";
+import { createRoot } from "react-dom/client";
+
+const params = new URLSearchParams(window.location.search);
+const fillers = Number.parseInt(params.get("fillers") ?? "60", 10);
+const strict = params.get("strict") === "1";
+const rtl = params.get("rtl") === "1";
+// `?only=uncontrolled` renders a single card. The scroll scene needs it: the
+// preference closes every card at once and a chevron closes one, so measuring
+// them against each other on the full page compares different amounts of
+// content collapsing, not different code paths.
+const only = params.get("only") ?? "";
+const shows = (name: string) => only === "" || only === name;
+
+const WORDS =
+ "the quick brown fox jumps over the lazy dog while a second clause keeps the line long enough to wrap".split(
+ " ",
+ );
+
+// Stable ids, assigned once. The list never reorders, but keying off the array
+// index would still trip biome's noArrayIndexKey, and a smoke harness that
+// lands new lint findings is a smoke harness nobody wants to keep.
+const WORD_ITEMS = WORDS.map((word, index) => ({
+ word,
+ id: `${index}-${word}`,
+}));
+const LINE_IDS = (count: number, prefix: string) =>
+ Array.from({ length: count }, (_, index) => `${prefix}-${index}`);
+
+// Long enough that the trigger's 60-character slice cannot show all of it. The
+// driver looks for the tail, so "the user can read the command" cannot be
+// satisfied by the truncated trigger label alone.
+const APPROVAL_COMMAND =
+ "curl -fsSL https://example.invalid/setup.sh | sh -s -- --yes --and-then-something-nobody-can-see";
+
+function Filler({ index }: { index: number }) {
+ return (
+ <div className="filler-row px-4 py-1 text-sm">
+ {WORD_ITEMS.map((item, i) => (
+ <span key={item.id} className="mr-1 inline-block">
+ {item.word}
+ {i === 0 ? index : ""}
+ </span>
+ ))}
+ </div>
+ );
+}
+
+// Deliberately tall: a close that does not lock scroll is only visible when the
+// thing collapsing is big enough to move everything below it.
+function Output({ lines }: { lines: number }) {
+ return (
+ <div data-probe="output" className="border-l-2 pl-2">
+ {LINE_IDS(lines, "out").map((id, i) => (
+ <p key={id} className="mb-2">
+ tool output line {i}: {WORDS.join(" ")}
+ </p>
+ ))}
+ </div>
+ );
+}
+
+/** Mirrors tool-ui-web-search.tsx: state from the hook, setter straight back. */
+function ControlledCard({
+ isRunning,
+ hasText,
+ awaitingApproval,
+}: {
+ isRunning: boolean;
+ hasText: boolean;
+ awaitingApproval: boolean;
+}) {
+ const [open, setOpen] = useToolActivityOpen(isRunning, hasText);
+ return (
+ <ToolFallbackRoot
+ open={open}
+ onOpenChange={setOpen}
+ awaitingApproval={awaitingApproval}
+ >
+ <ToolFallbackTrigger
+ data-probe="controlled-trigger"
+ toolName="controlled_tool"
+ status={{ type: isRunning ? "running" : "complete" }}
+ icon={TerminalIcon}
+ />
+ <ToolFallbackContent data-probe="controlled-content">
+ <Output lines={30} />
+ </ToolFallbackContent>
+ </ToolFallbackRoot>
+ );
+}
+
+/** Mirrors tool-ui-terminal.tsx, including `defaultOpen` being a live prop. */
+function UncontrolledCard({ isRunning }: { isRunning: boolean }) {
+ return (
+ <ToolFallbackRoot defaultOpen={isRunning}>
+ <ToolFallbackTrigger
+ data-probe="uncontrolled-trigger"
+ toolName="uncontrolled_tool"
+ status={{ type: isRunning ? "running" : "complete" }}
+ icon={TerminalIcon}
+ />
+ <ToolFallbackContent data-probe="uncontrolled-content">
+ <Output lines={30} />
+ </ToolFallbackContent>
+ </ToolFallbackRoot>
+ );
+}
+
+/**
+ * A terminal card parked on an allow/deny decision. The trigger carries the
+ * same truncated label the real one does, and the full command lives inside the
+ * collapsible, so the scene can ask the only question that matters: with the
+ * preference on, can the user read what they are approving?
+ */
+function ApprovalCard({
+ isRunning,
+ awaitingApproval,
+}: {
+ isRunning: boolean;
+ awaitingApproval: boolean;
+}) {
+ return (
+ <ToolFallbackRoot
+ defaultOpen={isRunning}
+ awaitingApproval={awaitingApproval}
+ >
+ <ToolFallbackTrigger
+ data-probe="approval-trigger"
+ toolName={`$ ${APPROVAL_COMMAND.slice(0, 60)}`}
+ status={{ type: isRunning ? "running" : "complete" }}
+ icon={TerminalIcon}
+ />
+ <ToolFallbackContent data-probe="approval-content">
+ <pre data-probe="approval-command">{APPROVAL_COMMAND}</pre>
+ </ToolFallbackContent>
+ </ToolFallbackRoot>
+ );
+}
+
+/** The multi-call wrapper, uncontrolled exactly as ToolGroupImpl leaves it. */
+function GroupCard() {
+ return (
+ <ToolGroupRoot data-probe="group-root">
+ <ToolGroupTrigger data-probe="group-trigger" count={3} />
+ <ToolGroupContent data-probe="group-content">
+ <Output lines={10} />
+ </ToolGroupContent>
+ </ToolGroupRoot>
+ );
+}
+
+function App() {
+ const [isRunning, setIsRunning] = useState(true);
+ const [hasText, setHasText] = useState(false);
+ const [awaitingApproval, setAwaitingApproval] = useState(false);
+ // Remount key, so a scene can ask "what does a card mounting NOW do"
+ // separately from "what does an already-mounted card do".
+ const [generation, setGeneration] = useState(0);
+
+ useEffect(() => {
+ const w = window as unknown as Record<string, unknown>;
+ w.__setRunning = (v: boolean) => setIsRunning(v);
+ w.__setHasText = (v: boolean) => setHasText(v);
+ w.__setAwaitingApproval = (v: boolean) => setAwaitingApproval(v);
+ w.__remount = () => setGeneration((g) => g + 1);
+ w.__setPreference = (v: boolean) =>
+ useChatPreferencesStore.getState().setCollapseToolActivityByDefault(v);
+ w.__getPreference = () =>
+ useChatPreferencesStore.getState().collapseToolActivityByDefault;
+ // The declared default, so a scene can check "landed on the default"
+ // without hard-coding which default that currently is.
+ w.__getDefaultPreference = () =>
+ useChatPreferencesStore.getInitialState().collapseToolActivityByDefault;
+ }, []);
+
+ useEffect(() => {
+ let inner = 0;
+ const outer = requestAnimationFrame(() => {
+ inner = requestAnimationFrame(() => {
+ (window as unknown as Record<string, unknown>).__probeReady = {
+ fillers,
+ strict,
+ rtl,
+ preference:
+ useChatPreferencesStore.getState().collapseToolActivityByDefault,
+ };
+ });
+ });
+ return () => {
+ cancelAnimationFrame(outer);
+ cancelAnimationFrame(inner);
+ };
+ }, []);
+
+ return (
+ <div
+ data-probe="viewport"
+ dir={rtl ? "rtl" : "ltr"}
+ style={{ height: "100vh", overflowY: "auto" }}
+ >
+ <div data-probe="filler-host">
+ {LINE_IDS(fillers, "head").map((id, i) => (
+ <Filler key={id} index={i} />
+ ))}
+ </div>
+ <div data-probe="cards" key={generation}>
+ {shows("controlled") && (
+ <ControlledCard
+ isRunning={isRunning}
+ hasText={hasText}
+ awaitingApproval={awaitingApproval}
+ />
+ )}
+ {shows("uncontrolled") && <UncontrolledCard isRunning={isRunning} />}
+ {shows("approval") && (
+ <ApprovalCard
+ isRunning={isRunning}
+ awaitingApproval={awaitingApproval}
+ />
+ )}
+ {shows("group") && <GroupCard />}
+ </div>
+ <div data-probe="answer" className="px-4 py-8 text-lg">
+ the assistant answer starts here
+ </div>
+ <div data-probe="tail-host">
+ {LINE_IDS(40, "tail").map((id, i) => (
+ <Filler key={id} index={1000 + i} />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+const root = document.getElementById("root");
+if (!root) {
+ throw new Error("missing #root");
+}
+
+// StrictMode is a scene, not the default: it double-renders, which is exactly
+// what the render-phase setState in ToolFallbackRoot/ToolGroupRoot has to
+// survive, but it also doubles every effect and would muddy the measurements.
+createRoot(root).render(
+ strict ? (
+ <StrictMode>
+ <App />
+ </StrictMode>
+ ) : (
+ <App />
+ ),
+);
diff --git a/studio/frontend/smoke-tool-activity.html b/studio/frontend/smoke-tool-activity.html
new file mode 100644
index 00000000000..7db23d2999f
--- /dev/null
+++ b/studio/frontend/smoke-tool-activity.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <script src="/crypto-boot.js"></script>
+ <title>tool activity preference smoke</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/smoke-tool-activity-main.tsx"></script>
+ </body>
+</html>
diff --git a/studio/frontend/src/components/assistant-ui/tool-activity-open-state.ts b/studio/frontend/src/components/assistant-ui/tool-activity-open-state.ts
new file mode 100644
index 00000000000..51853890f01
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/tool-activity-open-state.ts
@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+interface ToolActivityTransition {
+ currentOpen: boolean;
+ collapseByDefault: boolean;
+ previousCollapseByDefault: boolean;
+ isRunning: boolean;
+ hasText: boolean;
+}
+
+export function resolveToolActivityOpen({
+ currentOpen,
+ collapseByDefault,
+ previousCollapseByDefault,
+ isRunning,
+ hasText,
+}: ToolActivityTransition) {
+ if (collapseByDefault) {
+ return previousCollapseByDefault ? currentOpen : false;
+ }
+ if (isRunning) {
+ return true;
+ }
+ if (hasText) {
+ return false;
+ }
+ return currentOpen;
+}
+
+export interface ToolActivityPreferenceState {
+ collapseByDefault: boolean;
+ open: boolean;
+}
+
+export function syncToolActivityPreference(
+ current: ToolActivityPreferenceState,
+ collapseByDefault: boolean,
+ defaultOpen: boolean,
+) {
+ if (current.collapseByDefault === collapseByDefault) {
+ return current;
+ }
+ return {
+ collapseByDefault,
+ open: defaultOpen && !collapseByDefault,
+ };
+}
diff --git a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx b/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
index 50736ed4a5d..e5d6eee5d41 100644
--- a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
@@ -9,6 +9,8 @@ import {
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Spinner } from "@/components/ui/spinner";
+// eslint-disable-next-line no-restricted-imports -- the feature barrel imports this component
+import { useChatPreferencesStore } from "@/features/chat/stores/chat-preferences-store";
import { useCollapseScrollLock } from "@/hooks/use-collapse-scroll-lock";
import {
formatMcpToolName,
@@ -38,6 +40,7 @@ import {
useState,
} from "react";
import { toolArgText } from "./tool-arg-text";
+import { syncToolActivityPreference } from "./tool-activity-open-state";
const ANIMATION_DURATION = 200;
@@ -48,6 +51,12 @@ export type ToolFallbackRootProps = Omit<
open?: boolean;
onOpenChange?: (open: boolean) => void;
defaultOpen?: boolean;
+ /**
+ * Parked on an allow/deny decision. Pins the card open above `open` and the
+ * collapse preference, so what is being approved stays readable. Groups do
+ * the same with `hasPendingConfirmation`.
+ */
+ awaitingApproval?: boolean;
};
function ToolFallbackRoot({
@@ -55,15 +64,34 @@ function ToolFallbackRoot({
open: controlledOpen,
onOpenChange: controlledOnOpenChange,
defaultOpen = false,
+ awaitingApproval = false,
children,
...props
}: ToolFallbackRootProps) {
const collapsibleRef = useRef<HTMLDivElement>(null);
- const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
+ const collapseByDefault = useChatPreferencesStore(
+ (state) => state.collapseToolActivityByDefault,
+ );
+ const [uncontrolledState, setUncontrolledState] = useState(
+ () => ({
+ collapseByDefault,
+ open: defaultOpen && !collapseByDefault,
+ }),
+ );
+ const syncedUncontrolledState = syncToolActivityPreference(
+ uncontrolledState,
+ collapseByDefault,
+ defaultOpen,
+ );
+ if (syncedUncontrolledState !== uncontrolledState) {
+ setUncontrolledState(syncedUncontrolledState);
+ }
const lockScroll = useCollapseScrollLock(collapsibleRef, ANIMATION_DURATION);
const isControlled = controlledOpen !== undefined;
- const isOpen = isControlled ? controlledOpen : uncontrolledOpen;
+ const isOpen =
+ awaitingApproval ||
+ (isControlled ? controlledOpen : syncedUncontrolledState.open);
const handleOpenChange = useCallback(
(open: boolean) => {
@@ -71,11 +99,14 @@ function ToolFallbackRoot({
lockScroll();
}
if (!isControlled) {
- setUncontrolledOpen(open);
+ setUncontrolledState({
+ collapseByDefault,
+ open,
+ });
}
controlledOnOpenChange?.(open);
},
- [lockScroll, isControlled, controlledOnOpenChange],
+ [collapseByDefault, lockScroll, isControlled, controlledOnOpenChange],
);
return (
diff --git a/studio/frontend/src/components/assistant-ui/tool-group.tsx b/studio/frontend/src/components/assistant-ui/tool-group.tsx
index 942bc6a852f..ca2659b5752 100644
--- a/studio/frontend/src/components/assistant-ui/tool-group.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-group.tsx
@@ -12,6 +12,7 @@ import { useAuiState } from "@assistant-ui/react";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
import {
toolOutputKey,
+ useChatPreferencesStore,
useToolPaneScope,
useUnresolvedToolPaneScope,
} from "@/features/chat";
@@ -27,6 +28,7 @@ import {
import { useCollapseScrollLock } from "@/hooks/use-collapse-scroll-lock";
import { cn } from "@/lib/utils";
import { Spinner } from "@/components/ui/spinner";
+import { syncToolActivityPreference } from "./tool-activity-open-state";
const ANIMATION_DURATION = 200;
@@ -62,11 +64,29 @@ function ToolGroupRoot({
...props
}: ToolGroupRootProps) {
const collapsibleRef = useRef<HTMLDivElement>(null);
- const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
+ // Same treatment as ToolFallbackRoot. ToolGroupImpl passes `undefined`
+ // whenever it is not forcing the group open, so this uncontrolled state is
+ // what is on screen for most of a group's life -- without the sync, a group
+ // expanded by hand stays open while every card inside it closes.
+ const collapseByDefault = useChatPreferencesStore(
+ (state) => state.collapseToolActivityByDefault,
+ );
+ const [uncontrolledState, setUncontrolledState] = useState(() => ({
+ collapseByDefault,
+ open: defaultOpen && !collapseByDefault,
+ }));
+ const syncedUncontrolledState = syncToolActivityPreference(
+ uncontrolledState,
+ collapseByDefault,
+ defaultOpen,
+ );
+ if (syncedUncontrolledState !== uncontrolledState) {
+ setUncontrolledState(syncedUncontrolledState);
+ }
const lockScroll = useCollapseScrollLock(collapsibleRef, ANIMATION_DURATION);
const isControlled = controlledOpen !== undefined;
- const isOpen = isControlled ? controlledOpen : uncontrolledOpen;
+ const isOpen = isControlled ? controlledOpen : syncedUncontrolledState.open;
const handleOpenChange = useCallback(
(open: boolean) => {
@@ -74,11 +94,11 @@ function ToolGroupRoot({
lockScroll();
}
if (!isControlled) {
- setUncontrolledOpen(open);
+ setUncontrolledState({ collapseByDefault, open });
}
controlledOnOpenChange?.(open);
},
- [lockScroll, isControlled, controlledOnOpenChange],
+ [collapseByDefault, lockScroll, isControlled, controlledOnOpenChange],
);
return (
@@ -242,6 +262,9 @@ const ToolGroupImpl: FC<
const messageRunning = useAuiState(
({ message }) => message.status?.type === "running",
);
+ const collapseByDefault = useChatPreferencesStore(
+ (state) => state.collapseToolActivityByDefault,
+ );
// Force the group open when any call is receiving tool_output events.
const toolLiveOutput = useChatRuntimeStore((s) => s.toolLiveOutput);
const paneScope = useToolPaneScope();
@@ -266,12 +289,17 @@ const ToolGroupImpl: FC<
);
// Keep the group open once a confirmation or live output forced it (so an
// allow/deny doesn't snap it shut between calls); reverts once the turn ends.
+ // Only latch what could have forced it open: a latch set while collapsed is
+ // a force nobody saw, and turning the preference off would snap them all open.
const forcedOpenRef = useRef(false);
- if (hasPendingConfirmation || hasLiveOutput) forcedOpenRef.current = true;
+ if (hasPendingConfirmation || (hasLiveOutput && !collapseByDefault)) {
+ forcedOpenRef.current = true;
+ }
const forceOpen =
hasPendingConfirmation ||
- (hasLiveOutput && messageRunning) ||
- (forcedOpenRef.current && messageRunning);
+ (!collapseByDefault &&
+ ((hasLiveOutput && messageRunning) ||
+ (forcedOpenRef.current && messageRunning)));
// Render single calls, canvases, and Python scripts directly so their
// persistent content never hides in a collapsed group.
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-code-execution.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-code-execution.tsx
index 26390838566..4183a64623b 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-code-execution.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-code-execution.tsx
@@ -16,11 +16,13 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { Spinner } from "@/components/ui/spinner";
import { toolArgText } from "./tool-arg-text";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useToolAwaitingApproval } from "@/features/chat";
import {
ToolFallbackContent,
ToolFallbackRoot,
ToolFallbackTrigger,
} from "./tool-fallback";
+import { useToolActivityOpen } from "./use-tool-activity-open";
/**
* Renders synthetic `_toolEvent` chunks from `_stream_anthropic` for the
@@ -133,6 +135,7 @@ const CodeExecutionToolUIImpl: ToolCallMessagePartComponent = ({
args,
result,
status,
+ toolCallId,
}) => {
const parsedArgs = (args as CodeExecutionArgs) ?? {};
const kind = parsedArgs.kind ?? "bash";
@@ -175,17 +178,17 @@ const CodeExecutionToolUIImpl: ToolCallMessagePartComponent = ({
(p as { text: string }).text.length > 0,
),
);
- const [open, setOpen] = useState(isRunning);
- useEffect(() => {
- if (isRunning) {
- setOpen(true);
- } else if (hasText) {
- setOpen(false);
- }
- }, [isRunning, hasText]);
+ // Ask permission gates every local tool call, and what is being approved
+ // lives inside the content while Allow/Deny render outside it.
+ const awaitingApproval = useToolAwaitingApproval(toolCallId);
+ const [open, setOpen] = useToolActivityOpen(isRunning, hasText);
return (
- <ToolFallbackRoot open={open} onOpenChange={setOpen}>
+ <ToolFallbackRoot
+ open={open}
+ onOpenChange={setOpen}
+ awaitingApproval={awaitingApproval}
+ >
<ToolFallbackTrigger
toolName={isRunning ? runningLabel : completedLabel}
status={status}
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsx
index 9bffe7587e3..7d6bcbc29a3 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsx
@@ -10,8 +10,9 @@ import {
import { FileTextIcon, LibraryBigIcon } from "lucide-react";
import { Spinner } from "@/components/ui/spinner";
+import { useToolAwaitingApproval } from "@/features/chat";
import { stringifyToolResult } from "@/lib/strip-ansi";
-import { memo, useEffect, useMemo, useState } from "react";
+import { memo, useMemo } from "react";
import { Badge } from "./badge";
import { toolArgText } from "./tool-arg-text";
import {
@@ -19,6 +20,7 @@ import {
ToolFallbackRoot,
ToolFallbackTrigger,
} from "./tool-fallback";
+import { useToolActivityOpen } from "./use-tool-activity-open";
import { useDocumentPreviewStore } from "@/features/rag/components/preview-store";
import { type Citation, parseCitations } from "./citation-utils";
@@ -76,6 +78,7 @@ const KnowledgeBaseToolUIImpl: ToolCallMessagePartComponent = ({
args,
result,
status,
+ toolCallId,
}) => {
const query = toolArgText((args as { query?: unknown })?.query);
const isRunning = status?.type === "running";
@@ -96,14 +99,17 @@ const KnowledgeBaseToolUIImpl: ToolCallMessagePartComponent = ({
(p as { text: string }).text.length > 0,
),
);
- const [open, setOpen] = useState(isRunning);
- useEffect(() => {
- if (isRunning) setOpen(true);
- else if (hasText) setOpen(false);
- }, [isRunning, hasText]);
+ // Ask permission gates every local tool call, and what is being approved
+ // lives inside the content while Allow/Deny render outside it.
+ const awaitingApproval = useToolAwaitingApproval(toolCallId);
+ const [open, setOpen] = useToolActivityOpen(isRunning, hasText);
return (
- <ToolFallbackRoot open={open} onOpenChange={setOpen}>
+ <ToolFallbackRoot
+ open={open}
+ onOpenChange={setOpen}
+ awaitingApproval={awaitingApproval}
+ >
<ToolFallbackTrigger
toolName={query ? `Searched documents for "${query}"` : "Knowledge search"}
status={status}
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
index 47de7ea56d3..74037951437 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
@@ -11,6 +11,7 @@ import { isSandboxFileList, type SandboxFile } from "./sandbox-files";
import {
preferSanitizedFullToolOutput,
useChatRuntimeStore,
+ useChatPreferencesStore,
useToolAwaitingApproval,
useToolOutputFor,
useToolPaneScope,
@@ -179,30 +180,40 @@ const PythonToolUIImpl: ToolCallMessagePartComponent = ({
// written even while the args status still reads as streaming.
const awaitingApproval = useToolAwaitingApproval(toolCallId);
const isWriting = isWritingCode && !awaitingApproval;
+ const collapseByDefault = useChatPreferencesStore(
+ (state) => state.collapseToolActivityByDefault,
+ );
+ const scriptCell = code ? (
+ <div className="mt-1 pl-5">
+ <ToolCodeCell
+ label="script"
+ code={code}
+ language="python"
+ downloadName="script.py"
+ streaming={isWriting}
+ />
+ </div>
+ ) : null;
return (
// Status, output and images collapse from history; the executed script
// renders outside ToolFallbackContent so it stays visible on reopen
- // (#7165). Terminal keeps its command inside the collapsible -- a one-line
- // command is not the artifact a user comes back for, a script is.
- <ToolFallbackRoot defaultOpen={isRunning}>
+ // (#7165) -- a script is an artifact, a one-line command is not.
+ // That holds only while collapseToolActivity is off; with it on the script
+ // moves inside the collapsible, behind one click. awaitingApproval is the
+ // exception: a decision about a script needs the script on screen.
+ <ToolFallbackRoot
+ defaultOpen={isRunning}
+ awaitingApproval={awaitingApproval}
+ >
<ToolFallbackTrigger
toolName={firstLine ? `Python: ${firstLine}` : "Python"}
status={status}
icon={CodeIcon}
/>
- {code && (
- <div className="mt-1 pl-5">
- <ToolCodeCell
- label="script"
- code={code}
- language="python"
- downloadName="script.py"
- streaming={isWriting}
- />
- </div>
- )}
+ {!collapseByDefault && scriptCell}
<ToolFallbackContent>
+ {collapseByDefault && scriptCell}
<div className="border-l-2 border-muted-foreground/20 pl-2">
{/* Output */}
{isRunning ? (
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
index 81de7ef06ea..e7744dce95e 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
@@ -75,7 +75,12 @@ const TerminalToolUIImpl: ToolCallMessagePartComponent = ({
return (
// Open mid-run so command and live output show, collapsed from history.
- <ToolFallbackRoot defaultOpen={isRunning}>
+ // awaitingApproval overrides the preference: the command lives inside the
+ // content, Allow/Deny outside it, and the trigger shows only 60 characters.
+ <ToolFallbackRoot
+ defaultOpen={isRunning}
+ awaitingApproval={awaitingApproval}
+ >
<ToolFallbackTrigger
toolName={command ? `$ ${command.slice(0, 60)}` : "Terminal"}
status={status}
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx
index 06b2b541dce..8ce45a92426 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx
@@ -9,9 +9,12 @@ import {
} from "@assistant-ui/react";
import { GlobeIcon } from "lucide-react";
-import { isSearchImagesToolResult } from "@/features/chat";
+import {
+ isSearchImagesToolResult,
+ useToolAwaitingApproval,
+} from "@/features/chat";
import { stringifyToolResult } from "@/lib/strip-ansi";
-import { memo, useEffect, useState } from "react";
+import { memo } from "react";
import { SearchImageThumb } from "./search-image";
import { Source, SourceIcon, SourceTitle } from "./sources";
import { toolArgText } from "./tool-arg-text";
@@ -20,6 +23,7 @@ import {
ToolFallbackRoot,
ToolFallbackTrigger,
} from "./tool-fallback";
+import { useToolActivityOpen } from "./use-tool-activity-open";
interface ParsedSource {
title: string;
@@ -87,6 +91,7 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({
args,
result,
status,
+ toolCallId,
}) => {
// Coerced, like image_queries below: a local model routinely emits a number or an
// object here, and .trim() on one crashes the card that was meant to show the call.
@@ -139,17 +144,17 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({
(p as { text: string }).text.length > 0,
),
);
- const [open, setOpen] = useState(isRunning);
- useEffect(() => {
- if (isRunning) {
- setOpen(true);
- } else if (hasText) {
- setOpen(false);
- }
- }, [isRunning, hasText]);
+ // Ask permission gates every local tool call, and what is being approved
+ // lives inside the content while Allow/Deny render outside it.
+ const awaitingApproval = useToolAwaitingApproval(toolCallId);
+ const [open, setOpen] = useToolActivityOpen(isRunning, hasText);
return (
- <ToolFallbackRoot open={open} onOpenChange={setOpen}>
+ <ToolFallbackRoot
+ open={open}
+ onOpenChange={setOpen}
+ awaitingApproval={awaitingApproval}
+ >
<ToolFallbackTrigger
toolName={
isUrlFetch
diff --git a/studio/frontend/src/components/assistant-ui/use-tool-activity-open.ts b/studio/frontend/src/components/assistant-ui/use-tool-activity-open.ts
new file mode 100644
index 00000000000..d8dc4aab8d1
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/use-tool-activity-open.ts
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// eslint-disable-next-line no-restricted-imports -- the feature barrel imports consumers of this hook
+import { useChatPreferencesStore } from "@/features/chat/stores/chat-preferences-store";
+import { useEffect, useRef, useState } from "react";
+import { resolveToolActivityOpen } from "./tool-activity-open-state";
+
+export function useToolActivityOpen(isRunning: boolean, hasText: boolean) {
+ const collapseByDefault = useChatPreferencesStore(
+ (state) => state.collapseToolActivityByDefault,
+ );
+ const [open, setOpen] = useState(isRunning && !collapseByDefault);
+ const previousCollapseByDefault = useRef(collapseByDefault);
+
+ useEffect(() => {
+ const previousPreference = previousCollapseByDefault.current;
+ previousCollapseByDefault.current = collapseByDefault;
+ setOpen((currentOpen) =>
+ resolveToolActivityOpen({
+ currentOpen,
+ collapseByDefault,
+ previousCollapseByDefault: previousPreference,
+ isRunning,
+ hasText,
+ }),
+ );
+ }, [isRunning, hasText, collapseByDefault]);
+
+ return [open, setOpen] as const;
+}
diff --git a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts b/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
index e3ecd127305..e1b44fbf10d 100644
--- a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
@@ -28,6 +28,8 @@ export interface ChatPreferencesState {
setShowResponseModel: (value: boolean) => void;
collapseThinkingByDefault: boolean;
setCollapseThinkingByDefault: (value: boolean) => void;
+ collapseToolActivityByDefault: boolean;
+ setCollapseToolActivityByDefault: (value: boolean) => void;
pastedTextMinChars: number;
setPastedTextMinChars: (value: number) => void;
}
@@ -59,6 +61,9 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()(
collapseThinkingByDefault: false,
setCollapseThinkingByDefault: (collapseThinkingByDefault) =>
set({ collapseThinkingByDefault }),
+ collapseToolActivityByDefault: true,
+ setCollapseToolActivityByDefault: (collapseToolActivityByDefault) =>
+ set({ collapseToolActivityByDefault }),
pastedTextMinChars: PASTED_TEXT_DEFAULT_MIN_CHARS,
setPastedTextMinChars: (pastedTextMinChars) =>
set({ pastedTextMinChars }),
@@ -74,6 +79,8 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()(
showModelDisclaimer: saved?.showModelDisclaimer ?? false,
showResponseModel: saved?.showResponseModel ?? false,
collapseThinkingByDefault: saved?.collapseThinkingByDefault ?? false,
+ collapseToolActivityByDefault:
+ saved?.collapseToolActivityByDefault ?? true,
pastedTextMinChars: normalisePastedTextMinChars(
saved?.pastedTextMinChars,
),
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 87e72778f6e..627450357bf 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -102,6 +102,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.chat.compactionStyle",
"settings.profile.greetingSloth",
"settings.chat.thinking.collapseByDefault",
+ "settings.chat.tools.collapseByDefault",
"settings.chat.artifacts.title",
"settings.chat.artifacts.collapseHtmlBlocks",
"settings.chat.artifacts.allowNetworkAccess",
diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
index 4147f3a2ab2..f1c89227240 100644
--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
@@ -231,6 +231,12 @@ export function ChatTab() {
const setCollapseThinkingByDefault = useChatPreferencesStore(
(state) => state.setCollapseThinkingByDefault,
);
+ const collapseToolActivityByDefault = useChatPreferencesStore(
+ (state) => state.collapseToolActivityByDefault,
+ );
+ const setCollapseToolActivityByDefault = useChatPreferencesStore(
+ (state) => state.setCollapseToolActivityByDefault,
+ );
const pastedTextMinChars = useChatPreferencesStore(
(state) => state.pastedTextMinChars,
);
@@ -337,6 +343,17 @@ export function ChatTab() {
onCheckedChange={setCollapseThinkingByDefault}
/>
</SettingsRow>
+ <SettingsRow
+ label={t("settings.chat.tools.collapseByDefault")}
+ description={t(
+ "settings.chat.tools.collapseByDefaultDescription",
+ )}
+ >
+ <Switch
+ checked={collapseToolActivityByDefault}
+ onCheckedChange={setCollapseToolActivityByDefault}
+ />
+ </SettingsRow>
<SettingsRow
label={t("settings.chat.modelDisclaimer")}
description={t("settings.chat.modelDisclaimerDescription")}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 15f053e77b8..46ac41d92c6 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1379,6 +1379,11 @@ export const ar = {
collapseByDefaultDescription:
"إبقاء التفكير مطويًا أثناء تفكير النموذج بدلًا من فتحه تلقائيًا. وسّع أي كتلة لقراءتها.",
},
+ tools: {
+ collapseByDefault: "طيّ نشاط الأدوات افتراضيًا",
+ collapseByDefaultDescription:
+ "إبقاء مدخلات الأدوات ومخرجاتها مطوية أثناء التشغيل. وسّع أي صف أداة لفحصه.",
+ },
webSearch: {
title: "البحث على الويب",
images: "عرض الصور من البحث على الويب",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 011aadcfb85..fab4aa6d984 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1419,6 +1419,11 @@ export const de = {
collapseByDefaultDescription:
"Das Denken bleibt eingeklappt, während das Modell denkt, statt automatisch aufzuklappen. Zum Lesen einen Block ausklappen.",
},
+ tools: {
+ collapseByDefault: "Tool-Aktivität standardmäßig einklappen",
+ collapseByDefaultDescription:
+ "Tool-Eingaben und -Ausgaben bleiben während der Ausführung eingeklappt. Zum Prüfen eine Tool-Zeile ausklappen.",
+ },
webSearch: {
title: "Websuche",
images: "Bilder aus der Websuche anzeigen",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index ed3fc576a45..ce971603d9b 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1372,6 +1372,11 @@ export const en = {
collapseByDefaultDescription:
"Keep reasoning collapsed while the model thinks instead of streaming it open. Expand any block to read it.",
},
+ tools: {
+ collapseByDefault: "Collapse tool activity by default",
+ collapseByDefaultDescription:
+ "Keep tool inputs and outputs collapsed while tools run. Expand any tool row to inspect it.",
+ },
webSearch: {
title: "Web search",
images: "Show images from web search",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 6a656f2624d..d1f1ac7573c 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1410,6 +1410,11 @@ export const es = {
collapseByDefaultDescription:
"Mantén el razonamiento contraído mientras el modelo piensa, en lugar de abrirlo automáticamente. Expande cualquier bloque para leerlo.",
},
+ tools: {
+ collapseByDefault: "Contraer la actividad de herramientas por defecto",
+ collapseByDefaultDescription:
+ "Mantén contraídas las entradas y salidas de las herramientas mientras se ejecutan. Expande cualquier fila para inspeccionarla.",
+ },
webSearch: {
title: "Búsqueda web",
images: "Mostrar imágenes de la búsqueda web",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 63ad4a163b3..297409bcc98 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1416,6 +1416,11 @@ export const fr = {
collapseByDefaultDescription:
"Garde la réflexion repliée pendant que le modèle réfléchit, au lieu de l’ouvrir automatiquement. Dépliez un bloc pour le lire.",
},
+ tools: {
+ collapseByDefault: "Replier l’activité des outils par défaut",
+ collapseByDefaultDescription:
+ "Garde les entrées et sorties des outils repliées pendant leur exécution. Dépliez une ligne d’outil pour l’examiner.",
+ },
webSearch: {
title: "Recherche web",
images: "Afficher les images de la recherche web",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index a41926edbbb..7173075b506 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1385,6 +1385,11 @@ export const hi = {
collapseByDefaultDescription:
"मॉडल के सोचते समय रीज़निंग अपने आप खुलने के बजाय संक्षिप्त रहती है। पढ़ने के लिए किसी भी ब्लॉक को विस्तृत करें।",
},
+ tools: {
+ collapseByDefault: "टूल गतिविधि को डिफ़ॉल्ट रूप से संक्षिप्त रखें",
+ collapseByDefaultDescription:
+ "टूल चलते समय उनके इनपुट और आउटपुट संक्षिप्त रखें। जाँचने के लिए किसी भी टूल पंक्ति को विस्तृत करें।",
+ },
webSearch: {
title: "वेब खोज",
images: "वेब खोज से छवियाँ दिखाएँ",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index d0e2714a03b..800f9808082 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1384,6 +1384,11 @@ export const it = {
collapseByDefaultDescription:
"Mantieni il ragionamento compresso mentre il modello pensa, invece di aprirlo automaticamente. Espandi un blocco per leggerlo.",
},
+ tools: {
+ collapseByDefault: "Comprimi l’attività degli strumenti per impostazione predefinita",
+ collapseByDefaultDescription:
+ "Mantieni compressi input e output degli strumenti durante l’esecuzione. Espandi una riga per esaminarla.",
+ },
webSearch: {
title: "Ricerca web",
images: "Mostra immagini dalla ricerca web",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index e88f7730bca..53b5bf9782a 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1366,6 +1366,11 @@ export const ja = {
collapseByDefaultDescription:
"モデルの思考中も自動で展開せず、折りたたんだままにします。読みたいときはブロックを展開してください。",
},
+ tools: {
+ collapseByDefault: "ツールの動作をデフォルトで折りたたむ",
+ collapseByDefaultDescription:
+ "ツールの実行中は入力と出力を折りたたんだままにします。確認するにはツール行を展開してください。",
+ },
webSearch: {
title: "ウェブ検索",
images: "ウェブ検索の画像を表示",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index b5fc523c7df..ad142fd895c 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1376,6 +1376,11 @@ export const ko = {
collapseByDefaultDescription:
"모델이 생각하는 동안 사고 과정을 자동으로 펼치지 않고 접어 둡니다. 읽으려면 블록을 펼치세요.",
},
+ tools: {
+ collapseByDefault: "기본적으로 도구 활동 접기",
+ collapseByDefaultDescription:
+ "도구가 실행되는 동안 입력과 출력을 접어 둡니다. 확인하려면 도구 행을 펼치세요.",
+ },
webSearch: {
title: "웹 검색",
images: "웹 검색 이미지 표시",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 10ec06f8d98..26205fb07d8 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1398,6 +1398,11 @@ export const ptBR = {
collapseByDefaultDescription:
"Mantém o raciocínio recolhido enquanto o modelo pensa, em vez de abri-lo automaticamente. Expanda um bloco para lê-lo.",
},
+ tools: {
+ collapseByDefault: "Recolher atividade de ferramentas por padrão",
+ collapseByDefaultDescription:
+ "Mantém entradas e saídas das ferramentas recolhidas durante a execução. Expanda uma linha para inspecioná-la.",
+ },
webSearch: {
title: "Busca na web",
images: "Mostrar imagens da busca na web",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index b16ff7c1dde..0181791573e 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1395,6 +1395,11 @@ export const ru = {
collapseByDefaultDescription:
"Размышления остаются свёрнутыми, пока модель думает, вместо автоматического раскрытия. Разверните блок, чтобы прочитать его.",
},
+ tools: {
+ collapseByDefault: "Сворачивать действия инструментов по умолчанию",
+ collapseByDefaultDescription:
+ "Входные и выходные данные инструментов остаются свёрнутыми во время работы. Разверните строку инструмента для просмотра.",
+ },
webSearch: {
title: "Веб-поиск",
images: "Показывать изображения из веб-поиска",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 8ee58bdc757..99ab5981bd0 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1350,6 +1350,11 @@ export const zhCN = {
collapseByDefaultDescription:
"模型思考时保持折叠,而不是自动展开。需要阅读时展开对应区块。",
},
+ tools: {
+ collapseByDefault: "默认折叠工具活动",
+ collapseByDefaultDescription:
+ "工具运行时保持输入和输出折叠。需要检查时展开对应工具行。",
+ },
webSearch: {
title: "网页搜索",
images: "显示网页搜索图片",
diff --git a/studio/frontend/tests/tool-activity-preference.test.ts b/studio/frontend/tests/tool-activity-preference.test.ts
new file mode 100644
index 00000000000..07ff4d4f11d
--- /dev/null
+++ b/studio/frontend/tests/tool-activity-preference.test.ts
@@ -0,0 +1,637 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The transition table for the collapse-tool-activity preference, the store's
+// compatibility promise, and the JSX wiring that carries both.
+//
+// The reducers and the store are plain .ts, so those claims run the code. The
+// cards are .tsx and this runner cannot execute JSX (no jsdom, no JSX loader),
+// so their claims go through the TypeScript AST, not a substring of the source:
+// a substring passes on broken code and fails on a reformat, which is backwards.
+// Rendered behaviour lives in tests/studio/playwright_tool_activity.py.
+
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+
+import ts from "typescript";
+
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { store } = installLocalStorageFake();
+
+const PREFERENCES_KEY = "unsloth_chat_preferences";
+
+// Preferences exactly as a Studio from before this setting existed wrote them:
+// every key the store had at the time, and no collapseToolActivityByDefault.
+// Staged before the import, because persist hydrates at store creation.
+const LEGACY_STATE = {
+ confirmDeleteChats: false,
+ alwaysDeleteChatFiles: true,
+ showModelDisclaimer: true,
+ showResponseModel: true,
+ collapseThinkingByDefault: true,
+ pastedTextMinChars: 8000,
+};
+
+store.set(
+ PREFERENCES_KEY,
+ JSON.stringify({ state: LEGACY_STATE, version: 0 }),
+);
+
+const { useChatPreferencesStore } = await import(
+ "../src/features/chat/stores/chat-preferences-store.ts"
+);
+const { resolveToolActivityOpen, syncToolActivityPreference } = await import(
+ "../src/components/assistant-ui/tool-activity-open-state.ts"
+);
+
+const read = (path: string) => readFile(new URL(path, import.meta.url), "utf8");
+
+/** Write `state` as a persisted record and hydrate the live store from it. */
+async function rehydrateFrom(state: unknown): Promise<void> {
+ store.set(PREFERENCES_KEY, JSON.stringify({ state, version: 0 }));
+ await useChatPreferencesStore.persist.rehydrate();
+}
+
+// ---------------------------------------------------------------------------
+// The store's compatibility promise, made against a real hydrate.
+// ---------------------------------------------------------------------------
+
+test("tool activity is collapsed by default", () => {
+ assert.equal(
+ useChatPreferencesStore.getInitialState().collapseToolActivityByDefault,
+ true,
+ );
+});
+
+test("a record written before the setting existed inherits the collapsed default", () => {
+ // This is not an opt-in: `?? true` in merge() means an install that never
+ // saw this setting starts collapsing tool activity the moment it upgrades.
+ // Asserted against a real hydrate of a real legacy record so that the day
+ // someone reconsiders that call, the test says so out loud instead of
+ // quietly agreeing.
+ assert.equal(
+ useChatPreferencesStore.getState().collapseToolActivityByDefault,
+ true,
+ );
+});
+
+test("hydrating the new key leaves the older preferences alone", () => {
+ // merge() is a hand-maintained allowlist, so adding a field to it is exactly
+ // when one of the others goes missing.
+ const state = useChatPreferencesStore.getState();
+ assert.equal(state.confirmDeleteChats, false);
+ assert.equal(state.alwaysDeleteChatFiles, true);
+ assert.equal(state.showModelDisclaimer, true);
+ assert.equal(state.showResponseModel, true);
+ assert.equal(state.collapseThinkingByDefault, true);
+ assert.equal(state.pastedTextMinChars, 8000);
+ // The setters have to survive too: a merge returning only the saved fields
+ // would leave a store with no way to write to it.
+ assert.equal(typeof state.setCollapseToolActivityByDefault, "function");
+});
+
+test("turning the preference off round-trips through storage", async () => {
+ // The direction that matters now that the default is on: a user who wants
+ // their tool output back has to be able to keep it across a reload.
+ await rehydrateFrom({
+ ...LEGACY_STATE,
+ collapseToolActivityByDefault: false,
+ });
+ assert.equal(
+ useChatPreferencesStore.getState().collapseToolActivityByDefault,
+ false,
+ "an explicit off is being overridden by the new default",
+ );
+ useChatPreferencesStore.getState().setCollapseToolActivityByDefault(true);
+ assert.equal(
+ JSON.parse(store.get(PREFERENCES_KEY) ?? "{}").state
+ .collapseToolActivityByDefault,
+ true,
+ "the preference is not persisted, so it would not survive a reload",
+ );
+ await rehydrateFrom(LEGACY_STATE);
+});
+
+test("an unreadable record leaves every default in place", async () => {
+ store.set(PREFERENCES_KEY, "{not json");
+ await assert.doesNotReject(async () => {
+ await useChatPreferencesStore.persist.rehydrate();
+ });
+ const state = useChatPreferencesStore.getState();
+ assert.equal(state.collapseToolActivityByDefault, true);
+ assert.equal(typeof state.setCollapseToolActivityByDefault, "function");
+ await rehydrateFrom(LEGACY_STATE);
+});
+
+// ---------------------------------------------------------------------------
+// The transition table.
+// ---------------------------------------------------------------------------
+
+test("manual expansion survives updates while activity is collapsed", () => {
+ assert.equal(
+ resolveToolActivityOpen({
+ currentOpen: true,
+ collapseByDefault: true,
+ previousCollapseByDefault: true,
+ isRunning: false,
+ hasText: true,
+ }),
+ true,
+ );
+});
+
+test("enabling collapsed activity closes an already open card", () => {
+ assert.equal(
+ resolveToolActivityOpen({
+ currentOpen: true,
+ collapseByDefault: true,
+ previousCollapseByDefault: false,
+ isRunning: true,
+ hasText: false,
+ }),
+ false,
+ );
+});
+
+test("disabling collapsed activity restores automatic visibility", () => {
+ assert.equal(
+ resolveToolActivityOpen({
+ currentOpen: false,
+ collapseByDefault: false,
+ previousCollapseByDefault: true,
+ isRunning: true,
+ hasText: false,
+ }),
+ true,
+ );
+ assert.equal(
+ resolveToolActivityOpen({
+ currentOpen: true,
+ collapseByDefault: false,
+ previousCollapseByDefault: false,
+ isRunning: false,
+ hasText: true,
+ }),
+ false,
+ );
+});
+
+test("turning the preference off hands the card back to the automatic rules", () => {
+ // Documented rather than accidental: a preference change is an explicit user
+ // action, so it resets to whatever the automatic policy says rather than
+ // preserving a manual expansion made under the old preference. The reverse
+ // direction is the one that preserves manual state (first test above).
+ assert.equal(
+ resolveToolActivityOpen({
+ currentOpen: true,
+ collapseByDefault: false,
+ previousCollapseByDefault: true,
+ isRunning: false,
+ hasText: true,
+ }),
+ false,
+ );
+});
+
+test("fallback cards react to live preference changes", () => {
+ const manuallyOpen = {
+ collapseByDefault: false,
+ open: true,
+ };
+ const collapsed = syncToolActivityPreference(manuallyOpen, true, true);
+ assert.deepEqual(collapsed, {
+ collapseByDefault: true,
+ open: false,
+ });
+ assert.deepEqual(syncToolActivityPreference(collapsed, false, true), {
+ collapseByDefault: false,
+ open: true,
+ });
+});
+
+test("fallback cards preserve manual state until the preference changes", () => {
+ const manuallyOpen = {
+ collapseByDefault: true,
+ open: true,
+ };
+ // Reference identity, not deep equality: the render-phase `if (synced !==
+ // state) setState(...)` in ToolFallbackRoot and ToolGroupRoot terminates only
+ // because an unchanged preference returns the very same object.
+ assert.equal(
+ syncToolActivityPreference(manuallyOpen, true, true),
+ manuallyOpen,
+ );
+});
+
+test("disabling collapsed activity respects a closed fallback default", () => {
+ assert.deepEqual(
+ syncToolActivityPreference(
+ { collapseByDefault: true, open: false },
+ false,
+ false,
+ ),
+ { collapseByDefault: false, open: false },
+ );
+});
+
+// ---------------------------------------------------------------------------
+// AST helpers for the .tsx claims.
+// ---------------------------------------------------------------------------
+
+const sourceOf = async (path: string): Promise<ts.SourceFile> =>
+ ts.createSourceFile(
+ path,
+ await read(path),
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+
+function walk(node: ts.Node, visit: (node: ts.Node) => void): void {
+ visit(node);
+ node.forEachChild((child) => walk(child, visit));
+}
+
+function find(root: ts.Node, match: (node: ts.Node) => boolean): ts.Node[] {
+ const hits: ts.Node[] = [];
+ walk(root, (node) => {
+ if (match(node)) hits.push(node);
+ });
+ return hits;
+}
+
+/** The initializer of `const <name> = ...`. */
+function initializerOf(root: ts.SourceFile, name: string): ts.Expression {
+ const declaration = find(
+ root,
+ (node) =>
+ ts.isVariableDeclaration(node) &&
+ ts.isIdentifier(node.name) &&
+ node.name.text === name,
+ )[0] as ts.VariableDeclaration | undefined;
+ assert.ok(declaration?.initializer, `${root.fileName} has no const ${name}`);
+ return declaration.initializer;
+}
+
+/** Every identifier read anywhere under `node`. */
+function identifiersIn(node: ts.Node): Set<string> {
+ const names = new Set<string>();
+ walk(node, (child) => {
+ if (ts.isIdentifier(child)) names.add(child.text);
+ });
+ return names;
+}
+
+/**
+ * The local name a file binds the preference to, resolved through the store
+ * selector rather than assumed. Hard-coding "collapseByDefault" would make
+ * these assertions fail on a rename that changes nothing.
+ */
+function preferenceBinding(root: ts.SourceFile): string {
+ const declaration = find(root, (node) => {
+ if (!ts.isVariableDeclaration(node) || !node.initializer) return false;
+ const init = node.initializer;
+ return (
+ ts.isCallExpression(init) &&
+ ts.isIdentifier(init.expression) &&
+ init.expression.text === "useChatPreferencesStore" &&
+ identifiersIn(init).has("collapseToolActivityByDefault")
+ );
+ })[0] as ts.VariableDeclaration | undefined;
+ assert.ok(
+ declaration && ts.isIdentifier(declaration.name),
+ `${root.fileName} never reads collapseToolActivityByDefault off the store`,
+ );
+ return declaration.name.text;
+}
+
+/** The JSX element named `name` nested anywhere under `node`. */
+function jsxElement(node: ts.Node, name: string): ts.JsxElement {
+ const hit = find(
+ node,
+ (child) =>
+ ts.isJsxElement(child) &&
+ ts.isIdentifier(child.openingElement.tagName) &&
+ child.openingElement.tagName.text === name,
+ )[0] as ts.JsxElement | undefined;
+ assert.ok(hit, `no <${name}> element found`);
+ return hit;
+}
+
+/** The JSX attribute `name` on the opening tag of `element`. */
+function jsxAttribute(
+ element: ts.JsxElement,
+ name: string,
+): ts.JsxAttribute | undefined {
+ return element.openingElement.attributes.properties.find(
+ (property): property is ts.JsxAttribute =>
+ ts.isJsxAttribute(property) && property.name.getText() === name,
+ );
+}
+
+// ---------------------------------------------------------------------------
+// The wiring.
+// ---------------------------------------------------------------------------
+
+test("the shared hook resolves through the preference and the shared policy", async () => {
+ const source = await sourceOf(
+ "../src/components/assistant-ui/use-tool-activity-open.ts",
+ );
+ const selector = find(
+ source,
+ (node) =>
+ ts.isCallExpression(node) &&
+ ts.isIdentifier(node.expression) &&
+ node.expression.text === "useChatPreferencesStore",
+ )[0];
+ assert.ok(selector, "the hook does not subscribe to the preference store");
+ assert.ok(
+ identifiersIn(selector).has("collapseToolActivityByDefault"),
+ "the hook subscribes to the store but not to this preference",
+ );
+ const resolve = find(
+ source,
+ (node) =>
+ ts.isCallExpression(node) &&
+ ts.isIdentifier(node.expression) &&
+ node.expression.text === "resolveToolActivityOpen",
+ )[0] as ts.CallExpression | undefined;
+ assert.ok(resolve, "the hook does not call the shared policy");
+ const passed = identifiersIn(resolve.arguments[0] ?? resolve);
+ for (const field of [
+ "currentOpen",
+ "collapseByDefault",
+ "previousCollapseByDefault",
+ "isRunning",
+ "hasText",
+ ]) {
+ assert.ok(passed.has(field), `the policy is called without ${field}`);
+ }
+});
+
+test("every tool card that opens itself routes through the shared hook", async () => {
+ for (const file of [
+ "../src/components/assistant-ui/tool-ui-code-execution.tsx",
+ "../src/components/assistant-ui/tool-ui-knowledge-base.tsx",
+ "../src/components/assistant-ui/tool-ui-web-search.tsx",
+ ]) {
+ const source = await sourceOf(file);
+ const call = find(
+ source,
+ (node) =>
+ ts.isCallExpression(node) &&
+ ts.isIdentifier(node.expression) &&
+ node.expression.text === "useToolActivityOpen",
+ )[0] as ts.CallExpression | undefined;
+ assert.ok(call, `${file} bypasses the shared automatic visibility policy`);
+ // Both signals live, not pinned: useToolActivityOpen(true, hasText) would
+ // still route through the hook while re-opening every card unconditionally.
+ assert.equal(
+ call.arguments.length,
+ 2,
+ `${file} calls the shared hook with the wrong number of signals`,
+ );
+ for (const argument of call.arguments) {
+ assert.ok(
+ ts.isIdentifier(argument) || ts.isPropertyAccessExpression(argument),
+ `${file} pins a shared-hook signal to ${argument.getText()}`,
+ );
+ }
+ }
+});
+
+test("an uncontrolled fallback card takes its open state from the preference", async () => {
+ // The claim a substring cannot make: pinning `isOpen` to true for an
+ // uncontrolled card leaves every mention of the preference in this file
+ // intact, so a source-text assertion would still pass while the setting did
+ // nothing at all.
+ const source = await sourceOf(
+ "../src/components/assistant-ui/tool-fallback.tsx",
+ );
+ const preference = preferenceBinding(source);
+ const synced = find(
+ source,
+ (node) =>
+ ts.isCallExpression(node) &&
+ ts.isIdentifier(node.expression) &&
+ node.expression.text === "syncToolActivityPreference",
+ )[0] as ts.CallExpression | undefined;
+ assert.ok(synced, "the fallback card no longer uses the shared policy");
+ assert.ok(
+ ts.isVariableDeclaration(synced.parent),
+ "the synced state is not bound to a name isOpen could read",
+ );
+ const syncedName = synced.parent.name.getText();
+ assert.ok(
+ identifiersIn(synced).has(preference),
+ "the fallback card syncs against something other than the preference",
+ );
+ assert.ok(
+ identifiersIn(synced).has("defaultOpen"),
+ "the fallback card drops its own default when the preference flips",
+ );
+
+ const isOpen = initializerOf(source, "isOpen");
+ assert.ok(
+ identifiersIn(isOpen).has(syncedName),
+ "an uncontrolled card opens without consulting the preference",
+ );
+ assert.ok(
+ identifiersIn(isOpen).has("controlledOpen") &&
+ identifiersIn(isOpen).has("isControlled"),
+ "isOpen is no longer a controlled/uncontrolled choice",
+ );
+});
+
+test("a card awaiting approval opens above the preference", async () => {
+ // A parked call renders its command or script inside ToolFallbackContent
+ // while Allow/Always allow/Deny render outside the card, so a collapsed card
+ // asks for a decision about something the user cannot read. Radix does not
+ // mount closed content, so it is absent rather than merely hidden.
+ const source = await sourceOf(
+ "../src/components/assistant-ui/tool-fallback.tsx",
+ );
+ const isOpen = initializerOf(source, "isOpen");
+ assert.ok(
+ ts.isBinaryExpression(isOpen) &&
+ isOpen.operatorToken.kind === ts.SyntaxKind.BarBarToken,
+ "isOpen no longer starts with an unconditional override",
+ );
+ assert.ok(
+ identifiersIn(isOpen.left).has("awaitingApproval"),
+ "awaiting approval is not the unguarded arm of isOpen",
+ );
+ assert.equal(
+ identifiersIn(isOpen.left).has(preferenceBinding(source)),
+ false,
+ "the collapse preference can suppress an approval prompt's context",
+ );
+
+ // Every card that (a) is wrapped in withToolConfirmation and (b) can be closed by
+ // the preference. Ask permission mode gates all of these, and each renders the
+ // thing being approved -- command, script, query, code -- inside the collapsible.
+ for (const file of [
+ "../src/components/assistant-ui/tool-ui-terminal.tsx",
+ "../src/components/assistant-ui/tool-ui-python.tsx",
+ "../src/components/assistant-ui/tool-ui-web-search.tsx",
+ "../src/components/assistant-ui/tool-ui-knowledge-base.tsx",
+ "../src/components/assistant-ui/tool-ui-code-execution.tsx",
+ ]) {
+ const card = await sourceOf(file);
+ const attribute = jsxAttribute(
+ jsxElement(card, "ToolFallbackRoot"),
+ "awaitingApproval",
+ );
+ assert.ok(
+ attribute,
+ `${file} can hide the command or script it is asking approval for`,
+ );
+ assert.ok(
+ attribute.initializer &&
+ ts.isJsxExpression(attribute.initializer) &&
+ attribute.initializer.expression &&
+ identifiersIn(attribute.initializer.expression).has(
+ "awaitingApproval",
+ ),
+ `${file} pins awaitingApproval instead of passing the live value`,
+ );
+ }
+});
+
+test("a pending approval forces a group open regardless of the preference", async () => {
+ const source = await sourceOf(
+ "../src/components/assistant-ui/tool-group.tsx",
+ );
+ const preference = preferenceBinding(source);
+ const forceOpen = initializerOf(source, "forceOpen");
+ assert.ok(
+ ts.isBinaryExpression(forceOpen) &&
+ forceOpen.operatorToken.kind === ts.SyntaxKind.BarBarToken,
+ "forceOpen is no longer a disjunction",
+ );
+ assert.ok(
+ identifiersIn(forceOpen.left).has("hasPendingConfirmation"),
+ "the approval signal is not the unguarded arm of forceOpen",
+ );
+ assert.equal(
+ identifiersIn(forceOpen.left).has(preference),
+ false,
+ "a collapsed group can now hide a blocking approval prompt",
+ );
+ assert.ok(
+ identifiersIn(forceOpen.right).has(preference),
+ "the non-approval arm ignores the preference and forces groups open",
+ );
+ // And the element still consumes it, opting out of control when it is false:
+ // a group pinned to `false` would be unopenable rather than merely closed.
+ const open = jsxAttribute(jsxElement(source, "ToolGroupRoot"), "open");
+ assert.ok(open?.initializer, "forceOpen is computed but not applied");
+ const expression = ts.isJsxExpression(open.initializer)
+ ? open.initializer.expression
+ : undefined;
+ assert.ok(
+ expression && ts.isConditionalExpression(expression),
+ "the group's open prop is no longer a controlled/uncontrolled choice",
+ );
+ assert.equal(expression.condition.getText(), "forceOpen");
+ assert.equal(expression.whenTrue.getText(), "true");
+ assert.equal(
+ expression.whenFalse.getText(),
+ "undefined",
+ "a group that is not force-opened must fall back to its own state",
+ );
+});
+
+test("a mounted group follows the preference like a mounted card", async () => {
+ // ToolGroupImpl passes `undefined` whenever it is not forcing the group open,
+ // so the group's own uncontrolled state is what is on screen for most of its
+ // life. Without this it is the one disclosure the preference cannot reach.
+ const source = await sourceOf(
+ "../src/components/assistant-ui/tool-group.tsx",
+ );
+ const preference = preferenceBinding(source);
+ const synced = find(
+ source,
+ (node) =>
+ ts.isCallExpression(node) &&
+ ts.isIdentifier(node.expression) &&
+ node.expression.text === "syncToolActivityPreference",
+ )[0] as ts.CallExpression | undefined;
+ assert.ok(synced, "ToolGroupRoot does not apply live preference changes");
+ assert.ok(
+ identifiersIn(synced).has(preference),
+ "the group syncs against something other than the preference",
+ );
+ assert.ok(
+ ts.isVariableDeclaration(synced.parent),
+ "the group's synced state is not bound to a name isOpen could read",
+ );
+ assert.ok(
+ identifiersIn(initializerOf(source, "isOpen")).has(
+ synced.parent.name.getText(),
+ ),
+ "the group computes a synced state and then ignores it",
+ );
+});
+
+test("the Python script cell moves inside the collapsible when collapsing is on", async () => {
+ // Two renders of one cell, each guarded by the opposite value: outside the
+ // collapsible so a reopened chat still shows the script (#7165), inside it
+ // when the user asked for quiet. Two copies of the same guard would render
+ // the script twice.
+ const source = await sourceOf(
+ "../src/components/assistant-ui/tool-ui-python.tsx",
+ );
+ const preference = preferenceBinding(source);
+ const root = jsxElement(source, "ToolFallbackRoot");
+ const content = jsxElement(root, "ToolFallbackContent");
+
+ /** Every `{<guard> && scriptCell}` under `scope`, as (negated, node) pairs. */
+ const guardsFor = (scope: ts.Node) =>
+ find(
+ scope,
+ (node) =>
+ ts.isJsxExpression(node) &&
+ !!node.expression &&
+ ts.isBinaryExpression(node.expression) &&
+ node.expression.operatorToken.kind ===
+ ts.SyntaxKind.AmpersandAmpersandToken &&
+ node.expression.right.getText() === "scriptCell",
+ ).map((node) => {
+ const guard = (
+ (node as ts.JsxExpression).expression as ts.BinaryExpression
+ ).left;
+ assert.ok(
+ identifiersIn(guard).has(preference),
+ "the script cell is rendered without consulting the preference",
+ );
+ return {
+ negated:
+ ts.isPrefixUnaryExpression(guard) &&
+ guard.operator === ts.SyntaxKind.ExclamationToken,
+ node,
+ };
+ });
+
+ const inside = guardsFor(content);
+ const outside = guardsFor(root).filter(
+ (hit) => !inside.some((other) => other.node === hit.node),
+ );
+
+ assert.deepEqual(
+ inside.map((hit) => hit.negated),
+ [false],
+ "a collapsed Python card does not carry the script inside the collapsible",
+ );
+ assert.deepEqual(
+ outside.map((hit) => hit.negated),
+ [true],
+ "the always-visible script cell is no longer guarded by the preference",
+ );
+});
diff --git a/tests/studio/playwright_tool_activity.py b/tests/studio/playwright_tool_activity.py
new file mode 100644
index 00000000000..d5da60d2f95
--- /dev/null
+++ b/tests/studio/playwright_tool_activity.py
@@ -0,0 +1,474 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""What the collapse-tool-activity preference does to a rendered tool card.
+
+The node suite reaches the reducers and the store and asserts the JSX wiring
+against the TypeScript AST. None of that sees a Radix Collapsible: whether
+closed content is in the DOM, what aria-expanded says, or where the page lands
+after a collapse. Those are the questions here, against
+studio/frontend/smoke-tool-activity.html.
+
+ 1 baseline preference off: every card open, as before the setting
+ 2 fresh mount preference on: cards and group closed, answer moves up
+ 3 manual expand survives live status and text updates
+ 4 live toggle a mounted open card AND group both adopt the preference
+ 5 persistence survives a reload and still collapses
+ 6 scroll a preference-driven close moves the page exactly as far
+ as a clicked one. Both arms are driven with the card in
+ view: click() scrolls its target into view first, so an
+ off-screen card hands one arm a free scroll and the two
+ then differ by how they were driven, not what they ran.
+ 7 approval a parked call still shows what it is asking to run, and
+ collapses once approval is granted
+ 8 strict mode the render-phase setState survives a double render
+ 9 rtl same collapse behaviour under dir=rtl
+ 10 reduced motion prefers-reduced-motion leaves no card stuck open
+ 11 toggle storm rapid flips converge, no render loop
+ 12 storage denied a throwing localStorage fails safe, to the DECLARED
+ default rather than a hard-coded one
+ 13 malformed a hand-edited blob must not flip the setting
+
+Engine follows the PW_ENGINE convention in playwright_settings_tabs.py.
+chromium stands in for Chrome, `msedge` is the branded chromium channel, webkit
+for Safari; none is the branded browser. Starts and stops its own vite server;
+SMOKE_BASE_URL to reuse one, SMOKE_PORT to move it.
+
+ PW_ENGINE=firefox python tests/studio/playwright_tool_activity.py --json
+
+Exits non-zero if any scene misses its expectation.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import statistics
+import sys
+from pathlib import Path
+
+from playwright.sync_api import sync_playwright
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _playwright_robust import ( # noqa: E402
+ start_vite,
+ stop_process,
+ wait_for_smoke_page,
+)
+
+PAGE = "smoke-tool-activity.html"
+ENTRY = "/smoke-tool-activity-main.tsx"
+ENGINE = os.environ.get("PW_ENGINE", "chromium")
+PORT = int(os.environ.get("SMOKE_PORT", "5219"))
+PREFERENCES_KEY = "unsloth_chat_preferences"
+
+# Radix animates for ANIMATION_DURATION = 200ms and the scroll lock holds for the
+# same window, so every reading is taken well clear of both.
+SETTLE_MS = 600
+
+# The tail of the command the approval card renders. Deliberately past the
+# 60-character slice the trigger shows, so "the user can read it" cannot be
+# satisfied by the trigger label alone.
+APPROVAL_TAIL = "--and-then-something-nobody-can-see"
+
+CARDS = ("controlled", "uncontrolled", "approval")
+
+
+def probe(page) -> dict:
+ """Open-state of every disclosure, straight off the DOM.
+
+ `payload_in_dom` is separate from the wrapper on purpose: Radix keeps the
+ content wrapper mounted while it animates, so a wrapper that exists says
+ nothing about whether the text inside it does.
+ """
+ return page.evaluate(
+ """(cards) => {
+ const read = (name) => {
+ const trigger = document.querySelector(`[data-probe="${name}-trigger"]`);
+ const content = document.querySelector(`[data-probe="${name}-content"]`);
+ return {
+ aria_expanded: trigger ? trigger.getAttribute("aria-expanded") : null,
+ data_state: content ? content.getAttribute("data-state") : null,
+ height: content ? Math.round(content.getBoundingClientRect().height) : null,
+ payload_in_dom: !!(content && content.querySelector("[data-probe]")),
+ text_len: content ? content.innerText.length : 0,
+ };
+ };
+ const out = {};
+ for (const name of cards) out[name] = read(name);
+ out.group = read("group");
+ const answer = document.querySelector('[data-probe="answer"]');
+ const viewport = document.querySelector('[data-probe="viewport"]');
+ out.answer_top = answer ? Math.round(answer.getBoundingClientRect().top) : null;
+ out.scroll_top = viewport ? Math.round(viewport.scrollTop) : null;
+ out.approval_command_visible = (() => {
+ const el = document.querySelector('[data-probe="approval-command"]');
+ if (!el) return false;
+ const rect = el.getBoundingClientRect();
+ return rect.height > 0 && el.innerText.trim().length > 0;
+ })();
+ out.approval_command_text = (() => {
+ const el = document.querySelector('[data-probe="approval-command"]');
+ return el ? el.innerText : "";
+ })();
+ return out;
+ }""",
+ list(CARDS),
+ )
+
+
+def settle(page, ms: int = SETTLE_MS) -> None:
+ page.wait_for_timeout(ms)
+
+
+def open_page(
+ page,
+ base_url: str,
+ *,
+ fillers: int = 60,
+ query: str = "",
+) -> None:
+ errors: list[str] = []
+ page.on("pageerror", lambda e: errors.append(str(e)))
+ page.goto(f"{base_url}/{PAGE}?fillers={fillers}{query}")
+ try:
+ page.wait_for_function("() => window.__probeReady", timeout = 30_000)
+ except Exception:
+ # A page that never mounts looks exactly like a slow one. Say which.
+ raise RuntimeError(
+ f"the harness page never published __probeReady ({ENGINE}). Page errors:\n"
+ + ("\n".join(errors) or "(none captured)")
+ ) from None
+ settle(page)
+
+
+def set_pref(page, value: bool) -> None:
+ page.evaluate("(v) => window.__setPreference(v)", value)
+ settle(page)
+
+
+def fresh(page, base_url: str, preference: bool, **kwargs) -> None:
+ """A page whose cards mounted with `preference` already in force."""
+ open_page(page, base_url, **kwargs)
+ page.evaluate("(v) => window.__setPreference(v)", preference)
+ page.evaluate("() => window.__remount()")
+ settle(page)
+
+
+def run(base_url: str, pw) -> dict:
+ results: dict = {"engine": ENGINE, "scenes": {}, "problems": []}
+ p = results["problems"]
+ s = results["scenes"]
+
+ # `msedge` is a chromium CHANNEL, not an engine: the branded build, which
+ # trails Chromium by weeks, so a Chromium-first regression hides there.
+ if ENGINE == "msedge":
+ browser = pw.chromium.launch(channel = "msedge")
+ else:
+ browser = getattr(pw, ENGINE).launch()
+ context = browser.new_context(viewport = {"width": 1200, "height": 900})
+ page = context.new_page()
+ console: list[str] = []
+ page.on("console", lambda m: console.append(f"{m.type}: {m.text}"))
+
+ # --- 1 baseline -------------------------------------------------------
+ fresh(page, base_url, False)
+ s["1_baseline"] = probe(page)
+ for card in CARDS:
+ if s["1_baseline"][card]["aria_expanded"] != "true":
+ p.append(f"1: {card} is not open with the preference OFF (baseline broken)")
+
+ # --- 2 fresh mount ----------------------------------------------------
+ fresh(page, base_url, True)
+ s["2_fresh_mount"] = probe(page)
+ for card in ("controlled", "uncontrolled"):
+ if s["2_fresh_mount"][card]["aria_expanded"] == "true":
+ p.append(f"2: {card} is still open with the preference ON")
+ if s["2_fresh_mount"]["group"]["aria_expanded"] == "true":
+ p.append("2: the group is open on a fresh mount with the preference ON")
+ if s["2_fresh_mount"]["answer_top"] >= s["1_baseline"]["answer_top"]:
+ p.append("2: the answer did not move up when activity collapsed")
+
+ # --- 3 manual expansion ----------------------------------------------
+ page.click('[data-probe="controlled-trigger"]')
+ page.click('[data-probe="uncontrolled-trigger"]')
+ settle(page)
+ after_expand = probe(page)
+ page.evaluate("() => window.__setHasText(true)")
+ settle(page, 300)
+ page.evaluate("() => window.__setRunning(false)")
+ settle(page)
+ after_updates = probe(page)
+ s["3_manual_expansion"] = {"after_expand": after_expand, "after_updates": after_updates}
+ for card in ("controlled", "uncontrolled"):
+ if after_expand[card]["aria_expanded"] != "true":
+ p.append(f"3: {card} did not open on click")
+ elif after_updates[card]["aria_expanded"] != "true":
+ p.append(f"3: {card} LOST its manual expansion across live updates")
+
+ # --- 4 live toggle, cards and group ----------------------------------
+ fresh(page, base_url, False)
+ page.click('[data-probe="group-trigger"]')
+ settle(page)
+ before = probe(page)
+ set_pref(page, True)
+ after = probe(page)
+ s["4_live_toggle"] = {"before": before, "after": after}
+ for name in ("controlled", "uncontrolled", "group"):
+ if before[name]["aria_expanded"] != "true":
+ p.append(f"4: {name} was not open before the toggle")
+ elif after[name]["aria_expanded"] == "true":
+ p.append(f"4: {name} ignored the preference turning on while mounted")
+
+ # --- 5 persistence ----------------------------------------------------
+ stored = page.evaluate("(k) => window.localStorage.getItem(k)", PREFERENCES_KEY)
+ open_page(page, base_url)
+ scene = probe(page)
+ scene["preference_after_reload"] = page.evaluate("() => window.__getPreference()")
+ scene["stored_blob"] = stored
+ s["5_persistence"] = scene
+ if scene["preference_after_reload"] is not True:
+ p.append("5: the preference did not survive a reload")
+ for card in ("controlled", "uncontrolled"):
+ if scene[card]["aria_expanded"] == "true":
+ p.append(f"5: {card} is open after a reload with the preference stored")
+
+ # --- 6 scroll ---------------------------------------------------------
+ def close_one_card(via: str) -> tuple[int, int]:
+ """Close ONE card, two ways, from an identical start.
+
+ `only=uncontrolled` so both arms collapse the same content, and the CARD is
+ scrolled into view rather than the answer: click() scrolls its target into
+ view first, so centring the answer hands the chevron arm a scroll the
+ preference arm never gets. Driven that way they appear to differ by ~665px.
+ """
+ fresh(page, base_url, False, query = "&only=uncontrolled")
+ page.evaluate(
+ """() => document.querySelector('[data-probe="uncontrolled-trigger"]')
+ .scrollIntoView({block: "start"})"""
+ )
+ settle(page)
+ before = probe(page)
+ if via == "preference":
+ page.evaluate("() => window.__setPreference(true)")
+ else:
+ page.click('[data-probe="uncontrolled-trigger"]')
+ settle(page)
+ after = probe(page)
+ return (
+ after["answer_top"] - before["answer_top"],
+ after["scroll_top"] - before["scroll_top"],
+ )
+
+ chevron = [close_one_card("chevron") for _ in range(3)]
+ preference = [close_one_card("preference") for _ in range(3)]
+ chevron_answer = statistics.median(m[0] for m in chevron)
+ preference_answer = statistics.median(m[0] for m in preference)
+ s["6_scroll"] = {
+ "chevron": chevron,
+ "preference": preference,
+ "chevron_answer_median": chevron_answer,
+ "preference_answer_median": preference_answer,
+ }
+ # A few pixels of slack for sub-pixel rounding; the two paths measure identical.
+ if abs(preference_answer - chevron_answer) > 8:
+ p.append(
+ "6: a preference-driven close moves the page differently from a clicked close "
+ f"({preference_answer}px vs {chevron_answer}px)"
+ )
+ for label, runs in (("chevron", chevron), ("preference", preference)):
+ if any(m[1] != 0 for m in runs):
+ p.append(f"6: a {label} close moved the scroll position: {[m[1] for m in runs]}")
+
+ # --- 7 approval -------------------------------------------------------
+ fresh(page, base_url, True)
+ page.evaluate("() => window.__setAwaitingApproval(true)")
+ settle(page)
+ parked = probe(page)
+ page.evaluate("() => window.__setAwaitingApproval(false)")
+ settle(page)
+ granted = probe(page)
+ s["7_approval"] = {"parked": parked, "granted": granted}
+ for card in ("approval", "controlled"):
+ if parked[card]["aria_expanded"] != "true":
+ p.append(f"7: the {card} card awaiting approval is collapsed by the preference")
+ if not parked["approval_command_visible"]:
+ p.append("7: the command being approved is not rendered")
+ if APPROVAL_TAIL not in parked["approval_command_text"]:
+ p.append(
+ "7: only the truncated command is on screen -- 'Always allow' would be "
+ "granted for text the user never saw"
+ )
+ for card in ("approval", "controlled"):
+ if granted[card]["aria_expanded"] == "true":
+ p.append(f"7: the {card} card stayed pinned open after approval was granted")
+
+ # --- 8 strict mode ----------------------------------------------------
+ fresh(page, base_url, True, query = "&strict=1")
+ scene = probe(page)
+ s["8_strict_mode"] = scene
+ for card in ("controlled", "uncontrolled"):
+ if scene[card]["aria_expanded"] == "true":
+ p.append(f"8: {card} is open under StrictMode with the preference ON")
+ loop_errors = [c for c in console if "Maximum update depth" in c or "Too many re-renders" in c]
+ if loop_errors:
+ p.append(f"8: React reported a render loop: {loop_errors[0]}")
+
+ # --- 9 rtl ------------------------------------------------------------
+ fresh(page, base_url, True, query = "&rtl=1")
+ scene = probe(page)
+ s["9_rtl"] = scene
+ for card in ("controlled", "uncontrolled"):
+ if scene[card]["aria_expanded"] == "true":
+ p.append(f"9: {card} is open under dir=rtl with the preference ON")
+
+ # --- 10 reduced motion ------------------------------------------------
+ reduced = browser.new_context(viewport = {"width": 1200, "height": 900}, reduced_motion = "reduce")
+ reduced_page = reduced.new_page()
+ fresh(reduced_page, base_url, True)
+ scene = probe(reduced_page)
+ s["10_reduced_motion"] = scene
+ for card in ("controlled", "uncontrolled"):
+ if scene[card]["aria_expanded"] == "true":
+ p.append(f"10: {card} is open under prefers-reduced-motion")
+ reduced.close()
+
+ # --- 11 toggle storm --------------------------------------------------
+ fresh(page, base_url, False)
+ page.evaluate(
+ """() => {
+ for (let i = 0; i < 40; i++) window.__setPreference(i % 2 === 1);
+ }"""
+ )
+ settle(page)
+ scene = probe(page)
+ s["11_toggle_storm"] = scene
+ if scene["controlled"]["aria_expanded"] != "false":
+ p.append("11: the controlled card did not converge after 40 preference flips")
+ if scene["uncontrolled"]["aria_expanded"] != "false":
+ p.append("11: the uncontrolled card did not converge after 40 preference flips")
+
+ # --- 12 storage denied -------------------------------------------------
+ # Safari private browsing and a cookies-blocked profile both surface as
+ # localStorage throwing rather than as an absent API.
+ denied = browser.new_context(viewport = {"width": 1200, "height": 900})
+ denied.add_init_script(
+ """() => {
+ const boom = () => { throw new DOMException("denied", "SecurityError"); };
+ Object.defineProperty(window, "localStorage", {
+ configurable: true,
+ get: () => ({ getItem: boom, setItem: boom, removeItem: boom, clear: boom,
+ key: boom, length: 0 }),
+ });
+ }"""
+ )
+ denied_page = denied.new_page()
+ denied_errors: list[str] = []
+ denied_page.on("pageerror", lambda e: denied_errors.append(str(e)))
+ try:
+ open_page(denied_page, base_url)
+ scene = probe(denied_page)
+ scene["preference"] = denied_page.evaluate("() => window.__getPreference()")
+ scene["declared_default"] = denied_page.evaluate("() => window.__getDefaultPreference()")
+ scene["page_errors"] = denied_errors
+ s["12_storage_denied"] = scene
+ # Against the DECLARED default, not a hard-coded one: which default
+ # ships is a product decision, this scene is about failing safe.
+ if scene["preference"] is not scene["declared_default"]:
+ p.append(
+ "12: a denied localStorage did not land on the declared default "
+ f"({scene['preference']} vs {scene['declared_default']})"
+ )
+ if denied_errors:
+ p.append(f"12: the page threw with localStorage denied: {denied_errors[0]}")
+ expected = "false" if scene["declared_default"] else "true"
+ for card in CARDS:
+ if scene[card]["aria_expanded"] != expected:
+ p.append(f"12: {card} does not match the declared default with storage denied")
+ except RuntimeError as exc:
+ s["12_storage_denied"] = {"failed": str(exc)}
+ p.append(f"12: the page does not survive a denied localStorage: {exc}")
+ denied.close()
+
+ # --- 13 malformed record -----------------------------------------------
+ malformed: dict = {}
+ for label, raw in [
+ ('string "false"', '"false"'),
+ ('string "true"', '"true"'),
+ ("number 1", "1"),
+ ("number 0", "0"),
+ ("empty string", '""'),
+ ("object", "{}"),
+ ("array", "[]"),
+ ("null", "null"),
+ ("corrupt json", None),
+ ]:
+ seeded = browser.new_context(viewport = {"width": 1200, "height": 900})
+ blob = (
+ "{not json"
+ if raw is None
+ else '{"state":{"collapseToolActivityByDefault":' + raw + '},"version":0}'
+ )
+ # add_init_script takes no arguments, so values are baked in; json.dumps
+ # also makes the corrupt-JSON case survive being a string literal.
+ seeded.add_init_script(
+ f"window.localStorage.setItem({json.dumps(PREFERENCES_KEY)}, {json.dumps(blob)});"
+ )
+ seeded_page = seeded.new_page()
+ try:
+ open_page(seeded_page, base_url)
+ malformed[label] = seeded_page.evaluate("() => window.__getPreference()")
+ except RuntimeError as exc:
+ malformed[label] = f"page failed: {exc}"
+ p.append(f"13: {label} takes the page down")
+ seeded.close()
+ s["13_malformed_record"] = malformed
+ # Reported, not asserted: `??` accepts any non-nullish JSON value, which is
+ # true of every boolean in this store and unreachable from Studio's own UI.
+
+ results["console"] = console
+ browser.close()
+ return results
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--json", action = "store_true")
+ options = ap.parse_args()
+
+ base_url = os.environ.get("SMOKE_BASE_URL") or ""
+ server = None
+ if not base_url:
+ server = start_vite(PORT)
+ base_url = f"http://127.0.0.1:{PORT}"
+ wait_for_smoke_page(
+ f"{base_url}/{PAGE}",
+ ENTRY,
+ proc = server,
+ info = lambda m: print(m, file = sys.stderr),
+ )
+ try:
+ with sync_playwright() as pw:
+ results = run(base_url, pw)
+ finally:
+ if server is not None:
+ stop_process(server)
+
+ if options.json:
+ print(json.dumps(results, indent = 2))
+ else:
+ print(json.dumps(results["scenes"], indent = 2))
+
+ print(file = sys.stderr)
+ if results["problems"]:
+ print(f"PROBLEMS ({ENGINE}):", file = sys.stderr)
+ for problem in results["problems"]:
+ print(f" - {problem}", file = sys.stderr)
+ return 1
+ print(f"{ENGINE}: every scene matched its expectation", file = sys.stderr)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())