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: tell users when a canvas is blocked by the network access setting (#9894)

Nilayda25d06ba531
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.yml
index f7f207bbb7b..1200da617a7 100644
--- a/.github/workflows/studio-frontend-ci.yml
+++ b/.github/workflows/studio-frontend-ci.yml
@@ -25,6 +25,7 @@ on:
- 'tests/studio/probe_dismiss_guard.py'
- 'tests/studio/playwright_settings_tabs.py'
- 'tests/studio/playwright_keyboard_shortcuts.py'
+ - 'tests/studio/playwright_tool_activity.py'
- 'tests/studio/playwright_stream_pacing.py'
- 'tests/studio/playwright_code_block_flicker.py'
- 'tests/studio/_code_block_flicker_analysis.py'
@@ -434,6 +435,12 @@ jobs:
working-directory: ${{ github.workspace }}
run: python3 tests/studio/playwright_keyboard_shortcuts.py
+ - name: Browser smoke for tool activity collapse
+ working-directory: ${{ github.workspace }}
+ env:
+ PW_ENGINE: chromium
+ run: python3 tests/studio/playwright_tool_activity.py --json
+
# A panel that cannot be fetched is new with lazy loading, and nothing above the
# root-mounted dialog catches, so unguarded it unmounts Unsloth, not one panel.
- name: Browser smoke for a settings panel that cannot load
diff --git a/studio/backend/tests/test_gpu_init_crash_message.py b/studio/backend/tests/test_gpu_init_crash_message.py
index 63e5b62770c..f734136ef8e 100644
--- a/studio/backend/tests/test_gpu_init_crash_message.py
+++ b/studio/backend/tests/test_gpu_init_crash_message.py
@@ -206,7 +206,7 @@ def _run_cpu_fallback_load(
)
if not available:
return None
- return ["/staged/llama-server", "--device", "none"], None
+ return ["/staged/llama-server", "--device", "none"], None, None
backend._wait_for_health = _wait_for_health
backend._prepare_cpu_fallback_launch = _prepare_cpu_fallback
@@ -614,7 +614,7 @@ class TestCpuIsolatedReplay:
prepared = backend._prepare_cpu_fallback_launch("/original/server", ["original"], env, {})
- assert prepared == (["/staged/server", "--device", "none"], None)
+ assert prepared == (["/staged/server", "--device", "none"], None, None)
assert env[loader_path] == "/staged/libs"
assert env["KEEP"] == "1"
diff --git a/studio/backend/tests/test_memory_contract.py b/studio/backend/tests/test_memory_contract.py
index 3f24e73625c..38dafd30996 100644
--- a/studio/backend/tests/test_memory_contract.py
+++ b/studio/backend/tests/test_memory_contract.py
@@ -175,7 +175,9 @@ class TestTheRouteOverrides:
"""
from pathlib import Path
- source = (Path(__file__).resolve().parent.parent / "routes" / "models.py").read_text()
+ source = (Path(__file__).resolve().parent.parent / "routes" / "models.py").read_text(
+ encoding = "utf-8"
+ )
for field in ("gpu_bytes", "compute_bytes", "total_bytes", "n_ctx"):
assert f"_estimate.{field} =" not in source, (
f"routes/models.py assigns {field} onto a built MemoryEstimate. "
diff --git a/studio/frontend/smoke-tool-activity-main.tsx b/studio/frontend/smoke-tool-activity-main.tsx
index 81d9ea2e3ba..47a49edbfc0 100644
--- a/studio/frontend/smoke-tool-activity-main.tsx
+++ b/studio/frontend/smoke-tool-activity-main.tsx
@@ -19,15 +19,6 @@
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,
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 834e31cf963..03023d2c216 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -447,14 +447,17 @@ function RootLayout() {
// Gated like the workspace chords below: /login has no shell, and /chat
// bounces straight back off requireAuth.
- useShortcut("newChat", () => startNewChat(), { enabled: !isAuthFlowRoute });
+ const routeShortcutEnabled = !isAuthFlowRoute && !settingsDialogOpen;
+ useShortcut("newChat", () => startNewChat(), {
+ enabled: routeShortcutEnabled,
+ });
useShortcut(
"newTemporaryChat",
() => startNewChat({ incognito: true, standalone: true }),
- { enabled: !isAuthFlowRoute },
+ { enabled: routeShortcutEnabled },
);
useShortcut("newStandaloneChat", () => startNewChat({ standalone: true }), {
- enabled: !isAuthFlowRoute,
+ enabled: routeShortcutEnabled,
});
// Workspaces. The shell is mounted on every route, so the chords live here.
@@ -464,32 +467,40 @@ function RootLayout() {
useShortcut(
"switchToChat",
() => void navigate({ to: "/chat", search: chatSearch }),
- { enabled: !isAuthFlowRoute },
+ { enabled: routeShortcutEnabled },
);
useShortcut("switchToProjects", goTo("/projects"), {
- enabled: !isAuthFlowRoute,
+ enabled: routeShortcutEnabled,
+ });
+ useShortcut("switchToHub", goTo("/hub"), {
+ enabled: routeShortcutEnabled,
});
- useShortcut("switchToHub", goTo("/hub"), { enabled: !isAuthFlowRoute });
// Train is the one workspace the chat-only guard turns away, so its chord is
// the one that has to ask first: firing it on a host without the hardware
// would bounce off /studio and land the user on /chat, away from whatever
// they had open. The sidebar disables the row on the same measured check,
// and only once measured, since the guess is what the row waits out too.
useShortcut("switchToTrain", goTo("/studio"), {
- enabled: !isAuthFlowRoute && !chatOnlyMeasured,
+ enabled: routeShortcutEnabled && !chatOnlyMeasured,
});
useShortcut("switchToRecipes", goTo("/data-recipes"), {
- enabled: !isAuthFlowRoute,
+ enabled: routeShortcutEnabled,
+ });
+ useShortcut("switchToImages", goTo("/images"), {
+ enabled: routeShortcutEnabled,
});
- useShortcut("switchToImages", goTo("/images"), { enabled: !isAuthFlowRoute });
// /video checks auth and nothing else, so an ungated chord would put the
// unsupported-hardware gate where the user's workspace was. Train's chord
// waits on the same measurement; this one has its own predicate to wait on.
useShortcut("switchToVideo", goTo("/video"), {
- enabled: !isAuthFlowRoute && !videoDisabled,
+ enabled: routeShortcutEnabled && !videoDisabled,
+ });
+ useShortcut("switchToAudio", goTo("/audio"), {
+ enabled: routeShortcutEnabled,
+ });
+ useShortcut("switchToExport", goTo("/export"), {
+ enabled: routeShortcutEnabled,
});
- useShortcut("switchToAudio", goTo("/audio"), { enabled: !isAuthFlowRoute });
- useShortcut("switchToExport", goTo("/export"), { enabled: !isAuthFlowRoute });
useEffect(() => {
if (isChatRoute) return;
diff --git a/studio/frontend/src/components/assistant-ui/tool-group.tsx b/studio/frontend/src/components/assistant-ui/tool-group.tsx
index ca2659b5752..fe809caf9e2 100644
--- a/studio/frontend/src/components/assistant-ui/tool-group.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-group.tsx
@@ -10,12 +10,12 @@ import {
} from "react";
import { useAuiState } from "@assistant-ui/react";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
+import { useChatPreferencesStore } from "@/features/chat/stores/chat-preferences-store";
import {
toolOutputKey,
- useChatPreferencesStore,
useToolPaneScope,
useUnresolvedToolPaneScope,
-} from "@/features/chat";
+} from "@/features/chat/tool-output-scope";
import { ChevronDownIcon } from "lucide-react";
import { Wrench01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
diff --git a/studio/frontend/src/components/ui/alert.tsx b/studio/frontend/src/components/ui/alert.tsx
index 094b607d9a1..96f19c644e7 100644
--- a/studio/frontend/src/components/ui/alert.tsx
+++ b/studio/frontend/src/components/ui/alert.tsx
@@ -7,7 +7,7 @@ import type * as React from "react";
import { cn } from "@/lib/utils";
const alertVariants = cva(
- "grid gap-0.5 rounded-lg border px-4 py-3 text-left text-sm has-data-[slot=alert-action]:relative has-data-[slot=alert-action]:pr-18 has-[>svg]:grid-cols-[auto_1fr] has-[>svg]:gap-x-2.5 *:[svg]:row-span-2 *:[svg]:translate-y-0.5 *:[svg]:text-current *:[svg:not([class*='size-'])]:size-4 w-full relative group/alert",
+ "grid gap-0.5 rounded-lg border px-4 py-3 text-start text-sm has-data-[slot=alert-action]:relative has-data-[slot=alert-action]:pe-18 has-[>svg]:grid-cols-[auto_1fr] has-[>svg]:gap-x-2.5 *:[svg]:row-span-2 *:[svg]:translate-y-0.5 *:[svg]:text-current *:[svg:not([class*='size-'])]:size-4 w-full relative group/alert",
{
variants: {
variant: {
@@ -70,7 +70,7 @@ function AlertAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-action"
- className={cn("absolute top-2.5 right-3", className)}
+ className={cn("absolute top-2.5 end-3", className)}
{...props}
/>
);
diff --git a/studio/frontend/src/features/chat/artifacts/artifact-surface.tsx b/studio/frontend/src/features/chat/artifacts/artifact-surface.tsx
index 2039e4582f0..a4edc258371 100644
--- a/studio/frontend/src/features/chat/artifacts/artifact-surface.tsx
+++ b/studio/frontend/src/features/chat/artifacts/artifact-surface.tsx
@@ -110,6 +110,7 @@ export function ArtifactSurface({
const [copied, setCopied] = useState(false);
const copyResetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const surfaceRef = useRef<HTMLElement>(null);
+ const closeButtonRef = useRef<HTMLButtonElement>(null);
const previousFocusRef = useRef<Element | null>(null);
const filename = getArtifactFilename(artifact);
const sourceMarkdown = useMemo(
@@ -312,6 +313,7 @@ export function ArtifactSurface({
</Button>
) : null}
<Button
+ ref={closeButtonRef}
type="button"
variant="ghost"
size="icon"
@@ -344,6 +346,9 @@ export function ArtifactSurface({
title={artifact.title}
fill={true}
className="h-full"
+ actionFocusTargetRef={
+ variant === "overlay" ? closeButtonRef : undefined
+ }
/>
) : (
<div className="h-full overflow-auto text-xs leading-relaxed [&_[data-streamdown=code-block]]:!my-0 [&_[data-streamdown=code-block]]:!gap-0 [&_[data-streamdown=code-block]]:!rounded-none [&_[data-streamdown=code-block]]:!border-0 [&_[data-streamdown=code-block]]:!bg-transparent [&_[data-streamdown=code-block]]:!p-0 [&_[data-streamdown=code-block-body]]:!border-0 [&_[data-streamdown=code-block-body]]:!bg-transparent [&_[data-streamdown=code-block-body]]:!p-0 [&_pre]:!m-0 [&_pre]:!bg-transparent [&_pre]:!p-0 [&_pre]:text-xs [&_pre]:leading-relaxed [&_code]:text-xs">
diff --git a/studio/frontend/src/features/chat/artifacts/html-frame.tsx b/studio/frontend/src/features/chat/artifacts/html-frame.tsx
index f50ebca421b..66cda923424 100644
--- a/studio/frontend/src/features/chat/artifacts/html-frame.tsx
+++ b/studio/frontend/src/features/chat/artifacts/html-frame.tsx
@@ -3,11 +3,27 @@
"use client";
+import {
+ Alert,
+ AlertAction,
+ AlertDescription,
+ AlertTitle,
+} from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
-import { useT } from "@/i18n";
+// eslint-disable-next-line no-restricted-imports -- the settings barrel imports this feature back
+import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-store";
+import { useLocale, useT } from "@/i18n";
import { apiUrl } from "@/lib/api-base";
import { cn } from "@/lib/utils";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { ShieldAlertIcon, XIcon } from "lucide-react";
+import {
+ type RefObject,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { useChatRuntimeStore } from "../stores/chat-runtime-store";
import { hashArtifactCode } from "./types";
@@ -94,13 +110,16 @@ export function ArtifactHtmlFrame({
title = "HTML canvas preview",
className,
fill = false,
+ actionFocusTargetRef,
}: {
code: string;
title?: string;
className?: string;
fill?: boolean;
+ actionFocusTargetRef?: RefObject<HTMLElement | null>;
}) {
const t = useT();
+ const locale = useLocale();
const iframeRef = useRef<HTMLIFrameElement>(null);
// Every canvas honors this, fence or tool. Off by default; the standing half
// of the gate, alongside the per-canvas grant below.
@@ -125,6 +144,8 @@ export function ArtifactHtmlFrame({
const [grantedCode, setGrantedCode] = useState<string | null>(null);
const grantedForCanvas = grantedCode === code;
const networkAllowed = networkAccessEnabled || grantedForCanvas;
+ const [dismissedCode, setDismissedCode] = useState<string | null>(null);
+ const dismissedForCanvas = dismissedCode === code;
const artifactHtml = useMemo(() => buildArtifactSrcDoc(code), [code]);
// Identifies this load to the frame, which stamps its blocked reports with it.
const codeVersion = useMemo(() => hashArtifactCode(code), [code]);
@@ -196,7 +217,8 @@ export function ArtifactHtmlFrame({
// canvas on screen, rather than relying on postArtifactHtml changing.
}, [postArtifactHtml, code, codeVersion]);
- const showBlockedBanner = !networkAllowed && blockedForCanvas.uris.length > 0;
+ const showBlockedBanner =
+ !networkAllowed && !dismissedForCanvas && blockedForCanvas.uris.length > 0;
const shownHosts = blockedForCanvas.hosts
.slice(0, BLOCKED_HOSTS_SHOWN)
.join(", ");
@@ -204,36 +226,98 @@ export function ArtifactHtmlFrame({
blockedForCanvas.hosts.length > BLOCKED_HOSTS_SHOWN
? `${shownHosts}…`
: shownHosts;
+ const focusAfterAction = () => {
+ (actionFocusTargetRef?.current ?? iframeRef.current)?.focus({
+ preventScroll: true,
+ });
+ };
return (
- <div className={cn("relative", fill ? "h-full" : undefined)}>
+ <div
+ className={cn("relative", fill ? "h-full" : undefined)}
+ >
<iframe
ref={iframeRef}
src={src}
sandbox="allow-scripts"
referrerPolicy="no-referrer"
onLoad={postArtifactHtml}
- className={cn("block w-full border-0 bg-background", className)}
+ className={cn(
+ "block w-full border-0 bg-background outline-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring",
+ className,
+ )}
style={{ height: fill ? "100%" : height }}
title={title}
/>
{showBlockedBanner ? (
- <div className="absolute inset-x-0 bottom-0 flex flex-wrap items-center justify-between gap-2 border-t bg-background/95 px-3 py-2 text-xs backdrop-blur">
- <span className="text-muted-foreground">
- {t(
- blockedForCanvas.uris.length === 1
- ? "settings.chat.artifacts.blockedBanner"
- : "settings.chat.artifacts.blockedBannerPlural",
- { count: blockedForCanvas.uris.length, hosts: blockedFrom },
- )}
- </span>
- <Button
- size="sm"
- variant="outline"
- onClick={() => setGrantedCode(code)}
+ <div className="absolute inset-x-0 top-0 p-2">
+ <Alert
+ role="group"
+ dir={locale === "ar" ? "rtl" : "ltr"}
+ aria-label={t("settings.chat.artifacts.blockedTitle")}
+ className="border-amber-500/40 bg-background/95 shadow-md backdrop-blur"
>
- {t("settings.chat.artifacts.blockedBannerAction")}
- </Button>
+ <ShieldAlertIcon className="text-amber-500" />
+ <AlertAction>
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ aria-label={t("settings.chat.artifacts.blockedDismiss")}
+ onClick={() => {
+ focusAfterAction();
+ setDismissedCode(code);
+ }}
+ >
+ <XIcon />
+ </Button>
+ </AlertAction>
+ <AlertTitle role="alert">
+ {t("settings.chat.artifacts.blockedTitle")}
+ <span className="sr-only">
+ {" "}
+ {t("settings.chat.artifacts.blockedHint", {
+ setting: t("settings.chat.artifacts.allowNetworkAccess"),
+ })}
+ </span>
+ </AlertTitle>
+ <AlertDescription>
+ <p>
+ {t(
+ blockedForCanvas.uris.length === 1
+ ? "settings.chat.artifacts.blockedBanner"
+ : "settings.chat.artifacts.blockedBannerPlural",
+ { count: blockedForCanvas.uris.length, hosts: blockedFrom },
+ )}{" "}
+ {t("settings.chat.artifacts.blockedHint", {
+ setting: t("settings.chat.artifacts.allowNetworkAccess"),
+ })}
+ </p>
+ <div className="flex flex-wrap gap-2">
+ <Button
+ size="sm"
+ onClick={() => {
+ focusAfterAction();
+ setGrantedCode(code);
+ }}
+ >
+ {t("settings.chat.artifacts.blockedBannerAction")}
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => {
+ useSettingsDialogStore.getState().openDialog("chat", {
+ scrollTarget: "chat-canvas-network",
+ focusFallback:
+ actionFocusTargetRef?.current ?? iframeRef.current,
+ });
+ }}
+ >
+ {t("settings.chat.artifacts.blockedSettingsAction")}
+ </Button>
+ </div>
+ </AlertDescription>
+ </Alert>
</div>
) : null}
</div>
diff --git a/studio/frontend/src/features/chat/presets/preset-load-config.ts b/studio/frontend/src/features/chat/presets/preset-load-config.ts
index e4736f18604..328cd9d6cbb 100644
--- a/studio/frontend/src/features/chat/presets/preset-load-config.ts
+++ b/studio/frontend/src/features/chat/presets/preset-load-config.ts
@@ -5,7 +5,7 @@ import {
applyPerModelConfigToRuntime,
currentRuntimePerModelConfig,
perModelConfigsEqual,
-} from "@/features/model-picker";
+} from "@/features/model-picker/model-config/apply-per-model-config";
import {
CONTEXT_LENGTH_MIN,
DEFAULT_PER_MODEL_CONFIG,
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index ae655b206ac..3ec4c56f1a6 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -2,7 +2,10 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { authFetch } from "@/features/auth";
-import { mirrorHfTokenInto, useHfTokenStore } from "@/features/hub";
+import {
+ mirrorHfTokenInto,
+ useHfTokenStore,
+} from "@/features/hub/stores/hf-token-store";
import {
cachedPinnableGpuIndexKind,
reconcileCachedGpuSelection,
diff --git a/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts
index 347d2670273..647c1edf787 100644
--- a/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts
+++ b/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts
@@ -3,13 +3,13 @@
import {
GPU_LAYERS_AUTO,
- defaultInferenceParams,
normalizeSpeculativeType,
readPersistedGpuMemoryMode,
readPersistedSpeculativeType,
reconcilePersistedGpuSelection,
useChatRuntimeStore,
-} from "@/features/chat";
+} from "@/features/chat/stores/chat-runtime-store";
+import { defaultInferenceParams } from "@/features/chat/presets/preset-policy";
// Its own module so hosts needing only the signature skip the chat runtime store.
import { gpuFieldsSignature } from "./config-signature";
import {
diff --git a/studio/frontend/src/features/settings/settings-dialog.tsx b/studio/frontend/src/features/settings/settings-dialog.tsx
index 37baa1119bc..507f10f7083 100644
--- a/studio/frontend/src/features/settings/settings-dialog.tsx
+++ b/studio/frontend/src/features/settings/settings-dialog.tsx
@@ -250,6 +250,7 @@ export function SettingsDialog() {
const setActiveTab = useSettingsDialogStore((s) => s.setActiveTab);
const closeDialog = useSettingsDialogStore((s) => s.closeDialog);
const opener = useSettingsDialogStore((s) => s.opener);
+ const openerFallback = useSettingsDialogStore((s) => s.openerFallback);
const reduced = useReducedMotion();
// Mounting a heavy tab panel (System, Connections) in the same commit as
// the nav highlight makes the highlight lag the click. Render the panel
@@ -389,12 +390,14 @@ export function SettingsDialog() {
showCloseButton={false}
overlayClassName="bg-black/30 supports-backdrop-filter:backdrop-blur-[2px]"
onCloseAutoFocus={(e) => {
- // Restore focus to the element that triggered openDialog(). Radix's
- // FocusScope races our rAF-scheduled tab focus and loses the
- // previous-focus reference, so restore it by hand.
- if (opener && opener.isConnected) {
+ // radix loses its previous-focus reference when the tab focus runs in requestAnimationFrame.
+ const focusTarget = [opener, openerFallback].find(
+ (element) =>
+ element?.isConnected && !element.closest("[inert], [hidden]"),
+ );
+ if (focusTarget) {
e.preventDefault();
- opener.focus({ preventScroll: true });
+ focusTarget.focus({ preventScroll: true });
}
}}
className={cn(
diff --git a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
index cc2fc4129ac..17ec1772f98 100644
--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
@@ -26,13 +26,17 @@ export const SETTINGS_TABS = [
export type SettingsTab = (typeof SETTINGS_TABS)[number];
-export type SettingsScrollTarget = "about-updates" | "appearance-sidebar-nav";
+export type SettingsScrollTarget =
+ | "about-updates"
+ | "appearance-sidebar-nav"
+ | "chat-canvas-network";
/** Which archive the Data tab should open straight into. */
export type ArchivedShelf = "chats" | "images" | "videos";
interface OpenDialogOptions {
scrollTarget?: SettingsScrollTarget;
+ focusFallback?: HTMLElement | null;
}
interface SettingsDialogState {
@@ -44,6 +48,7 @@ interface SettingsDialogState {
// previous-focus capture, leaving focus on <body> after close. We restore
// explicitly via onCloseAutoFocus.
opener: HTMLElement | null;
+ openerFallback: HTMLElement | null;
// Set when something asks to jump straight to an archive listing (the archive
// toast). DataTab uses it as its initial subpage, then clears it. See requestsFor
// for how long it lives unconsumed.
@@ -65,6 +70,26 @@ function captureOpener(): HTMLElement | null {
: null;
}
+function focusForOpen(
+ state: SettingsDialogState,
+ requestedFallback: HTMLElement | null = null,
+) {
+ if (state.open) {
+ return {
+ opener: state.opener,
+ openerFallback: state.openerFallback,
+ };
+ }
+ const opener = captureOpener();
+ if (opener?.closest("[data-slot=dialog-content]")) {
+ return {
+ opener: state.opener,
+ openerFallback: state.openerFallback,
+ };
+ }
+ return { opener, openerFallback: requestedFallback };
+}
+
const ACTIVE_TAB_KEY = "unsloth_settings_active_tab";
function loadInitialTab(): SettingsTab {
@@ -84,6 +109,7 @@ function loadInitialTab(): SettingsTab {
const SCROLL_TARGET_TAB: Record<SettingsScrollTarget, SettingsTab> = {
"about-updates": "about",
"appearance-sidebar-nav": "appearance",
+ "chat-canvas-network": "chat",
};
/**
@@ -110,6 +136,7 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
activeTab: loadInitialTab(),
scrollTarget: null,
opener: null,
+ openerFallback: null,
archivedRequested: null,
openDialog: (tab, options) =>
set((state) => {
@@ -121,25 +148,25 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
// A caller that names a target replaces whatever was still pending.
scrollTarget: options?.scrollTarget ?? pending.scrollTarget,
archivedRequested: pending.archivedRequested,
- opener: captureOpener(),
+ ...focusForOpen(state, options?.focusFallback),
};
}),
openArchivedChats: () =>
- set({
+ set((state) => ({
open: true,
activeTab: "data",
scrollTarget: null,
archivedRequested: "chats",
- opener: captureOpener(),
- }),
+ ...focusForOpen(state),
+ })),
openArchivedMedia: (shelf) =>
- set({
+ set((state) => ({
open: true,
activeTab: "data",
scrollTarget: null,
archivedRequested: shelf,
- opener: captureOpener(),
- }),
+ ...focusForOpen(state),
+ })),
consumeArchivedChatsRequest: () => set({ archivedRequested: null }),
consumeScrollTarget: (target) =>
set((state) => ({
diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
index f1c89227240..f172d812600 100644
--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
@@ -38,10 +38,11 @@ import {
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { Columns2Icon } from "lucide-react";
-import { useEffect } from "react";
+import { useEffect, useRef } from "react";
import type { ReactNode } from "react";
import { SettingsRow } from "../components/settings-row";
import { SettingsSection } from "../components/settings-section";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
// Adjustable "+" menu items shown in settings, in display order. Icons mirror
// the ones used in the composer + menu itself.
@@ -195,6 +196,22 @@ export function ChatTab() {
const setSearchImages = useChatRuntimeStore(
(state) => state.setSearchImages,
);
+ const networkAccessRowRef = useRef<HTMLDivElement | null>(null);
+ const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);
+ const consumeScrollTarget = useSettingsDialogStore(
+ (s) => s.consumeScrollTarget,
+ );
+ useEffect(() => {
+ if (scrollTarget !== "chat-canvas-network") return;
+ const frame = window.requestAnimationFrame(() => {
+ networkAccessRowRef.current?.scrollIntoView({
+ block: "center",
+ behavior: "smooth",
+ });
+ consumeScrollTarget("chat-canvas-network");
+ });
+ return () => window.cancelAnimationFrame(frame);
+ }, [consumeScrollTarget, scrollTarget]);
const hydratePersistedSettings = useChatRuntimeStore(
(state) => state.hydratePersistedSettings,
);
@@ -503,17 +520,19 @@ export function ChatTab() {
onCheckedChange={setCollapseHtmlArtifacts}
/>
</SettingsRow>
- <SettingsRow
- label={t("settings.chat.artifacts.allowNetworkAccess")}
- description={t(
- "settings.chat.artifacts.allowNetworkAccessDescription",
- )}
- >
- <Switch
- checked={allowArtifactNetworkAccess}
- onCheckedChange={setAllowArtifactNetworkAccess}
- />
- </SettingsRow>
+ <div ref={networkAccessRowRef}>
+ <SettingsRow
+ label={t("settings.chat.artifacts.allowNetworkAccess")}
+ description={t(
+ "settings.chat.artifacts.allowNetworkAccessDescription",
+ )}
+ >
+ <Switch
+ checked={allowArtifactNetworkAccess}
+ onCheckedChange={setAllowArtifactNetworkAccess}
+ />
+ </SettingsRow>
+ </div>
</SettingsSection>
<SettingsSection title={t("settings.chat.webSearch.title")}>
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 46ac41d92c6..0d493c89ee2 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1401,6 +1401,11 @@ export const ar = {
blockedBanner: "تم حظر {count} مورد خارجي من {hosts}.",
blockedBannerPlural: "تم حظر {count} موارد خارجية من {hosts}.",
blockedBannerAction: "السماح لهذا الـ Canvas",
+ blockedTitle: "الوصول إلى الشبكة لـ Canvas معطّل",
+ blockedHint:
+ "فعّل «{setting}» في الإعدادات ← الدردشة للسماح لـ Canvas بتحميل الموارد الخارجية، أو اسمح بذلك لهذا الـ Canvas فقط.",
+ blockedSettingsAction: "فتح الإعدادات",
+ blockedDismiss: "تجاهل",
},
data: "البيانات",
exportHistory: "تصدير سجل المحادثات",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index fab4aa6d984..721b11fa970 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1441,6 +1441,11 @@ export const de = {
blockedBanner: "{count} externe Ressource von {hosts} blockiert.",
blockedBannerPlural: "{count} externe Ressourcen von {hosts} blockiert.",
blockedBannerAction: "Für dieses Canvas erlauben",
+ blockedTitle: "Canvas-Netzwerkzugriff ist deaktiviert",
+ blockedHint:
+ "Aktiviere „{setting}“ unter Einstellungen → Chat, damit Canvases externe Ressourcen laden können, oder erlaube es nur für dieses Canvas.",
+ blockedSettingsAction: "Einstellungen öffnen",
+ blockedDismiss: "Schließen",
},
data: "Daten",
exportHistory: "Chatverlauf exportieren",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index ce971603d9b..d0ed479087a 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1394,6 +1394,11 @@ export const en = {
blockedBanner: "Blocked {count} external resource from {hosts}.",
blockedBannerPlural: "Blocked {count} external resources from {hosts}.",
blockedBannerAction: "Allow for this canvas",
+ blockedTitle: "Canvas network access is off",
+ blockedHint:
+ "Turn on “{setting}” in Settings → Chat to let canvases load external resources, or allow it just for this canvas.",
+ blockedSettingsAction: "Open Settings",
+ blockedDismiss: "Dismiss",
},
data: "Data",
exportHistory: "Export chat history",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index d1f1ac7573c..590ff14bdc2 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1432,6 +1432,11 @@ export const es = {
blockedBanner: "Se bloqueó {count} recurso externo de {hosts}.",
blockedBannerPlural: "Se bloquearon {count} recursos externos de {hosts}.",
blockedBannerAction: "Permitir en este Canvas",
+ blockedTitle: "El acceso a la red del Canvas está desactivado",
+ blockedHint:
+ "Activa “{setting}” en Ajustes → Chat para que los Canvas carguen recursos externos, o permítelo solo en este Canvas.",
+ blockedSettingsAction: "Abrir ajustes",
+ blockedDismiss: "Descartar",
},
data: "Datos",
exportHistory: "Exportar historial de chat",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 297409bcc98..a29a689e24f 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1438,6 +1438,11 @@ export const fr = {
blockedBanner: "{count} ressource externe bloquée depuis {hosts}.",
blockedBannerPlural: "{count} ressources externes bloquées depuis {hosts}.",
blockedBannerAction: "Autoriser pour ce Canvas",
+ blockedTitle: "L'accès réseau du Canvas est désactivé",
+ blockedHint:
+ "Activez « {setting} » dans Paramètres → Chat pour que les Canvas chargent des ressources externes, ou autorisez-le uniquement pour ce Canvas.",
+ blockedSettingsAction: "Ouvrir les paramètres",
+ blockedDismiss: "Ignorer",
},
data: "Données",
exportHistory: "Exporter l'historique des discussions",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 7173075b506..dd0f87ee81e 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1407,6 +1407,11 @@ export const hi = {
blockedBanner: "{hosts} से {count} बाहरी संसाधन अवरुद्ध किया गया।",
blockedBannerPlural: "{hosts} से {count} बाहरी संसाधन अवरुद्ध किए गए।",
blockedBannerAction: "इस Canvas के लिए अनुमति दें",
+ blockedTitle: "Canvas नेटवर्क एक्सेस बंद है",
+ blockedHint:
+ "Canvas को बाहरी संसाधन लोड करने देने के लिए सेटिंग्स → चैट में “{setting}” चालू करें, या केवल इस Canvas के लिए अनुमति दें।",
+ blockedSettingsAction: "सेटिंग्स खोलें",
+ blockedDismiss: "खारिज करें",
},
data: "डेटा",
exportHistory: "चैट इतिहास एक्सपोर्ट करें",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 800f9808082..b47e6ca341f 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1406,6 +1406,11 @@ export const it = {
blockedBanner: "Bloccata {count} risorsa esterna da {hosts}.",
blockedBannerPlural: "Bloccate {count} risorse esterne da {hosts}.",
blockedBannerAction: "Consenti per questo Canvas",
+ blockedTitle: "L'accesso alla rete del Canvas è disattivato",
+ blockedHint:
+ "Attiva “{setting}” in Impostazioni → Chat per consentire ai Canvas di caricare risorse esterne, oppure consentilo solo per questo Canvas.",
+ blockedSettingsAction: "Apri impostazioni",
+ blockedDismiss: "Ignora",
},
data: "Dati",
exportHistory: "Esporta la cronologia delle chat",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 53b5bf9782a..1d58e5fd3f7 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1387,6 +1387,11 @@ export const ja = {
blockedBanner: "{hosts} からの外部リソース {count} 件をブロックしました。",
blockedBannerPlural: "{hosts} からの外部リソース {count} 件をブロックしました。",
blockedBannerAction: "この Canvas で許可",
+ blockedTitle: "Canvas のネットワークアクセスはオフです",
+ blockedHint:
+ "設定 → チャットで「{setting}」をオンにすると Canvas が外部リソースを読み込めます。この Canvas だけ許可することもできます。",
+ blockedSettingsAction: "設定を開く",
+ blockedDismiss: "閉じる",
},
data: "データ",
exportHistory: "チャット履歴をエクスポート",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index ad142fd895c..4b18b5b050e 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1398,6 +1398,11 @@ export const ko = {
blockedBanner: "{hosts}의 외부 리소스 {count}개를 차단했습니다.",
blockedBannerPlural: "{hosts}의 외부 리소스 {count}개를 차단했습니다.",
blockedBannerAction: "이 Canvas에서 허용",
+ blockedTitle: "Canvas 네트워크 액세스가 꺼져 있습니다",
+ blockedHint:
+ "설정 → 채팅에서 “{setting}”을 켜면 Canvas가 외부 리소스를 불러올 수 있습니다. 이 Canvas에서만 허용할 수도 있습니다.",
+ blockedSettingsAction: "설정 열기",
+ blockedDismiss: "닫기",
},
data: "데이터",
exportHistory: "채팅 기록 내보내기",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 26205fb07d8..5388e135542 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1420,6 +1420,11 @@ export const ptBR = {
blockedBanner: "{count} recurso externo de {hosts} bloqueado.",
blockedBannerPlural: "{count} recursos externos de {hosts} bloqueados.",
blockedBannerAction: "Permitir neste Canvas",
+ blockedTitle: "O acesso à rede do Canvas está desativado",
+ blockedHint:
+ "Ative “{setting}” em Configurações → Chat para que os Canvas carreguem recursos externos, ou permita apenas neste Canvas.",
+ blockedSettingsAction: "Abrir configurações",
+ blockedDismiss: "Dispensar",
},
data: "Dados",
exportHistory: "Exportar histórico de chat",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 0181791573e..cc8fb4cd54e 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1417,6 +1417,11 @@ export const ru = {
blockedBanner: "Заблокирован {count} внешний ресурс с {hosts}.",
blockedBannerPlural: "Заблокировано внешних ресурсов: {count} с {hosts}.",
blockedBannerAction: "Разрешить для этого Canvas",
+ blockedTitle: "Доступ Canvas к сети отключён",
+ blockedHint:
+ "Включите «{setting}» в разделе Настройки → Чат, чтобы Canvas мог загружать внешние ресурсы, или разрешите только для этого Canvas.",
+ blockedSettingsAction: "Открыть настройки",
+ blockedDismiss: "Закрыть",
},
data: "Данные",
exportHistory: "Экспортировать историю чатов",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 99ab5981bd0..295eb260482 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1372,6 +1372,11 @@ export const zhCN = {
blockedBanner: "已阻止来自 {hosts} 的 {count} 个外部资源。",
blockedBannerPlural: "已阻止来自 {hosts} 的 {count} 个外部资源。",
blockedBannerAction: "允许此 Canvas",
+ blockedTitle: "Canvas 网络访问已关闭",
+ blockedHint:
+ "在“设置 → 聊天”中开启“{setting}”以允许 Canvas 加载外部资源,或仅对此 Canvas 允许。",
+ blockedSettingsAction: "打开设置",
+ blockedDismiss: "关闭",
},
data: "数据",
exportHistory: "导出聊天记录",
diff --git a/studio/frontend/tests/artifact-frame-network-access.test.ts b/studio/frontend/tests/artifact-frame-network-access.test.ts
index ee754d19fe4..2513042a9eb 100644
--- a/studio/frontend/tests/artifact-frame-network-access.test.ts
+++ b/studio/frontend/tests/artifact-frame-network-access.test.ts
@@ -25,6 +25,7 @@ const sourceFile = (relative: string): ts.SourceFile => {
const SURFACE = "../src/features/chat/artifacts/artifact-surface.tsx";
const FRAME = "../src/features/chat/artifacts/html-frame.tsx";
+const ALERT = "../src/components/ui/alert.tsx";
/** Every `<ArtifactHtmlFrame>` opening tag in the artifact surface. */
function readFrameOpeningTags(): string[] {
@@ -159,15 +160,14 @@ test("no write resets the blocked list wholesale", () => {
const GRANT_SETTER = /\bsetGranted\w*\(/;
-/** Arguments of every `setGrantedCode(...)` call, with the enclosing JSX handler. */
-function readGrantCalls(): { argument: string; handler: string | null }[] {
+/** Arguments of every `<setter>(...)` call, with the enclosing JSX handler. */
+function readSetterCalls(
+ setter: string,
+): { argument: string; handler: string | null }[] {
const source = sourceFile(FRAME);
const calls: { argument: string; handler: string | null }[] = [];
const visit = (node: ts.Node): void => {
- if (
- ts.isCallExpression(node) &&
- node.expression.getText() === "setGrantedCode"
- ) {
+ if (ts.isCallExpression(node) && node.expression.getText() === setter) {
let handler: string | null = null;
for (let at: ts.Node = node; at.parent; at = at.parent) {
if (ts.isJsxAttribute(at.parent)) {
@@ -183,6 +183,8 @@ function readGrantCalls(): { argument: string; handler: string | null }[] {
return calls;
}
+const readGrantCalls = () => readSetterCalls("setGrantedCode");
+
// The canvas is what reports being blocked, so the grant must never be reachable
// from that path or a page could post its way onto the network. Only a JSX click
// handler may grant, and it stores the code it was clicked for.
@@ -360,3 +362,243 @@ test("blocked-resource state is capped against the untrusted canvas", () => {
);
assert.match(updater, BAILS_OUT);
});
+
+test("only a click can dismiss the banner, and only for the code on screen", () => {
+ const calls = readSetterCalls("setDismissedCode");
+ assert.ok(calls.length > 0, "setDismissedCode is never called");
+ for (const { argument, handler } of calls) {
+ assert.equal(argument, "code", "the dismissal stores the current code");
+ assert.equal(
+ handler,
+ "onClick",
+ "the dismissal must come from a click handler",
+ );
+ }
+});
+
+test("the dismissal is tied to the code it was dismissed for", () => {
+ assert.equal(readConst("dismissedForCanvas"), "dismissedCode === code");
+ assert.match(readConst("showBlockedBanner"), /!dismissedForCanvas/);
+});
+
+test("the banner deep-links to the network access setting", () => {
+ const source = sourceFile(FRAME);
+ const deepLinks: { tab: string; options: string; handler: string | null }[] =
+ [];
+ const visit = (node: ts.Node): void => {
+ if (
+ ts.isCallExpression(node) &&
+ node.expression.getText().endsWith(".openDialog")
+ ) {
+ let handler: string | null = null;
+ for (let at: ts.Node = node; at.parent; at = at.parent) {
+ if (ts.isJsxAttribute(at.parent)) {
+ handler = at.parent.name.getText();
+ break;
+ }
+ }
+ deepLinks.push({
+ tab: node.arguments[0]?.getText() ?? "",
+ options: node.arguments[1]?.getText() ?? "",
+ handler,
+ });
+ }
+ node.forEachChild(visit);
+ };
+ source.forEachChild(visit);
+ assert.equal(
+ deepLinks.length,
+ 1,
+ "the banner opens the settings dialog once",
+ );
+ assert.equal(deepLinks[0].tab, '"chat"');
+ assert.match(deepLinks[0].options, /scrollTarget:\s*"chat-canvas-network"/);
+ assert.equal(deepLinks[0].handler, "onClick");
+});
+
+/** The opening tag of whichever element carries `ref={<name>}`. */
+function readTagWithRef(name: string): string {
+ const source = sourceFile(FRAME);
+ let text: string | undefined;
+ const visit = (node: ts.Node): void => {
+ const opening = openingTag(node);
+ if (opening?.getText().includes(`ref={${name}}`)) {
+ text = opening.getText();
+ }
+ node.forEachChild(visit);
+ };
+ source.forEachChild(visit);
+ assert.ok(text, `no element carries ref={${name}}`);
+ return text;
+}
+
+/** The JSX handler that contains a call to `needle`. */
+function readHandlerCalling(needle: string): string {
+ const source = sourceFile(FRAME);
+ let text: string | undefined;
+ const visit = (node: ts.Node): void => {
+ if (ts.isCallExpression(node) && node.expression.getText() === needle) {
+ for (let at: ts.Node = node; at.parent; at = at.parent) {
+ if (ts.isJsxAttribute(at.parent)) {
+ text = at.parent.getText();
+ break;
+ }
+ }
+ }
+ node.forEachChild(visit);
+ };
+ source.forEachChild(visit);
+ assert.ok(text, `no JSX handler calls ${needle}`);
+ return text;
+}
+
+test("dismissing the banner leaves focus on the canvas", () => {
+ const handler = readHandlerCalling("setDismissedCode");
+ const focusAt = handler.indexOf("focusAfterAction");
+ const dismissAt = handler.indexOf("setDismissedCode");
+ assert.ok(focusAt >= 0, "the dismissal must hand focus to the canvas");
+ assert.ok(focusAt < dismissAt, "focus must move before the button unmounts");
+});
+
+test("granting network access leaves focus on the canvas", () => {
+ const handler = readHandlerCalling("setGrantedCode");
+ const focusAt = handler.indexOf("focusAfterAction");
+ const grantAt = handler.indexOf("setGrantedCode");
+ assert.ok(focusAt >= 0, "the grant must hand focus to the canvas");
+ assert.ok(focusAt < grantAt, "focus must move before the button unmounts");
+});
+
+test("the settings deep link keeps the invoking button as its opener", () => {
+ const handler = readHandlerCalling(
+ "useSettingsDialogStore.getState().openDialog",
+ );
+ assert.match(
+ handler,
+ /focusFallback:\s*actionFocusTargetRef\?\.current \?\? iframeRef\.current/,
+ );
+ assert.doesNotMatch(handler, /iframeRef\.current\?\.focus/);
+});
+
+test("fullscreen canvas actions return focus inside the dialog", () => {
+ const tags = readFrameOpeningTags();
+ assert.equal(tags.length, 1);
+ assert.match(
+ tags[0],
+ /actionFocusTargetRef=\{\s*variant === "overlay" \? closeButtonRef : undefined\s*\}/,
+ );
+ const surface = readFileSync(
+ fileURLToPath(new URL(SURFACE, import.meta.url)),
+ "utf8",
+ );
+ assert.match(
+ surface,
+ /ref=\{closeButtonRef\}[\s\S]*?aria-label="Close canvas"/,
+ );
+ assert.match(
+ readConst("focusAfterAction"),
+ /\(actionFocusTargetRef\?\.current \?\? iframeRef\.current\)\?\.focus/,
+ );
+});
+
+test("the named iframe is the visible focus fallback", () => {
+ const tag = readTagWithRef("iframeRef");
+ assert.match(tag, /title=\{title\}/);
+ assert.match(
+ tag,
+ /focus-visible:outline/,
+ "the restored focus target needs a visible focus treatment",
+ );
+});
+
+test("the shared alert uses logical alignment and action spacing", () => {
+ const source = readFileSync(
+ fileURLToPath(new URL(ALERT, import.meta.url)),
+ "utf8",
+ );
+ assert.match(source, /text-start/);
+ assert.match(source, /has-data-\[slot=alert-action\]:pe-18/);
+ assert.match(source, /absolute top-2\.5 end-3/);
+ assert.doesNotMatch(source, /\btext-left\b|\bpr-18\b|\bright-3\b/);
+});
+
+test("the blocked alert scopes direction to its locale", () => {
+ const source = sourceFile(FRAME);
+ let alert: string | undefined;
+ const visit = (node: ts.Node): void => {
+ const opening = openingTag(node);
+ if (opening?.tagName.getText() === "Alert") alert = opening.getText();
+ node.forEachChild(visit);
+ };
+ source.forEachChild(visit);
+ assert.ok(alert, "blocked alert not found");
+ assert.match(alert, /dir=\{locale === "ar" \? "rtl" : "ltr"\}/);
+});
+
+test("the climbing blocked count stays outside the assertive live region", () => {
+ const source = sourceFile(FRAME);
+ let alert: string | undefined;
+ let alertTitle: string | undefined;
+ let paragraph: string | undefined;
+ const visit = (node: ts.Node): void => {
+ const opening = openingTag(node);
+ if (opening?.tagName.getText() === "Alert") {
+ alert = opening.getText();
+ }
+ if (opening?.tagName.getText() === "AlertTitle") {
+ alertTitle = opening.getText();
+ }
+ if (
+ ts.isJsxElement(node) &&
+ node.openingElement.tagName.getText() === "p" &&
+ node.getText().includes("blockedBanner")
+ ) {
+ paragraph = node.getText();
+ }
+ node.forEachChild(visit);
+ };
+ source.forEachChild(visit);
+ assert.ok(alert, "the blocked alert is missing");
+ assert.ok(alertTitle, "the blocked alert title is missing");
+ assert.ok(paragraph, "the paragraph carrying the blocked count is missing");
+ assert.match(alert, /role="group"/);
+ assert.match(alertTitle, /role="alert"/);
+ assert.doesNotMatch(paragraph, /aria-live/);
+});
+
+/** The opening tag of the `<Button>` whose subtree calls `needle`. */
+function readButtonCalling(needle: string): string {
+ const source = sourceFile(FRAME);
+ let text: string | undefined;
+ const visit = (node: ts.Node): void => {
+ const opening = openingTag(node);
+ if (
+ opening?.tagName.getText() === "Button" &&
+ node.getText().includes(needle)
+ ) {
+ text = opening.getText();
+ }
+ node.forEachChild(visit);
+ };
+ source.forEachChild(visit);
+ assert.ok(text, `no <Button> calls ${needle}`);
+ return text;
+}
+
+// The grant covers one canvas; the settings link turns network access on for
+// every canvas from here on. Studio's tool controls lead with the narrow grant
+// -- Allow is the primary, Always allow the outline beside it -- so the banner
+// matches, and the emphasis never lands on the action that widens the most.
+test("the emphasized action is the per-canvas grant, not the global setting", () => {
+ const grant = readButtonCalling("setGrantedCode");
+ const settings = readButtonCalling("openDialog");
+ assert.doesNotMatch(
+ grant,
+ /variant=/,
+ "the per-canvas grant must stay the default (primary) button",
+ );
+ assert.match(
+ settings,
+ /variant="outline"/,
+ "the global setting must be the quieter outline button",
+ );
+});
diff --git a/studio/frontend/tests/keyboard-shortcuts.test.ts b/studio/frontend/tests/keyboard-shortcuts.test.ts
index b339ce17167..340793daa2d 100644
--- a/studio/frontend/tests/keyboard-shortcuts.test.ts
+++ b/studio/frontend/tests/keyboard-shortcuts.test.ts
@@ -347,7 +347,11 @@ test("the workspace chords land where the guard lets them", async () => {
);
assert.match(
root,
- /useShortcut\("switchToTrain", goTo\("\/studio"\), \{\n\s*enabled: !isAuthFlowRoute && !chatOnlyMeasured,/,
+ /const routeShortcutEnabled = !isAuthFlowRoute && !settingsDialogOpen;/,
+ );
+ assert.match(
+ root,
+ /useShortcut\("switchToTrain", goTo\("\/studio"\), \{\n\s*enabled: routeShortcutEnabled && !chatOnlyMeasured,/,
);
// Video has its own predicate rather than the chat-only one: /video checks
// auth and nothing else, so the chord would land on the unsupported-hardware
@@ -358,7 +362,7 @@ test("the workspace chords land where the guard lets them", async () => {
);
assert.match(
root,
- /useShortcut\("switchToVideo", goTo\("\/video"\), \{\n\s*enabled: !isAuthFlowRoute && !videoDisabled,/,
+ /useShortcut\("switchToVideo", goTo\("\/video"\), \{\n\s*enabled: routeShortcutEnabled && !videoDisabled,/,
);
const sidebar = await readFile(
new URL("../src/components/app-sidebar.tsx", import.meta.url),
@@ -1372,7 +1376,7 @@ test("the new-chat chords stay out of the auth flow", async () => {
const at = root.indexOf(`"${id}"`);
assert.ok(at !== -1, `${id} is registered`);
const call = root.slice(at, root.indexOf("\n );", at) + 5);
- assert.match(call, /enabled: !isAuthFlowRoute/, `${id} is gated`);
+ assert.match(call, /enabled: routeShortcutEnabled/, `${id} is gated`);
}
});
@@ -1387,7 +1391,7 @@ test("switching back to Chat lands on the view the user left", async () => {
assert.ok(at !== -1, "switchToChat is registered");
const call = root.slice(at, root.indexOf("\n );", at) + 5);
assert.match(call, /navigate\(\{ to: "\/chat", search: chatSearch \}\)/);
- assert.match(call, /enabled: !isAuthFlowRoute/);
+ assert.match(call, /enabled: routeShortcutEnabled/);
// The other workspaces keep the bare helper; only chat carries a search.
assert.match(root, /useShortcut\("switchToImages", goTo\("\/images"\)/);
// location.search is the raw URL's, not the matched route's, so a seeded
diff --git a/studio/frontend/tests/module-scope-cycle-safety.test.ts b/studio/frontend/tests/module-scope-cycle-safety.test.ts
index 6e3efc26624..a7653189ab4 100644
--- a/studio/frontend/tests/module-scope-cycle-safety.test.ts
+++ b/studio/frontend/tests/module-scope-cycle-safety.test.ts
@@ -21,6 +21,19 @@ import ts from "typescript";
const SRC = fileURLToPath(new URL("../src", import.meta.url));
const KEYS = path.join(SRC, "features/chat/stores/sidebar-organization-keys.ts");
const GENERAL_TAB = path.join(SRC, "features/settings/tabs/general-tab.tsx");
+const CHAT_RUNTIME = path.join(
+ SRC,
+ "features/chat/stores/chat-runtime-store.ts",
+);
+const PRESET_LOAD_CONFIG = path.join(
+ SRC,
+ "features/chat/presets/preset-load-config.ts",
+);
+const APPLY_PER_MODEL_CONFIG = path.join(
+ SRC,
+ "features/model-picker/model-config/apply-per-model-config.ts",
+);
+const TOOL_GROUP = path.join(SRC, "components/assistant-ui/tool-group.tsx");
const parse = (file: string, text: string) =>
ts.createSourceFile(
@@ -151,3 +164,34 @@ test("the model memory hook imports no feature barrel", async () => {
"a bare @/features/<name> import here closes the cycle and the dev server white screens again",
);
});
+
+test("the chat runtime imports the Hub token store directly", async () => {
+ const text = await readFile(CHAT_RUNTIME, "utf8");
+ const specifiers = staticSpecifiers(CHAT_RUNTIME, text);
+ assert.ok(
+ specifiers.includes("@/features/hub/stores/hf-token-store"),
+ "chat-runtime-store.ts must import the token store directly",
+ );
+ assert.ok(
+ !specifiers.includes("@/features/hub"),
+ "the Hub barrel closes a module-scope cycle through the model picker",
+ );
+});
+
+test("the startup cycle imports no feature barrel", async () => {
+ for (const file of [
+ PRESET_LOAD_CONFIG,
+ APPLY_PER_MODEL_CONFIG,
+ TOOL_GROUP,
+ ]) {
+ const text = await readFile(file, "utf8");
+ const barrels = staticSpecifiers(file, text).filter((specifier) =>
+ /^@\/features\/[^/]+$/.test(specifier),
+ );
+ assert.deepEqual(
+ barrels,
+ [],
+ `${path.relative(SRC, file)} closes the chat-store and model-picker cycle`,
+ );
+ }
+});
diff --git a/studio/frontend/tests/settings-deep-open-requests.test.ts b/studio/frontend/tests/settings-deep-open-requests.test.ts
index a32a35812f0..b066229cf08 100644
--- a/studio/frontend/tests/settings-deep-open-requests.test.ts
+++ b/studio/frontend/tests/settings-deep-open-requests.test.ts
@@ -19,6 +19,7 @@ function reset(): void {
activeTab: "general",
scrollTarget: null,
opener: null,
+ openerFallback: null,
archivedRequested: null,
});
}
@@ -123,3 +124,40 @@ test("consuming a scroll target clears it", () => {
store.getState().consumeScrollTarget("about-updates");
assert.equal(store.getState().scrollTarget, null);
});
+
+test("the canvas network target lands on Chat and stays until Chat reads it", () => {
+ reset();
+ store.getState().openDialog("chat", { scrollTarget: "chat-canvas-network" });
+ assert.equal(store.getState().activeTab, "chat");
+ assert.equal(store.getState().scrollTarget, "chat-canvas-network");
+ store.getState().setActiveTab("about");
+ assert.equal(store.getState().scrollTarget, null);
+});
+
+test("a deep link can provide a stable focus fallback", () => {
+ reset();
+ const fallback = {} as HTMLElement;
+ store.getState().openDialog("chat", {
+ scrollTarget: "chat-canvas-network",
+ focusFallback: fallback,
+ });
+ assert.equal(store.getState().openerFallback, fallback);
+});
+
+test("repeated opens preserve the external focus targets", () => {
+ reset();
+ const opener = {} as HTMLElement;
+ const fallback = {} as HTMLElement;
+ store.setState({ open: true, opener, openerFallback: fallback });
+
+ const repeatOpens = [
+ () => store.getState().openDialog("keyboard-shortcuts"),
+ () => store.getState().openArchivedChats(),
+ () => store.getState().openArchivedMedia("images"),
+ ];
+ for (const repeatOpen of repeatOpens) {
+ repeatOpen();
+ assert.equal(store.getState().opener, opener);
+ assert.equal(store.getState().openerFallback, fallback);
+ }
+});
diff --git a/studio/frontend/tests/shortcut-dispatch-guards.test.ts b/studio/frontend/tests/shortcut-dispatch-guards.test.ts
index 90593274294..5bdd179eaa7 100644
--- a/studio/frontend/tests/shortcut-dispatch-guards.test.ts
+++ b/studio/frontend/tests/shortcut-dispatch-guards.test.ts
@@ -5,6 +5,8 @@ import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
+import ts from "typescript";
+
import { registerBundlerResolver } from "./helpers/kit.ts";
registerBundlerResolver();
@@ -183,6 +185,66 @@ test("both composers gate dictation on the foreground", async () => {
}
});
+test("route shortcuts stay idle while Settings is open", async () => {
+ const sourceText = await readFile(
+ new URL("../src/app/routes/__root.tsx", import.meta.url),
+ "utf8",
+ );
+ const source = ts.createSourceFile(
+ "__root.tsx",
+ sourceText,
+ ts.ScriptTarget.ESNext,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const enabledById = new Map<string, string>();
+ const visit = (node: ts.Node): void => {
+ if (
+ ts.isCallExpression(node) &&
+ node.expression.getText() === "useShortcut" &&
+ ts.isStringLiteral(node.arguments[0]) &&
+ ts.isObjectLiteralExpression(node.arguments[2])
+ ) {
+ const enabled = node.arguments[2].properties.find(
+ (property): property is ts.PropertyAssignment =>
+ ts.isPropertyAssignment(property) && property.name.getText() === "enabled",
+ );
+ if (enabled) {
+ enabledById.set(node.arguments[0].text, enabled.initializer.getText());
+ }
+ }
+ node.forEachChild(visit);
+ };
+ source.forEachChild(visit);
+
+ for (const id of [
+ "newChat",
+ "newTemporaryChat",
+ "newStandaloneChat",
+ "switchToChat",
+ "switchToProjects",
+ "switchToHub",
+ "switchToRecipes",
+ "switchToImages",
+ "switchToAudio",
+ "switchToExport",
+ ]) {
+ assert.equal(enabledById.get(id), "routeShortcutEnabled", id);
+ }
+ assert.equal(
+ enabledById.get("switchToTrain"),
+ "routeShortcutEnabled && !chatOnlyMeasured",
+ );
+ assert.equal(
+ enabledById.get("switchToVideo"),
+ "routeShortcutEnabled && !videoDisabled",
+ );
+ assert.match(
+ sourceText,
+ /const routeShortcutEnabled = !isAuthFlowRoute && !settingsDialogOpen;/,
+ );
+});
+
// The sidebar used to hold the unread set in component state, which died with
// it. A module store does not, so the next account inherits it.
test("signing out drops the previous account's navigation state", async () => {
@@ -523,8 +585,8 @@ test("the workspace chords wait on the same verdict their rows do", async () =>
new URL("../src/app/routes/__root.tsx", import.meta.url),
"utf8",
);
- assert.match(root, /enabled: !isAuthFlowRoute && !chatOnlyMeasured,/);
- assert.match(root, /enabled: !isAuthFlowRoute && !videoDisabled,/);
+ assert.match(root, /enabled: routeShortcutEnabled && !chatOnlyMeasured,/);
+ assert.match(root, /enabled: routeShortcutEnabled && !videoDisabled,/);
const rowState = await readFile(
new URL("../src/components/nav-row-state.ts", import.meta.url),
"utf8",
diff --git a/tests/studio/probe_dismiss_guard.py b/tests/studio/probe_dismiss_guard.py
index 53e157cd737..6c050661f80 100644
--- a/tests/studio/probe_dismiss_guard.py
+++ b/tests/studio/probe_dismiss_guard.py
@@ -48,12 +48,11 @@ The guard must swallow too little nowhere:
swallow-too-little direction only: the second pointer's own press raises no
`click` while a touch point is live, on either tree, so it cannot also stand in
for the swallow-too-much direction.
- dismiss_then_ click the button to dismiss, then press Space, the key a reader uses to scroll.
- space No click is involved for the guard to swallow: the press it DID swallow left the
- button focused, and a focused button activates on Space. Discriminates on
- chromium, firefox and webkit. The modal shape cannot reach it, because with
- `pointer-events: none` on the body the press lands on `HTML` and focus never
- moves off `BODY`.
+ dismiss_then_ click the button to dismiss, then press Space. The swallowed press must move
+ space focus off the dangerous control and back to the menu trigger. Space then reopens
+ the menu instead of activating Delete. Discriminates on chromium, firefox and
+ webkit. The modal shape cannot reach it, because with `pointer-events: none` on
+ the body the press lands on `HTML` and focus never moves off `BODY`.
and too much nowhere:
@@ -113,6 +112,12 @@ CHARS = int(os.environ.get("PROBE_CHARS", "25000"))
HOLD_MS = int(os.environ.get("PROBE_HOLD_MS", "600"))
# Deliberately beyond CLICK_GRACE_MS (500).
GRACE_HOLD_MS = int(os.environ.get("PROBE_GRACE_HOLD_MS", "900"))
+SPACE_REOPEN_CASES = {
+ "held_space_then_space",
+ "dismiss_then_space",
+ "drag_then_space",
+ "blur_then_space",
+}
OPEN_MENU_JS = """
async () => {
@@ -148,6 +153,16 @@ FACTS_JS = """
}
"""
+FOCUS_FACTS_JS = """
+() => {
+ const trigger = window.__heavyThread.actionButton("More");
+ return {
+ menuClosed: !document.querySelector(".aui-action-bar-more-content"),
+ focusReturnedToTrigger: document.activeElement === trigger,
+ };
+}
+"""
+
# Simulate main-thread work between pointerdown and the synthesized click.
BLOCK_JS = """
(ms) => { const end = Date.now() + ms; while (Date.now() < end) {} }
@@ -284,6 +299,7 @@ async def one_case(
if not opened.get("ok"):
return {"case": case, "error": "menu never opened"}
before = await page.evaluate(FACTS_JS)
+ before_space = None
rect = before["deleteRect"]
if not rect:
return {"case": case, "error": "no Delete button"}
@@ -342,11 +358,13 @@ async def one_case(
await page.wait_for_timeout(120)
await page.keyboard.up("Space")
await page.wait_for_timeout(300)
+ before_space = await page.evaluate(FOCUS_FACTS_JS)
await page.keyboard.press("Space")
elif case == "dismiss_then_space":
# A swallowed dismissal must not leave Delete focused for Space activation.
await page.mouse.click(x, y)
await page.wait_for_timeout(300)
+ before_space = await page.evaluate(FOCUS_FACTS_JS)
await page.keyboard.press("Space")
elif case in ("drag_then_space", "blur_then_space"):
# A drag may retarget the click; blur exercises the no-click cleanup path.
@@ -361,6 +379,7 @@ async def one_case(
await page.mouse.move(spot["x"], spot["y"])
await page.mouse.up()
await page.wait_for_timeout(700)
+ before_space = await page.evaluate(FOCUS_FACTS_JS)
await page.keyboard.press("Space")
elif case == "dismiss_on_composer":
# Dismissing into the composer must preserve its caret.
@@ -562,7 +581,7 @@ async def one_case(
await page.wait_for_timeout(1500)
after = await page.evaluate(FACTS_JS)
- return {
+ result = {
"case": case,
"bodyPointerEvents": before["bodyPointerEvents"],
"assistantMessagesBefore": before["assistantMessages"],
@@ -570,6 +589,15 @@ async def one_case(
"deleted": after["assistantMessages"] < before["assistantMessages"],
"menuClosed": not after["menuOpen"],
}
+ if before_space is not None:
+ result.update(
+ {
+ "menuClosedBeforeSpace": before_space["menuClosed"],
+ "focusReturnedToTrigger": before_space["focusReturnedToTrigger"],
+ "menuReopenedBySpace": after["menuOpen"],
+ }
+ )
+ return result
async def run(engine: str, cases: list[str]) -> dict:
@@ -636,7 +664,21 @@ def main() -> int:
for case, why in skipped:
print(f"[probe] SKIPPED {case}: {why}", flush = True)
deleted = [c["case"] for c in result["cases"] if c.get("deleted")]
- stuck = [c["case"] for c in result["cases"] if "menuClosed" in c and not c["menuClosed"]]
+ stuck = [
+ c["case"]
+ for c in result["cases"]
+ if "menuClosed" in c and not c["menuClosed"] and c["case"] not in SPACE_REOPEN_CASES
+ ]
+ unsafe_space = [
+ c["case"]
+ for c in result["cases"]
+ if c["case"] in SPACE_REOPEN_CASES
+ and (
+ not c.get("menuClosedBeforeSpace")
+ or not c.get("focusReturnedToTrigger")
+ or not c.get("menuReopenedBySpace")
+ )
+ ]
broken = [c["case"] for c in result["cases"] if c.get("error")]
over = [
c["case"]
@@ -658,7 +700,13 @@ def main() -> int:
print(f"[probe] FAIL: cases did not run: {broken}", flush = True)
if stuck:
print(f"[probe] FAIL: the menu did not close on {stuck}", flush = True)
- if deleted or broken or stuck:
+ if unsafe_space:
+ print(
+ "[probe] FAIL: the Space follow-up did not dismiss safely, restore trigger focus, "
+ f"and reopen the menu: {unsafe_space}",
+ flush = True,
+ )
+ if deleted or broken or stuck or unsafe_space:
return 1
print("[probe] PASS: no dismissal variant reached the control underneath", flush = True)
return 0