Files
ss-tools/specs/035-agent-chat-context/ux_reference.md
busya ff60865183 feat(agent-chat): 035-agent-chat-context — контекст, guardrails, tools, database discovery
== User stories ==
US1: Контекст с дашборда/датасета → /agent с URL params
US2: Guardrails card — env badge, 7 risk tones, countdown, permission_denied
US3: Tools optimization — retry, timeout, summarise, RBAC + context affinity

== Backend ==
- _context.py (NEW): UIContext validation (7 checks)
- _tool_filter.py (NEW): RBAC + context affinity pipeline
- _confirmation.py: build_confirmation_contract_v2, permission_denied_payload
- tools.py: superset_list_databases, retry/summarise/timeout wrappers
- app.py: _inject_uicontext, _inject_env_id_into_tools, database
  prefetch в runtime context
- _persistence.py: prefetch_databases()
- agent_superset_explore.py: GET /databases endpoint
- _llm_async_http.py, _persistence.py: fix double /v1 в LLM URL
  (LM Studio Unexpected endpoint)

== Frontend ==
- AgentChatModel.svelte.ts: 5 atoms, 3 actions, countdown, context
- AgentChat.svelte: production banner, process steps, debug panel
- ConfirmationCard.svelte: 7 risk tones, permission_denied, countdown
- ToolCallCard.svelte: retrying/timeout/cancelled states
- StreamProcessor.svelte.ts: tool_retry, timeout, permission_denied
- TopNavbar: sparkles icon + Ассистент
- sidebarNavigation: AI section
- DashboardHeader, datasets/+page: contextual AI buttons
- Icon: sparkles, brain, cpu icons
- tailwind: assistant category colors
- i18n: en/ru nav keys

== Tests ==
- 159 backend agent tests (+16 US3: retry, timeout, summarise, contracts)
- 2544 frontend tests (+11 model + component tests)
- 15 JSON fixtures (10 API + 5 model)

== Specs ==
- specs/035-agent-chat-context/: spec, UX, plan, tasks, research,
  data-model, contracts, quickstart, traceability, fixtures, checklists

Closes #035
2026-07-04 22:47:17 +03:00

8.6 KiB
Raw Blame History

#region UxReference [C:3] [TYPE ADR] [SEMANTICS ux, reference, agent-chat, context, guardrails, confirmation] @BRIEF UX interaction reference — persona, flows, states, and recovery paths for enriched agent chat context and refined guardrails. @RELATION DEPENDS_ON -> [AgentChatSpec]

Feature Branch: 035-agent-chat-context Created: 2026-07-04 | Status: Draft

1. User Persona & Context

  • Who is the user?: BI analyst or DevOps engineer working with Superset dashboards and datasets. They navigate between pages (dashboard hub, dataset hub, migration wizard, settings) and expect the AI agent to understand their current context without re-explaining.
  • What is their goal?: Get instant, context-aware help — ask about the dashboard they're viewing, trigger migrations for the current environment, validate the dataset on screen — without copy-pasting IDs or names. The agent receives a JSON context object assembled by the frontend from the current page state.
  • Context: Browser-based SPA (SvelteKit, 1920×1080 typical). The agent chat panel can be toggled from any page via a sidebar button. The chat overlays or sits beside the main content.

2. The "Happy Path" Narrative

The analyst opens dashboard «Отчёт по энергопотреблению» on the /dashboards/42 page. They notice a validation warning badge and click the agent chat button in the sidebar. The chat panel opens. They type: «почему этот дашборд не прошёл валидацию?» The agent — already aware of dashboard ID 42 and current environment prod — calls the validation status tool for that dashboard, receives results, and responds: «Дашборд "Отчёт по энергопотреблению" не прошёл валидацию из-за трёх проблем: ...» The analyst never had to type the dashboard name. They then type «исправь первую проблему и перезапусти валидацию». The agent proposes a fix plan. Since it involves a mutation, a guardrails confirmation card appears — showing the dashboard name, environment badge «⚠️ PRODUCTION», and the specific change. The analyst reviews and confirms. The fix is applied and validation re-runs.

3. Interface Mockups

UI Layout & Flow

Screen/Component: AgentChat panel (existing AgentChat.svelte) with enhanced context awareness.

  • Layout: Right-side slide-out panel, 420px wide. Message list at top (scrollable), input bar at bottom. Context indicator as a subtle pill/badge near the input area showing what the agent «sees».

  • Key Elements:

    • Context pill (new): Small badge above or inside the input area: «📋 Дашборд: Отчёт по энергопотреблению» or «🌐 Окружение: prod» or «Нет активного контекста». Updates in real-time as the user navigates. Non-interactive — informational only.
    • Confirmation Card (refined): Enhanced version of existing ConfirmationCard.svelte. Now includes:
      • Environment badge (e.g. «PRODUCTION», «STAGING», «DEV») with corresponding tone
      • Impact estimate (e.g. «3 дашборда будут изменены»)
      • Risk classification badge (Read / Write / Dangerous)
      • Confirm and Deny buttons (existing)
      • Permission-denied variant: lock icon, «Недостаточно прав», only dismiss button
    • Input bar (existing): Textarea with auto-resize, send button, file attach, stop button.
  • Screen Model: AgentChatModel.svelte.ts — enhanced with uiContext atom.

