Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
feat(webui): simplify automation management and unify disclosure motion
Xubin Ren1640784d4514
diff --git a/nanobot/channels/weixin/webui/WeixinPanel.tsx b/nanobot/channels/weixin/webui/WeixinPanel.tsxindex 6836b7cdc..64df53b1b 100644--- a/nanobot/channels/weixin/webui/WeixinPanel.tsx+++ b/nanobot/channels/weixin/webui/WeixinPanel.tsx@@ -18,6 +18,7 @@ import {ChannelLogo,} from "@/components/settings/channels/ChannelIdentity";import { Button } from "@/components/ui/button";+import { DisclosureContent } from "@/components/ui/disclosure";import { normalizeLocale } from "@/i18n/config";import { configureChannel } from "@/lib/api";import type {@@ -293,7 +294,7 @@ export function WeixinPanel({) : null}{advancedFields.length ? (- <div id={advancedPanelId} hidden={!advancedOpen} className="text-[12px] leading-5 text-muted-foreground">+ <DisclosureContent id={advancedPanelId} open={advancedOpen} className="text-[12px] leading-5 text-muted-foreground"><CredentialFormfields={advancedFields}values={fieldValues}@@ -305,7 +306,7 @@ export function WeixinPanel({}}compact/>- </div>+ </DisclosureContent>) : null}</div>diff --git a/nanobot/webui/session_automations.py b/nanobot/webui/session_automations.pyindex 93bdb8c21..b4a8d13f9 100644--- a/nanobot/webui/session_automations.py+++ b/nanobot/webui/session_automations.py@@ -7,7 +7,10 @@ from typing import Any, Protocol, castfrom nanobot.cron.types import CronJobfrom nanobot.session.history_visibility import is_hidden_history_message-from nanobot.session.manager import _message_preview_text # pyright: ignore[reportPrivateUsage]+from nanobot.session.manager import (+ _message_preview_text, # pyright: ignore[reportPrivateUsage]+ _metadata_title, # pyright: ignore[reportPrivateUsage]+)from nanobot.triggers.local_types import LocalTriggerAutomationJob = CronJob | LocalTrigger@@ -309,7 +312,7 @@ def _websocket_origin_payload(if session_manager is not None:data = session_manager.read_session_file(session_key)if isinstance(data, dict):- title = str(data.get("title") or "")+ title = _metadata_title(data.get("metadata"))preview = _session_preview(data.get("messages"))return {diff --git a/tests/webui/test_session_automations.py b/tests/webui/test_session_automations.pynew file mode 100644index 000000000..4d2f1e3c2--- /dev/null+++ b/tests/webui/test_session_automations.py@@ -0,0 +1,59 @@+"""Linked-chat titles must use the same session metadata as the sidebar."""++from pathlib import Path+from typing import Any++import pytest++from nanobot.cron.types import CronJob, CronPayload+from nanobot.session.manager import SessionManager+from nanobot.triggers.local_types import LocalTrigger+from nanobot.webui.session_automations import serialize_automation_jobs+++ ("metadata", "title"),+ [+ ({"title": "推特大战场"}, "推特大战场"),+ ({"title": "<think>internal</think>Release planning"}, "Release planning"),+ ({"title": "<think>literal</think>", "title_user_edited": True}, "<think>literal</think>"),+ ({"title": 42}, ""),+ ({}, ""),+ ],+)+def test_linked_chat_title_reads_current_session_metadata(+ tmp_path: Path, metadata: dict[str, Any], title: str,+) -> None:+ manager = SessionManager(tmp_path)+ key = "websocket:linked-chat"+ session = manager.get_or_create(key)+ session.metadata.update(metadata)+ session.add_message("user", "Original message preview")+ manager.save(session)+ cron = CronJob(+ id="reminder", name="Drink water",+ payload=CronPayload(+ message="Take a break", session_key=key,+ origin_channel="websocket", origin_chat_id="linked-chat",+ ),+ )+ trigger = LocalTrigger(+ id="trigger", name="Build finished", enabled=True,+ channel="websocket", chat_id="linked-chat", session_key=key,+ )++ for expected in (title, "Updated title"):+ rows = serialize_automation_jobs([cron, trigger], include_details=True, session_manager=manager)+ for row in rows:+ assert row["origin"] == {+ "session_key": key,+ "channel": "websocket",+ "chat_id": "linked-chat",+ "title": expected,+ "preview": "Original message preview",+ }+ manager.update_session_metadata(key, {"title": "Updated title"})++ assert cron.payload.session_key == key+ assert cron.payload.message == "Take a break"+ assert trigger.session_key == keydiff --git a/webui/src/App.tsx b/webui/src/App.tsxindex 0bac91278..9f73fbd57 100644--- a/webui/src/App.tsx+++ b/webui/src/App.tsx@@ -2831,6 +2831,7 @@ function Shell({onModelNameChange={onModelNameChange}onSettingsChange={setSettingsSnapshot}skills={skills}+ titleOverrides={sidebarState.title_overrides}onSectionChange={onSettingsSectionChange}onLogout={onLogout}onRestart={onRestart}diff --git a/webui/src/components/MessageBubble.tsx b/webui/src/components/MessageBubble.tsxindex 6e158fb76..9a7ab3c42 100644--- a/webui/src/components/MessageBubble.tsx+++ b/webui/src/components/MessageBubble.tsx@@ -1,6 +1,7 @@import {useCallback,useEffect,+ useId,useMemo,useRef,useState,@@ -18,6 +19,7 @@ import {Wrench,} from "lucide-react";import { useTranslation } from "react-i18next";+import { DisclosureContent } from "@/components/ui/disclosure";import { AttachmentTile } from "@/components/AttachmentTile";import { SessionHandleLabel } from "@/components/SessionHandleLabel";@@ -934,6 +936,7 @@ function TraceGroup({ message }: TraceGroupProps) {const lines = message.traces ?? [message.content];const count = lines.length;const [open, setOpen] = useState(false);+ const contentId = useId();return (<div className="w-full"><button@@ -944,6 +947,7 @@ function TraceGroup({ message }: TraceGroupProps) {"text-xs text-muted-foreground transition-colors hover:bg-muted/45",)}aria-expanded={open}+ aria-controls={contentId}><Wrench className="h-3.5 w-3.5" aria-hidden /><span className="font-medium">@@ -954,17 +958,14 @@ function TraceGroup({ message }: TraceGroupProps) {<ChevronRightaria-hiddenclassName={cn(- "ml-auto h-3.5 w-3.5 transition-transform duration-200",+ "ml-auto h-3.5 w-3.5 transition-transform duration-200 motion-reduce:transition-none",open && "rotate-90",)}/></button>- {open && (+ <DisclosureContent id={contentId} open={open}><ul- className={cn(- "mt-1 space-y-0.5 border-l border-muted-foreground/20 pl-3",- "animate-in fade-in-0 slide-in-from-top-1 duration-200",- )}+ className="mt-1 space-y-0.5 border-l border-muted-foreground/20 pl-3">{lines.map((line, i) => (<li@@ -975,7 +976,7 @@ function TraceGroup({ message }: TraceGroupProps) {</li>))}</ul>- )}+ </DisclosureContent></div>);}diff --git a/webui/src/components/settings/SettingsPage.tsx b/webui/src/components/settings/SettingsPage.tsxindex c4ea93646..cdccc7169 100644--- a/webui/src/components/settings/SettingsPage.tsx+++ b/webui/src/components/settings/SettingsPage.tsx@@ -51,6 +51,7 @@ interface SettingsPageProps {onToggleTheme: () => void;onBackToChat: () => void;skills: SkillSummary[];+ titleOverrides?: Record<string, string>;onLogout?: () => void;isRestarting: boolean;hostChromeInset: boolean;@@ -64,6 +65,7 @@ export function SettingsPage({onToggleTheme,onBackToChat,skills,+ titleOverrides,onLogout,isRestarting,hostChromeInset,@@ -562,6 +564,7 @@ export function SettingsPage({<div className="settings-stack"><AutomationsSettingspayload={automations}+ titleOverrides={titleOverrides}loading={automationsLoading}query={automationsQuery}filter={automationsFilter}@@ -574,7 +577,6 @@ export function SettingsPage({onAction={handleAutomationAction}onRequestEdit={setAutomationPendingEdit}onRequestDelete={setAutomationPendingDelete}- onBackToChat={onBackToChat}/></div>);@@ -730,7 +732,7 @@ export function SettingsPage({)}>{!showSidebar ? (- <div className="mb-7">+ <div className={activeSection === "automations" ? "lg:hidden" : "mb-7"}><buttontype="button"onClick={backToChat}@@ -739,11 +741,11 @@ export function SettingsPage({<ChevronLeft className="h-3.5 w-3.5" aria-hidden />{t("settings.backToChat")}</button>- <h1 className="text-[24px] font-normal leading-tight tracking-normal text-foreground sm:text-[28px]">+ {activeSection !== "automations" ? <h1 className="text-[24px] font-normal leading-tight tracking-normal text-foreground sm:text-[28px]">{t(`settings.nav.${activeSection}`, {defaultValue: standaloneSectionTitle(activeSection),})}- </h1>+ </h1> : null}</div>) : null}diff --git a/webui/src/components/settings/SettingsView.tsx b/webui/src/components/settings/SettingsView.tsxindex 104d3004a..b688d6bc6 100644--- a/webui/src/components/settings/SettingsView.tsx+++ b/webui/src/components/settings/SettingsView.tsx@@ -16,6 +16,7 @@ interface SettingsViewProps {onModelNameChange: (modelName: string | null) => void;onSettingsChange?: (payload: SettingsPayload) => void;skills?: SkillSummary[];+ titleOverrides?: Record<string, string>;onSectionChange?: (section: SettingsSectionKey) => void;onLogout?: () => void;onRestart?: () => void;@@ -35,6 +36,7 @@ export function SettingsView({onModelNameChange,onSettingsChange,skills = [],+ titleOverrides,onSectionChange,onLogout,onRestart,@@ -61,6 +63,7 @@ export function SettingsView({onToggleTheme={onToggleTheme}onBackToChat={onBackToChat}skills={skills}+ titleOverrides={titleOverrides}onLogout={onLogout}isRestarting={isRestarting}hostChromeInset={hostChromeInset}diff --git a/webui/src/components/settings/SkillsCatalogSettings.tsx b/webui/src/components/settings/SkillsCatalogSettings.tsxindex a42e07f39..621d1c86d 100644--- a/webui/src/components/settings/SkillsCatalogSettings.tsx+++ b/webui/src/components/settings/SkillsCatalogSettings.tsx@@ -1,4 +1,4 @@-import { useEffect, useState, type ReactNode } from "react";+import { useEffect, useId, useState, type ReactNode } from "react";import type { TFunction } from "i18next";import {Check,@@ -25,6 +25,8 @@ import {AlertDialogTitle,} from "@/components/ui/alert-dialog";import { Button } from "@/components/ui/button";+import { Disclosure } from "@/components/ui/disclosure";+import { ExpandableText } from "@/components/ui/expandable-text";import { Input } from "@/components/ui/input";import { SegmentedControl } from "@/components/ui/segmented-control";import { Sheet, SheetContent, SheetDescription, SheetTitle } from "@/components/ui/sheet";@@ -279,6 +281,7 @@ function SkillDetailSheet({const [deleteOpen, setDeleteOpen] = useState(false);const [refreshKey, setRefreshKey] = useState(0);const [descriptionExpanded, setDescriptionExpanded] = useState(false);+ const descriptionId = useId();useEffect(() => {if (!open || !skill) return;@@ -407,18 +410,21 @@ function SkillDetailSheet({{statusLabel}</Pill></div>- <p- className={cn(- "mt-3 text-[13px] leading-5 text-muted-foreground",- descriptionExpandable && !descriptionExpanded && "line-clamp-5",- )}- >- {activeSkill.description}- </p>+ <div className="mt-3">+ <ExpandableText+ id={descriptionId}+ expanded={descriptionExpanded || !descriptionExpandable}+ lines={5}+ className="text-[13px] leading-5 text-muted-foreground"+ >+ {activeSkill.description}+ </ExpandableText>+ </div>{descriptionExpandable ? (<buttontype="button"aria-expanded={descriptionExpanded}+ aria-controls={descriptionId}onClick={() => setDescriptionExpanded((value) => !value)}className="mt-1.5 min-h-8 rounded-full text-[12px] font-medium text-foreground/70 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">@@ -574,15 +580,18 @@ function RawInstructionsBlock({ markdown }: { markdown: string }) {});return (- <details className="group rounded-floating border border-border/45 bg-muted/20 px-3 py-3">- <summary className="flex min-h-11 cursor-pointer select-none items-center justify-between gap-3 text-[13px] font-medium text-foreground/90 transition-colors hover:text-foreground">+ <Disclosure+ className="rounded-floating border border-border/45 bg-muted/20 px-3 py-3"+ summaryClassName="flex min-h-11 cursor-pointer items-center justify-between gap-3 rounded-sm text-[13px] font-medium text-foreground/90 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ summary={<><span>{t("settings.skills.instructionsTitle", { defaultValue: "Skill instructions" })}</span><code className="font-mono text-[10px] font-normal text-muted-foreground">SKILL.md</code>- </summary>+ </>}+ ><div className="mt-3 overflow-hidden rounded-control border border-border/35 bg-background/70"><preclassName={cn(@@ -596,7 +605,7 @@ function RawInstructionsBlock({ markdown }: { markdown: string }) {{content}</pre></div>- </details>+ </Disclosure>);}diff --git a/webui/src/components/settings/models/ModelsSettings.tsx b/webui/src/components/settings/models/ModelsSettings.tsxindex fcaaa8477..d99ec31f4 100644--- a/webui/src/components/settings/models/ModelsSettings.tsx+++ b/webui/src/components/settings/models/ModelsSettings.tsx@@ -1,6 +1,7 @@import { ProviderIcon } from "@/components/settings/models/ProviderSettings";import { useAutoSave } from "@/components/settings/shared/useAutoSave";-import { useEffect, useRef, useState, type Dispatch, type SetStateAction } from "react";+import { useEffect, useId, useRef, useState, type Dispatch, type SetStateAction } from "react";+import { DisclosureContent } from "@/components/ui/disclosure";import {ChevronDown,GripVertical,@@ -237,6 +238,7 @@ export function ModelsSettings({const suggestedPresetNameRef = useRef<string | null>(null);const [editorRowKey, setEditorRowKey] = useState<string | null>(null);const [advancedOpen, setAdvancedOpen] = useState(false);+ const advancedId = useId();const [draggedCallOrderIndex, setDraggedCallOrderIndex] = useState<number | null>(null);const [dragOverCallOrderIndex, setDragOverCallOrderIndex] = useState<number | null>(null);const [draggedRowHeight, setDraggedRowHeight] = useState(0);@@ -499,6 +501,7 @@ export function ModelsSettings({<buttontype="button"aria-expanded={advancedOpen}+ aria-controls={advancedId}onClick={() => setAdvancedOpen((value) => !value)}className="flex min-h-[62px] w-full items-center justify-between gap-4 px-4 py-3.5 text-left transition-colors settings-hover sm:px-5">@@ -519,13 +522,13 @@ export function ModelsSettings({</span><ChevronDownclassName={cn(- "h-4 w-4 shrink-0 text-muted-foreground transition-transform",+ "h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200 motion-reduce:transition-none",advancedOpen && "rotate-180",)}aria-hidden/></button>- {advancedOpen ? (+ <DisclosureContent id={advancedId} open={advancedOpen}><div className="bg-muted/12 px-4 py-4 sm:px-5"><ModelAdvancedFieldsmaxTokens={form.maxTokens}@@ -535,7 +538,7 @@ export function ModelsSettings({onChange={(value) => setForm((prev) => ({ ...prev, ...value }))}/></div>- ) : null}+ </DisclosureContent><div className="flex min-h-[58px] flex-col gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-5">{creating ? (<Buttondiff --git a/webui/src/components/settings/models/ProviderSettings.tsx b/webui/src/components/settings/models/ProviderSettings.tsxindex 33beef911..8d56e173e 100644--- a/webui/src/components/settings/models/ProviderSettings.tsx+++ b/webui/src/components/settings/models/ProviderSettings.tsx@@ -1,4 +1,5 @@-import { useMemo, useState, type ReactNode } from "react";+import { useId, useMemo, useState, type ReactNode } from "react";+import { DisclosureContent } from "@/components/ui/disclosure";import {ChevronDown,Clipboard,@@ -431,6 +432,7 @@ function ProviderAdvancedOptions({const { t } = useTranslation();const [open, setOpen] = useState(false);const enabled = new Set(fields);+ const contentId = useId();if (enabled.size === 0) return null;const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });@@ -446,6 +448,7 @@ function ProviderAdvancedOptions({<buttontype="button"aria-expanded={open}+ aria-controls={contentId}onClick={() => setOpen((value) => !value)}className="flex min-h-[48px] w-full items-center justify-between gap-4 px-1 py-2.5 text-left transition-colors hover:text-foreground">@@ -454,13 +457,13 @@ function ProviderAdvancedOptions({</span><ChevronDownclassName={cn(- "h-4 w-4 shrink-0 text-muted-foreground transition-transform",+ "h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200 motion-reduce:transition-none",open && "rotate-180",)}aria-hidden/></button>- {open ? (+ <DisclosureContent id={contentId} open={open}><div className="py-3"><div className="grid gap-3 md:grid-cols-2">{enabled.has("api_type") ? (@@ -622,7 +625,7 @@ function ProviderAdvancedOptions({) : null}</div></div>- ) : null}+ </DisclosureContent>{footer ? (<div className="flex items-center justify-end gap-2 py-3">{footer}diff --git a/webui/src/components/settings/shared/SettingsFeature.tsx b/webui/src/components/settings/shared/SettingsFeature.tsxindex b414941bc..cd30ddbdf 100644--- a/webui/src/components/settings/shared/SettingsFeature.tsx+++ b/webui/src/components/settings/shared/SettingsFeature.tsx@@ -4,17 +4,20 @@ import { useTranslation } from "react-i18next";import { ToggleButton } from "@/components/settings/ToggleButton";import { SettingsGroup, SettingsRow } from "@/components/settings/shared/SettingsControls";import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";+import { Disclosure } from "@/components/ui/disclosure";export function SettingsAdvancedOptions({ children }: { children: ReactNode }) {const { t } = useTranslation();return (- <details className="group/advanced [&>summary]:select-none">- <summary className="settings-list-inset flex min-h-12 cursor-pointer list-none items-center justify-between gap-4 rounded-xl text-[13px] leading-5 text-muted-foreground settings-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [&::-webkit-details-marker]:hidden">+ <Disclosure+ summaryClassName="settings-list-inset flex min-h-12 cursor-pointer items-center justify-between gap-4 rounded-xl text-[13px] leading-5 text-muted-foreground settings-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ summary={<>{t("settings.runtimeConfig.advancedOptions")}- <ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 group-open/advanced:rotate-180" />- </summary>+ <ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 transition-transform duration-200 group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" />+ </>}+ ><div className="space-y-1">{children}</div>- </details>+ </Disclosure>);}diff --git a/webui/src/components/settings/system/AutomationsSettings.tsx b/webui/src/components/settings/system/AutomationsSettings.tsxindex 41008b390..7bb14584c 100644--- a/webui/src/components/settings/system/AutomationsSettings.tsx+++ b/webui/src/components/settings/system/AutomationsSettings.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useState } from "react";+import { useEffect, useId, useMemo, useRef, useState } from "react";import type { FormEvent, ReactNode } from "react";import type { TFunction } from "i18next";import {@@ -8,21 +8,19 @@ import {ChevronRight,CircleAlert,Clipboard,- ExternalLink,Loader2,- PauseCircle,- Pencil,- PlayCircle,+ MoreHorizontal,Search,- Trash2,+ SlidersHorizontal,} from "lucide-react";import { useTranslation } from "react-i18next";import { channelTranslator } from "@/channel-plugins/i18n";import { channelUiOwner, channelUiPresentation } from "@/channel-plugins/registry";-import { SETTINGS_SEARCH_INPUT_CLASS } from "@/components/settings/shared/SettingsControls";-import { AppsActionButton } from "@/components/settings/system/AppsSettings";+import { SETTINGS_SEARCH_INPUT_CLASS, SettingsGroup } from "@/components/settings/shared/SettingsControls";import { Button } from "@/components/ui/button";+import { Disclosure, DisclosureContent } from "@/components/ui/disclosure";+import { ExpandableText } from "@/components/ui/expandable-text";import {Dialog,DialogContent,@@ -41,6 +39,7 @@ import { formControlFocusClassName } from "@/components/ui/form-control";import { Input } from "@/components/ui/input";import { SegmentedControl } from "@/components/ui/segmented-control";import { Textarea } from "@/components/ui/textarea";+import { displayTitle } from "@/lib/chat-groups";import { copyTextToClipboard } from "@/lib/clipboard";import { fmtDateTime, relativeTime } from "@/lib/format";import type { AutomationsPayload, AutomationUpdatePayload, SessionAutomationJob } from "@/lib/types";@@ -50,23 +49,17 @@ export type AutomationFilter = "all" | "active" | "paused" | "failed" | "system"export type AutomationSort = "next" | "last" | "updated" | "name";export type AutomationAction = "enable" | "disable" | "delete" | "run";+const EMPTY_TITLE_OVERRIDES: Record<string, string> = {};+const SYSTEM_TASKS_OPEN_STORAGE_KEY = "nanobot-webui.automation-system-tasks-open";+export function AutomationsSettings({- payload,- loading,- query,- filter,- sort,- actionKey,- error,- onQueryChange,- onFilterChange,- onSortChange,- onAction,- onRequestEdit,- onRequestDelete,- onBackToChat,+ payload, loading, query, filter, sort, actionKey, error,+ titleOverrides = EMPTY_TITLE_OVERRIDES,+ onQueryChange, onFilterChange, onSortChange, onAction,+ onRequestEdit, onRequestDelete,}: {payload: AutomationsPayload | null;+ titleOverrides?: Record<string, string>;loading: boolean;query: string;filter: AutomationFilter;@@ -79,33 +72,58 @@ export function AutomationsSettings({onAction: (action: AutomationAction, job: SessionAutomationJob) => void | Promise<void>;onRequestEdit: (job: SessionAutomationJob) => void;onRequestDelete: (job: SessionAutomationJob) => void;- onBackToChat: () => void;}) {const { t, i18n } = useTranslation();const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>t(key, { defaultValue: fallback, ...(values ?? {}) });- const jobs = payload?.jobs ?? [];+ const jobs = useMemo(() => (payload?.jobs ?? []).map((job) => {+ const origin = job.origin;+ if (origin?.channel !== "websocket") return job;+ // Resolve UI-only titles from live sidebar state without changing task bindings.+ const title = displayTitle({+ key: origin.session_key ?? "", title: origin.title, preview: origin.preview ?? "",+ }, titleOverrides, t("chat.newChat"));+ return title === origin.title ? job : { ...job, origin: { ...origin, title } };+ }), [payload, titleOverrides, t]);const locale = i18n.resolvedLanguage || i18n.language;- const [selectedJobId, setSelectedJobId] = useState<string | null>(null);+ const [inspectedJob, setInspectedJob] = useState<SessionAutomationJob | null>(null);+ const [detailOpen, setDetailOpen] = useState(false);+ const [toolsOpen, setToolsOpen] = useState(Boolean(query) || filter !== "all" || sort !== "next");+ const [sortMenuOpen, setSortMenuOpen] = useState(false);+ const [systemOpen, setSystemOpen] = useState(() => {+ try {+ return window.localStorage.getItem(SYSTEM_TASKS_OPEN_STORAGE_KEY) !== "false";+ } catch {+ return true;+ }+ });+ const searchInput = useRef<HTMLInputElement | null>(null);+ const toolsToggle = useRef<HTMLButtonElement | null>(null);+ const pageTitle = useRef<HTMLHeadingElement | null>(null);+ const selectedTrigger = useRef<HTMLButtonElement | null>(null);+ const afterDetailClose = useRef<((job: SessionAutomationJob) => void) | null>(null);+ const toolsActive = Boolean(query) || filter !== "all" || sort !== "next";const filtered = useMemo(() => {const searchTokens = parseAutomationSearchQuery(query);return sortAutomationJobs(jobs, sort).filter((job) => automationMatchesFilter(job, filter)).filter((job) => !searchTokens.length || automationMatchesSearch(job, searchTokens));}, [filter, jobs, query, sort]);- const activeCount = jobs.filter((job) => {- const key = automationStatusKey(job);- return key === "active" || key === "running";- }).length;- const pausedCount = jobs.filter((job) => automationStatusKey(job) === "paused").length;- const failedCount = jobs.filter(automationNeedsAttention).length;- const systemCount = jobs.filter((job) => job.protected).length;+ const personalJobs = jobs.filter((job) => !job.protected);+ const personal = filtered.filter((job) => !job.protected);+ const system = filtered.filter((job) => job.protected);+ // Keep an inspected task open when an action moves it outside the current filter.+ const liveSelectedJob = jobs.find((job) => job.id === inspectedJob?.id);+ // Retain the last detail through its exit, even if a one-shot task disappears.+ const selectedJob = liveSelectedJob ?? inspectedJob;const summaryOptions: Array<{ value: AutomationFilter; label: string; count: number }> = [- { value: "all", label: tx("settings.automations.filters.all", "All"), count: jobs.length },- { value: "active", label: tx("settings.automations.filters.active", "Active"), count: activeCount },- { value: "paused", label: tx("settings.automations.filters.paused", "Paused"), count: pausedCount },- { value: "failed", label: tx("settings.automations.filters.failed", "Needs attention"), count: failedCount },- { value: "system", label: tx("settings.automations.filters.system", "System"), count: systemCount },+ { value: "all", label: tx("settings.automations.filters.all", "All"), count: personalJobs.length },+ { value: "active", label: tx("settings.automations.filters.active", "Active"),+ count: personalJobs.filter((job) => automationMatchesFilter(job, "active")).length },+ { value: "paused", label: tx("settings.automations.filters.paused", "Paused"),+ count: personalJobs.filter((job) => automationMatchesFilter(job, "paused")).length },+ { value: "failed", label: tx("settings.automations.filters.failed", "Needs attention"),+ count: personalJobs.filter(automationNeedsAttention).length },];const sortLabel = {next: tx("settings.automations.sort.next", "Next run"),@@ -113,268 +131,309 @@ export function AutomationsSettings({updated: tx("settings.automations.sort.updated", "Updated"),name: tx("settings.automations.sort.name", "Name"),} satisfies Record<AutomationSort, string>;- const selectedJob = filtered.find((job) => job.id === selectedJobId) ?? filtered[0] ?? null;useEffect(() => {- if (!filtered.length) {- if (selectedJobId !== null) setSelectedJobId(null);- return;- }- if (!selectedJobId || !filtered.some((job) => job.id === selectedJobId)) {- setSelectedJobId(filtered[0].id);- }- }, [filtered, selectedJobId]);+ if (liveSelectedJob) setInspectedJob(liveSelectedJob);+ else setDetailOpen(false);+ }, [liveSelectedJob]);++ useEffect(() => {+ if (query) setSystemOpen(true);+ }, [query]);++ useEffect(() => {+ if (toolsOpen) searchInput.current?.focus({ preventScroll: true });+ }, [toolsOpen]);++ const renderJob = (job: SessionAutomationJob) => (+ <AutomationListItem+ key={job.id}+ job={job}+ locale={locale}+ disabled={Boolean(job.protected) && !systemOpen}+ onSelect={(button) => {+ selectedTrigger.current = button;+ setInspectedJob(job);+ setDetailOpen(true);+ }}+ />+ );+ const handOff = (callback: (job: SessionAutomationJob) => void) => {+ // Restore the row before opening the next dialog, so it has a mounted+ // element to return focus to when editing or confirmation finishes.+ afterDetailClose.current = callback;+ setDetailOpen(false);+ };return (- <div className="automations-page space-y-5">+ <div className="automations-page">+ <header className="mb-6 flex items-center justify-between gap-4 sm:mb-8">+ <h1 ref={pageTitle} tabIndex={-1} className="text-[26px] font-semibold leading-tight tracking-[-0.025em] text-foreground outline-none sm:text-[30px]">+ {tx("settings.nav.automations", "Automations")}+ </h1>+ {jobs.length ? (+ <Button+ ref={toolsToggle}+ variant="ghost"+ size="icon"+ aria-label={tx("settings.automations.viewOptions", "Search and filter")}+ title={tx("settings.automations.viewOptions", "Search and filter")}+ aria-expanded={toolsOpen}+ aria-controls="automation-view-options"+ className={cn("h-9 w-9 shrink-0 rounded-full text-muted-foreground", toolsActive && "bg-muted text-foreground")}+ onClick={() => {+ setSortMenuOpen(false);+ setToolsOpen((value) => !value);+ }}+ >+ <SlidersHorizontal className="h-4 w-4" aria-hidden />+ </Button>+ ) : null}+ </header>+{jobs.length ? (- <section className="shrink-0">- <div className="flex w-full flex-col gap-3">- <div className="-mx-1 overflow-x-auto px-1 pb-0.5">- <div className="grid w-full min-w-[36rem] grid-cols-5 gap-1 rounded-floating bg-muted p-1">+ <DisclosureContent+ id="automation-view-options"+ open={toolsOpen}+ className="space-y-3 pb-5 pt-1"+ onKeyDown={(event) => {+ if (event.key !== "Escape" || event.defaultPrevented || event.nativeEvent.isComposing || sortMenuOpen) return;+ event.preventDefault();+ event.stopPropagation();+ toolsToggle.current?.focus({ preventScroll: true });+ setToolsOpen(false);+ }}+ >+ <div className="grid min-w-0 gap-2 sm:grid-cols-[minmax(0,1fr)_auto]">+ <div className="relative min-w-0">+ <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" aria-hidden />+ <Input+ ref={searchInput}+ disabled={!toolsOpen}+ value={query}+ onChange={(event) => onQueryChange(event.target.value)}+ aria-label={tx("settings.automations.search", "Search task, message, linked chat, or schedule")}+ placeholder={tx("settings.automations.search", "Search task, message, linked chat, or schedule")}+ className={cn("h-9 w-full rounded-full pl-9 text-[13px]", SETTINGS_SEARCH_INPUT_CLASS)}+ />+ </div>+ <DropdownMenu open={toolsOpen && sortMenuOpen} onOpenChange={setSortMenuOpen}>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" disabled={!toolsOpen} className="h-9 gap-2 rounded-full text-[12px] text-muted-foreground">+ <ArrowUpDown className="h-3.5 w-3.5" aria-hidden />+ {sortLabel[sort]}+ <ChevronDown className="h-3.5 w-3.5" aria-hidden />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {(Object.keys(sortLabel) as AutomationSort[]).map((value) => (+ <DropdownMenuItem key={value} onClick={() => onSortChange(value)}>+ <span>{sortLabel[value]}</span>+ {sort === value ? <Check className="ml-auto h-3.5 w-3.5" aria-hidden /> : null}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ <div role="group" aria-label={tx("settings.nav.automations", "Automations")} className="flex flex-wrap gap-1">{summaryOptions.map((option) => (<buttonkey={option.value}type="button"+ disabled={!toolsOpen}+ aria-pressed={filter === option.value}onClick={() => onFilterChange(option.value)}className={cn(- "inline-flex h-8 min-w-0 shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-control px-3 text-[12px] font-medium text-muted-foreground transition-colors",- filter === option.value && "bg-background text-foreground",- automationFilterToneClass(option.value, option.count, filter === option.value),+ "touch-target inline-flex min-h-8 max-w-full items-center gap-2 rounded-full px-3 py-1.5 text-[12px] text-muted-foreground transition-colors hover:text-foreground",+ filter === option.value && "bg-muted text-foreground",)}>- <span>{option.label}</span>- <span- className={cn(- "min-w-5 shrink-0 rounded-full bg-background/75 px-1.5 py-0.5 text-center text-[11px] tabular-nums text-muted-foreground",- automationFilterCountClass(option.value, option.count),- )}- >- {option.count}- </span>+ <span className="min-w-0 [overflow-wrap:anywhere]">{option.label}</span>+ <span className="shrink-0 text-[11px] tabular-nums text-muted-foreground">{option.count}</span></button>))}</div>- </div>-- <div className="grid min-w-0 gap-2 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center">- <div className="relative min-w-0">- <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/70" />- <Input- value={query}- onChange={(event) => onQueryChange(event.target.value)}- placeholder={tx(- "settings.automations.search",- "Search task, message, linked chat, or schedule",- )}- className={cn(- "h-9 w-full rounded-full pl-9 text-[13px]",- SETTINGS_SEARCH_INPUT_CLASS,- )}- />- </div>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button- type="button"- className="inline-flex h-9 min-w-[8.5rem] items-center justify-center gap-1.5 whitespace-nowrap rounded-control border border-border/45 bg-settings-surface px-3 text-[12px] font-medium text-muted-foreground transition-colors settings-hover hover:text-foreground sm:w-auto"- >- <ArrowUpDown className="h-3.5 w-3.5" aria-hidden />- <span>{sortLabel[sort]}</span>- <ChevronDown className="h-3.5 w-3.5" aria-hidden />- </button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="min-w-40">- {(Object.keys(sortLabel) as AutomationSort[]).map((value) => (- <DropdownMenuItem key={value} onClick={() => onSortChange(value)}>- <span>{sortLabel[value]}</span>- {sort === value ? <Check className="ml-auto h-3.5 w-3.5" aria-hidden /> : null}- </DropdownMenuItem>- ))}- </DropdownMenuContent>- </DropdownMenu>- </div>- </div>- </section>- ) : null}-- {error ? (- <div className="flex items-center gap-2 rounded-floating border border-destructive/20 bg-destructive/5 px-4 py-3 text-[13px] text-destructive">- <CircleAlert className="h-4 w-4 shrink-0" aria-hidden />- <span>{error}</span>- </div>+ </DisclosureContent>) : null}+ {error ? <AutomationError message={error} /> : null}{loading && !payload ? (- <div className="flex h-44 items-center justify-center rounded-panel bg-settings-surface text-[13px] text-muted-foreground">+ <div role="status" className="flex h-44 items-center justify-center text-[13px] text-muted-foreground"><Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden />{tx("settings.automations.loading", "Loading automations...")}</div>- ) : filtered.length && selectedJob ? (- <section className="automations-workspace grid min-h-0 overflow-hidden rounded-panel bg-settings-surface">- <aside className="automations-queue flex min-h-0 flex-col overflow-hidden border-b border-border/35 bg-settings-surface">- <div className="flex shrink-0 items-center justify-between gap-3 px-4 py-3">- <h2 className="text-[13px] font-semibold tracking-[-0.01em] text-foreground/85">- {tx("settings.automations.queue", "Queue")}- </h2>- <span className="rounded-full bg-orange-100/60 px-2 py-0.5 text-[11px] text-orange-800/70 tabular-nums dark:bg-orange-300/10 dark:text-orange-200/75">- {filtered.length}- </span>+ ) : (+ <>+ {personal.length ? (+ <ul aria-label={tx("settings.automations.yourTasks", "Your automations")} className="divide-y divide-border/45">+ {personal.map(renderJob)}+ </ul>+ ) : !personalJobs.length && !query && filter === "all" ? (+ <div className="py-12 text-center sm:py-16">+ <p className="text-[17px] font-medium text-foreground">+ {tx("settings.automations.empty", "No automations yet.")}+ </p>+ <p className="mx-auto mt-2 max-w-sm text-[13px] leading-6 text-muted-foreground">+ {tx("settings.automations.emptyHint", "Tell nanobot in a chat what you'd like it to do on a schedule.")}+ </p></div>- <div- className="automations-queue-list max-h-[28rem] space-y-1 overflow-y-auto overscroll-contain px-2 pb-2"- role="list"- aria-label={tx("settings.automations.queue", "Queue")}- >- {filtered.map((job) => (- <AutomationListItem- key={job.id}- job={job}- locale={locale}- selected={job.id === selectedJob.id}- onSelect={() => setSelectedJobId(job.id)}- />- ))}+ ) : !filtered.length ? (+ <div className="py-12 text-center text-[13px] text-muted-foreground">+ <p>{tx("settings.automations.noMatches", "No automations match this view.")}</p>+ <Button variant="outline" className="mt-4 rounded-full" onClick={() => {+ onQueryChange("");+ onFilterChange("all");+ }}>+ {tx("settings.automations.clearFilters", "Clear filters")}+ </Button></div>- </aside>- <AutomationDetailPanel- job={selectedJob}- locale={locale}- actionKey={actionKey}- onAction={onAction}- onRequestEdit={onRequestEdit}- onRequestDelete={onRequestDelete}- />- </section>- ) : (- <div className="rounded-panel bg-settings-surface px-5 py-12 text-center text-[13px] text-muted-foreground">- <div>- {jobs.length- ? tx("settings.automations.noMatches", "No automations match this view.")- : tx("settings.automations.empty", "No automations yet.")}- </div>- {!jobs.length ? (- <>- <div className="mx-auto mt-2 max-w-[28rem] text-[12px] leading-5">- {tx(- "settings.automations.emptyHint",- "Create automations in a chat so they keep the right context.",- )}- </div>- <Button+ ) : null}+ {system.length ? (+ <section className="mt-8 border-t border-border/45 pt-2">+ <buttontype="button"- variant="outline"- className="mt-4 rounded-full"- onClick={onBackToChat}+ aria-expanded={systemOpen}+ aria-controls="automation-system-tasks"+ onClick={() => {+ const open = !systemOpen;+ setSystemOpen(open);+ try {+ // Persist only the user's choice, not automatic search expansion.+ window.localStorage.setItem(SYSTEM_TASKS_OPEN_STORAGE_KEY, String(open));+ } catch {+ // Unavailable storage must not prevent expanding or collapsing.+ }+ }}+ className={cn("flex min-h-16 w-full items-center gap-3 rounded-lg py-4 text-left text-[14px] font-medium", formControlFocusClassName)}>- {tx("settings.automations.emptyAction", "Open a chat")}- </Button>- </>- ) : (- <Button- type="button"- variant="outline"- className="mt-4 rounded-full"- onClick={() => {- onQueryChange("");- onFilterChange("all");- }}- >- {tx("settings.automations.clearFilters", "Clear filters")}- </Button>- )}- </div>+ <span>{tx("settings.automations.systemTasks", "System tasks")}</span>+ <span className="text-[12px] font-normal tabular-nums text-muted-foreground">{system.length}</span>+ {system.some(automationNeedsAttention) ? (+ <span className="ml-auto inline-flex items-center gap-1.5 text-[12px] font-normal text-amber-700 dark:text-amber-400">+ <CircleAlert className="h-3.5 w-3.5" aria-hidden />+ {tx("settings.automations.filters.failed", "Needs attention")}+ </span>+ ) : null}+ <ChevronRight className={cn("ml-auto h-4 w-4 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none", systemOpen && "rotate-90")} aria-hidden />+ </button>+ <DisclosureContent+ id="automation-system-tasks"+ open={systemOpen}+ >+ <SettingsGroup>+ <ul aria-label={tx("settings.automations.systemTasks", "System tasks")} className="divide-y divide-border/45">+ {system.map(renderJob)}+ </ul>+ </SettingsGroup>+ </DisclosureContent>+ </section>+ ) : null}+ </>)}++ <Dialog open={detailOpen} onOpenChange={setDetailOpen}>+ {selectedJob ? (+ <DialogContent+ {...(selectedJob.protected ? { "aria-describedby": undefined } : {})}+ {...(!detailOpen ? { inert: "", "aria-hidden": true } : {})}+ showCloseButton={false}+ overlayClassName="bg-black/15 backdrop-blur-none"+ className={cn(+ "flex max-h-[calc(100dvh-2rem)] max-w-[520px] flex-col gap-0 overflow-hidden rounded-[20px] p-0",+ selectedJob.protected && "max-w-[440px]",+ )}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ if (detailOpen) return;+ setInspectedJob(null);+ const target = selectedTrigger.current?.isConnected+ ? selectedTrigger.current : toolsToggle.current ?? pageTitle.current;+ target?.focus({ preventScroll: true });+ const next = afterDetailClose.current;+ afterDetailClose.current = null;+ if (liveSelectedJob) next?.(liveSelectedJob);+ }}+ >+ <AutomationDetailPanel+ key={selectedJob.id}+ job={selectedJob}+ locale={locale}+ actionKey={actionKey}+ error={error}+ onClose={() => setDetailOpen(false)}+ onAction={onAction}+ onRequestEdit={() => handOff(onRequestEdit)}+ onRequestDelete={() => handOff(onRequestDelete)}+ />+ </DialogContent>+ ) : null}+ </Dialog></div>);}-function AutomationListItem({- job,- locale,- selected,- onSelect,-}: {+function AutomationListItem({ job, locale, disabled, onSelect }: {job: SessionAutomationJob;locale: string;- selected: boolean;- onSelect: () => void;+ disabled: boolean;+ onSelect: (button: HTMLButtonElement) => void;}) {const { t } = useTranslation();const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>t(key, { defaultValue: fallback, ...(values ?? {}) });- const status = automationStatus(job, tx);- const origin = automationOriginLabel(job, t);- const nextRun = formatAutomationNext(job, tx);- const summary = automationSummary(job, tx);-+ const attention = automationNeedsAttention(job);+ const compact = Boolean(job.protected);+ const summary = job.state.last_error || (compact ? null : automationSummary(job, tx));+ const running = Boolean(job.state.pending);return (- <div role="listitem">+ <li><buttontype="button"- aria-pressed={selected}- onClick={onSelect}+ disabled={disabled}+ aria-haspopup="dialog"+ onClick={(event) => onSelect(event.currentTarget)}className={cn(- "group grid w-full grid-cols-[minmax(0,1fr)_auto] gap-3 rounded-floating px-3 py-3.5 text-left transition-colors",- selected- ? "bg-background/80 text-foreground"- : "text-muted-foreground settings-hover hover:text-foreground",+ "automation-task-row group grid w-full grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-2 text-left transition-colors",+ compact ? "settings-list-row py-3 settings-hover" : "min-h-[92px] rounded-lg py-5 hover:bg-muted/35",+ formControlFocusClassName,)}><span className="min-w-0">- <span className="flex min-w-0 items-center gap-2.5">- <span- className={cn("h-2 w-2 shrink-0 rounded-full", automationStatusDotClass(job))}- aria-hidden- />- <span className="truncate text-[13.5px] font-medium text-foreground">- {job.name || job.id}- </span>- </span>- <span className="mt-1.5 line-clamp-2 text-[12px] leading-5 text-muted-foreground">- {summary}- </span>- <span className="mt-2.5 flex min-w-0 items-center gap-2 text-[11.5px] leading-none text-muted-foreground">- <span className="truncate" title={formatAutomationNextTitle(job, locale, tx)}>- {nextRun}- </span>- <span className="h-1 w-1 shrink-0 rounded-full bg-muted-foreground/35" aria-hidden />- <span className="truncate">{origin}</span>- </span>+ <span className={cn(+ "block truncate font-medium text-foreground",+ compact ? "text-[14px] leading-5" : "text-[16px] leading-6 tracking-[-0.015em] sm:text-[17px]",+ )}>{job.name || job.id}</span>+ {summary ? <span className="mt-1 block truncate text-[13px] leading-5 text-muted-foreground">{summary}</span> : null}</span>- <span className="flex shrink-0 flex-col items-end gap-2 pt-0.5">- <span className="rounded-full bg-background/70 px-2 py-0.5 text-[11px] font-medium text-muted-foreground">- {status.label}- </span>- {job.delete_after_run ? (- <span className="rounded-full bg-background/80 px-2 py-0.5 text-[11px] font-medium text-muted-foreground">- {tx("settings.automations.oneShot", "One-time")}- </span>- ) : null}- <ChevronRight- className={cn(- "h-3.5 w-3.5 text-muted-foreground/55 transition-opacity",- selected ? "opacity-100" : "opacity-0 group-hover:opacity-70",- )}- aria-hidden- />+ <span className={cn(+ "automation-task-state flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-[12px] text-muted-foreground",+ !compact && "sm:text-[13px]",+ )}>+ {running ? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden /> : null}+ {attention && !running ? (+ <>+ <CircleAlert className="h-4 w-4 shrink-0 text-amber-700 dark:text-amber-400" aria-hidden />+ <span className="text-amber-700 dark:text-amber-400">{tx("settings.automations.filters.failed", "Needs attention")}</span>+ {!job.enabled ? <span>· {tx("settings.automations.next.paused", "Paused")}</span> : null}+ </>+ ) : (+ <span title={formatAutomationNextTitle(job, locale, tx)}>{formatAutomationNext(job, tx)}</span>+ )}</span>+ <ChevronRight className="automation-task-chevron h-4 w-4 text-muted-foreground/70" aria-hidden /></button>- </div>+ </li>);}function AutomationDetailPanel({- job,- locale,- actionKey,- onAction,- onRequestEdit,- onRequestDelete,+ job, locale, actionKey, error, onClose, onAction, onRequestEdit, onRequestDelete,}: {job: SessionAutomationJob;locale: string;actionKey: string | null;+ error: string | null;+ onClose: () => void;onAction: (action: AutomationAction, job: SessionAutomationJob) => void | Promise<void>;onRequestEdit: (job: SessionAutomationJob) => void;onRequestDelete: (job: SessionAutomationJob) => void;@@ -382,318 +441,178 @@ function AutomationDetailPanel({const { t } = useTranslation();const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>t(key, { defaultValue: fallback, ...(values ?? {}) });- const status = automationStatus(job, tx);const origin = automationOriginLabel(job, t);const originHref = job.origin?.channel === "websocket" && job.origin.session_key- ? `#/chat/${encodeURIComponent(job.origin.session_key)}`- : null;- const created = job.created_at_ms ? fmtDateTime(job.created_at_ms, locale) : null;- const updated = job.updated_at_ms ? fmtDateTime(job.updated_at_ms, locale) : null;+ ? `#/chat/${encodeURIComponent(job.origin.session_key)}` : null;const localTrigger = isLocalTriggerAutomation(job);- const triggerCommand = automationTriggerCommand(job);+ const command = automationTriggerCommand(job);const message = automationDetailText(job, tx);- const messageLabel = localTrigger- ? tx("settings.automations.fields.command", "Command")- : tx("settings.automations.fields.message", "Message");- const schedule = formatAutomationSchedule(job, locale, tx);const [messageExpanded, setMessageExpanded] = useState(false);+ const messageId = useId();const [commandCopied, setCommandCopied] = useState(false);const messageNeedsExpansion = automationMessageNeedsExpansion(message);-- useEffect(() => {- setMessageExpanded(false);- setCommandCopied(false);- }, [job.id]);+ const busy = Boolean(actionKey);+ const canManage = !job.protected;+ const canToggle = canManage && (job.enabled || Boolean(job.origin));+ const canRun = canManage && Boolean(job.origin) && job.enabled && !job.state.pending && !localTrigger;+ const lastStatus = job.state.last_status === "ok"+ ? tx("settings.automations.status.completed", "Completed")+ : job.state.last_status === "error"+ ? tx("settings.automations.status.failed", "Failed")+ : job.state.last_status === "skipped"+ ? tx("settings.automations.skipped", "Skipped")+ : job.state.last_status;return (- <article className="automation-detail-panel flex min-h-0 min-w-0 flex-col overflow-hidden bg-settings-surface">- <div className="shrink-0 border-b border-border/35 px-4 py-3.5 dark:border-white/10 sm:px-5">- <div className="flex flex-wrap items-start justify-between gap-3">- <div className="min-w-0">- <div className="flex min-w-0 flex-wrap items-center gap-2">- <h3 className="min-w-0 truncate text-[18px] font-medium leading-7 text-foreground">- {job.name || job.id}- </h3>- <AutomationStatusBadge tone={status.tone}>{status.label}</AutomationStatusBadge>- {job.delete_after_run ? (- <AutomationStatusBadge>{tx("settings.automations.oneShot", "One-time")}</AutomationStatusBadge>- ) : null}- </div>- <p className="mt-1 truncate text-[12.5px] leading-5 text-muted-foreground">- {schedule} · {origin}- </p>- </div>- <AutomationActionGroup- job={job}- actionKey={actionKey}- onAction={onAction}- onRequestEdit={onRequestEdit}- onRequestDelete={onRequestDelete}- />+ <>+ <div className="shrink-0 px-6 pb-5 pt-6 sm:px-7 sm:pt-7">+ <div className="flex items-start justify-between gap-4">+ <DialogTitle className="min-w-0 break-words text-[22px] font-semibold leading-7 tracking-[-0.025em]">{job.name || job.id}</DialogTitle>+ <Button variant="ghost" size="sm" className={cn("-mr-2 -mt-1 shrink-0 rounded-full text-[13px] text-muted-foreground", job.protected && "text-foreground")} onClick={onClose}>+ {tx("settings.automations.done", "Done")}+ </Button></div>+ {canManage ? (+ <DialogDescription className="mt-2 text-[13px] leading-5">+ {formatAutomationSchedule(job, locale, tx)} · {formatAutomationNext(job, tx)}+ </DialogDescription>+ ) : null}</div>-- <div className="automation-detail-body grid min-h-0 min-w-0 flex-1 overflow-hidden">- <div className="min-h-0 min-w-0 space-y-3 overflow-y-auto overscroll-contain p-4 sm:p-5">- <section className="rounded-floating bg-background/55 px-4 py-3.5">- <div className="flex items-center justify-between gap-3">- <div className="text-[11px] font-medium leading-none text-muted-foreground/75">- {messageLabel}- </div>- {localTrigger && triggerCommand ? (- <Button- type="button"- variant="ghost"- size="sm"- className="h-7 shrink-0 rounded-full px-2 text-[11.5px]"- onClick={() => {- void copyTextToClipboard(triggerCommand).then((ok) => {- if (ok) setCommandCopied(true);- });- }}- >- {commandCopied ? (- <Check className="mr-1.5 h-3.5 w-3.5" aria-hidden />- ) : (- <Clipboard className="mr-1.5 h-3.5 w-3.5" aria-hidden />- )}- {commandCopied- ? tx("settings.automations.commandCopied", "Copied")- : tx("settings.automations.copyCommand", "Copy")}- </Button>- ) : null}- </div>- <div- className={cn(- "mt-3 whitespace-pre-wrap break-words text-[13px] leading-6 text-foreground/85",- localTrigger && "font-mono text-[12.5px]",- !messageExpanded && messageNeedsExpansion && "line-clamp-6",- )}- >- {message}- </div>- {messageNeedsExpansion ? (- <button- type="button"- className="mt-3 inline-flex text-[12px] font-medium text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"- onClick={() => setMessageExpanded((value) => !value)}- >- {messageExpanded- ? tx("settings.automations.message.showLess", "Show less")- : tx("settings.automations.message.showMore", "Show full message")}- </button>+ <div className={cn("min-h-0 overflow-y-auto overscroll-contain px-6 pb-6 sm:px-7", job.protected && "pb-3")}>+ {canManage ? <section className="pb-6 pt-2">+ <div className="flex items-center justify-between gap-3 text-[12px] text-muted-foreground">+ <span>{localTrigger ? tx("settings.automations.fields.command", "Command") : tx("settings.automations.instructions", "Instructions")}</span>+ {localTrigger && command ? (+ <Button variant="ghost" size="sm" className="h-7 rounded-full px-2 text-[12px]" onClick={() => {+ void copyTextToClipboard(command).then((ok) => { if (ok) setCommandCopied(true); });+ }}>+ {commandCopied ? <Check className="mr-1.5 h-3.5 w-3.5" aria-hidden /> : <Clipboard className="mr-1.5 h-3.5 w-3.5" aria-hidden />}+ {commandCopied ? tx("settings.automations.commandCopied", "Copied") : tx("settings.automations.copyCommand", "Copy")}+ </Button>) : null}- </section>-- <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,10rem),1fr))] gap-3">- <AutomationDetail- label={tx("settings.automations.labels.next", "Next")}- title={formatAutomationNextTitle(job, locale, tx)}- >- {formatAutomationNext(job, tx)}- </AutomationDetail>- <AutomationDetail label={tx("settings.automations.labels.origin", "Linked chat")} title={origin}>+ </div>+ <div className="mt-2">+ <ExpandableText id={messageId} expanded={messageExpanded || !messageNeedsExpansion} lines={6} className={cn("whitespace-pre-wrap break-words text-[14px] leading-6 text-foreground/90 [overflow-wrap:anywhere]", localTrigger && "font-mono text-[12px]")}>+ {message}+ </ExpandableText>+ </div>+ {messageNeedsExpansion ? (+ <button type="button" aria-expanded={messageExpanded} aria-controls={messageId} onClick={() => setMessageExpanded((value) => !value)} className="mt-2 rounded-sm text-[12px] text-muted-foreground underline-offset-4 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ {messageExpanded ? tx("settings.automations.message.showLess", "Show less") : tx("settings.automations.message.showMore", "Show full message")}+ </button>+ ) : null}+ </section> : null}+ {job.state.last_error ? <AutomationError message={job.state.last_error} /> : null}+ {error ? <AutomationError message={error} /> : null}+ <dl className="divide-y divide-border/45 border-y border-border/45">+ {job.protected ? (+ <>+ <AutomationDetail label={tx("settings.automations.labels.schedule", "Schedule")}>+ {formatAutomationSchedule(job, locale, tx)}+ </AutomationDetail>+ <AutomationDetail label={tx("settings.automations.sort.next", "Next run")} title={formatAutomationNextTitle(job, locale, tx)}>+ {formatAutomationNext(job, tx)}+ </AutomationDetail>+ </>+ ) : null}+ <AutomationDetail label={tx("settings.automations.sort.last", "Last run")} title={job.state.last_run_at_ms ? fmtDateTime(job.state.last_run_at_ms, locale) : undefined}>+ {job.state.last_run_at_ms+ ? [lastStatus, relativeTime(job.state.last_run_at_ms)].filter(Boolean).join(" · ")+ : lastStatus || tx("settings.automations.neverRun", "Not run yet")}+ </AutomationDetail>+ {!job.protected ? (+ <AutomationDetail label={tx("settings.automations.labels.origin", "Linked chat")}>{originHref ? (- <a- className="inline-flex max-w-full items-center gap-1 text-foreground/80 underline-offset-2 hover:underline"- href={originHref}- >+ <a href={originHref} className="inline-flex min-w-0 max-w-full items-center gap-2 hover:text-foreground hover:underline"><span className="truncate">{origin}</span>- <ExternalLink className="h-3 w-3 shrink-0" aria-hidden />+ <ChevronRight className="h-3.5 w-3.5 shrink-0" aria-hidden /></a>- ) : (- origin- )}+ ) : origin}</AutomationDetail>- </div>-- {job.state.last_error ? (- <div className="rounded-floating border border-destructive/20 bg-destructive/8 px-3 py-2 text-[12px] leading-5 text-destructive">- {job.state.last_error}- </div>) : null}- </div>-- <aside className="automation-detail-metadata min-h-0 overflow-y-auto overscroll-contain border-t border-border/35 bg-settings-surface p-4 text-[12px] text-muted-foreground">- <div className="grid gap-3">- <AutomationDetail- label={tx("settings.automations.labels.schedule", "Schedule")}- title={schedule}- >- {schedule}- </AutomationDetail>- <div className="rounded-floating bg-background/55 p-3">- <div className="grid gap-3">- {created ? (- <div>- <div className="text-[11px] leading-none text-muted-foreground/75">- {tx("settings.automations.labels.created", "Created")}- </div>- <div className="mt-1.5 text-[12.5px] leading-5 text-foreground/80">{created}</div>- </div>- ) : null}- {updated ? (- <div>- <div className="text-[11px] leading-none text-muted-foreground/75">- {tx("settings.automations.labels.updated", "Updated")}- </div>- <div className="mt-1.5 text-[12.5px] leading-5 text-foreground/80">{updated}</div>- </div>- ) : null}- <div>- <div className="text-[11px] leading-none text-muted-foreground/75">ID</div>- <div className="mt-1.5 break-all font-mono text-[11.5px] leading-5 text-foreground/70">- {job.id}- </div>- </div>- </div>- </div>- </div>- </aside>- </div>- </article>- );-}--function AutomationActionGroup({- job,- actionKey,- onAction,- onRequestEdit,- onRequestDelete,-}: {- job: SessionAutomationJob;- actionKey: string | null;- onAction: (action: AutomationAction, job: SessionAutomationJob) => void | Promise<void>;- onRequestEdit: (job: SessionAutomationJob) => void;- onRequestDelete: (job: SessionAutomationJob) => void;-}) {- const { t } = useTranslation();- const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>- t(key, { defaultValue: fallback, ...(values ?? {}) });- const canManage = !job.protected;- const hasLinkedChat = Boolean(job.origin);- const localTrigger = isLocalTriggerAutomation(job);- const canRun = canManage && hasLinkedChat && job.enabled && !job.state.pending && !localTrigger;- const toggleAction: AutomationAction = job.enabled ? "disable" : "enable";- const canToggle = canManage && (job.enabled || hasLinkedChat);- const toggleBusy = actionKey === `${toggleAction}:${job.id}`;-- if (!canManage) {- return (- <span className="inline-flex h-9 items-center rounded-full bg-muted px-3 text-[12px] font-medium text-muted-foreground">- {tx("settings.automations.protected", "Protected")}- </span>- );- }-- return (- <div className="flex shrink-0 items-center gap-1 rounded-full bg-background/65 p-1">- <AppsActionButton- ariaLabel={tx("settings.automations.edit", "Edit")}- disabled={Boolean(actionKey)}- onClick={() => onRequestEdit(job)}- >- <Pencil className="h-4 w-4" aria-hidden />- </AppsActionButton>- {!localTrigger ? (- <AppsActionButton- ariaLabel={tx("settings.automations.runNow", "Run now")}- busy={actionKey === `run:${job.id}`}- disabled={!canRun}- onClick={() => void onAction("run", job)}+ </dl>+ <Disclosure+ className={cn("mt-3", job.protected && "mt-1")}+ summaryClassName={cn("flex cursor-pointer items-center justify-between gap-3 rounded-lg py-4 text-[13px] text-muted-foreground", job.protected && "py-3", formControlFocusClassName)}+ summary={<>+ {tx("settings.automations.moreDetails", "More details")}+ <ChevronRight className="h-3.5 w-3.5 transition-transform duration-200 group-data-[state=open]/disclosure:rotate-90 motion-reduce:transition-none" aria-hidden />+ </>}>- <PlayCircle className="h-4 w-4" aria-hidden />- </AppsActionButton>+ <dl className="divide-y divide-border/45">+ {job.delete_after_run ? <AutomationDetail label={tx("settings.automations.oneShot", "One-time")}>{tx("settings.automations.oneShotHint", "Removed after running")}</AutomationDetail> : null}+ {job.created_at_ms ? <AutomationDetail label={tx("settings.automations.labels.created", "Created")}>{fmtDateTime(job.created_at_ms, locale)}</AutomationDetail> : null}+ {job.updated_at_ms ? <AutomationDetail label={tx("settings.automations.labels.updated", "Updated")}>{fmtDateTime(job.updated_at_ms, locale)}</AutomationDetail> : null}+ <AutomationDetail label="ID"><span className="break-all font-mono text-[11px]">{job.id}</span></AutomationDetail>+ </dl>+ </Disclosure>+ </div>+ {canManage ? (+ <div className="flex shrink-0 flex-wrap items-center gap-2 border-t border-border/45 px-5 py-4 sm:px-7">+ <Button variant="ghost" size="sm" className="rounded-full px-2 text-[13px] text-muted-foreground" disabled={busy || !canToggle} onClick={() => void onAction(job.enabled ? "disable" : "enable", job)}>+ {actionKey === `${job.enabled ? "disable" : "enable"}:${job.id}` ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden /> : null}+ {job.enabled ? tx("settings.automations.pause", "Pause") : tx("settings.automations.resume", "Resume")}+ </Button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="icon" className="h-8 w-8 rounded-full text-muted-foreground" disabled={busy} aria-label={tx("settings.automations.moreActions", "More actions")}>+ <MoreHorizontal className="h-4 w-4" aria-hidden />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start">+ {!localTrigger ? <DropdownMenuItem disabled={!canRun || busy} onClick={() => void onAction("run", job)}>{tx("settings.automations.runNow", "Run now")}</DropdownMenuItem> : null}+ <DropdownMenuItem disabled={busy} onClick={() => onRequestDelete(job)} className="text-destructive focus:text-destructive">{tx("settings.automations.delete", "Delete")}</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <Button variant="outline" size="sm" className="ml-auto rounded-full px-4" disabled={busy} onClick={() => onRequestEdit(job)}>+ {tx("settings.automations.edit", "Edit")}+ </Button>+ {originHref ? <Button asChild size="sm" className="rounded-full px-4"><a href={originHref}>{tx("settings.automations.emptyAction", "Open a chat")}</a></Button> : null}+ </div>) : null}- <AppsActionButton- ariaLabel={- job.enabled- ? tx("settings.automations.pause", "Pause")- : tx("settings.automations.resume", "Resume")- }- busy={toggleBusy}- disabled={!canToggle}- onClick={() => void onAction(toggleAction, job)}- >- {job.enabled ? (- <PauseCircle className="h-4 w-4" aria-hidden />- ) : (- <PlayCircle className="h-4 w-4" aria-hidden />- )}- </AppsActionButton>- <AppsActionButton- ariaLabel={tx("settings.automations.delete", "Delete")}- tone="danger"- disabled={Boolean(actionKey)}- onClick={() => onRequestDelete(job)}- >- <Trash2 className="h-4 w-4" aria-hidden />- </AppsActionButton>- </div>+ </>);}-function AutomationStatusBadge({- tone = "neutral",- children,-}: {- tone?: "neutral" | "success" | "warning";- children: ReactNode;-}) {- return (- <span- className={cn(- "inline-flex h-6 items-center rounded-full px-2.5 text-[11.5px] font-medium",- tone === "success" &&- "bg-orange-100/72 text-orange-800 dark:bg-orange-300/12 dark:text-orange-200",- tone === "warning" &&- "bg-amber-100/80 text-amber-800 dark:bg-amber-300/14 dark:text-amber-200",- tone === "neutral" &&- "bg-white/64 text-muted-foreground dark:bg-background/35 dark:text-muted-foreground",- )}- >- {children}- </span>- );+function AutomationError({ message }: { message: string }) {+ return <div role="alert" className="mb-4 flex items-start gap-2 rounded-lg bg-destructive/5 px-3 py-2.5 text-[13px] leading-5 text-destructive">+ <CircleAlert className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />+ <span className="min-w-0 break-words [overflow-wrap:anywhere]">{message}</span>+ </div>;}function automationMessageNeedsExpansion(message: string): boolean {return message.length > 360 || message.split(/\r?\n/).length > 6;}-function AutomationDetail({- label,- title,- secondary,- children,-}: {- label: string;- title?: string;- secondary?: ReactNode;- children: ReactNode;-}) {+function AutomationDetail({ label, title, children }: { label: string; title?: string; children: ReactNode }) {return (- <div className="min-w-0 rounded-floating bg-background/55 px-3 py-3">- <div className="text-[11px] font-medium leading-none text-muted-foreground/75">- {label}- </div>- <div className="mt-1.5 min-w-0">- <div className="line-clamp-2 text-[13px] leading-5 text-foreground/85" title={title}>- {children}- </div>- {secondary ? (- <div className="mt-0.5 truncate text-[11.5px] leading-4 text-muted-foreground" title={title}>- {secondary}- </div>- ) : null}- </div>+ <div className="grid min-w-0 grid-cols-[minmax(0,1fr)_minmax(0,1.7fr)] items-start gap-4 py-3.5 text-[13px] leading-5">+ <dt className="text-muted-foreground">{label}</dt>+ <dd className="min-w-0 break-words text-right text-foreground/85 [overflow-wrap:anywhere]" title={title}>{children}</dd></div>);}type AutomationEveryUnit = "second" | "minute" | "hour" | "day";+// These dialogs are opened programmatically, without a mounted DialogTrigger.+function useAutomationDialogFocus() {+ const previousFocus = useRef<HTMLElement | null>(null);+ return {+ onOpenAutoFocus: (event: Event) => {+ previousFocus.current = document.activeElement instanceof HTMLElement+ ? document.activeElement : null;+ event.preventDefault();+ if (event.target instanceof HTMLElement) event.target.focus({ preventScroll: true });+ },+ onCloseAutoFocus: (event: Event) => {+ event.preventDefault();+ previousFocus.current?.focus({ preventScroll: true });+ },+ };+}+type AutomationEditDraft = {name: string;message: string;@@ -724,6 +643,7 @@ export function AutomationEditDialog({onOpenChange: (open: boolean) => void;onSave: (job: SessionAutomationJob, values: AutomationUpdatePayload) => void | Promise<void>;}) {+ const dialogFocus = useAutomationDialogFocus();const { t } = useTranslation();const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>t(key, { defaultValue: fallback, ...(values ?? {}) });@@ -758,6 +678,7 @@ export function AutomationEditDialog({<Dialog open={Boolean(job)} onOpenChange={onOpenChange}>{job ? (<DialogContent+ {...dialogFocus}aria-describedby={undefined}className="w-[min(calc(100vw-2rem),34rem)]">@@ -930,12 +851,13 @@ export function AutomationDeleteDialog({onOpenChange: (open: boolean) => void;onConfirm: (job: SessionAutomationJob) => void | Promise<void>;}) {+ const dialogFocus = useAutomationDialogFocus();const { t } = useTranslation();const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>t(key, { defaultValue: fallback, ...(values ?? {}) });return (<Dialog open={Boolean(job)} onOpenChange={onOpenChange}>- <DialogContent className="w-[min(calc(100vw-2rem),26rem)]">+ <DialogContent {...dialogFocus} className="w-[min(calc(100vw-2rem),26rem)]"><DialogHeader><DialogTitle>{tx("settings.automations.deleteTitle", "Delete automation")}</DialogTitle><DialogDescription>@@ -1300,63 +1222,6 @@ function automationMatchesFilter(job: SessionAutomationJob, filter: AutomationFireturn true;}-const AUTOMATION_FILTER_TONES: Partial<- Record<AutomationFilter, { text: string; selectedText: string; count: string }>-> = {- active: {- text: "text-emerald-600 dark:text-emerald-400",- selectedText: "text-emerald-700 dark:text-emerald-300",- count: "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",- },- paused: {- text: "text-amber-600 dark:text-amber-400",- selectedText: "text-amber-700 dark:text-amber-300",- count: "bg-amber-500/10 text-amber-700 dark:text-amber-300",- },- failed: {- text: "text-rose-600 dark:text-rose-400",- selectedText: "text-rose-700 dark:text-rose-300",- count: "bg-rose-500/10 text-rose-700 dark:text-rose-300",- },- system: {- text: "text-sky-600 dark:text-sky-400",- selectedText: "text-sky-700 dark:text-sky-300",- count: "bg-sky-500/10 text-sky-700 dark:text-sky-300",- },-};--function automationFilterToneClass(value: AutomationFilter, count: number, selected: boolean): string {- const tone = AUTOMATION_FILTER_TONES[value];- if (count <= 0 || !tone) return "";- return selected ? tone.selectedText : tone.text;-}--function automationFilterCountClass(value: AutomationFilter, count: number): string {- const tone = AUTOMATION_FILTER_TONES[value];- return count > 0 && tone ? tone.count : "";-}--function automationStatus(- job: SessionAutomationJob,- tx: (key: string, fallback: string, values?: Record<string, unknown>) => string,-): { label: string; tone: "neutral" | "success" | "warning" } {- const status = automationStatusKey(job);- if (status === "system") return { label: tx("settings.automations.status.system", "System"), tone: "neutral" };- if (status === "running") {- return { label: tx("settings.automations.status.running", "Running now"), tone: "warning" };- }- if (status === "paused") return { label: tx("settings.automations.status.paused", "Paused"), tone: "neutral" };- if (status === "failed") {- return { label: tx("settings.automations.status.failed", "Failed"), tone: "warning" };- }- if (status === "completed") {- return { label: tx("settings.automations.status.completed", "Completed"), tone: "neutral" };- }- if (status === "idle") {- return { label: tx("settings.automations.status.noSchedule", "No schedule"), tone: "neutral" };- }- return { label: tx("settings.automations.status.active", "Active"), tone: "success" };-}function automationOriginLabel(job: SessionAutomationJob,@@ -1481,6 +1346,9 @@ function formatAutomationNext(if (isLocalTriggerAutomation(job)) {return tx("settings.automations.next.local", "Waiting for trigger");}+ if (automationStatusKey(job) === "completed") {+ return tx("settings.automations.status.completed", "Completed");+ }if (!job.state.next_run_at_ms) return tx("settings.automations.next.none", "No next run");return relativeTime(job.state.next_run_at_ms);}@@ -1494,13 +1362,6 @@ function formatAutomationNextTitle(return fmtDateTime(job.state.next_run_at_ms, locale);}-function automationStatusDotClass(job: SessionAutomationJob): string {- const status = automationStatusKey(job);- if (status === "active" || status === "running") return "bg-orange-500";- if (status === "failed") return "bg-amber-500";- return "bg-muted-foreground/45";-}-function formatAutomationUnit(value: number,unit: Intl.NumberFormatOptions["unit"],diff --git a/webui/src/components/thread/ThreadComposer.tsx b/webui/src/components/thread/ThreadComposer.tsxindex f978b553b..d2cfa2039 100644--- a/webui/src/components/thread/ThreadComposer.tsx+++ b/webui/src/components/thread/ThreadComposer.tsx@@ -2562,13 +2562,13 @@ export function ThreadComposer({</div>{projectPickerAvailable ? (<div- className="composer-workspace-drawer"+ className="inline-disclosure"data-composer-workspace-drawer=""data-state={showProjectPicker ? "open" : "closed"}aria-hidden={showProjectPicker ? undefined : true}>- <div className="composer-workspace-drawer-clip">- <div className="composer-workspace-drawer-content">+ <div className="inline-disclosure-clip">+ <div className="inline-disclosure-content"><WorkspaceProjectPickerisHero={isHero}disabled={interactionDisabled || workspaceScopeDisabled || !showProjectPicker}diff --git a/webui/src/components/thread/activity/FileEditRow.tsx b/webui/src/components/thread/activity/FileEditRow.tsxindex 071161df1..8669ba3ad 100644--- a/webui/src/components/thread/activity/FileEditRow.tsx+++ b/webui/src/components/thread/activity/FileEditRow.tsx@@ -1,4 +1,5 @@-import { useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useId, useMemo, useState } from "react";+import { DisclosureContent } from "@/components/ui/disclosure";import {ChevronDown,ChevronRight,@@ -166,13 +167,15 @@ function FileUnifiedDiff({const { t } = useTranslation();const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });const [open, setOpen] = useState(false);+ const [hasOpened, setHasOpened] = useState(false);+ const contentId = useId();const [expandedLines, setExpandedLines] = useState(false);const renderableDiff = useMemo(() => parseRenderableFileDiff(diff), [diff]);const language = useMemo(() => codeLanguageFromPath(previewPath), [previewPath]);const totalLineCount = useMemo(() => countDiffLines(renderableDiff), [renderableDiff]);const shouldAutoCollapse = totalLineCount > AUTO_COLLAPSE_DIFF_LINES || !!diff.truncated;const startsCollapsed = collapsed || shouldAutoCollapse;- const shouldRenderBody = !startsCollapsed || open;+ const shouldRenderBody = !startsCollapsed || hasOpened;const shouldLimitLines = totalLineCount > INITIAL_VISIBLE_DIFF_LINES;const lineLimit = expandedLines || !shouldLimitLines? totalLineCount@@ -193,13 +196,21 @@ function FileUnifiedDiff({useEffect(() => {setOpen(false);+ setHasOpened(false);setExpandedLines(false);}, [diff]);const handleToggleOpen = () => {- if (open) setExpandedLines(false);+ if (!open) {+ setHasOpened(true);+ setExpandedLines(false);+ }setOpen(!open);};+ const releaseBody = useCallback(() => {+ setHasOpened(false);+ setExpandedLines(false);+ }, []);if (totalLineCount === 0) return null;@@ -287,6 +298,7 @@ function FileUnifiedDiff({<buttontype="button"aria-expanded={open}+ aria-controls={contentId}data-testid="file-edit-diff-toggle"onClick={handleToggleOpen}className={cn(@@ -295,13 +307,15 @@ function FileUnifiedDiff({)}><ChevronRight- className={cn("h-3 w-3 shrink-0 transition-transform", open && "rotate-90")}+ className={cn("h-3 w-3 shrink-0 transition-transform duration-200 motion-reduce:transition-none", open && "rotate-90")}aria-hidden/><span className="min-w-0 flex-1">{viewDiffLabel}</span><span className="shrink-0 text-muted-foreground/65">{lineCountLabel}</span></button>- {open ? renderBody() : null}+ <DisclosureContent id={contentId} open={open} onExitComplete={releaseBody}>+ {shouldRenderBody ? renderBody() : null}+ </DisclosureContent></div>);}diff --git a/webui/src/components/ui/dialog.tsx b/webui/src/components/ui/dialog.tsxindex 0a57888cb..7e8b8f8a8 100644--- a/webui/src/components/ui/dialog.tsx+++ b/webui/src/components/ui/dialog.tsx@@ -24,6 +24,7 @@ const DialogOverlay = React.forwardRef<ref={ref}className={cn(modalOverlayClassName,+ "motion-reduce:animate-none",className,)}{...props}@@ -31,15 +32,30 @@ const DialogOverlay = React.forwardRef<));DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;+// The portal's presence ref must reach the animated content, not the plain+// positioning wrapper; otherwise the wrapper unmounts before the exit finishes.+const DialogPositionedContent = React.forwardRef<+ React.ElementRef<typeof DialogPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {+ positionerStyle?: React.CSSProperties;+ }+>(({ positionerStyle, ...props }, ref) => (+ <div className="fixed inset-0 z-50 flex items-center justify-center p-4" style={positionerStyle}>+ <DialogPrimitive.Content ref={ref} {...props} />+ </div>+));+DialogPositionedContent.displayName = "DialogPositionedContent";+interface DialogContentPropsextends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {showCloseButton?: boolean;+ overlayClassName?: string;}const DialogContent = React.forwardRef<React.ElementRef<typeof DialogPrimitive.Content>,DialogContentProps->(({ className, children, showCloseButton = true, onOpenAutoFocus, ...props }, ref) => {+>(({ className, children, showCloseButton = true, overlayClassName, onOpenAutoFocus, ...props }, ref) => {const { t } = useTranslation();const [container, setContainer] = React.useState<HTMLDivElement | null>(null);const contentNode = React.useRef<HTMLDivElement | null>(null);@@ -74,9 +90,9 @@ const DialogContent = React.forwardRef<}, [ref]);return (<DialogPortal>- <DialogOverlay />- <div className="fixed inset-0 z-50 flex items-center justify-center p-4" style={layout}>- <DialogPrimitive.Content+ <DialogOverlay className={overlayClassName} />+ <DialogPositionedContent+ positionerStyle={layout}ref={contentRef}onOpenAutoFocus={(event) => {if (onOpenAutoFocus) onOpenAutoFocus(event);@@ -87,7 +103,7 @@ const DialogContent = React.forwardRef<}}className={cn(modalSurfaceClassName,- "relative grid w-full max-w-lg origin-center gap-4 rounded-modal p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",+ "relative grid w-full max-w-lg origin-center gap-4 rounded-modal p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 motion-reduce:animate-none",className,)}{...props}@@ -101,8 +117,7 @@ const DialogContent = React.forwardRef<<span className="sr-only">{t("common.close")}</span></DialogPrimitive.Close>) : null}- </DialogPrimitive.Content>- </div>+ </DialogPositionedContent></DialogPortal>);});diff --git a/webui/src/components/ui/disclosure.tsx b/webui/src/components/ui/disclosure.tsxnew file mode 100644index 000000000..6eae8c004--- /dev/null+++ b/webui/src/components/ui/disclosure.tsx@@ -0,0 +1,77 @@+import { useEffect, useId, useRef, useState, type KeyboardEventHandler, type ReactNode } from "react";++import { cn } from "@/lib/utils";++/** Keep the content mounted so both directions animate and form drafts survive closing. */+export function DisclosureContent({+ open, children, id, className, onKeyDown, onExitComplete,+}: {+ open: boolean;+ children: ReactNode;+ id?: string;+ className?: string;+ onKeyDown?: KeyboardEventHandler<HTMLDivElement>;+ onExitComplete?: () => void;+}) {+ const node = useRef<HTMLDivElement>(null);+ useEffect(() => {+ if (open || !onExitComplete) return;+ // Read the actual CSS transitions, including a reversal in progress. With+ // reduced motion (or no transition), there is nothing to wait for.+ const animations = node.current?.getAnimations?.() ?? [];+ if (!animations.length) {+ onExitComplete();+ return;+ }+ let cancelled = false;+ void Promise.allSettled(animations.map((animation) => animation.finished)).then(() => {+ if (!cancelled) onExitComplete();+ });+ return () => { cancelled = true; };+ }, [open, onExitComplete]);+ return (+ <div+ ref={node}+ id={id}+ className="inline-disclosure"+ data-state={open ? "open" : "closed"}+ aria-hidden={open ? undefined : true}+ onKeyDown={onKeyDown}+ {...(!open ? { inert: "" } : {})}+ >+ <div className="inline-disclosure-clip">+ <div className={cn("inline-disclosure-content", className)}>{children}</div>+ </div>+ </div>+ );+}++export function Disclosure({+ summary, children, className, summaryClassName, contentClassName,+}: {+ summary: ReactNode;+ children: ReactNode;+ className?: string;+ summaryClassName?: string;+ contentClassName?: string;+}) {+ const [open, setOpen] = useState(false);+ const id = useId();+ return (+ <div className={className}>+ <button+ type="button"+ className={cn("group/disclosure w-full select-none text-start", summaryClassName)}+ data-state={open ? "open" : "closed"}+ aria-expanded={open}+ aria-controls={id}+ onClick={() => setOpen((value) => !value)}+ >+ {summary}+ </button>+ <DisclosureContent id={id} open={open} className={contentClassName}>+ {children}+ </DisclosureContent>+ </div>+ );+}diff --git a/webui/src/components/ui/expandable-text.tsx b/webui/src/components/ui/expandable-text.tsxnew file mode 100644index 000000000..a353b3379--- /dev/null+++ b/webui/src/components/ui/expandable-text.tsx@@ -0,0 +1,46 @@+import { useLayoutEffect, useRef, useState } from "react";++/** Animate a line-limited preview without swapping or duplicating its text. */+export function ExpandableText({+ children, expanded, lines, className, id,+}: {+ children: string;+ expanded: boolean;+ lines: number;+ className?: string;+ id?: string;+}) {+ const content = useRef<HTMLParagraphElement>(null);+ const [size, setSize] = useState<{ full: number; preview: number }>();+ useLayoutEffect(() => {+ const node = content.current;+ if (!node) return;+ const measure = () => {+ const full = node.scrollHeight;+ const lineHeight = parseFloat(getComputedStyle(node).lineHeight);+ if (!full || !Number.isFinite(lineHeight)) return;+ const preview = Math.min(full, lineHeight * lines);+ setSize((current) => current?.full === full && current.preview === preview+ ? current : { full, preview });+ };+ measure();+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);+ observer?.observe(node);+ window.addEventListener("resize", measure);+ return () => {+ observer?.disconnect();+ window.removeEventListener("resize", measure);+ };+ }, [children, lines, className]);++ return (+ <div+ id={id}+ className="expandable-text flow-root overflow-hidden"+ data-state={expanded ? "open" : "closed"}+ style={{ height: size ? expanded ? size.full : size.preview : undefined }}+ >+ <p ref={content} className={className}>{children}</p>+ </div>+ );+}diff --git a/webui/src/globals.css b/webui/src/globals.cssindex d9223c242..28d94cb8f 100644--- a/webui/src/globals.css+++ b/webui/src/globals.css@@ -528,38 +528,42 @@opacity: 1;transform: translateY(0);}- .composer-workspace-drawer {- --composer-workspace-drawer-duration: 220ms;+ /* Shared in-flow disclosure: animate intrinsic height without measuring it. */+ .inline-disclosure {+ --inline-disclosure-duration: 220ms;display: grid;grid-template-rows: 0fr;opacity: 0;pointer-events: none;}- .composer-workspace-drawer[data-state="open"] {- --composer-workspace-drawer-duration: 240ms;+ .inline-disclosure[data-state="open"] {+ --inline-disclosure-duration: 240ms;grid-template-rows: 1fr;opacity: 1;pointer-events: auto;}- .composer-workspace-drawer-clip {+ .inline-disclosure-clip {min-height: 0;overflow: hidden;}@media (prefers-reduced-motion: no-preference) {- .composer-workspace-drawer {+ .expandable-text {+ transition: height 240ms cubic-bezier(0.4, 0, 0.2, 1);+ }+ .inline-disclosure {transition:- grid-template-rows var(--composer-workspace-drawer-duration)+ grid-template-rows var(--inline-disclosure-duration)cubic-bezier(0.4, 0, 0.2, 1),- opacity var(--composer-workspace-drawer-duration) ease-in-out;+ opacity var(--inline-disclosure-duration) ease-in-out;}- .composer-workspace-drawer-content {+ .inline-disclosure-content {transform: translateY(-6px);- transition: transform var(--composer-workspace-drawer-duration)+ transition: transform var(--inline-disclosure-duration)cubic-bezier(0.4, 0, 0.2, 1);}- .composer-workspace-drawer[data-state="open"] .composer-workspace-drawer-content {+ .inline-disclosure[data-state="open"] .inline-disclosure-content {transform: translateY(0);}}@@ -1017,31 +1021,27 @@--settings-margin: 0.75rem;max-inline-size: calc(var(--content-column-width) + 2 * var(--settings-margin));}- /* Standalone feature pages have room for catalogs and multi-pane layouts.- Split automations only when each container can actually fit its columns. */+ /* Stack a task's status below its title when the content column is narrow. */.automations-page {container: automations / inline-size;}- .automation-detail-panel {- container: automation-detail / inline-size;- }- @container automations (min-width: 48rem) {- .automations-workspace {- grid-template-columns: minmax(16rem, 18rem) minmax(0, 1fr);- align-items: stretch;- }- .automations-workspace > .automations-queue {- border-bottom-width: 0;- border-right-width: 1px;- }- .automations-queue > .automations-queue-list { max-height: calc(100vh - 24rem); }- }- @container automation-detail (min-width: 40rem) {- .automation-detail-body { grid-template-columns: minmax(0, 1fr) 14.5rem; }- .automation-detail-body > .automation-detail-metadata {- border-top-width: 0;- border-left-width: 1px;+ .automation-task-state {+ grid-column: 1;+ grid-row: 2;+ }+ .automation-task-chevron {+ grid-column: 2;+ grid-row: 1 / span 2;+ }+ @container automations (min-width: 36rem) {+ .automation-task-row { grid-template-columns: minmax(0, 1fr) auto auto; }+ .automation-task-state {+ grid-column: 2;+ grid-row: 1;+ max-width: 18rem;+ justify-content: flex-end;}+ .automation-task-chevron { grid-column: 3; grid-row: 1; }}.settings-stack > :not([hidden]) ~ :not([hidden]) {margin-block-start: var(--settings-module-gap, 20px);diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.jsonindex a18f8421a..db345fe56 100644--- a/webui/src/i18n/locales/en/common.json+++ b/webui/src/i18n/locales/en/common.json@@ -1086,6 +1086,16 @@"notEnabled": "Not enabled"},"automations": {+ "viewOptions": "Search and filter",+ "yourTasks": "Your automations",+ "systemTasks": "System tasks",+ "instructions": "Instructions",+ "done": "Done",+ "moreDetails": "More details",+ "moreActions": "More actions",+ "neverRun": "Not run yet",+ "skipped": "Skipped",+ "oneShotHint": "Removed after running","filters": {"all": "All","active": "Active",@@ -1104,7 +1114,7 @@"loading": "Loading automations...","noMatches": "No automations match this view.","empty": "No automations yet.",- "emptyHint": "Create automations in a chat so they keep the right context.",+ "emptyHint": "Tell nanobot in a chat what you'd like it to do on a schedule.","emptyAction": "Open a chat","clearFilters": "Clear filters","oneShot": "One-time",diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.jsonindex 9fe46338a..c6e79f558 100644--- a/webui/src/i18n/locales/es/common.json+++ b/webui/src/i18n/locales/es/common.json@@ -887,6 +887,16 @@"notEnabled": "No activado"},"automations": {+ "viewOptions": "Buscar y filtrar",+ "yourTasks": "Tus automatizaciones",+ "systemTasks": "Tareas del sistema",+ "instructions": "Instrucciones",+ "done": "Listo",+ "moreDetails": "Más detalles",+ "moreActions": "Más acciones",+ "neverRun": "Aún no se ha ejecutado",+ "skipped": "Omitido",+ "oneShotHint": "Se elimina después de ejecutarse","filters": {"all": "Todas","active": "Activas",@@ -905,7 +915,7 @@"loading": "Cargando automatizaciones...","noMatches": "No hay automatizaciones que coincidan con esta vista.","empty": "Aún no hay automatizaciones.",- "emptyHint": "Crea automatizaciones en un chat para que conserven el contexto correcto.",+ "emptyHint": "Dile a nanobot en un chat qué quieres que haga y cuándo.","emptyAction": "Abrir un chat","clearFilters": "Borrar filtros","oneShot": "Una vez",diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.jsonindex f9fa09949..ba980d91f 100644--- a/webui/src/i18n/locales/fr/common.json+++ b/webui/src/i18n/locales/fr/common.json@@ -886,6 +886,16 @@"notEnabled": "Non activé"},"automations": {+ "viewOptions": "Rechercher et filtrer",+ "yourTasks": "Vos automatisations",+ "systemTasks": "Tâches système",+ "instructions": "Instructions",+ "done": "Terminé",+ "moreDetails": "Plus de détails",+ "moreActions": "Plus d’actions",+ "neverRun": "Pas encore exécuté",+ "skipped": "Ignoré",+ "oneShotHint": "Supprimée après exécution","filters": {"all": "Toutes","active": "Actives",@@ -904,7 +914,7 @@"loading": "Chargement des automatisations...","noMatches": "Aucune automatisation ne correspond à cette vue.","empty": "Aucune automatisation pour le moment.",- "emptyHint": "Créez les automatisations dans un chat afin de conserver le bon contexte.",+ "emptyHint": "Dites à nanobot dans une conversation ce que vous souhaitez planifier.","emptyAction": "Ouvrir un chat","clearFilters": "Effacer les filtres","oneShot": "Ponctuelle",diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.jsonindex ede38e6b9..473064acd 100644--- a/webui/src/i18n/locales/id/common.json+++ b/webui/src/i18n/locales/id/common.json@@ -886,6 +886,16 @@"notEnabled": "Belum aktif"},"automations": {+ "viewOptions": "Cari dan filter",+ "yourTasks": "Otomatisasi Anda",+ "systemTasks": "Tugas sistem",+ "instructions": "Instruksi",+ "done": "Selesai",+ "moreDetails": "Detail lainnya",+ "moreActions": "Tindakan lainnya",+ "neverRun": "Belum dijalankan",+ "skipped": "Dilewati",+ "oneShotHint": "Dihapus setelah dijalankan","filters": {"all": "Semua","active": "Aktif",@@ -904,7 +914,7 @@"loading": "Memuat otomasi...","noMatches": "Tidak ada otomasi yang cocok dengan tampilan ini.","empty": "Belum ada otomasi.",- "emptyHint": "Buat otomatisasi di chat agar konteks yang tepat tetap tersimpan.",+ "emptyHint": "Beri tahu nanobot di chat apa yang ingin Anda jalankan secara terjadwal.","emptyAction": "Buka chat","clearFilters": "Hapus filter","oneShot": "Satu kali",diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.jsonindex dbd27d823..19ad18565 100644--- a/webui/src/i18n/locales/ja/common.json+++ b/webui/src/i18n/locales/ja/common.json@@ -886,6 +886,16 @@"notEnabled": "無効"},"automations": {+ "viewOptions": "検索と絞り込み",+ "yourTasks": "自分の自動化",+ "systemTasks": "システムタスク",+ "instructions": "指示",+ "done": "完了",+ "moreDetails": "詳細情報",+ "moreActions": "その他の操作",+ "neverRun": "未実行",+ "skipped": "スキップ済み",+ "oneShotHint": "実行後に削除","filters": {"all": "すべて","active": "有効",@@ -904,7 +914,7 @@"loading": "自動タスクを読み込み中...","noMatches": "この表示に一致する自動タスクはありません。","empty": "自動タスクはまだありません。",- "emptyHint": "チャットで自動タスクを作成すると、その会話の内容を引き継いで実行できます。",+ "emptyHint": "決まった時間に実行してほしいことを、チャットで nanobot に伝えてください。","emptyAction": "チャットを開く","clearFilters": "フィルターをクリア","oneShot": "一回限り",diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.jsonindex 954c8ec5c..5f460734b 100644--- a/webui/src/i18n/locales/ko/common.json+++ b/webui/src/i18n/locales/ko/common.json@@ -886,6 +886,16 @@"notEnabled": "비활성화됨"},"automations": {+ "viewOptions": "검색 및 필터",+ "yourTasks": "내 자동화",+ "systemTasks": "시스템 작업",+ "instructions": "지침",+ "done": "완료",+ "moreDetails": "상세 정보",+ "moreActions": "추가 작업",+ "neverRun": "아직 실행되지 않음",+ "skipped": "건너뜀",+ "oneShotHint": "실행 후 삭제됨","filters": {"all": "전체","active": "활성",@@ -904,7 +914,7 @@"loading": "자동화를 불러오는 중...","noMatches": "이 보기와 일치하는 자동화가 없습니다.","empty": "아직 자동화가 없습니다.",- "emptyHint": "채팅에서 자동화를 만들면 해당 대화의 맥락을 활용할 수 있습니다.",+ "emptyHint": "예약 실행할 작업을 채팅에서 nanobot에게 알려 주세요.","emptyAction": "채팅 열기","clearFilters": "필터 지우기","oneShot": "일회성",diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.jsonindex 3787225fc..a16e47a7c 100644--- a/webui/src/i18n/locales/pt-BR/common.json+++ b/webui/src/i18n/locales/pt-BR/common.json@@ -900,6 +900,16 @@"notEnabled": "Não habilitado"},"automations": {+ "viewOptions": "Buscar e filtrar",+ "yourTasks": "Suas automações",+ "systemTasks": "Tarefas do sistema",+ "instructions": "Instruções",+ "done": "Concluído",+ "moreDetails": "Mais detalhes",+ "moreActions": "Mais ações",+ "neverRun": "Ainda não executado",+ "skipped": "Ignorado",+ "oneShotHint": "Removida após a execução","filters": {"all": "Todas","active": "Ativas",@@ -918,7 +928,7 @@"loading": "Carregando automações...","noMatches": "Nenhuma automação corresponde a esta visualização.","empty": "Nenhuma automação ainda.",- "emptyHint": "Crie automações em uma conversa para que mantenham o contexto correto.",+ "emptyHint": "Diga ao nanobot em uma conversa o que você quer que ele faça e quando.","emptyAction": "Abrir uma conversa","clearFilters": "Limpar filtros","oneShot": "Uma vez",diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.jsonindex a1aa754f2..7570228ae 100644--- a/webui/src/i18n/locales/vi/common.json+++ b/webui/src/i18n/locales/vi/common.json@@ -886,6 +886,16 @@"notEnabled": "Chưa bật"},"automations": {+ "viewOptions": "Tìm kiếm và lọc",+ "yourTasks": "Tác vụ tự động của bạn",+ "systemTasks": "Tác vụ hệ thống",+ "instructions": "Chỉ dẫn",+ "done": "Xong",+ "moreDetails": "Chi tiết khác",+ "moreActions": "Thao tác khác",+ "neverRun": "Chưa chạy",+ "skipped": "Đã bỏ qua",+ "oneShotHint": "Xóa sau khi chạy","filters": {"all": "Tất cả","active": "Đã bật",@@ -904,7 +914,7 @@"loading": "Đang tải tự động hóa...","noMatches": "Không có tự động hóa phù hợp với chế độ xem này.","empty": "Chưa có tự động hóa.",- "emptyHint": "Tạo tác vụ tự động trong cuộc trò chuyện để giữ đúng ngữ cảnh.",+ "emptyHint": "Cho nanobot biết trong cuộc trò chuyện việc bạn muốn thực hiện theo lịch.","emptyAction": "Mở cuộc trò chuyện","clearFilters": "Xóa bộ lọc","oneShot": "Một lần",diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.jsonindex f98599da1..5d8adb80e 100644--- a/webui/src/i18n/locales/zh-CN/common.json+++ b/webui/src/i18n/locales/zh-CN/common.json@@ -1086,6 +1086,16 @@"notEnabled": "未启用"},"automations": {+ "viewOptions": "搜索与筛选",+ "yourTasks": "你的自动任务",+ "systemTasks": "系统任务",+ "instructions": "任务指令",+ "done": "完成",+ "moreDetails": "更多信息",+ "moreActions": "更多操作",+ "neverRun": "尚未运行",+ "skipped": "已跳过",+ "oneShotHint": "运行后自动移除","filters": {"all": "全部","active": "已启用",@@ -1104,7 +1114,7 @@"loading": "正在加载自动任务...","noMatches": "当前视图没有匹配的自动任务。","empty": "暂无自动任务。",- "emptyHint": "请在对话中创建自动任务,以便保留正确的上下文。",+ "emptyHint": "在聊天中告诉 nanobot 你想定期做什么,即可创建自动任务。","emptyAction": "打开对话","clearFilters": "清除筛选","oneShot": "一次性",diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.jsonindex 3f654a85b..7aa82a24f 100644--- a/webui/src/i18n/locales/zh-TW/common.json+++ b/webui/src/i18n/locales/zh-TW/common.json@@ -886,6 +886,16 @@"notEnabled": "未啟用"},"automations": {+ "viewOptions": "搜尋與篩選",+ "yourTasks": "你的自動任務",+ "systemTasks": "系統任務",+ "instructions": "任務指示",+ "done": "完成",+ "moreDetails": "更多詳細資訊",+ "moreActions": "更多操作",+ "neverRun": "尚未執行",+ "skipped": "已略過",+ "oneShotHint": "執行後移除","filters": {"all": "全部","active": "已啟用",@@ -904,7 +914,7 @@"loading": "正在載入自動任務…","noMatches": "目前沒有符合條件的自動任務。","empty": "尚無自動任務。",- "emptyHint": "請在聊天中建立自動任務,以保留正確的對話脈絡。",+ "emptyHint": "在聊天中告訴 nanobot 你想定期做什麼,即可建立自動任務。","emptyAction": "開啟聊天","clearFilters": "清除篩選","oneShot": "單次",diff --git a/webui/src/lib/chat-groups.ts b/webui/src/lib/chat-groups.tsindex 9a0120587..1ebca5d91 100644--- a/webui/src/lib/chat-groups.ts+++ b/webui/src/lib/chat-groups.ts@@ -216,7 +216,7 @@ export function visibleSessionsForGroup(}export function displayTitle(- session: ChatSummary,+ session: Pick<ChatSummary, "key" | "title" | "preview">,titleOverrides: Record<string, string>,fallbackTitle: string,): string {diff --git a/webui/src/tests/agent-activity-cluster.test.tsx b/webui/src/tests/agent-activity-cluster.test.tsxindex 91dbd28c8..3af76ecae 100644--- a/webui/src/tests/agent-activity-cluster.test.tsx+++ b/webui/src/tests/agent-activity-cluster.test.tsx@@ -848,7 +848,7 @@ describe("AgentActivityCluster", () => {}});- it("keeps long file edit diffs collapsed until opened", () => {+ it("keeps long file edit diffs lazy and releases them after closing", async () => {localStorage.setItem("nanobot-webui.settings-preferences",JSON.stringify({ fileEditDisplayMode: "diff" }),@@ -917,10 +917,20 @@ describe("AgentActivityCluster", () => {"Show 5 more lines",);+ const content = document.getElementById(toggle.getAttribute("aria-controls")!)!;+ let finish!: () => void;+ const finished = new Promise<void>((resolve) => { finish = resolve; });+ Object.defineProperty(content, "getAnimations", { value: () => [{ finished }] });fireEvent.click(toggle);-expect(toggle).toHaveAttribute("aria-expanded", "false");+ expect(content).toHaveAttribute("data-state", "closed");+ expect(content).toHaveAttribute("inert");+ expect(screen.getByTestId("file-edit-diff")).toBeInTheDocument();+ await act(async () => { finish(); });expect(screen.queryByTestId("file-edit-diff")).not.toBeInTheDocument();+ fireEvent.click(toggle);+ expect(screen.getByText("line-160")).toBeInTheDocument();+ expect(screen.queryByText("line-161")).not.toBeInTheDocument();} finally {localStorage.removeItem("nanobot-webui.settings-preferences");}diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsxindex a3ea12152..8a324f7f4 100644--- a/webui/src/tests/app-layout.test.tsx+++ b/webui/src/tests/app-layout.test.tsx@@ -1439,11 +1439,18 @@ describe("App layout", () => {expect(within(automationsMain as HTMLElement).queryByText("Settings")).not.toBeInTheDocument();expect(screen.getAllByText("Daily repo check").length).toBeGreaterThanOrEqual(1);expect(screen.getAllByText("Check the repo status").length).toBeGreaterThanOrEqual(1);+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: /Daily repo check/ }));expect(screen.getAllByText("Release prep").length).toBeGreaterThanOrEqual(1);+ fireEvent.click(screen.getByRole("button", { name: "Done", exact: true }));expect(screen.getByText("WeChat quiz")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: /WeChat quiz/ }));expect(screen.getByText("WeChat")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Done", exact: true }));expect(screen.queryByText("weixin:wx-chat")).not.toBeInTheDocument();expect(screen.queryByText("memory with dream state")).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: /heartbeat/ })).toBeVisible();+ expect(screen.getByRole("button", { name: "System tasks 1" })).toHaveAttribute("aria-expanded", "true");expect(screen.getByText("heartbeat")).toBeInTheDocument();expect(within(sidebar).getByRole("button", { name: "Automations" })).toHaveAttribute("aria-current",@@ -1451,6 +1458,7 @@ describe("App layout", () => {);expect(document.title).toBe("Automations · nanobot");+ fireEvent.click(screen.getByRole("button", { name: "Search and filter" }));const searchInput = within(automationsMain as HTMLElement).getByPlaceholderText("Search task, message, linked chat, or schedule",);@@ -1463,6 +1471,54 @@ describe("App layout", () => {expect(screen.getAllByText("WeChat quiz").length).toBeGreaterThanOrEqual(1);});+ it("keeps automation linked-chat titles in sync with live sidebar renames", async () => {+ const key = "websocket:linked-chat";+ mockSessions = [{+ key, channel: "websocket", chatId: "linked-chat", createdAt: null, updatedAt: null,+ title: "Stored title", preview: "Original preview",+ }];+ const sidebarState: SidebarStatePayload = {+ schema_version: 1, pinned_keys: [], archived_keys: [], session_order: [],+ title_overrides: { [key]: "推特大战场" }, project_name_overrides: {},+ tags_by_key: {}, collapsed_groups: {}, workbench: { version: 1, tabs: {} },+ view: { density: "comfortable", show_previews: false, show_timestamps: false,+ show_archived: false, sort: "updated_desc" },+ };+ mockFetchRoutes({+ "/api/settings": baseSettingsPayload(),+ "/api/webui/sidebar-state": sidebarState,+ "/api/webui/automations": { jobs: [{+ id: "reminder", name: "Drink water", enabled: true,+ schedule: { kind: "every", every_ms: 60_000 },+ payload: { message: "Take a break" }, state: {},+ origin: { session_key: key, channel: "websocket", chat_id: "linked-chat",+ title: "Stored title", preview: "Original preview" },+ }] },+ });+ render(<App />);+ const sidebar = await screen.findByRole("navigation", { name: "Sidebar navigation" });+ await within(sidebar).findByRole("button", { name: "推特大战场", exact: true });+ fireEvent.click(within(sidebar).getByRole("button", { name: "Automations" }));+ fireEvent.click(await screen.findByRole("button", { name: /Drink water/ }));+ const dialog = screen.getByRole("dialog", { name: "Drink water" });+ expect(within(dialog).getByRole("link", { name: "推特大战场" })).toHaveAttribute(+ "href", "#/chat/websocket%3Alinked-chat",+ );+ for (const title of ["新会话名称", ""]) {+ act(() => {+ sidebarStateUpdateHandlers.forEach((handler) => handler({+ ...sidebarState, title_overrides: title ? { [key]: title } : {},+ }));+ });+ const expected = title || "Stored title";+ expect(within(sidebar).getByText(expected)).toBeInTheDocument();+ expect(within(dialog).getByRole("link", { name: expected })).toHaveAttribute(+ "href", "#/chat/websocket%3Alinked-chat",+ );+ }+ expect(requestMutationSpy).not.toHaveBeenCalled();+ });+it("edits a past one-time automation without resubmitting its old schedule", async () => {const pastOneShot = {id: "past-one-shot",@@ -1507,7 +1563,9 @@ describe("App layout", () => {fireEvent.click(within(sidebar).getByRole("button", { name: "Automations" }));expect((await screen.findAllByText("Past one-shot")).length).toBeGreaterThanOrEqual(1);+ fireEvent.click(screen.getByRole("button", { name: /Past one-shot/ }));fireEvent.click(screen.getByRole("button", { name: "Edit" }));+ await screen.findByRole("dialog", { name: "Edit automation" });expect(screen.queryByText("Run time must be in the future.")).not.toBeInTheDocument();expect(screen.queryByText("Update the prompt and schedule. The linked chat stays unchanged."),@@ -1593,18 +1651,19 @@ describe("App layout", () => {const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });fireEvent.click(within(sidebar).getByRole("button", { name: "Automations" }));- const detailHeading = await screen.findByRole("heading", { name: "Long detail automation" });- const detailPanel = detailHeading.closest("article") as HTMLElement;- expect(detailPanel).not.toBeNull();- const message = Array.from(detailPanel.querySelectorAll("section div")).find(+ fireEvent.click(await screen.findByRole("button", { name: /Long detail automation/ }));+ const detailPanel = await screen.findByRole("dialog", { name: "Long detail automation" });+ const message = Array.from(detailPanel.querySelectorAll("section p")).find((node) => node.textContent === longMessage,) as HTMLElement | undefined;expect(message).toBeTruthy();- expect(message!).toHaveClass("line-clamp-6");+ const preview = message!.closest(".expandable-text")!;+ expect(preview).toHaveAttribute("data-state", "closed");fireEvent.click(within(detailPanel).getByRole("button", { name: "Show full message" }));expect(within(detailPanel).getByRole("button", { name: "Show less" })).toBeInTheDocument();- expect(message!).not.toHaveClass("line-clamp-6");+ expect(preview).toHaveAttribute("data-state", "open");+ expect(preview).toContainElement(message!);expect(within(detailPanel).queryByText("Recent health")).not.toBeInTheDocument();expect(within(detailPanel).queryByRole("button", { name: /Run history/ })).not.toBeInTheDocument();@@ -1665,10 +1724,11 @@ describe("App layout", () => {const automationsMain = heading.closest("main");expect(automationsMain).not.toBeNull();expect(within(automationsMain as HTMLElement).queryByText("设置")).not.toBeInTheDocument();- expect(screen.getByText("任务队列")).toBeInTheDocument();+ expect(screen.queryByText("任务队列")).not.toBeInTheDocument();expect(screen.getAllByText("每日检查").length).toBeGreaterThanOrEqual(1);expect(screen.getAllByText("检查仓库状态").length).toBeGreaterThanOrEqual(1);- expect(screen.getByText("每 1天")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: /每日检查/ }));+ expect(within(screen.getByRole("dialog", { name: "每日检查" })).getByText(/每 1天/)).toBeInTheDocument();expect(screen.queryByText("最近健康状态")).not.toBeInTheDocument();expect(screen.queryByText("近期无问题")).not.toBeInTheDocument();expect(screen.queryByText("Workspace automations")).not.toBeInTheDocument();diff --git a/webui/src/tests/automations-settings.test.tsx b/webui/src/tests/automations-settings.test.tsxnew file mode 100644index 000000000..0f7a3f166--- /dev/null+++ b/webui/src/tests/automations-settings.test.tsx@@ -0,0 +1,562 @@+import { useState } from "react";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { AutomationEditDialog, AutomationsSettings } from "@/components/settings/system/AutomationsSettings";+import type { AutomationFilter, AutomationSort } from "@/components/settings/system/AutomationsSettings";+import type { SessionAutomationJob } from "@/lib/types";++const now = Date.now();+const task: SessionAutomationJob = {+ id: "private-job-id", name: "PR watch", enabled: true,+ schedule: { kind: "every", every_ms: 1_800_000 },+ payload: { message: "Check open pull requests and report failed CI." },+ state: { next_run_at_ms: now + 540_000, last_run_at_ms: now - 60_000, last_status: "ok" },+ origin: { channel: "websocket", session_key: "websocket:demo", title: "nanobot-development" },+ created_at_ms: now - 86_400_000,+};+const systemTask: SessionAutomationJob = {+ ...task, id: "heartbeat", name: "heartbeat", protected: true, origin: null,+ payload: { message: "" },+};+type Props = Partial<React.ComponentProps<typeof AutomationsSettings>>;+const SYSTEM_TASKS_OPEN_STORAGE_KEY = "nanobot-webui.automation-system-tasks-open";++function Harness({ payload = { jobs: [task, systemTask] }, ...props }: Props) {+ const [query, setQuery] = useState("");+ const [filter, setFilter] = useState<AutomationFilter>("all");+ const [sort, setSort] = useState<AutomationSort>("next");+ return <AutomationsSettings+ payload={payload} loading={false} query={query} filter={filter} sort={sort}+ actionKey={null} error={null} onQueryChange={setQuery} onFilterChange={setFilter}+ onSortChange={setSort} onAction={() => {}} onRequestEdit={() => {}}+ onRequestDelete={() => {}} {...props}+ />;+}++beforeEach(() => {+ window.localStorage.removeItem(SYSTEM_TASKS_OPEN_STORAGE_KEY);+});++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ window.localStorage.removeItem(SYSTEM_TASKS_OPEN_STORAGE_KEY);+});++describe("Automation task list and detail sheet", () => {+ it("opens system tasks by default and remembers manual changes across visits", () => {+ const first = render(<Harness />);+ expect(screen.getByRole("button", { name: "System tasks 1" })).toHaveAttribute("aria-expanded", "true");+ expect(window.localStorage.getItem(SYSTEM_TASKS_OPEN_STORAGE_KEY)).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "System tasks 1" }));+ first.unmount();++ const second = render(<Harness />);+ expect(screen.getByRole("button", { name: "System tasks 1" })).toHaveAttribute("aria-expanded", "false");+ expect(screen.queryByRole("button", { name: /heartbeat/ })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "System tasks 1" }));+ second.unmount();++ render(<Harness />);+ expect(screen.getByRole("button", { name: "System tasks 1" })).toHaveAttribute("aria-expanded", "true");+ expect(window.localStorage.getItem(SYSTEM_TASKS_OPEN_STORAGE_KEY)).toBe("true");+ });++ it("does not replace a remembered collapse when search reveals system tasks", () => {+ window.localStorage.setItem(SYSTEM_TASKS_OPEN_STORAGE_KEY, "false");+ const view = render(<Harness query="heartbeat" />);+ expect(screen.getByRole("button", { name: /heartbeat/ })).toBeVisible();+ expect(window.localStorage.getItem(SYSTEM_TASKS_OPEN_STORAGE_KEY)).toBe("false");+ view.unmount();+ render(<Harness />);+ expect(screen.getByRole("button", { name: "System tasks 1" })).toHaveAttribute("aria-expanded", "false");+ });++ it("keeps the system toggle usable when browser storage is unavailable", () => {+ vi.spyOn(window.localStorage, "getItem").mockImplementation(() => { throw new Error("Blocked"); });+ vi.spyOn(window.localStorage, "setItem").mockImplementation(() => { throw new Error("Blocked"); });+ render(<Harness />);+ const toggle = screen.getByRole("button", { name: "System tasks 1" });+ expect(toggle).toHaveAttribute("aria-expanded", "true");+ fireEvent.click(toggle);+ expect(toggle).toHaveAttribute("aria-expanded", "false");+ fireEvent.click(toggle);+ expect(toggle).toHaveAttribute("aria-expanded", "true");+ });++ it.each(["Done", "Escape", "removed", "Edit", "Edit removed"])("finishes the detail exit before cleanup and handoff: %s", async (action) => {+ // Happy DOM has no CSS animations. Give Radix live animation names so its+ // real presence lifecycle runs, including the outer portal's ref boundary.+ const getStyle = window.getComputedStyle.bind(window);+ vi.spyOn(window, "getComputedStyle").mockImplementation((node) => {+ const style = getStyle(node);+ if (node.getAttribute("role") !== "dialog") return style;+ return new Proxy(style, {+ get(target, property) {+ if (property === "animationName") return node.getAttribute("data-state") === "closed" ? "exit" : "enter";+ const value = Reflect.get(target, property, target);+ return typeof value === "function" ? value.bind(target) : value;+ },+ });+ });+ const user = userEvent.setup();+ const edit = vi.fn();+ const { rerender } = render(<Harness onRequestEdit={edit} />);+ const row = screen.getByRole("button", { name: /PR watch/ });+ await user.click(row);+ const dialog = screen.getByRole("dialog", { name: "PR watch" });+ if (action === "removed") rerender(<Harness payload={{ jobs: [] }} onRequestEdit={edit} />);+ else if (action === "Escape") fireEvent.keyDown(dialog, { key: "Escape" });+ else fireEvent.click(within(dialog).getByRole("button", { name: action.startsWith("Edit") ? "Edit" : action, exact: true }));+ if (action === "Edit removed") rerender(<Harness payload={{ jobs: [] }} onRequestEdit={edit} />);+ expect(dialog).toBeInTheDocument();+ expect(dialog).toHaveAttribute("data-state", "closed");+ expect(dialog).toHaveAttribute("inert");+ expect(dialog).toHaveTextContent("PR watch");+ expect(edit).not.toHaveBeenCalled();+ const exit = new Event("animationend", { bubbles: true });+ Object.defineProperty(exit, "animationName", { value: "exit" });+ fireEvent(dialog, exit);+ await waitFor(() => expect(dialog).not.toBeInTheDocument());+ if (action.includes("removed")) expect(screen.getByRole("heading", { name: "Automations" })).toHaveFocus();+ else await waitFor(() => expect(row).toHaveFocus());+ if (action === "Edit") {+ expect(edit).toHaveBeenCalledOnce();+ expect(edit).toHaveBeenCalledWith(task);+ }+ else expect(edit).not.toHaveBeenCalled();+ });++ it("keeps the default list quiet and opens details only on request", async () => {+ const user = userEvent.setup();+ render(<Harness />);+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: /^Active/ })).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: /heartbeat/ })).toBeVisible();+ expect(screen.queryByRole("button", { name: "Create in chat" })).not.toBeInTheDocument();+ const row = screen.getByRole("button", { name: /PR watch/ });+ await user.click(row);+ const dialog = screen.getByRole("dialog", { name: "PR watch" });+ expect(dialog).toHaveAccessibleDescription(/Every 30 minutes/);+ expect(within(dialog).getByText("Instructions")).toBeVisible();+ expect(within(dialog).getByRole("link", { name: "Open a chat" })).toHaveAttribute(+ "href", "#/chat/websocket%3Ademo",+ );+ expect(within(dialog).getByRole("button", { name: "More details" })).toHaveAttribute("aria-expanded", "false");+ await user.click(within(dialog).getByRole("button", { name: "Done" }));+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());+ expect(row).toHaveFocus();+ await user.keyboard("{Enter}");+ expect(screen.getByRole("dialog", { name: "PR watch" })).toBeVisible();+ await user.keyboard("{Escape}");+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(row).toHaveFocus();+ });++ it("keeps a text-only empty state when only system tasks exist", () => {+ render(<Harness payload={{ jobs: [systemTask] }} />);+ expect(screen.getByText("No automations yet.")).toBeVisible();+ expect(screen.getByText("Tell nanobot in a chat what you'd like it to do on a schedule.")).toBeVisible();+ expect(screen.queryByRole("button", { name: "Create in chat" })).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Open a chat" })).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Search and filter" })).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: /heartbeat/ }));+ const dialog = screen.getByRole("dialog", { name: "heartbeat" });+ expect(within(dialog).queryByRole("button", { name: "Edit" })).not.toBeInTheDocument();+ expect(within(dialog).queryByRole("button", { name: "Pause" })).not.toBeInTheDocument();+ expect(within(dialog).queryByRole("button", { name: "More actions" })).not.toBeInTheDocument();+ expect(within(dialog).queryByText("Linked chat")).not.toBeInTheDocument();+ });++ it("distinguishes a finished one-time task from a task with no scheduled run", () => {+ render(<Harness payload={{ jobs: [{ ...task, delete_after_run: true,+ state: { last_status: "ok", next_run_at_ms: null } }] }} />);+ expect(screen.getByRole("button", { name: /PR watch/ })).toHaveTextContent("Completed");+ expect(screen.queryByText("No next run")).not.toBeInTheDocument();+ });++ it.each(["heartbeat", "dream", "other-system-job"])("shows only actual task data for %s", (id) => {+ render(<Harness payload={{ jobs: [{ ...systemTask, id, name: id, state: {+ next_run_at_ms: now + 540_000,+ } }] }} />);+ fireEvent.click(screen.getByRole("button", { name: new RegExp(id) }));+ const dialog = screen.getByRole("dialog", { name: id });+ expect(dialog).toHaveClass("max-w-[440px]");+ expect(dialog).not.toHaveAttribute("aria-describedby");+ expect(dialog.querySelector("p")).toBeNull();+ expect(within(dialog).queryByText("Instructions")).not.toBeInTheDocument();+ expect(within(dialog).queryByText("System-managed automation")).not.toBeInTheDocument();+ for (const label of ["Schedule", "Next run", "Last run"]) {+ expect(within(dialog).getByText(label).tagName).toBe("DT");+ }+ expect(within(dialog).getByText("Every 30 minutes")).toBeVisible();+ expect(within(dialog).getByText("Not run yet")).toBeVisible();+ expect(within(dialog).getAllByRole("button")).toHaveLength(2);+ expect(within(dialog).getByRole("button", { name: "Done" })).toHaveClass("text-foreground");+ const toggle = within(dialog).getByRole("button", { name: "More details" });+ const metadata = document.getElementById(toggle.getAttribute("aria-controls")!)!;+ expect(metadata).toHaveAttribute("data-state", "closed");+ fireEvent.click(toggle);+ expect(metadata).toHaveAttribute("data-state", "open");+ expect(within(metadata).getByText("ID")).toBeVisible();+ fireEvent.click(toggle);+ expect(metadata).toHaveAttribute("data-state", "closed");+ expect(metadata).toHaveAttribute("inert");+ expect(metadata).toHaveClass("inline-disclosure");+ expect(within(metadata).getByText("ID")).toBeInTheDocument();+ });++ it("keeps system failures visible and does not infer purpose from a task name", () => {+ render(<Harness payload={{ jobs: [{ ...systemTask, id: "other-system-job", name: "heartbeat",+ state: { last_status: "error", last_error: "Background check failed", next_run_at_ms: null },+ }] }} />);+ fireEvent.click(screen.getByRole("button", { name: /heartbeat/ }));+ const dialog = screen.getByRole("dialog", { name: "heartbeat" });+ expect(within(dialog).queryByText("System-managed automation")).not.toBeInTheDocument();+ expect(within(dialog).getByRole("alert")).toHaveTextContent("Background check failed");+ expect(within(dialog).getByText("Failed")).toBeVisible();+ expect(within(dialog).getByText("No next run")).toBeVisible();+ expect(dialog).not.toHaveAttribute("aria-describedby");+ });++ it("reuses compact settings rows for system tasks without changing personal rows", async () => {+ const user = userEvent.setup();+ render(<Harness payload={{ jobs: [task, systemTask, {+ ...systemTask, id: "dream", name: "dream",+ state: { last_status: "error", last_error: "Memory update failed" },+ }] }} />);+ const personalRow = screen.getByRole("button", { name: /PR watch/ });+ expect(personalRow).toHaveClass("min-h-[92px]");+ expect(personalRow).not.toHaveClass("settings-list-row");+ const list = screen.getByRole("list", { name: "System tasks" });+ expect(list.parentElement).toHaveClass("rounded-panel", "bg-settings-surface");+ const heartbeat = within(list).getByRole("button", { name: /heartbeat/ });+ expect(heartbeat).toHaveClass("settings-list-row", "settings-hover");+ expect(heartbeat).not.toHaveClass("min-h-[92px]");+ expect(within(list).queryByText("System-managed automation")).not.toBeInTheDocument();+ expect(within(list).getByText("Memory update failed")).toBeVisible();+ expect(within(list).getByText("Needs attention")).toBeVisible();+ heartbeat.focus();+ await user.keyboard("{Enter}");+ expect(screen.getByRole("dialog", { name: "heartbeat" })).toBeVisible();+ await user.keyboard("{Escape}");+ await waitFor(() => expect(heartbeat).toHaveFocus());+ });++ it("keeps system tasks mounted for shared expand and collapse transitions without hidden tab stops", async () => {+ const user = userEvent.setup();+ render(<Harness />);+ const toggle = screen.getByRole("button", { name: "System tasks 1" });+ expect(toggle).toHaveAttribute("aria-expanded", "true");+ await user.click(toggle);+ const drawer = document.getElementById(toggle.getAttribute("aria-controls")!);+ expect(drawer).toHaveClass("inline-disclosure");+ expect(drawer).toHaveAttribute("data-state", "closed");+ expect(drawer).toHaveAttribute("aria-hidden", "true");+ expect(drawer!.firstElementChild).toHaveClass("inline-disclosure-clip");+ expect(drawer!.firstElementChild?.firstElementChild).toHaveClass("inline-disclosure-content");+ const row = within(drawer!).getByRole("button", { hidden: true });+ expect(row).toBeDisabled();+ toggle.focus();+ await user.tab();+ expect(row).not.toHaveFocus();++ toggle.focus();+ await user.keyboard("{Enter}");+ expect(toggle).toHaveAttribute("aria-expanded", "true");+ expect(drawer).toHaveAttribute("data-state", "open");+ expect(drawer).not.toHaveAttribute("aria-hidden");+ expect(row).toBeEnabled();+ await user.tab();+ expect(row).toHaveFocus();+ await user.keyboard("{Enter}");+ expect(screen.getByRole("dialog", { name: "heartbeat" })).toBeVisible();+ await user.keyboard("{Escape}");+ await waitFor(() => expect(row).toHaveFocus());+ await user.tab({ shift: true });+ expect(toggle).toHaveFocus();+ await user.keyboard("{Enter}");+ expect(document.getElementById("automation-system-tasks")).toBe(drawer);+ expect(drawer).toHaveAttribute("data-state", "closed");+ expect(drawer).toHaveAttribute("aria-hidden", "true");+ expect(row).toBeDisabled();+ expect(screen.queryByRole("button", { name: /heartbeat/ })).not.toBeInTheDocument();+ await user.click(toggle);+ expect(screen.getByRole("button", { name: /heartbeat/ })).toBe(row);+ });++ it("keeps search, status filters and sorting available on demand", async () => {+ const user = userEvent.setup();+ render(<Harness payload={{ jobs: [task, { ...task, id: "paused", name: "Weekly review", enabled: false }, systemTask] }} />);+ await user.click(screen.getByRole("button", { name: "Search and filter" }));+ const search = screen.getByRole("textbox");+ await user.type(search, "chat:nanobot");+ expect(screen.getByRole("button", { name: /PR watch/ })).toBeVisible();+ await user.clear(search);+ await user.type(search, "heartbeat");+ expect(screen.getByRole("button", { name: /heartbeat/ })).toBeVisible();+ expect(screen.getByRole("button", { name: "System tasks 1" })).toHaveAttribute("aria-expanded", "true");+ await user.clear(search);+ await user.click(screen.getByRole("button", { name: "Paused 1" }));+ expect(screen.queryByRole("button", { name: /PR watch/ })).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: /Weekly review/ })).toBeVisible();+ await user.click(screen.getByRole("button", { name: "Search and filter" }));+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Search and filter" }));+ expect(screen.getByRole("button", { name: "Paused 1" })).toHaveAttribute("aria-pressed", "true");+ await user.click(screen.getByRole("button", { name: "All 2" }));+ await user.click(screen.getByRole("button", { name: "Next run" }));+ await user.click(screen.getByRole("menuitem", { name: "Name" }));+ const rows = within(screen.getByRole("list", { name: "Your automations" })).getAllByRole("button");+ expect(rows[0]).toHaveTextContent("PR watch");+ });++ it("uses live renamed chat titles in details and search without changing the bound task", async () => {+ const user = userEvent.setup();+ const action = vi.fn();+ const payload = { jobs: [task] };+ const { rerender } = render(<Harness payload={payload} onAction={action}+ titleOverrides={{ "websocket:demo": "推特大战场" }} />);+ await user.click(screen.getByRole("button", { name: /PR watch/ }));+ const dialog = screen.getByRole("dialog", { name: "PR watch" });+ const chatLink = within(dialog).getByRole("link", { name: "推特大战场" });+ expect(chatLink).toHaveAttribute("href", "#/chat/websocket%3Ademo");+ rerender(<Harness payload={payload} onAction={action}+ titleOverrides={{ "websocket:demo": "新会话名称" }} />);+ expect(within(dialog).getByRole("link", { name: "新会话名称" })).toBe(chatLink);+ await user.click(within(dialog).getByRole("button", { name: "Pause" }));+ expect(action).toHaveBeenCalledWith("disable", expect.objectContaining({+ id: task.id, payload: task.payload,+ origin: expect.objectContaining({ session_key: "websocket:demo" }),+ }));+ expect(task.origin?.title).toBe("nanobot-development");+ await user.click(within(dialog).getByRole("button", { name: "Done" }));+ await user.click(screen.getByRole("button", { name: "Search and filter" }));+ await user.type(screen.getByRole("textbox"), "chat:新会话名称");+ expect(screen.getByRole("button", { name: /PR watch/ })).toBeVisible();+ rerender(<Harness payload={payload} titleOverrides={{}} />);+ expect(screen.queryByRole("button", { name: /PR watch/ })).not.toBeInTheDocument();+ await user.clear(screen.getByRole("textbox"));+ await user.click(screen.getByRole("button", { name: /PR watch/ }));+ expect(screen.getByRole("link", { name: "nanobot-development" })).toHaveAttribute("href", "#/chat/websocket%3Ademo");+ });++ it("retains the inspected task across refreshes and closes if it is removed", () => {+ const action = vi.fn();+ const { rerender } = render(<Harness onAction={action} />);+ fireEvent.click(screen.getByRole("button", { name: /PR watch/ }));+ fireEvent.click(screen.getByRole("button", { name: "Pause" }));+ expect(action).toHaveBeenCalledWith("disable", task);+ rerender(<Harness payload={{ jobs: [{ ...task, enabled: false }] }} onAction={action} filter="active" />);+ expect(screen.getByRole("dialog", { name: "PR watch" })).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: "Resume" }));+ expect(action).toHaveBeenLastCalledWith("enable", { ...task, enabled: false });+ rerender(<Harness payload={{ jobs: [] }} />);+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });++ it("focuses search on expansion and restores the toggle on Escape without clearing filters", async () => {+ const user = userEvent.setup();+ render(<Harness />);+ const toggle = screen.getByRole("button", { name: "Search and filter" });+ await user.click(toggle);+ const search = screen.getByRole("textbox");+ expect(search).toHaveFocus();+ await user.keyboard("PR");+ await user.keyboard("{Escape}");+ expect(toggle).toHaveAttribute("aria-expanded", "false");+ expect(toggle).toHaveFocus();+ expect(search).toHaveValue("PR");+ expect(search).toBeDisabled();++ await user.keyboard("{Enter}");+ expect(search).toHaveFocus();+ expect(search).toHaveValue("PR");+ fireEvent.keyDown(search, { key: "Escape", isComposing: true });+ expect(toggle).toHaveAttribute("aria-expanded", "true");+ await user.click(screen.getByRole("button", { name: "Next run", exact: true }));+ await user.keyboard("{Escape}");+ expect(screen.queryByRole("menu")).not.toBeInTheDocument();+ expect(toggle).toHaveAttribute("aria-expanded", "true");+ expect(screen.getByRole("button", { name: "Next run", exact: true })).toHaveFocus();+ await user.keyboard("{Escape}");+ expect(toggle).toHaveAttribute("aria-expanded", "false");+ expect(toggle).toHaveFocus();+ });++ it("returns focus to the filter or page heading when the inspected row is no longer present", async () => {+ const user = userEvent.setup();+ const { rerender } = render(<Harness filter="active" />);+ await user.click(screen.getByRole("button", { name: /PR watch/ }));+ rerender(<Harness payload={{ jobs: [{ ...task, enabled: false }] }} filter="active" />);+ await user.click(screen.getByRole("button", { name: "Done" }));+ await waitFor(() => expect(screen.getByRole("button", { name: "Search and filter" })).toHaveFocus());++ rerender(<Harness payload={{ jobs: [task] }} filter="all" />);+ await user.click(screen.getByRole("button", { name: /PR watch/ }));+ rerender(<Harness payload={{ jobs: [] }} filter="all" />);+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());+ expect(screen.getByRole("heading", { name: "Automations" })).toHaveFocus();+ expect(screen.getByText("No automations yet.")).toBeVisible();+ expect(screen.queryByRole("button")).not.toBeInTheDocument();+ });++ it("keeps the filter drawer mounted for both transitions and disables hidden controls", async () => {+ const user = userEvent.setup();+ render(<Harness />);+ const toggle = screen.getByRole("button", { name: "Search and filter" });+ const drawer = document.getElementById(toggle.getAttribute("aria-controls")!)!;+ const search = within(drawer).getByRole("textbox", { hidden: true });+ expect(drawer).toHaveClass("inline-disclosure");+ expect(drawer).toHaveAttribute("data-state", "closed");+ expect(drawer).toHaveAttribute("aria-hidden", "true");+ expect(drawer.firstElementChild).toHaveClass("inline-disclosure-clip");+ expect(drawer.firstElementChild?.firstElementChild).toHaveClass("inline-disclosure-content");+ for (const control of [search, ...within(drawer).getAllByRole("button", { hidden: true })]) {+ expect(control).toBeDisabled();+ }++ await user.click(toggle);+ expect(drawer).toHaveAttribute("data-state", "open");+ expect(drawer).not.toHaveAttribute("aria-hidden");+ expect(screen.getByRole("textbox")).toBe(search);+ await user.type(search, "PR");+ await user.click(toggle);+ expect(document.getElementById("automation-view-options")).toBe(drawer);+ expect(drawer).toHaveAttribute("data-state", "closed");+ expect(search).toHaveValue("PR");+ expect(search).toBeDisabled();+ await user.tab();+ expect(screen.getByRole("button", { name: /PR watch/ })).toHaveFocus();++ await user.click(toggle);+ await user.dblClick(toggle);+ expect(drawer).toHaveAttribute("data-state", "open");+ expect(screen.getByRole("textbox")).toBe(search);+ expect(search).toHaveValue("PR");+ await user.click(screen.getByRole("button", { name: "Next run", exact: true }));+ expect(screen.getByRole("menu")).toBeVisible();+ fireEvent.click(toggle);+ await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());+ expect(drawer).toHaveAttribute("data-state", "closed");+ await user.click(toggle);+ expect(screen.queryByRole("menu")).not.toBeInTheDocument();+ });++ it("hands off editing and deletion without leaving a second modal open", async () => {+ const user = userEvent.setup();+ const edit = vi.fn();+ const remove = vi.fn();+ render(<Harness onRequestEdit={edit} onRequestDelete={remove} />);+ await user.click(screen.getByRole("button", { name: /PR watch/ }));+ await user.click(screen.getByRole("button", { name: "Edit" }));+ await waitFor(() => expect(edit).toHaveBeenCalledWith(task));+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: /PR watch/ }));+ await user.click(screen.getByRole("button", { name: "More actions" }));+ await user.click(screen.getByRole("menuitem", { name: "Delete" }));+ await waitFor(() => expect(remove).toHaveBeenCalledWith(task));+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });++ it("returns keyboard focus to the task after cancelling or saving the real editor", async () => {+ const user = userEvent.setup();+ const save = vi.fn();+ function EditorHarness() {+ const [editing, setEditing] = useState<SessionAutomationJob | null>(null);+ return <>+ <Harness onRequestEdit={setEditing} />+ <AutomationEditDialog job={editing} saving={false}+ onOpenChange={(open) => { if (!open) setEditing(null); }}+ onSave={(job, values) => { save(job, values); setEditing(null); }} />+ </>;+ }+ render(<EditorHarness />);+ const row = screen.getByRole("button", { name: /PR watch/ });+ for (const operation of ["Cancel", "Save"]) {+ await user.click(row);+ await user.click(screen.getByRole("button", { name: "Edit", exact: true }));+ const editor = await screen.findByRole("dialog", { name: "Edit automation" });+ expect(screen.getAllByRole("dialog")).toHaveLength(1);+ if (operation === "Save") {+ await user.clear(within(editor).getByRole("textbox", { name: "Name", exact: true }));+ await user.type(within(editor).getByRole("textbox", { name: "Name", exact: true }), "Updated watch");+ }+ await user.click(within(editor).getByRole("button", { name: operation, exact: true }));+ await waitFor(() => expect(row).toHaveFocus());+ }+ expect(save).toHaveBeenCalledWith(task, expect.objectContaining({ name: "Updated watch" }));+ });++ it("runs a linked task through the existing action and prevents duplicate actions while busy", async () => {+ const user = userEvent.setup();+ const action = vi.fn();+ const { rerender } = render(<Harness onAction={action} />);+ await user.click(screen.getByRole("button", { name: /PR watch/ }));+ await user.click(screen.getByRole("button", { name: "More actions" }));+ await user.click(screen.getByRole("menuitem", { name: "Run now" }));+ expect(action).toHaveBeenCalledWith("run", task);+ rerender(<Harness actionKey="run:private-job-id" />);+ for (const name of ["Edit", "Pause", "More actions"]) {+ expect(screen.getByRole("button", { name })).toBeDisabled();+ }+ rerender(<Harness error="Unable to run task" />);+ expect(within(screen.getByRole("dialog")).getByRole("alert")).toHaveTextContent("Unable to run task");+ });++ it("does not allow running a pending task or resuming an unlinked task", async () => {+ const user = userEvent.setup();+ const { rerender } = render(<Harness payload={{ jobs: [{ ...task, state: { pending: true } }] }} />);+ await user.click(screen.getByRole("button", { name: /PR watch/ }));+ await user.click(screen.getByRole("button", { name: "More actions" }));+ expect(screen.getByRole("menuitem", { name: "Run now" })).toHaveAttribute("aria-disabled", "true");+ await user.keyboard("{Escape}");+ rerender(<Harness payload={{ jobs: [{ ...task, enabled: false, origin: null }] }} />);+ expect(screen.getByRole("button", { name: "Resume" })).toBeDisabled();+ expect(screen.queryByRole("link", { name: "Open a chat" })).not.toBeInTheDocument();+ });++ it("keeps local trigger commands and excludes the scheduled-run action", async () => {+ const user = userEvent.setup();+ render(<Harness payload={{ jobs: [{+ ...task, kind: "local_trigger", schedule: { kind: "local" },+ trigger: { id: "trigger-1", command: "nanobot trigger run trigger-1" },+ }] }} />);+ await user.click(screen.getByRole("button", { name: /PR watch/ }));+ expect(screen.getByText("Command")).toBeVisible();+ expect(within(screen.getByRole("dialog")).getByText("nanobot trigger run trigger-1")).toBeVisible();+ expect(screen.getByRole("button", { name: "Copy" })).toBeEnabled();+ await user.click(screen.getByRole("button", { name: "More actions" }));+ expect(screen.queryByRole("menuitem", { name: "Run now" })).not.toBeInTheDocument();+ });++ it("shows paused failures honestly and does not fabricate successful runs", () => {+ render(<Harness payload={{ jobs: [{+ ...task, enabled: false, state: { last_status: "error", last_error: "Connection interrupted" },+ }, { ...systemTask, state: { last_status: "error" } }] }} />);+ const row = screen.getByRole("button", { name: /PR watch/ });+ expect(row).toHaveTextContent("Needs attention");+ expect(row).toHaveTextContent("Paused");+ expect(screen.getByRole("button", { name: /System tasks 1 Needs attention/ })).toBeVisible();+ fireEvent.click(row);+ expect(within(screen.getByRole("dialog")).getByText("Failed")).toBeVisible();+ expect(within(screen.getByRole("dialog")).queryByText(/Completed/)).not.toBeInTheDocument();+ });++ it("allows expanding long instructions without exposing technical metadata by default", () => {+ render(<Harness payload={{ jobs: [{ ...task, payload: { message: "Long instructions. ".repeat(50) }, state: {} }] }} />);+ fireEvent.click(screen.getByRole("button", { name: /PR watch/ }));+ const dialog = screen.getByRole("dialog");+ expect(within(dialog).getByText("Not run yet")).toBeVisible();+ fireEvent.click(within(dialog).getByRole("button", { name: "Show full message" }));+ expect(within(dialog).getByRole("button", { name: "Show less" })).toHaveAttribute("aria-expanded", "true");+ const disclosure = within(dialog).getByRole("button", { name: "More details" });+ expect(disclosure).toHaveAttribute("aria-expanded", "false");+ fireEvent.click(within(dialog).getByText("More details"));+ expect(disclosure).toHaveAttribute("aria-expanded", "true");+ expect(within(dialog).getByText(task.id)).toBeVisible();+ });+});diff --git a/webui/src/tests/disclosure.test.tsx b/webui/src/tests/disclosure.test.tsxnew file mode 100644index 000000000..fa6845f37--- /dev/null+++ b/webui/src/tests/disclosure.test.tsx@@ -0,0 +1,139 @@+import { act, fireEvent, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, describe, expect, it, vi } from "vitest";++import { Disclosure, DisclosureContent } from "@/components/ui/disclosure";+import { ExpandableText } from "@/components/ui/expandable-text";++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe("shared disclosures", () => {+ it("releases disposable content only after all closing transitions finish", async () => {+ const closed = vi.fn();+ const { container, rerender } = render(<DisclosureContent open onExitComplete={closed}>Diff</DisclosureContent>);+ let finishHeight!: () => void;+ let finishOpacity!: () => void;+ const height = new Promise<void>((resolve) => { finishHeight = resolve; });+ const opacity = new Promise<void>((resolve) => { finishOpacity = resolve; });+ Object.defineProperty(container.firstElementChild, "getAnimations", {+ value: () => [{ finished: height }, { finished: opacity }],+ });+ rerender(<DisclosureContent open={false} onExitComplete={closed}>Diff</DisclosureContent>);+ expect(closed).not.toHaveBeenCalled();+ expect(container.firstElementChild).toHaveAttribute("inert");+ await act(async () => { finishHeight(); });+ expect(closed).not.toHaveBeenCalled();+ await act(async () => { finishOpacity(); });+ expect(closed).toHaveBeenCalledOnce();+ });++ it.each(["reopen", "unmount"])("does not release content after %s interrupts a close", async (action) => {+ const closed = vi.fn();+ let finish!: () => void;+ const finished = new Promise<void>((resolve) => { finish = resolve; });+ const { container, rerender, unmount } = render(<DisclosureContent open onExitComplete={closed}>Diff</DisclosureContent>);+ Object.defineProperty(container.firstElementChild, "getAnimations", { value: () => [{ finished }] });+ rerender(<DisclosureContent open={false} onExitComplete={closed}>Diff</DisclosureContent>);+ if (action === "reopen") rerender(<DisclosureContent open onExitComplete={closed}>Diff</DisclosureContent>);+ else unmount();+ await act(async () => { finish(); });+ expect(closed).not.toHaveBeenCalled();+ });++ it("finishes immediately without motion and also handles a cancelled transition", async () => {+ const closed = vi.fn();+ const { container, rerender } = render(<DisclosureContent open onExitComplete={closed}>Diff</DisclosureContent>);+ const animations = vi.fn((): Array<{ finished: Promise<void> }> => []);+ Object.defineProperty(container.firstElementChild, "getAnimations", { value: animations });+ rerender(<DisclosureContent open={false} onExitComplete={closed}>Diff</DisclosureContent>);+ expect(closed).toHaveBeenCalledOnce();+ rerender(<DisclosureContent open onExitComplete={closed}>Diff</DisclosureContent>);+ let cancel!: () => void;+ const finished = new Promise<void>((_resolve, reject) => { cancel = () => reject(new Error("motion disabled")); });+ animations.mockReturnValue([{ finished }]);+ rerender(<DisclosureContent open={false} onExitComplete={closed}>Diff</DisclosureContent>);+ await act(async () => { cancel(); });+ expect(closed).toHaveBeenCalledTimes(2);+ });++ it("animates both ways without discarding form drafts, and hides collapsed controls", async () => {+ const user = userEvent.setup();+ render(<Disclosure summary="More details"><input aria-label="Draft" defaultValue="initial" /></Disclosure>);+ const toggle = screen.getByRole("button", { name: "More details" });+ const content = document.getElementById(toggle.getAttribute("aria-controls")!)!;+ expect(content).toHaveClass("inline-disclosure");+ expect(content).toHaveAttribute("data-state", "closed");+ expect(content).toHaveAttribute("inert");+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();++ toggle.focus();+ await user.keyboard("{Enter}");+ expect(toggle).toHaveAttribute("aria-expanded", "true");+ expect(content).not.toHaveAttribute("inert");+ const input = screen.getByRole("textbox", { name: "Draft" });+ await user.clear(input);+ await user.type(input, "unsaved draft");+ await user.click(toggle);+ expect(toggle).toHaveFocus();+ expect(content).toHaveAttribute("data-state", "closed");+ expect(content).toHaveAttribute("aria-hidden", "true");+ expect(content).toHaveAttribute("inert");+ expect(input).toBeInTheDocument();+ await user.keyboard(" ");+ expect(screen.getByRole("textbox", { name: "Draft" })).toBe(input);+ expect(input).toHaveValue("unsaved draft");+ });++ it("keeps independent IDs and handles rapid reversals without timers or stale closing state", () => {+ render(<><Disclosure summary="First">One</Disclosure><Disclosure summary="Second">Two</Disclosure></>);+ const first = screen.getByRole("button", { name: "First" });+ const second = screen.getByRole("button", { name: "Second" });+ expect(first.getAttribute("aria-controls")).not.toBe(second.getAttribute("aria-controls"));+ const content = document.getElementById(first.getAttribute("aria-controls")!)!;+ for (let index = 0; index < 7; index++) fireEvent.click(first);+ expect(content).toHaveAttribute("data-state", "open");+ expect(second).toHaveAttribute("aria-expanded", "false");+ fireEvent.click(first);+ expect(content).toHaveAttribute("data-state", "closed");+ });+});++describe("expandable text", () => {+ it("measures natural text height, handles resize and content changes, and preserves one text node", () => {+ let fullHeight = 280;+ let resize: ResizeObserverCallback | undefined;+ const disconnect = vi.fn();+ vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockImplementation(() => fullHeight);+ const getStyle = window.getComputedStyle.bind(window);+ vi.spyOn(window, "getComputedStyle").mockImplementation((node) => node.tagName === "P"+ ? { lineHeight: "20px" } as CSSStyleDeclaration : getStyle(node));+ vi.stubGlobal("ResizeObserver", class {+ constructor(callback: ResizeObserverCallback) { resize = callback; }+ observe() {}+ disconnect = disconnect;+ });+ const { container, rerender, unmount } = render(+ <ExpandableText lines={6} expanded={false}>Long instructions</ExpandableText>,+ );+ const viewport = container.firstElementChild!;+ const text = screen.getByText("Long instructions");+ expect(viewport).toHaveStyle({ height: "120px" });+ rerender(<ExpandableText lines={6} expanded>Long instructions</ExpandableText>);+ expect(viewport).toHaveStyle({ height: "280px" });+ expect(screen.getByText("Long instructions")).toBe(text);+ fullHeight = 380;+ act(() => resize?.([], {} as ResizeObserver));+ expect(viewport).toHaveStyle({ height: "380px" });+ rerender(<ExpandableText lines={6} expanded={false}>Long instructions</ExpandableText>);+ expect(viewport).toHaveStyle({ height: "120px" });+ fullHeight = 40;+ rerender(<ExpandableText lines={6} expanded={false}>Short replacement</ExpandableText>);+ expect(viewport).toHaveStyle({ height: "40px" });+ expect(container.querySelectorAll("p")).toHaveLength(1);+ unmount();+ expect(disconnect).toHaveBeenCalled();+ });+});diff --git a/webui/src/tests/message-bubble.test.tsx b/webui/src/tests/message-bubble.test.tsxindex 6c5041ea7..a03dc63a6 100644--- a/webui/src/tests/message-bubble.test.tsx+++ b/webui/src/tests/message-bubble.test.tsx@@ -840,12 +840,19 @@ describe("MessageBubble", () => {render(<MessageBubble message={message} />);const toggle = screen.getByRole("button", { name: /used 2 tools/i });- expect(screen.queryByText('weather("get")')).not.toBeInTheDocument();- expect(screen.queryByText('search "hk weather"')).not.toBeInTheDocument();+ const content = document.getElementById(toggle.getAttribute("aria-controls")!)!;+ expect(content).toHaveAttribute("data-state", "closed");+ expect(content).toHaveAttribute("inert");+ expect(screen.queryByRole("list")).not.toBeInTheDocument();fireEvent.click(toggle);expect(screen.getByText('weather("get")')).toBeInTheDocument();expect(screen.getByText('search "hk weather"')).toBeInTheDocument();+ expect(content).toHaveAttribute("data-state", "open");+ fireEvent.click(toggle);+ expect(content).toHaveAttribute("data-state", "closed");+ expect(content).toHaveAttribute("aria-hidden", "true");+ expect(screen.getByText('weather("get")')).toBeInTheDocument();});it("renders video media as an inline player", () => {diff --git a/webui/src/tests/settings-automations.test.tsx b/webui/src/tests/settings-automations.test.tsxindex 8f2558214..e5b77aca8 100644--- a/webui/src/tests/settings-automations.test.tsx+++ b/webui/src/tests/settings-automations.test.tsx@@ -1,4 +1,4 @@-import { act, cleanup, render, screen } from "@testing-library/react";+import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";import { AutomationsSettings } from "@/components/settings/system/AutomationsSettings";@@ -6,8 +6,8 @@ import i18n from "@/i18n";afterEach(cleanup);-function renderAutomations(channel: string) {- return render(+function renderAutomationDetail(channel: string) {+ render(<AutomationsSettingspayload={{ jobs: [{id: "task-1",@@ -30,15 +30,16 @@ function renderAutomations(channel: string) {onAction={vi.fn()}onRequestEdit={vi.fn()}onRequestDelete={vi.fn()}- onBackToChat={vi.fn()}/>,);+ fireEvent.click(screen.getByRole("button", { name: /Scheduled task/ }));+ return within(screen.getByRole("dialog", { name: "Scheduled task" }));}describe("automation channel identity", () => {- it("uses channel-owned names in the list and details when the language changes", async () => {- renderAutomations("email");- expect(screen.getAllByText("Email")).toHaveLength(2);+ it("uses channel-owned names in the detail when the language changes", async () => {+ const detail = renderAutomationDetail("email");+ expect(detail.getByText("Email")).toBeVisible();for (const [locale, name] of [["zh-CN", "电子邮件"],@@ -46,15 +47,15 @@ describe("automation channel identity", () => {["es", "Correo electrónico"],]) {await act(() => i18n.changeLanguage(locale));- expect(screen.getAllByText(name)).toHaveLength(2);- expect(screen.queryByText("Email")).not.toBeInTheDocument();+ expect(detail.getByText(name)).toBeVisible();+ expect(detail.queryByText("Email")).not.toBeInTheDocument();}});it("resolves aliases through the owning channel namespace", async () => {await i18n.changeLanguage("zh-CN");- renderAutomations("wechat");- expect(screen.getAllByText("微信")).toHaveLength(2);+ const detail = renderAutomationDetail("wechat");+ expect(detail.getByText("微信")).toBeVisible();});it.each([@@ -62,7 +63,7 @@ describe("automation channel identity", () => {["cli", "CLI"],["extension-chat", "extension-chat"],])("preserves the label for %s", (channel, label) => {- renderAutomations(channel);- expect(screen.getAllByText(label)).toHaveLength(2);+ const detail = renderAutomationDetail(channel);+ expect(detail.getByText(label)).toBeVisible();});});diff --git a/webui/src/tests/settings-system.test.tsx b/webui/src/tests/settings-system.test.tsxindex 726cf66f1..46eaf8bf3 100644--- a/webui/src/tests/settings-system.test.tsx+++ b/webui/src/tests/settings-system.test.tsx@@ -180,7 +180,10 @@ describe("Settings system domains", () => {expect(screen.getByRole("heading", { name: "Automations" })).toBeInTheDocument();expect(await screen.findByText("No automations yet.")).toBeInTheDocument();- fireEvent.click(screen.getByRole("button", { name: "Open a chat" }));+ expect(screen.getByText("Tell nanobot in a chat what you'd like it to do on a schedule.")).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Create in chat" })).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Open a chat" })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Back to chat" }));expect(onBackToChat).toHaveBeenCalledTimes(1);});@@ -209,11 +212,50 @@ describe("Settings system domains", () => {showSidebar: false,});- expect(await screen.findByRole("heading", { name: "Daily summary" })).toBeInTheDocument();+ expect(await screen.findByRole("button", { name: /Daily summary/ })).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Search and filter" }));fireEvent.click(screen.getByRole("button", { name: "Paused 0" }));expect(await screen.findByText("No automations match this view.")).toBeInTheDocument();fireEvent.click(screen.getByRole("button", { name: "Clear filters" }));- expect(await screen.findByRole("heading", { name: "Daily summary" })).toBeInTheDocument();+ expect(await screen.findByRole("button", { name: /Daily summary/ })).toBeInTheDocument();+ });++ it("wraps automation filters and keeps every option selectable", async () => {+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {+ if (String(input) === "/api/settings") return jsonResponse(settingsPayload());+ if (String(input) === "/api/webui/automations") {+ return jsonResponse({ jobs: [+ {+ id: "heartbeat", name: "heartbeat", enabled: true, protected: true,+ schedule: { kind: "every", every_ms: 1_800_000 },+ payload: { message: "System-managed automation" }, state: {},+ },+ {+ id: "paused-job", name: "Paused reminder", enabled: false,+ schedule: { kind: "every", every_ms: 86_400_000 },+ payload: { message: "Check the repo" }, state: {},+ },+ ] });+ }+ return jsonResponse({});+ }));+ renderSettingsView({ initialSection: "automations", initialSettings: settingsPayload(), showSidebar: false });++ fireEvent.click(await screen.findByRole("button", { name: "Search and filter" }));+ const filters = screen.getByRole("group", { name: "Automations" });+ expect(filters).toHaveClass("flex-wrap");+ expect(within(filters).getAllByRole("button")).toHaveLength(4);+ expect(within(filters).getByRole("button", { name: "All 1" })).toHaveAttribute("aria-pressed", "true");+ expect(within(filters).queryByRole("button", { name: /System/ })).not.toBeInTheDocument();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "System tasks 1" })).toHaveAttribute("aria-expanded", "true");+ expect(screen.getByRole("button", { name: /heartbeat/ })).toBeVisible();++ fireEvent.click(within(filters).getByRole("button", { name: "Paused 1" }));+ expect(within(filters).getByRole("button", { name: "Paused 1" })).toHaveAttribute("aria-pressed", "true");+ expect(screen.getByRole("button", { name: /Paused reminder/ })).toBeVisible();+ expect(screen.queryByRole("button", { name: /heartbeat/ })).not.toBeInTheDocument();+ expect(within(filters).getAllByRole("button", { pressed: true })).toHaveLength(1);});it("coalesces focus refreshes while automations are already loading", async () => {diff --git a/webui/src/tests/thread-composer.test.tsx b/webui/src/tests/thread-composer.test.tsxindex 3e6b287ab..38c7b6f60 100644--- a/webui/src/tests/thread-composer.test.tsx+++ b/webui/src/tests/thread-composer.test.tsx@@ -1312,6 +1312,9 @@ describe("ThreadComposer", () => {const { container, rerender } = render(composer(false));const drawer = container.querySelector("[data-composer-workspace-drawer]");+ expect(drawer).toHaveClass("inline-disclosure");+ expect(drawer?.firstElementChild).toHaveClass("inline-disclosure-clip");+ expect(drawer?.firstElementChild?.firstElementChild).toHaveClass("inline-disclosure-content");expect(drawer).toHaveAttribute("data-state", "open");expect(drawer).not.toHaveAttribute("aria-hidden");expect(container.querySelector("[data-composer-workspace-compact]")).not.toBeInTheDocument();