Context States

  • Dashboard page → /agent: Пользователь на /dashboards/42?env_id=ss-dev нажимает «Спросить агента» → переход на /agent?objectType=dashboard&objectId=42&objectName=Отчёт%20по%20энергопотреблению&envId=ss-dev&route=/dashboards/42. Pill в process steps: «📋 Дашборд #42 · ss-dev».
  • Dataset page → /agent: Переход с /datasets/15?env_id=staging. Pill: «📊 Датасет #15 · staging».
  • Migration page → /agent: Переход с /migration?env_id=prod. Pill: «🔄 Миграция · prod».
  • No object context: Переход с /settings (без objectType). Pill: «🌐 prod» (только окружение) или « Контекст не выбран».

Confirmation Card States

  • Read confirmation: Success-tone card, database/search icon, «Разрешить чтение данных?», green border.

  • Write confirmation (dev/staging): Warning-tone card, «Изменения в dev-окружении», amber border, reduced alarm.

  • Write confirmation (production): Destructive-tone card, «⚠️ PRODUCTION — изменение данных», red border, heightened alarm.

  • Permission denied: Gray-tone card, lock icon, «Недостаточно прав (требуется: admin)», only «Закрыть» button.

  • Loading: Buttons show spinners during confirm/deny dispatch.

  • Contract Mapping:

    • @UX_STATE: idle, streaming, awaiting_confirmation (with sub-states: read/write/dangerous/permission_denied), error, disconnected
    • @UX_FEEDBACK: Toast on confirm/deny; streaming cursor animation; tool execution inline cards; context pill updates on route change
    • @UX_RECOVERY: Denied confirmation → «Операция отменена» message in chat; Permission denied → dismiss card, agent reports «недостаточно прав»; Connection lost → reconnect button; Expired token → «Сессия истекла» banner
    • @UX_REACTIVITY: Context pill derives from AgentChatModel.uiContext ($derived); confirmation tone derives from guardrailDecision atom; route changes trigger context sync via onBeforeSend callback

4. The "Error" Experience

Scenario A: Stale Context (User navigated away mid-stream)

  • User Action: Starts streaming while on dashboard A (фронтенд отправил objectId: "A"), switches to dashboard B before response completes.
  • System Response: Agent completes response using dashboard A's context (the JSON it was given at send time). The context pill shows dashboard B — a subtle mismatch.
  • Recovery: Следующее сообщение пользователя отправит свежий JSON с objectId: "B".

Scenario B: Permission Denied (analyst tries guarded tool)

  • User Action: Asks agent «задеплой этот дашборд на prod».
  • System Response: Guardrail evaluates — user has analyst role, deploy requires admin. Confirmation card renders with lock icon and «Недостаточно прав (требуется: admin)». No confirm button.
  • Recovery: User dismisses the card. Agent responds: «Для деплоя на production требуются права администратора. Обратитесь к администратору системы.»

Scenario C: Tool Timeout

  • User Action: Agent invokes a tool that hangs (Superset API unresponsive).
  • System Response: After 30 seconds, agent receives timeout error. Chat shows: «⏱️ Операция превысила время ожидания (30с). Попробуйте позже или проверьте состояние Superset.»
  • Recovery: User can retry the same request or ask the agent for an alternative approach.

Scenario D: FastAPI Transient Error (Retry Success)

  • System Response: First tool call fails with 502. Agent retries once (1s backoff). Second attempt succeeds. User sees tool execution card transition: spinner → completed. No error message visible.
  • Recovery: Transparent to the user.

Scenario E: FastAPI Persistent Error (Retry Exhausted)

  • System Response: Both attempts fail. Agent shows: « Сервис временно недоступен. Ошибка при вызове search_dashboards.» Tool card shows icon.
  • Recovery: User can retry the full message later.

5. Tone & Voice

  • Style: Concise, technical, Russian-first (English for code/technical terms). The agent speaks in short paragraphs with bullet points for structured data.
  • Terminology: «Дашборд» (not «дэшборд»), «Окружение» (not «среда»), «Валидация» (not «проверка»), «Инструмент» (for tool), «Подтверждение» (for confirmation). Code identifiers in English (tool names, API paths).

#endregion UxReference